2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
47 # include "afs/sysincludes.h"
48 # include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
54 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
55 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
56 extern afs_int32 afs_termState;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
76 #include "rx_atomic.h"
77 #include "rx_globals.h"
79 #include "rx_internal.h"
86 #include "rx_packet.h"
88 #include <afs/rxgen_consts.h>
91 #ifdef AFS_PTHREAD_ENV
93 int (*registerProgram) (pid_t, char *) = 0;
94 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
97 int (*registerProgram) (PROCESS, char *) = 0;
98 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
102 /* Local static routines */
103 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
104 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
105 struct rx_call *, struct rx_peer *,
107 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
109 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
110 void *dummy, int dummy2);
111 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
112 void *dummy, int dummy2);
113 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
114 void *unused, int unused2);
115 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
116 void *unused2, int unused3);
117 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
118 struct rx_packet *packet,
119 int istack, int force);
120 static void rxi_AckAll(struct rx_call *call);
121 static struct rx_connection
122 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
123 u_short serviceId, afs_uint32 cid,
124 afs_uint32 epoch, int type, u_int securityIndex);
125 static struct rx_packet
126 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
127 int istack, osi_socket socket,
128 afs_uint32 host, u_short port, int *tnop,
129 struct rx_call **newcallp);
130 static struct rx_packet
131 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
133 static struct rx_packet
134 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
135 struct rx_packet *np, int istack);
136 static struct rx_packet
137 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
138 struct rx_packet *np, int istack);
139 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
140 int *tnop, struct rx_call **newcallp);
141 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
142 static void rxi_ClearReceiveQueue(struct rx_call *call);
143 static void rxi_ResetCall(struct rx_call *call, int newcall);
144 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
145 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
146 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
147 static void rxi_KeepAliveOn(struct rx_call *call);
148 static void rxi_GrowMTUOn(struct rx_call *call);
149 static void rxi_ChallengeOn(struct rx_connection *conn);
151 #ifdef RX_ENABLE_LOCKS
152 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
153 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
155 static int rxi_CheckCall(struct rx_call *call);
158 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
160 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
161 rx_atomic_t rxi_start_in_error;
163 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
165 /* Constant delay time before sending an acknowledge of the last packet
166 * received. This is to avoid sending an extra acknowledge when the
167 * client is about to make another call, anyway, or the server is
170 * The lastAckDelay may not exceeed 400ms without causing peers to
171 * unecessarily timeout.
173 struct clock rx_lastAckDelay = {0, 400000};
175 /* Constant delay time before sending a soft ack when none was requested.
176 * This is to make sure we send soft acks before the sender times out,
177 * Normally we wait and send a hard ack when the receiver consumes the packet
179 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
180 * will require changes to the peer's RTT calculations.
182 struct clock rx_softAckDelay = {0, 100000};
185 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
186 * currently allocated within rx. This number is used to allocate the
187 * memory required to return the statistics when queried.
188 * Protected by the rx_rpc_stats mutex.
191 static unsigned int rxi_rpc_peer_stat_cnt;
194 * rxi_rpc_process_stat_cnt counts the total number of local process stat
195 * structures currently allocated within rx. The number is used to allocate
196 * the memory required to return the statistics when queried.
197 * Protected by the rx_rpc_stats mutex.
200 static unsigned int rxi_rpc_process_stat_cnt;
203 * rxi_busyChannelError is a boolean. It indicates whether or not RX_CALL_BUSY
204 * errors should be reported to the application when a call channel appears busy
205 * (inferred from the receipt of RX_PACKET_TYPE_BUSY packets on the channel),
206 * and there are other call channels in the connection that are not busy.
207 * If 0, we do not return errors upon receiving busy packets; we just keep
208 * trying on the same call channel until we hit a timeout.
210 static afs_int32 rxi_busyChannelError = 0;
212 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
213 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
215 #if !defined(offsetof)
216 #include <stddef.h> /* for definition of offsetof() */
219 #ifdef RX_ENABLE_LOCKS
220 afs_kmutex_t rx_atomic_mutex;
223 /* Forward prototypes */
224 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
227 putConnection (struct rx_connection *conn) {
228 MUTEX_ENTER(&rx_refcnt_mutex);
230 MUTEX_EXIT(&rx_refcnt_mutex);
233 #ifdef AFS_PTHREAD_ENV
236 * Use procedural initialization of mutexes/condition variables
240 extern afs_kmutex_t rx_quota_mutex;
241 extern afs_kmutex_t rx_pthread_mutex;
242 extern afs_kmutex_t rx_packets_mutex;
243 extern afs_kmutex_t rx_refcnt_mutex;
244 extern afs_kmutex_t des_init_mutex;
245 extern afs_kmutex_t des_random_mutex;
246 extern afs_kmutex_t rx_clock_mutex;
247 extern afs_kmutex_t rxi_connCacheMutex;
248 extern afs_kmutex_t event_handler_mutex;
249 extern afs_kmutex_t listener_mutex;
250 extern afs_kmutex_t rx_if_init_mutex;
251 extern afs_kmutex_t rx_if_mutex;
253 extern afs_kcondvar_t rx_event_handler_cond;
254 extern afs_kcondvar_t rx_listener_cond;
256 static afs_kmutex_t epoch_mutex;
257 static afs_kmutex_t rx_init_mutex;
258 static afs_kmutex_t rx_debug_mutex;
259 static afs_kmutex_t rx_rpc_stats;
262 rxi_InitPthread(void)
264 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
265 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
266 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
267 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
268 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
269 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
270 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
271 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
272 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
273 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
274 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
275 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
278 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
280 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
281 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
283 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
284 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
286 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
288 #ifdef RX_ENABLE_LOCKS
291 #endif /* RX_LOCKS_DB */
292 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
295 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
297 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
299 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
301 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
302 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
303 #endif /* RX_ENABLE_LOCKS */
306 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
307 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
309 * The rx_stats_mutex mutex protects the following global variables:
310 * rxi_lowConnRefCount
311 * rxi_lowPeerRefCount
320 * The rx_quota_mutex mutex protects the following global variables:
328 * The rx_freePktQ_lock protects the following global variables:
333 * The rx_packets_mutex mutex protects the following global variables:
341 * The rx_pthread_mutex mutex protects the following global variables:
342 * rxi_fcfs_thread_num
345 #define INIT_PTHREAD_LOCKS
349 /* Variables for handling the minProcs implementation. availProcs gives the
350 * number of threads available in the pool at this moment (not counting dudes
351 * executing right now). totalMin gives the total number of procs required
352 * for handling all minProcs requests. minDeficit is a dynamic variable
353 * tracking the # of procs required to satisfy all of the remaining minProcs
355 * For fine grain locking to work, the quota check and the reservation of
356 * a server thread has to come while rxi_availProcs and rxi_minDeficit
357 * are locked. To this end, the code has been modified under #ifdef
358 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
359 * same time. A new function, ReturnToServerPool() returns the allocation.
361 * A call can be on several queue's (but only one at a time). When
362 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
363 * that no one else is touching the queue. To this end, we store the address
364 * of the queue lock in the call structure (under the call lock) when we
365 * put the call on a queue, and we clear the call_queue_lock when the
366 * call is removed from a queue (once the call lock has been obtained).
367 * This allows rxi_ResetCall to safely synchronize with others wishing
368 * to manipulate the queue.
371 #if defined(RX_ENABLE_LOCKS)
372 static afs_kmutex_t rx_rpc_stats;
375 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
376 ** pretty good that the next packet coming in is from the same connection
377 ** as the last packet, since we're send multiple packets in a transmit window.
379 struct rx_connection *rxLastConn = 0;
381 #ifdef RX_ENABLE_LOCKS
382 /* The locking hierarchy for rx fine grain locking is composed of these
385 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
386 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
387 * call->lock - locks call data fields.
388 * These are independent of each other:
389 * rx_freeCallQueue_lock
394 * serverQueueEntry->lock
395 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
397 * peer->lock - locks peer data fields.
398 * conn_data_lock - that more than one thread is not updating a conn data
399 * field at the same time.
410 * Do we need a lock to protect the peer field in the conn structure?
411 * conn->peer was previously a constant for all intents and so has no
412 * lock protecting this field. The multihomed client delta introduced
413 * a RX code change : change the peer field in the connection structure
414 * to that remote interface from which the last packet for this
415 * connection was sent out. This may become an issue if further changes
418 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
419 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
421 /* rxdb_fileID is used to identify the lock location, along with line#. */
422 static int rxdb_fileID = RXDB_FILE_RX;
423 #endif /* RX_LOCKS_DB */
424 #else /* RX_ENABLE_LOCKS */
425 #define SET_CALL_QUEUE_LOCK(C, L)
426 #define CLEAR_CALL_QUEUE_LOCK(C)
427 #endif /* RX_ENABLE_LOCKS */
428 struct rx_serverQueueEntry *rx_waitForPacket = 0;
429 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
431 /* ------------Exported Interfaces------------- */
433 /* This function allows rxkad to set the epoch to a suitably random number
434 * which rx_NewConnection will use in the future. The principle purpose is to
435 * get rxnull connections to use the same epoch as the rxkad connections do, at
436 * least once the first rxkad connection is established. This is important now
437 * that the host/port addresses aren't used in FindConnection: the uniqueness
438 * of epoch/cid matters and the start time won't do. */
440 #ifdef AFS_PTHREAD_ENV
442 * This mutex protects the following global variables:
446 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
447 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
451 #endif /* AFS_PTHREAD_ENV */
454 rx_SetEpoch(afs_uint32 epoch)
461 /* Initialize rx. A port number may be mentioned, in which case this
462 * becomes the default port number for any service installed later.
463 * If 0 is provided for the port number, a random port will be chosen
464 * by the kernel. Whether this will ever overlap anything in
465 * /etc/services is anybody's guess... Returns 0 on success, -1 on
470 int rxinit_status = 1;
471 #ifdef AFS_PTHREAD_ENV
473 * This mutex protects the following global variables:
477 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
478 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
481 #define UNLOCK_RX_INIT
485 rx_InitHost(u_int host, u_int port)
492 char *htable, *ptable;
499 if (rxinit_status == 0) {
500 tmp_status = rxinit_status;
502 return tmp_status; /* Already started; return previous error code. */
508 if (afs_winsockInit() < 0)
514 * Initialize anything necessary to provide a non-premptive threading
517 rxi_InitializeThreadSupport();
520 /* Allocate and initialize a socket for client and perhaps server
523 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
524 if (rx_socket == OSI_NULLSOCKET) {
528 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
531 #endif /* RX_LOCKS_DB */
532 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
539 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
540 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
541 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
543 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
545 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
547 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
549 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
550 #if defined(AFS_HPUX110_ENV)
552 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
553 #endif /* AFS_HPUX110_ENV */
554 #endif /* RX_ENABLE_LOCKS && KERNEL */
557 rx_connDeadTime = 12;
558 rx_tranquil = 0; /* reset flag */
559 rxi_ResetStatistics();
560 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
561 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
562 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
563 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
564 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
565 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
567 /* Malloc up a bunch of packets & buffers */
569 queue_Init(&rx_freePacketQueue);
570 rxi_NeedMorePackets = FALSE;
571 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
573 /* enforce a minimum number of allocated packets */
574 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
575 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
577 /* allocate the initial free packet pool */
578 #ifdef RX_ENABLE_TSFPQ
579 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
580 #else /* RX_ENABLE_TSFPQ */
581 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
582 #endif /* RX_ENABLE_TSFPQ */
589 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
590 tv.tv_sec = clock_now.sec;
591 tv.tv_usec = clock_now.usec;
592 srand((unsigned int)tv.tv_usec);
599 #if defined(KERNEL) && !defined(UKERNEL)
600 /* Really, this should never happen in a real kernel */
603 struct sockaddr_in addr;
605 int addrlen = sizeof(addr);
607 socklen_t addrlen = sizeof(addr);
609 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
611 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
614 rx_port = addr.sin_port;
617 rx_stats.minRtt.sec = 9999999;
619 rx_SetEpoch(tv.tv_sec | 0x80000000);
621 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
622 * will provide a randomer value. */
624 MUTEX_ENTER(&rx_quota_mutex);
625 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
626 MUTEX_EXIT(&rx_quota_mutex);
627 /* *Slightly* random start time for the cid. This is just to help
628 * out with the hashing function at the peer */
629 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
630 rx_connHashTable = (struct rx_connection **)htable;
631 rx_peerHashTable = (struct rx_peer **)ptable;
633 rx_hardAckDelay.sec = 0;
634 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
636 rxevent_Init(20, rxi_ReScheduleEvents);
638 /* Initialize various global queues */
639 queue_Init(&rx_idleServerQueue);
640 queue_Init(&rx_incomingCallQueue);
641 queue_Init(&rx_freeCallQueue);
643 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
644 /* Initialize our list of usable IP addresses. */
648 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
649 /* Start listener process (exact function is dependent on the
650 * implementation environment--kernel or user space) */
655 tmp_status = rxinit_status = 0;
663 return rx_InitHost(htonl(INADDR_ANY), port);
669 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
670 * maintaing the round trip timer.
675 * Start a new RTT timer for a given call and packet.
677 * There must be no resendEvent already listed for this call, otherwise this
678 * will leak events - intended for internal use within the RTO code only
681 * the RX call to start the timer for
682 * @param[in] lastPacket
683 * a flag indicating whether the last packet has been sent or not
685 * @pre call must be locked before calling this function
689 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
691 struct clock now, retryTime;
696 clock_Add(&retryTime, &call->rto);
698 /* If we're sending the last packet, and we're the client, then the server
699 * may wait for an additional 400ms before returning the ACK, wait for it
700 * rather than hitting a timeout */
701 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
702 clock_Addmsec(&retryTime, 400);
704 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
705 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
710 * Cancel an RTT timer for a given call.
714 * the RX call to cancel the timer for
716 * @pre call must be locked before calling this function
721 rxi_rto_cancel(struct rx_call *call)
723 rxevent_Cancel(&call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
727 * Tell the RTO timer that we have sent a packet.
729 * If the timer isn't already running, then start it. If the timer is running,
733 * the RX call that the packet has been sent on
734 * @param[in] lastPacket
735 * A flag which is true if this is the last packet for the call
737 * @pre The call must be locked before calling this function
742 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
744 if (call->resendEvent)
747 rxi_rto_startTimer(call, lastPacket, istack);
751 * Tell the RTO timer that we have received an new ACK message
753 * This function should be called whenever a call receives an ACK that
754 * acknowledges new packets. Whatever happens, we stop the current timer.
755 * If there are unacked packets in the queue which have been sent, then
756 * we restart the timer from now. Otherwise, we leave it stopped.
759 * the RX call that the ACK has been received on
763 rxi_rto_packet_acked(struct rx_call *call, int istack)
765 struct rx_packet *p, *nxp;
767 rxi_rto_cancel(call);
769 if (queue_IsEmpty(&call->tq))
772 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
773 if (p->header.seq > call->tfirst + call->twind)
776 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
777 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
785 * Set an initial round trip timeout for a peer connection
787 * @param[in] secs The timeout to set in seconds
791 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
792 peer->rtt = secs * 8000;
796 * Enables or disables the busy call channel error (RX_CALL_BUSY).
798 * @param[in] onoff Non-zero to enable busy call channel errors.
800 * @pre Neither rx_Init nor rx_InitHost have been called yet
803 rx_SetBusyChannelError(afs_int32 onoff)
805 osi_Assert(rxinit_status != 0);
806 rxi_busyChannelError = onoff ? 1 : 0;
810 * Set a delayed ack event on the specified call for the given time
812 * @param[in] call - the call on which to set the event
813 * @param[in] offset - the delay from now after which the event fires
816 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
818 struct clock now, when;
822 clock_Add(&when, offset);
824 if (!call->delayedAckEvent
825 || clock_Gt(&call->delayedAckTime, &when)) {
827 rxevent_Cancel(&call->delayedAckEvent, call,
828 RX_CALL_REFCOUNT_DELAY);
829 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
831 call->delayedAckEvent = rxevent_Post(&when, &now,
834 call->delayedAckTime = when;
838 /* called with unincremented nRequestsRunning to see if it is OK to start
839 * a new thread in this service. Could be "no" for two reasons: over the
840 * max quota, or would prevent others from reaching their min quota.
842 #ifdef RX_ENABLE_LOCKS
843 /* This verion of QuotaOK reserves quota if it's ok while the
844 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
847 QuotaOK(struct rx_service *aservice)
849 /* check if over max quota */
850 if (aservice->nRequestsRunning >= aservice->maxProcs) {
854 /* under min quota, we're OK */
855 /* otherwise, can use only if there are enough to allow everyone
856 * to go to their min quota after this guy starts.
859 MUTEX_ENTER(&rx_quota_mutex);
860 if ((aservice->nRequestsRunning < aservice->minProcs)
861 || (rxi_availProcs > rxi_minDeficit)) {
862 aservice->nRequestsRunning++;
863 /* just started call in minProcs pool, need fewer to maintain
865 if (aservice->nRequestsRunning <= aservice->minProcs)
868 MUTEX_EXIT(&rx_quota_mutex);
871 MUTEX_EXIT(&rx_quota_mutex);
877 ReturnToServerPool(struct rx_service *aservice)
879 aservice->nRequestsRunning--;
880 MUTEX_ENTER(&rx_quota_mutex);
881 if (aservice->nRequestsRunning < aservice->minProcs)
884 MUTEX_EXIT(&rx_quota_mutex);
887 #else /* RX_ENABLE_LOCKS */
889 QuotaOK(struct rx_service *aservice)
892 /* under min quota, we're OK */
893 if (aservice->nRequestsRunning < aservice->minProcs)
896 /* check if over max quota */
897 if (aservice->nRequestsRunning >= aservice->maxProcs)
900 /* otherwise, can use only if there are enough to allow everyone
901 * to go to their min quota after this guy starts.
903 MUTEX_ENTER(&rx_quota_mutex);
904 if (rxi_availProcs > rxi_minDeficit)
906 MUTEX_EXIT(&rx_quota_mutex);
909 #endif /* RX_ENABLE_LOCKS */
912 /* Called by rx_StartServer to start up lwp's to service calls.
913 NExistingProcs gives the number of procs already existing, and which
914 therefore needn't be created. */
916 rxi_StartServerProcs(int nExistingProcs)
918 struct rx_service *service;
923 /* For each service, reserve N processes, where N is the "minimum"
924 * number of processes that MUST be able to execute a request in parallel,
925 * at any time, for that process. Also compute the maximum difference
926 * between any service's maximum number of processes that can run
927 * (i.e. the maximum number that ever will be run, and a guarantee
928 * that this number will run if other services aren't running), and its
929 * minimum number. The result is the extra number of processes that
930 * we need in order to provide the latter guarantee */
931 for (i = 0; i < RX_MAX_SERVICES; i++) {
933 service = rx_services[i];
934 if (service == (struct rx_service *)0)
936 nProcs += service->minProcs;
937 diff = service->maxProcs - service->minProcs;
941 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
942 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
943 for (i = 0; i < nProcs; i++) {
944 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
950 /* This routine is only required on Windows */
952 rx_StartClientThread(void)
954 #ifdef AFS_PTHREAD_ENV
956 pid = pthread_self();
957 #endif /* AFS_PTHREAD_ENV */
959 #endif /* AFS_NT40_ENV */
961 /* This routine must be called if any services are exported. If the
962 * donateMe flag is set, the calling process is donated to the server
965 rx_StartServer(int donateMe)
967 struct rx_service *service;
973 /* Start server processes, if necessary (exact function is dependent
974 * on the implementation environment--kernel or user space). DonateMe
975 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
976 * case, one less new proc will be created rx_StartServerProcs.
978 rxi_StartServerProcs(donateMe);
980 /* count up the # of threads in minProcs, and add set the min deficit to
981 * be that value, too.
983 for (i = 0; i < RX_MAX_SERVICES; i++) {
984 service = rx_services[i];
985 if (service == (struct rx_service *)0)
987 MUTEX_ENTER(&rx_quota_mutex);
988 rxi_totalMin += service->minProcs;
989 /* below works even if a thread is running, since minDeficit would
990 * still have been decremented and later re-incremented.
992 rxi_minDeficit += service->minProcs;
993 MUTEX_EXIT(&rx_quota_mutex);
996 /* Turn on reaping of idle server connections */
997 rxi_ReapConnections(NULL, NULL, NULL, 0);
1002 #ifndef AFS_NT40_ENV
1006 #ifdef AFS_PTHREAD_ENV
1008 pid = afs_pointer_to_int(pthread_self());
1009 #else /* AFS_PTHREAD_ENV */
1011 LWP_CurrentProcess(&pid);
1012 #endif /* AFS_PTHREAD_ENV */
1014 sprintf(name, "srv_%d", ++nProcs);
1015 if (registerProgram)
1016 (*registerProgram) (pid, name);
1018 #endif /* AFS_NT40_ENV */
1019 rx_ServerProc(NULL); /* Never returns */
1021 #ifdef RX_ENABLE_TSFPQ
1022 /* no use leaving packets around in this thread's local queue if
1023 * it isn't getting donated to the server thread pool.
1025 rxi_FlushLocalPacketsTSFPQ();
1026 #endif /* RX_ENABLE_TSFPQ */
1030 /* Create a new client connection to the specified service, using the
1031 * specified security object to implement the security model for this
1033 struct rx_connection *
1034 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1035 struct rx_securityClass *securityObject,
1036 int serviceSecurityIndex)
1040 struct rx_connection *conn;
1045 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1046 "serviceSecurityIndex %d)\n",
1047 ntohl(shost), ntohs(sport), sservice, securityObject,
1048 serviceSecurityIndex));
1050 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1051 * the case of kmem_alloc? */
1052 conn = rxi_AllocConnection();
1053 #ifdef RX_ENABLE_LOCKS
1054 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1055 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1056 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1059 MUTEX_ENTER(&rx_connHashTable_lock);
1060 cid = (rx_nextCid += RX_MAXCALLS);
1061 conn->type = RX_CLIENT_CONNECTION;
1063 conn->epoch = rx_epoch;
1064 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
1065 conn->serviceId = sservice;
1066 conn->securityObject = securityObject;
1067 conn->securityData = (void *) 0;
1068 conn->securityIndex = serviceSecurityIndex;
1069 rx_SetConnDeadTime(conn, rx_connDeadTime);
1070 rx_SetConnSecondsUntilNatPing(conn, 0);
1071 conn->ackRate = RX_FAST_ACK_RATE;
1072 conn->nSpecific = 0;
1073 conn->specific = NULL;
1074 conn->challengeEvent = NULL;
1075 conn->delayedAbortEvent = NULL;
1076 conn->abortCount = 0;
1078 for (i = 0; i < RX_MAXCALLS; i++) {
1079 conn->twind[i] = rx_initSendWindow;
1080 conn->rwind[i] = rx_initReceiveWindow;
1081 conn->lastBusy[i] = 0;
1084 RXS_NewConnection(securityObject, conn);
1086 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1088 conn->refCount++; /* no lock required since only this thread knows... */
1089 conn->next = rx_connHashTable[hashindex];
1090 rx_connHashTable[hashindex] = conn;
1091 if (rx_stats_active)
1092 rx_atomic_inc(&rx_stats.nClientConns);
1093 MUTEX_EXIT(&rx_connHashTable_lock);
1099 * Ensure a connection's timeout values are valid.
1101 * @param[in] conn The connection to check
1103 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1104 * unless idleDeadTime and/or hardDeadTime are not set
1108 rxi_CheckConnTimeouts(struct rx_connection *conn)
1110 /* a connection's timeouts must have the relationship
1111 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1112 * total loss of network to a peer may cause an idle timeout instead of a
1113 * dead timeout, simply because the idle timeout gets hit first. Also set
1114 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1115 /* this logic is slightly complicated by the fact that
1116 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1118 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1119 if (conn->idleDeadTime) {
1120 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1122 if (conn->hardDeadTime) {
1123 if (conn->idleDeadTime) {
1124 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1126 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1132 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1134 /* The idea is to set the dead time to a value that allows several
1135 * keepalives to be dropped without timing out the connection. */
1136 conn->secondsUntilDead = seconds;
1137 rxi_CheckConnTimeouts(conn);
1138 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1142 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1144 conn->hardDeadTime = seconds;
1145 rxi_CheckConnTimeouts(conn);
1149 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1151 conn->idleDeadTime = seconds;
1152 conn->idleDeadDetection = (seconds ? 1 : 0);
1153 rxi_CheckConnTimeouts(conn);
1156 int rxi_lowPeerRefCount = 0;
1157 int rxi_lowConnRefCount = 0;
1160 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1161 * NOTE: must not be called with rx_connHashTable_lock held.
1164 rxi_CleanupConnection(struct rx_connection *conn)
1166 /* Notify the service exporter, if requested, that this connection
1167 * is being destroyed */
1168 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1169 (*conn->service->destroyConnProc) (conn);
1171 /* Notify the security module that this connection is being destroyed */
1172 RXS_DestroyConnection(conn->securityObject, conn);
1174 /* If this is the last connection using the rx_peer struct, set its
1175 * idle time to now. rxi_ReapConnections will reap it if it's still
1176 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1178 MUTEX_ENTER(&rx_peerHashTable_lock);
1179 if (conn->peer->refCount < 2) {
1180 conn->peer->idleWhen = clock_Sec();
1181 if (conn->peer->refCount < 1) {
1182 conn->peer->refCount = 1;
1183 if (rx_stats_active) {
1184 MUTEX_ENTER(&rx_stats_mutex);
1185 rxi_lowPeerRefCount++;
1186 MUTEX_EXIT(&rx_stats_mutex);
1190 conn->peer->refCount--;
1191 MUTEX_EXIT(&rx_peerHashTable_lock);
1193 if (rx_stats_active)
1195 if (conn->type == RX_SERVER_CONNECTION)
1196 rx_atomic_dec(&rx_stats.nServerConns);
1198 rx_atomic_dec(&rx_stats.nClientConns);
1201 if (conn->specific) {
1203 for (i = 0; i < conn->nSpecific; i++) {
1204 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1205 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1206 conn->specific[i] = NULL;
1208 free(conn->specific);
1210 conn->specific = NULL;
1211 conn->nSpecific = 0;
1212 #endif /* !KERNEL */
1214 MUTEX_DESTROY(&conn->conn_call_lock);
1215 MUTEX_DESTROY(&conn->conn_data_lock);
1216 CV_DESTROY(&conn->conn_call_cv);
1218 rxi_FreeConnection(conn);
1221 /* Destroy the specified connection */
1223 rxi_DestroyConnection(struct rx_connection *conn)
1225 MUTEX_ENTER(&rx_connHashTable_lock);
1226 rxi_DestroyConnectionNoLock(conn);
1227 /* conn should be at the head of the cleanup list */
1228 if (conn == rx_connCleanup_list) {
1229 rx_connCleanup_list = rx_connCleanup_list->next;
1230 MUTEX_EXIT(&rx_connHashTable_lock);
1231 rxi_CleanupConnection(conn);
1233 #ifdef RX_ENABLE_LOCKS
1235 MUTEX_EXIT(&rx_connHashTable_lock);
1237 #endif /* RX_ENABLE_LOCKS */
1241 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1243 struct rx_connection **conn_ptr;
1245 struct rx_packet *packet;
1252 MUTEX_ENTER(&conn->conn_data_lock);
1253 MUTEX_ENTER(&rx_refcnt_mutex);
1254 if (conn->refCount > 0)
1257 if (rx_stats_active) {
1258 MUTEX_ENTER(&rx_stats_mutex);
1259 rxi_lowConnRefCount++;
1260 MUTEX_EXIT(&rx_stats_mutex);
1264 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1265 /* Busy; wait till the last guy before proceeding */
1266 MUTEX_EXIT(&rx_refcnt_mutex);
1267 MUTEX_EXIT(&conn->conn_data_lock);
1272 /* If the client previously called rx_NewCall, but it is still
1273 * waiting, treat this as a running call, and wait to destroy the
1274 * connection later when the call completes. */
1275 if ((conn->type == RX_CLIENT_CONNECTION)
1276 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1277 conn->flags |= RX_CONN_DESTROY_ME;
1278 MUTEX_EXIT(&conn->conn_data_lock);
1282 MUTEX_EXIT(&rx_refcnt_mutex);
1283 MUTEX_EXIT(&conn->conn_data_lock);
1285 /* Check for extant references to this connection */
1286 MUTEX_ENTER(&conn->conn_call_lock);
1287 for (i = 0; i < RX_MAXCALLS; i++) {
1288 struct rx_call *call = conn->call[i];
1291 if (conn->type == RX_CLIENT_CONNECTION) {
1292 MUTEX_ENTER(&call->lock);
1293 if (call->delayedAckEvent) {
1294 /* Push the final acknowledgment out now--there
1295 * won't be a subsequent call to acknowledge the
1296 * last reply packets */
1297 rxevent_Cancel(&call->delayedAckEvent, call,
1298 RX_CALL_REFCOUNT_DELAY);
1299 if (call->state == RX_STATE_PRECALL
1300 || call->state == RX_STATE_ACTIVE) {
1301 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1306 MUTEX_EXIT(&call->lock);
1310 MUTEX_EXIT(&conn->conn_call_lock);
1312 #ifdef RX_ENABLE_LOCKS
1314 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1315 MUTEX_EXIT(&conn->conn_data_lock);
1317 /* Someone is accessing a packet right now. */
1321 #endif /* RX_ENABLE_LOCKS */
1324 /* Don't destroy the connection if there are any call
1325 * structures still in use */
1326 MUTEX_ENTER(&conn->conn_data_lock);
1327 conn->flags |= RX_CONN_DESTROY_ME;
1328 MUTEX_EXIT(&conn->conn_data_lock);
1333 if (conn->natKeepAliveEvent) {
1334 rxi_NatKeepAliveOff(conn);
1337 if (conn->delayedAbortEvent) {
1338 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1339 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1341 MUTEX_ENTER(&conn->conn_data_lock);
1342 rxi_SendConnectionAbort(conn, packet, 0, 1);
1343 MUTEX_EXIT(&conn->conn_data_lock);
1344 rxi_FreePacket(packet);
1348 /* Remove from connection hash table before proceeding */
1350 &rx_connHashTable[CONN_HASH
1351 (peer->host, peer->port, conn->cid, conn->epoch,
1353 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1354 if (*conn_ptr == conn) {
1355 *conn_ptr = conn->next;
1359 /* if the conn that we are destroying was the last connection, then we
1360 * clear rxLastConn as well */
1361 if (rxLastConn == conn)
1364 /* Make sure the connection is completely reset before deleting it. */
1365 /* get rid of pending events that could zap us later */
1366 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1367 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1368 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1370 /* Add the connection to the list of destroyed connections that
1371 * need to be cleaned up. This is necessary to avoid deadlocks
1372 * in the routines we call to inform others that this connection is
1373 * being destroyed. */
1374 conn->next = rx_connCleanup_list;
1375 rx_connCleanup_list = conn;
1378 /* Externally available version */
1380 rx_DestroyConnection(struct rx_connection *conn)
1385 rxi_DestroyConnection(conn);
1390 rx_GetConnection(struct rx_connection *conn)
1395 MUTEX_ENTER(&rx_refcnt_mutex);
1397 MUTEX_EXIT(&rx_refcnt_mutex);
1401 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1402 /* Wait for the transmit queue to no longer be busy.
1403 * requires the call->lock to be held */
1405 rxi_WaitforTQBusy(struct rx_call *call) {
1406 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1407 call->flags |= RX_CALL_TQ_WAIT;
1409 #ifdef RX_ENABLE_LOCKS
1410 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1411 CV_WAIT(&call->cv_tq, &call->lock);
1412 #else /* RX_ENABLE_LOCKS */
1413 osi_rxSleep(&call->tq);
1414 #endif /* RX_ENABLE_LOCKS */
1416 if (call->tqWaiters == 0) {
1417 call->flags &= ~RX_CALL_TQ_WAIT;
1424 rxi_WakeUpTransmitQueue(struct rx_call *call)
1426 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1427 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1428 call, call->tqWaiters, call->flags));
1429 #ifdef RX_ENABLE_LOCKS
1430 osirx_AssertMine(&call->lock, "rxi_Start start");
1431 CV_BROADCAST(&call->cv_tq);
1432 #else /* RX_ENABLE_LOCKS */
1433 osi_rxWakeup(&call->tq);
1434 #endif /* RX_ENABLE_LOCKS */
1438 /* Start a new rx remote procedure call, on the specified connection.
1439 * If wait is set to 1, wait for a free call channel; otherwise return
1440 * 0. Maxtime gives the maximum number of seconds this call may take,
1441 * after rx_NewCall returns. After this time interval, a call to any
1442 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1443 * For fine grain locking, we hold the conn_call_lock in order to
1444 * to ensure that we don't get signalle after we found a call in an active
1445 * state and before we go to sleep.
1448 rx_NewCall(struct rx_connection *conn)
1450 int i, wait, ignoreBusy = 1;
1451 struct rx_call *call;
1452 struct clock queueTime;
1453 afs_uint32 leastBusy = 0;
1457 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1460 clock_GetTime(&queueTime);
1462 * Check if there are others waiting for a new call.
1463 * If so, let them go first to avoid starving them.
1464 * This is a fairly simple scheme, and might not be
1465 * a complete solution for large numbers of waiters.
1467 * makeCallWaiters keeps track of the number of
1468 * threads waiting to make calls and the
1469 * RX_CONN_MAKECALL_WAITING flag bit is used to
1470 * indicate that there are indeed calls waiting.
1471 * The flag is set when the waiter is incremented.
1472 * It is only cleared when makeCallWaiters is 0.
1473 * This prevents us from accidently destroying the
1474 * connection while it is potentially about to be used.
1476 MUTEX_ENTER(&conn->conn_call_lock);
1477 MUTEX_ENTER(&conn->conn_data_lock);
1478 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1479 conn->flags |= RX_CONN_MAKECALL_WAITING;
1480 conn->makeCallWaiters++;
1481 MUTEX_EXIT(&conn->conn_data_lock);
1483 #ifdef RX_ENABLE_LOCKS
1484 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1488 MUTEX_ENTER(&conn->conn_data_lock);
1489 conn->makeCallWaiters--;
1490 if (conn->makeCallWaiters == 0)
1491 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1494 /* We are now the active thread in rx_NewCall */
1495 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1496 MUTEX_EXIT(&conn->conn_data_lock);
1501 for (i = 0; i < RX_MAXCALLS; i++) {
1502 call = conn->call[i];
1504 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1505 /* we're not ignoring busy call slots; only look at the
1506 * call slot that is the "least" busy */
1510 if (call->state == RX_STATE_DALLY) {
1511 MUTEX_ENTER(&call->lock);
1512 if (call->state == RX_STATE_DALLY) {
1513 if (ignoreBusy && conn->lastBusy[i]) {
1514 /* if we're ignoring busy call slots, skip any ones that
1515 * have lastBusy set */
1516 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1517 leastBusy = conn->lastBusy[i];
1519 MUTEX_EXIT(&call->lock);
1524 * We are setting the state to RX_STATE_RESET to
1525 * ensure that no one else will attempt to use this
1526 * call once we drop the conn->conn_call_lock and
1527 * call->lock. We must drop the conn->conn_call_lock
1528 * before calling rxi_ResetCall because the process
1529 * of clearing the transmit queue can block for an
1530 * extended period of time. If we block while holding
1531 * the conn->conn_call_lock, then all rx_EndCall
1532 * processing will block as well. This has a detrimental
1533 * effect on overall system performance.
1535 call->state = RX_STATE_RESET;
1536 (*call->callNumber)++;
1537 MUTEX_EXIT(&conn->conn_call_lock);
1538 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1539 rxi_ResetCall(call, 0);
1540 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1544 * If we failed to be able to safely obtain the
1545 * conn->conn_call_lock we will have to drop the
1546 * call->lock to avoid a deadlock. When the call->lock
1547 * is released the state of the call can change. If it
1548 * is no longer RX_STATE_RESET then some other thread is
1551 MUTEX_EXIT(&call->lock);
1552 MUTEX_ENTER(&conn->conn_call_lock);
1553 MUTEX_ENTER(&call->lock);
1555 if (call->state == RX_STATE_RESET)
1559 * If we get here it means that after dropping
1560 * the conn->conn_call_lock and call->lock that
1561 * the call is no longer ours. If we can't find
1562 * a free call in the remaining slots we should
1563 * not go immediately to RX_CONN_MAKECALL_WAITING
1564 * because by dropping the conn->conn_call_lock
1565 * we have given up synchronization with rx_EndCall.
1566 * Instead, cycle through one more time to see if
1567 * we can find a call that can call our own.
1569 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1572 MUTEX_EXIT(&call->lock);
1575 if (ignoreBusy && conn->lastBusy[i]) {
1576 /* if we're ignoring busy call slots, skip any ones that
1577 * have lastBusy set */
1578 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1579 leastBusy = conn->lastBusy[i];
1584 /* rxi_NewCall returns with mutex locked */
1585 call = rxi_NewCall(conn, i);
1586 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1590 if (i < RX_MAXCALLS) {
1591 conn->lastBusy[i] = 0;
1592 call->flags &= ~RX_CALL_PEER_BUSY;
1597 if (leastBusy && ignoreBusy) {
1598 /* we didn't find a useable call slot, but we did see at least one
1599 * 'busy' slot; look again and only use a slot with the 'least
1605 MUTEX_ENTER(&conn->conn_data_lock);
1606 conn->flags |= RX_CONN_MAKECALL_WAITING;
1607 conn->makeCallWaiters++;
1608 MUTEX_EXIT(&conn->conn_data_lock);
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1615 MUTEX_ENTER(&conn->conn_data_lock);
1616 conn->makeCallWaiters--;
1617 if (conn->makeCallWaiters == 0)
1618 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1619 MUTEX_EXIT(&conn->conn_data_lock);
1621 /* Client is initially in send mode */
1622 call->state = RX_STATE_ACTIVE;
1623 call->error = conn->error;
1625 call->mode = RX_MODE_ERROR;
1627 call->mode = RX_MODE_SENDING;
1629 #ifdef AFS_RXERRQ_ENV
1630 /* remember how many network errors the peer has when we started, so if
1631 * more errors are encountered after the call starts, we know the other endpoint won't be
1632 * responding to us */
1633 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1636 /* remember start time for call in case we have hard dead time limit */
1637 call->queueTime = queueTime;
1638 clock_GetTime(&call->startTime);
1639 call->bytesSent = 0;
1640 call->bytesRcvd = 0;
1642 /* Turn on busy protocol. */
1643 rxi_KeepAliveOn(call);
1645 /* Attempt MTU discovery */
1646 rxi_GrowMTUOn(call);
1649 * We are no longer the active thread in rx_NewCall
1651 MUTEX_ENTER(&conn->conn_data_lock);
1652 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1653 MUTEX_EXIT(&conn->conn_data_lock);
1656 * Wake up anyone else who might be giving us a chance to
1657 * run (see code above that avoids resource starvation).
1659 #ifdef RX_ENABLE_LOCKS
1660 CV_BROADCAST(&conn->conn_call_cv);
1664 MUTEX_EXIT(&conn->conn_call_lock);
1666 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1667 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1668 osi_Panic("rx_NewCall call about to be used without an empty tq");
1670 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1672 MUTEX_EXIT(&call->lock);
1675 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1680 rxi_HasActiveCalls(struct rx_connection *aconn)
1683 struct rx_call *tcall;
1687 for (i = 0; i < RX_MAXCALLS; i++) {
1688 if ((tcall = aconn->call[i])) {
1689 if ((tcall->state == RX_STATE_ACTIVE)
1690 || (tcall->state == RX_STATE_PRECALL)) {
1701 rxi_GetCallNumberVector(struct rx_connection *aconn,
1702 afs_int32 * aint32s)
1705 struct rx_call *tcall;
1709 MUTEX_ENTER(&aconn->conn_call_lock);
1710 for (i = 0; i < RX_MAXCALLS; i++) {
1711 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1712 aint32s[i] = aconn->callNumber[i] + 1;
1714 aint32s[i] = aconn->callNumber[i];
1716 MUTEX_EXIT(&aconn->conn_call_lock);
1722 rxi_SetCallNumberVector(struct rx_connection *aconn,
1723 afs_int32 * aint32s)
1726 struct rx_call *tcall;
1730 MUTEX_ENTER(&aconn->conn_call_lock);
1731 for (i = 0; i < RX_MAXCALLS; i++) {
1732 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1733 aconn->callNumber[i] = aint32s[i] - 1;
1735 aconn->callNumber[i] = aint32s[i];
1737 MUTEX_EXIT(&aconn->conn_call_lock);
1742 /* Advertise a new service. A service is named locally by a UDP port
1743 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1746 char *serviceName; Name for identification purposes (e.g. the
1747 service name might be used for probing for
1750 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1751 char *serviceName, struct rx_securityClass **securityObjects,
1752 int nSecurityObjects,
1753 afs_int32(*serviceProc) (struct rx_call * acall))
1755 osi_socket socket = OSI_NULLSOCKET;
1756 struct rx_service *tservice;
1762 if (serviceId == 0) {
1764 "rx_NewService: service id for service %s is not non-zero.\n",
1771 "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",
1779 tservice = rxi_AllocService();
1782 #ifdef RX_ENABLE_LOCKS
1783 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1786 for (i = 0; i < RX_MAX_SERVICES; i++) {
1787 struct rx_service *service = rx_services[i];
1789 if (port == service->servicePort && host == service->serviceHost) {
1790 if (service->serviceId == serviceId) {
1791 /* The identical service has already been
1792 * installed; if the caller was intending to
1793 * change the security classes used by this
1794 * service, he/she loses. */
1796 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1797 serviceName, serviceId, service->serviceName);
1799 rxi_FreeService(tservice);
1802 /* Different service, same port: re-use the socket
1803 * which is bound to the same port */
1804 socket = service->socket;
1807 if (socket == OSI_NULLSOCKET) {
1808 /* If we don't already have a socket (from another
1809 * service on same port) get a new one */
1810 socket = rxi_GetHostUDPSocket(host, port);
1811 if (socket == OSI_NULLSOCKET) {
1813 rxi_FreeService(tservice);
1818 service->socket = socket;
1819 service->serviceHost = host;
1820 service->servicePort = port;
1821 service->serviceId = serviceId;
1822 service->serviceName = serviceName;
1823 service->nSecurityObjects = nSecurityObjects;
1824 service->securityObjects = securityObjects;
1825 service->minProcs = 0;
1826 service->maxProcs = 1;
1827 service->idleDeadTime = 60;
1828 service->idleDeadErr = 0;
1829 service->connDeadTime = rx_connDeadTime;
1830 service->executeRequestProc = serviceProc;
1831 service->checkReach = 0;
1832 service->nSpecific = 0;
1833 service->specific = NULL;
1834 rx_services[i] = service; /* not visible until now */
1840 rxi_FreeService(tservice);
1841 (osi_Msg "rx_NewService: cannot support > %d services\n",
1846 /* Set configuration options for all of a service's security objects */
1849 rx_SetSecurityConfiguration(struct rx_service *service,
1850 rx_securityConfigVariables type,
1854 for (i = 0; i<service->nSecurityObjects; i++) {
1855 if (service->securityObjects[i]) {
1856 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1864 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1865 struct rx_securityClass **securityObjects, int nSecurityObjects,
1866 afs_int32(*serviceProc) (struct rx_call * acall))
1868 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1871 /* Generic request processing loop. This routine should be called
1872 * by the implementation dependent rx_ServerProc. If socketp is
1873 * non-null, it will be set to the file descriptor that this thread
1874 * is now listening on. If socketp is null, this routine will never
1877 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1879 struct rx_call *call;
1881 struct rx_service *tservice = NULL;
1888 call = rx_GetCall(threadID, tservice, socketp);
1889 if (socketp && *socketp != OSI_NULLSOCKET) {
1890 /* We are now a listener thread */
1896 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1897 #ifdef RX_ENABLE_LOCKS
1899 #endif /* RX_ENABLE_LOCKS */
1900 afs_termState = AFSOP_STOP_AFS;
1901 afs_osi_Wakeup(&afs_termState);
1902 #ifdef RX_ENABLE_LOCKS
1904 #endif /* RX_ENABLE_LOCKS */
1909 /* if server is restarting( typically smooth shutdown) then do not
1910 * allow any new calls.
1913 if (rx_tranquil && (call != NULL)) {
1917 MUTEX_ENTER(&call->lock);
1919 rxi_CallError(call, RX_RESTARTING);
1920 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1922 MUTEX_EXIT(&call->lock);
1927 tservice = call->conn->service;
1929 if (tservice->beforeProc)
1930 (*tservice->beforeProc) (call);
1932 code = tservice->executeRequestProc(call);
1934 if (tservice->afterProc)
1935 (*tservice->afterProc) (call, code);
1937 rx_EndCall(call, code);
1939 if (tservice->postProc)
1940 (*tservice->postProc) (code);
1942 if (rx_stats_active) {
1943 MUTEX_ENTER(&rx_stats_mutex);
1945 MUTEX_EXIT(&rx_stats_mutex);
1952 rx_WakeupServerProcs(void)
1954 struct rx_serverQueueEntry *np, *tqp;
1958 MUTEX_ENTER(&rx_serverPool_lock);
1960 #ifdef RX_ENABLE_LOCKS
1961 if (rx_waitForPacket)
1962 CV_BROADCAST(&rx_waitForPacket->cv);
1963 #else /* RX_ENABLE_LOCKS */
1964 if (rx_waitForPacket)
1965 osi_rxWakeup(rx_waitForPacket);
1966 #endif /* RX_ENABLE_LOCKS */
1967 MUTEX_ENTER(&freeSQEList_lock);
1968 for (np = rx_FreeSQEList; np; np = tqp) {
1969 tqp = *(struct rx_serverQueueEntry **)np;
1970 #ifdef RX_ENABLE_LOCKS
1971 CV_BROADCAST(&np->cv);
1972 #else /* RX_ENABLE_LOCKS */
1974 #endif /* RX_ENABLE_LOCKS */
1976 MUTEX_EXIT(&freeSQEList_lock);
1977 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1978 #ifdef RX_ENABLE_LOCKS
1979 CV_BROADCAST(&np->cv);
1980 #else /* RX_ENABLE_LOCKS */
1982 #endif /* RX_ENABLE_LOCKS */
1984 MUTEX_EXIT(&rx_serverPool_lock);
1989 * One thing that seems to happen is that all the server threads get
1990 * tied up on some empty or slow call, and then a whole bunch of calls
1991 * arrive at once, using up the packet pool, so now there are more
1992 * empty calls. The most critical resources here are server threads
1993 * and the free packet pool. The "doreclaim" code seems to help in
1994 * general. I think that eventually we arrive in this state: there
1995 * are lots of pending calls which do have all their packets present,
1996 * so they won't be reclaimed, are multi-packet calls, so they won't
1997 * be scheduled until later, and thus are tying up most of the free
1998 * packet pool for a very long time.
2000 * 1. schedule multi-packet calls if all the packets are present.
2001 * Probably CPU-bound operation, useful to return packets to pool.
2002 * Do what if there is a full window, but the last packet isn't here?
2003 * 3. preserve one thread which *only* runs "best" calls, otherwise
2004 * it sleeps and waits for that type of call.
2005 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2006 * the current dataquota business is badly broken. The quota isn't adjusted
2007 * to reflect how many packets are presently queued for a running call.
2008 * So, when we schedule a queued call with a full window of packets queued
2009 * up for it, that *should* free up a window full of packets for other 2d-class
2010 * calls to be able to use from the packet pool. But it doesn't.
2012 * NB. Most of the time, this code doesn't run -- since idle server threads
2013 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2014 * as a new call arrives.
2016 /* Sleep until a call arrives. Returns a pointer to the call, ready
2017 * for an rx_Read. */
2018 #ifdef RX_ENABLE_LOCKS
2020 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2022 struct rx_serverQueueEntry *sq;
2023 struct rx_call *call = (struct rx_call *)0;
2024 struct rx_service *service = NULL;
2026 MUTEX_ENTER(&freeSQEList_lock);
2028 if ((sq = rx_FreeSQEList)) {
2029 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2030 MUTEX_EXIT(&freeSQEList_lock);
2031 } else { /* otherwise allocate a new one and return that */
2032 MUTEX_EXIT(&freeSQEList_lock);
2033 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2034 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2035 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2038 MUTEX_ENTER(&rx_serverPool_lock);
2039 if (cur_service != NULL) {
2040 ReturnToServerPool(cur_service);
2043 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2044 struct rx_call *tcall, *ncall, *choice2 = NULL;
2046 /* Scan for eligible incoming calls. A call is not eligible
2047 * if the maximum number of calls for its service type are
2048 * already executing */
2049 /* One thread will process calls FCFS (to prevent starvation),
2050 * while the other threads may run ahead looking for calls which
2051 * have all their input data available immediately. This helps
2052 * keep threads from blocking, waiting for data from the client. */
2053 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2054 service = tcall->conn->service;
2055 if (!QuotaOK(service)) {
2058 MUTEX_ENTER(&rx_pthread_mutex);
2059 if (tno == rxi_fcfs_thread_num
2060 || queue_IsLast(&rx_incomingCallQueue, tcall)) {
2061 MUTEX_EXIT(&rx_pthread_mutex);
2062 /* If we're the fcfs thread , then we'll just use
2063 * this call. If we haven't been able to find an optimal
2064 * choice, and we're at the end of the list, then use a
2065 * 2d choice if one has been identified. Otherwise... */
2066 call = (choice2 ? choice2 : tcall);
2067 service = call->conn->service;
2069 MUTEX_EXIT(&rx_pthread_mutex);
2070 if (!queue_IsEmpty(&tcall->rq)) {
2071 struct rx_packet *rp;
2072 rp = queue_First(&tcall->rq, rx_packet);
2073 if (rp->header.seq == 1) {
2075 || (rp->header.flags & RX_LAST_PACKET)) {
2077 } else if (rxi_2dchoice && !choice2
2078 && !(tcall->flags & RX_CALL_CLEARED)
2079 && (tcall->rprev > rxi_HardAckRate)) {
2089 ReturnToServerPool(service);
2096 MUTEX_EXIT(&rx_serverPool_lock);
2097 MUTEX_ENTER(&call->lock);
2099 if (call->flags & RX_CALL_WAIT_PROC) {
2100 call->flags &= ~RX_CALL_WAIT_PROC;
2101 rx_atomic_dec(&rx_nWaiting);
2104 if (call->state != RX_STATE_PRECALL || call->error) {
2105 MUTEX_EXIT(&call->lock);
2106 MUTEX_ENTER(&rx_serverPool_lock);
2107 ReturnToServerPool(service);
2112 if (queue_IsEmpty(&call->rq)
2113 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2114 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2116 CLEAR_CALL_QUEUE_LOCK(call);
2119 /* If there are no eligible incoming calls, add this process
2120 * to the idle server queue, to wait for one */
2124 *socketp = OSI_NULLSOCKET;
2126 sq->socketp = socketp;
2127 queue_Append(&rx_idleServerQueue, sq);
2128 #ifndef AFS_AIX41_ENV
2129 rx_waitForPacket = sq;
2131 rx_waitingForPacket = sq;
2132 #endif /* AFS_AIX41_ENV */
2134 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2136 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2137 MUTEX_EXIT(&rx_serverPool_lock);
2138 return (struct rx_call *)0;
2141 } while (!(call = sq->newcall)
2142 && !(socketp && *socketp != OSI_NULLSOCKET));
2143 MUTEX_EXIT(&rx_serverPool_lock);
2145 MUTEX_ENTER(&call->lock);
2151 MUTEX_ENTER(&freeSQEList_lock);
2152 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2153 rx_FreeSQEList = sq;
2154 MUTEX_EXIT(&freeSQEList_lock);
2157 clock_GetTime(&call->startTime);
2158 call->state = RX_STATE_ACTIVE;
2159 call->mode = RX_MODE_RECEIVING;
2160 #ifdef RX_KERNEL_TRACE
2161 if (ICL_SETACTIVE(afs_iclSetp)) {
2162 int glockOwner = ISAFS_GLOCK();
2165 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2166 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2173 rxi_calltrace(RX_CALL_START, call);
2174 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2175 call->conn->service->servicePort, call->conn->service->serviceId,
2178 MUTEX_EXIT(&call->lock);
2179 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2181 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2186 #else /* RX_ENABLE_LOCKS */
2188 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2190 struct rx_serverQueueEntry *sq;
2191 struct rx_call *call = (struct rx_call *)0, *choice2;
2192 struct rx_service *service = NULL;
2196 MUTEX_ENTER(&freeSQEList_lock);
2198 if ((sq = rx_FreeSQEList)) {
2199 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2200 MUTEX_EXIT(&freeSQEList_lock);
2201 } else { /* otherwise allocate a new one and return that */
2202 MUTEX_EXIT(&freeSQEList_lock);
2203 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2204 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2205 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2207 MUTEX_ENTER(&sq->lock);
2209 if (cur_service != NULL) {
2210 cur_service->nRequestsRunning--;
2211 MUTEX_ENTER(&rx_quota_mutex);
2212 if (cur_service->nRequestsRunning < cur_service->minProcs)
2215 MUTEX_EXIT(&rx_quota_mutex);
2217 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2218 struct rx_call *tcall, *ncall;
2219 /* Scan for eligible incoming calls. A call is not eligible
2220 * if the maximum number of calls for its service type are
2221 * already executing */
2222 /* One thread will process calls FCFS (to prevent starvation),
2223 * while the other threads may run ahead looking for calls which
2224 * have all their input data available immediately. This helps
2225 * keep threads from blocking, waiting for data from the client. */
2226 choice2 = (struct rx_call *)0;
2227 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2228 service = tcall->conn->service;
2229 if (QuotaOK(service)) {
2230 MUTEX_ENTER(&rx_pthread_mutex);
2231 if (tno == rxi_fcfs_thread_num
2232 || !tcall->queue_item_header.next) {
2233 MUTEX_EXIT(&rx_pthread_mutex);
2234 /* If we're the fcfs thread, then we'll just use
2235 * this call. If we haven't been able to find an optimal
2236 * choice, and we're at the end of the list, then use a
2237 * 2d choice if one has been identified. Otherwise... */
2238 call = (choice2 ? choice2 : tcall);
2239 service = call->conn->service;
2241 MUTEX_EXIT(&rx_pthread_mutex);
2242 if (!queue_IsEmpty(&tcall->rq)) {
2243 struct rx_packet *rp;
2244 rp = queue_First(&tcall->rq, rx_packet);
2245 if (rp->header.seq == 1
2247 || (rp->header.flags & RX_LAST_PACKET))) {
2249 } else if (rxi_2dchoice && !choice2
2250 && !(tcall->flags & RX_CALL_CLEARED)
2251 && (tcall->rprev > rxi_HardAckRate)) {
2265 /* we can't schedule a call if there's no data!!! */
2266 /* send an ack if there's no data, if we're missing the
2267 * first packet, or we're missing something between first
2268 * and last -- there's a "hole" in the incoming data. */
2269 if (queue_IsEmpty(&call->rq)
2270 || queue_First(&call->rq, rx_packet)->header.seq != 1
2271 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2272 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2274 call->flags &= (~RX_CALL_WAIT_PROC);
2275 service->nRequestsRunning++;
2276 /* just started call in minProcs pool, need fewer to maintain
2278 MUTEX_ENTER(&rx_quota_mutex);
2279 if (service->nRequestsRunning <= service->minProcs)
2282 MUTEX_EXIT(&rx_quota_mutex);
2283 rx_atomic_dec(&rx_nWaiting);
2284 /* MUTEX_EXIT(&call->lock); */
2286 /* If there are no eligible incoming calls, add this process
2287 * to the idle server queue, to wait for one */
2290 *socketp = OSI_NULLSOCKET;
2292 sq->socketp = socketp;
2293 queue_Append(&rx_idleServerQueue, sq);
2297 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2299 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2300 return (struct rx_call *)0;
2303 } while (!(call = sq->newcall)
2304 && !(socketp && *socketp != OSI_NULLSOCKET));
2306 MUTEX_EXIT(&sq->lock);
2308 MUTEX_ENTER(&freeSQEList_lock);
2309 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2310 rx_FreeSQEList = sq;
2311 MUTEX_EXIT(&freeSQEList_lock);
2314 clock_GetTime(&call->startTime);
2315 call->state = RX_STATE_ACTIVE;
2316 call->mode = RX_MODE_RECEIVING;
2317 #ifdef RX_KERNEL_TRACE
2318 if (ICL_SETACTIVE(afs_iclSetp)) {
2319 int glockOwner = ISAFS_GLOCK();
2322 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2323 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2330 rxi_calltrace(RX_CALL_START, call);
2331 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2332 call->conn->service->servicePort, call->conn->service->serviceId,
2335 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2342 #endif /* RX_ENABLE_LOCKS */
2346 /* Establish a procedure to be called when a packet arrives for a
2347 * call. This routine will be called at most once after each call,
2348 * and will also be called if there is an error condition on the or
2349 * the call is complete. Used by multi rx to build a selection
2350 * function which determines which of several calls is likely to be a
2351 * good one to read from.
2352 * NOTE: the way this is currently implemented it is probably only a
2353 * good idea to (1) use it immediately after a newcall (clients only)
2354 * and (2) only use it once. Other uses currently void your warranty
2357 rx_SetArrivalProc(struct rx_call *call,
2358 void (*proc) (struct rx_call * call,
2361 void * handle, int arg)
2363 call->arrivalProc = proc;
2364 call->arrivalProcHandle = handle;
2365 call->arrivalProcArg = arg;
2368 /* Call is finished (possibly prematurely). Return rc to the peer, if
2369 * appropriate, and return the final error code from the conversation
2373 rx_EndCall(struct rx_call *call, afs_int32 rc)
2375 struct rx_connection *conn = call->conn;
2379 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2380 call, rc, call->error, call->abortCode));
2383 MUTEX_ENTER(&call->lock);
2385 if (rc == 0 && call->error == 0) {
2386 call->abortCode = 0;
2387 call->abortCount = 0;
2390 call->arrivalProc = (void (*)())0;
2391 if (rc && call->error == 0) {
2392 rxi_CallError(call, rc);
2393 call->mode = RX_MODE_ERROR;
2394 /* Send an abort message to the peer if this error code has
2395 * only just been set. If it was set previously, assume the
2396 * peer has already been sent the error code or will request it
2398 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2400 if (conn->type == RX_SERVER_CONNECTION) {
2401 /* Make sure reply or at least dummy reply is sent */
2402 if (call->mode == RX_MODE_RECEIVING) {
2403 MUTEX_EXIT(&call->lock);
2404 rxi_WriteProc(call, 0, 0);
2405 MUTEX_ENTER(&call->lock);
2407 if (call->mode == RX_MODE_SENDING) {
2408 MUTEX_EXIT(&call->lock);
2409 rxi_FlushWrite(call);
2410 MUTEX_ENTER(&call->lock);
2412 rxi_calltrace(RX_CALL_END, call);
2413 /* Call goes to hold state until reply packets are acknowledged */
2414 if (call->tfirst + call->nSoftAcked < call->tnext) {
2415 call->state = RX_STATE_HOLD;
2417 call->state = RX_STATE_DALLY;
2418 rxi_ClearTransmitQueue(call, 0);
2419 rxi_rto_cancel(call);
2420 rxevent_Cancel(&call->keepAliveEvent, call,
2421 RX_CALL_REFCOUNT_ALIVE);
2423 } else { /* Client connection */
2425 /* Make sure server receives input packets, in the case where
2426 * no reply arguments are expected */
2427 if ((call->mode == RX_MODE_SENDING)
2428 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2429 MUTEX_EXIT(&call->lock);
2430 (void)rxi_ReadProc(call, &dummy, 1);
2431 MUTEX_ENTER(&call->lock);
2434 /* If we had an outstanding delayed ack, be nice to the server
2435 * and force-send it now.
2437 if (call->delayedAckEvent) {
2438 rxevent_Cancel(&call->delayedAckEvent, call,
2439 RX_CALL_REFCOUNT_DELAY);
2440 rxi_SendDelayedAck(NULL, call, NULL, 0);
2443 /* We need to release the call lock since it's lower than the
2444 * conn_call_lock and we don't want to hold the conn_call_lock
2445 * over the rx_ReadProc call. The conn_call_lock needs to be held
2446 * here for the case where rx_NewCall is perusing the calls on
2447 * the connection structure. We don't want to signal until
2448 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2449 * have checked this call, found it active and by the time it
2450 * goes to sleep, will have missed the signal.
2452 MUTEX_EXIT(&call->lock);
2453 MUTEX_ENTER(&conn->conn_call_lock);
2454 MUTEX_ENTER(&call->lock);
2456 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2457 conn->lastBusy[call->channel] = 0;
2460 MUTEX_ENTER(&conn->conn_data_lock);
2461 conn->flags |= RX_CONN_BUSY;
2462 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2463 MUTEX_EXIT(&conn->conn_data_lock);
2464 #ifdef RX_ENABLE_LOCKS
2465 CV_BROADCAST(&conn->conn_call_cv);
2470 #ifdef RX_ENABLE_LOCKS
2472 MUTEX_EXIT(&conn->conn_data_lock);
2474 #endif /* RX_ENABLE_LOCKS */
2475 call->state = RX_STATE_DALLY;
2477 error = call->error;
2479 /* currentPacket, nLeft, and NFree must be zeroed here, because
2480 * ResetCall cannot: ResetCall may be called at splnet(), in the
2481 * kernel version, and may interrupt the macros rx_Read or
2482 * rx_Write, which run at normal priority for efficiency. */
2483 if (call->currentPacket) {
2484 #ifdef RX_TRACK_PACKETS
2485 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2487 rxi_FreePacket(call->currentPacket);
2488 call->currentPacket = (struct rx_packet *)0;
2491 call->nLeft = call->nFree = call->curlen = 0;
2493 /* Free any packets from the last call to ReadvProc/WritevProc */
2494 #ifdef RXDEBUG_PACKET
2496 #endif /* RXDEBUG_PACKET */
2497 rxi_FreePackets(0, &call->iovq);
2498 MUTEX_EXIT(&call->lock);
2500 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2501 if (conn->type == RX_CLIENT_CONNECTION) {
2502 MUTEX_ENTER(&conn->conn_data_lock);
2503 conn->flags &= ~RX_CONN_BUSY;
2504 MUTEX_EXIT(&conn->conn_data_lock);
2505 MUTEX_EXIT(&conn->conn_call_lock);
2509 * Map errors to the local host's errno.h format.
2511 error = ntoh_syserr_conv(error);
2515 #if !defined(KERNEL)
2517 /* Call this routine when shutting down a server or client (especially
2518 * clients). This will allow Rx to gracefully garbage collect server
2519 * connections, and reduce the number of retries that a server might
2520 * make to a dead client.
2521 * This is not quite right, since some calls may still be ongoing and
2522 * we can't lock them to destroy them. */
2526 struct rx_connection **conn_ptr, **conn_end;
2530 if (rxinit_status == 1) {
2532 return; /* Already shutdown. */
2534 rxi_DeleteCachedConnections();
2535 if (rx_connHashTable) {
2536 MUTEX_ENTER(&rx_connHashTable_lock);
2537 for (conn_ptr = &rx_connHashTable[0], conn_end =
2538 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2540 struct rx_connection *conn, *next;
2541 for (conn = *conn_ptr; conn; conn = next) {
2543 if (conn->type == RX_CLIENT_CONNECTION) {
2544 MUTEX_ENTER(&rx_refcnt_mutex);
2546 MUTEX_EXIT(&rx_refcnt_mutex);
2547 #ifdef RX_ENABLE_LOCKS
2548 rxi_DestroyConnectionNoLock(conn);
2549 #else /* RX_ENABLE_LOCKS */
2550 rxi_DestroyConnection(conn);
2551 #endif /* RX_ENABLE_LOCKS */
2555 #ifdef RX_ENABLE_LOCKS
2556 while (rx_connCleanup_list) {
2557 struct rx_connection *conn;
2558 conn = rx_connCleanup_list;
2559 rx_connCleanup_list = rx_connCleanup_list->next;
2560 MUTEX_EXIT(&rx_connHashTable_lock);
2561 rxi_CleanupConnection(conn);
2562 MUTEX_ENTER(&rx_connHashTable_lock);
2564 MUTEX_EXIT(&rx_connHashTable_lock);
2565 #endif /* RX_ENABLE_LOCKS */
2570 afs_winsockCleanup();
2578 /* if we wakeup packet waiter too often, can get in loop with two
2579 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2581 rxi_PacketsUnWait(void)
2583 if (!rx_waitingForPackets) {
2587 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2588 return; /* still over quota */
2591 rx_waitingForPackets = 0;
2592 #ifdef RX_ENABLE_LOCKS
2593 CV_BROADCAST(&rx_waitingForPackets_cv);
2595 osi_rxWakeup(&rx_waitingForPackets);
2601 /* ------------------Internal interfaces------------------------- */
2603 /* Return this process's service structure for the
2604 * specified socket and service */
2605 static struct rx_service *
2606 rxi_FindService(osi_socket socket, u_short serviceId)
2608 struct rx_service **sp;
2609 for (sp = &rx_services[0]; *sp; sp++) {
2610 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2616 #ifdef RXDEBUG_PACKET
2617 #ifdef KDUMP_RX_LOCK
2618 static struct rx_call_rx_lock *rx_allCallsp = 0;
2620 static struct rx_call *rx_allCallsp = 0;
2622 #endif /* RXDEBUG_PACKET */
2624 /* Allocate a call structure, for the indicated channel of the
2625 * supplied connection. The mode and state of the call must be set by
2626 * the caller. Returns the call with mutex locked. */
2627 static struct rx_call *
2628 rxi_NewCall(struct rx_connection *conn, int channel)
2630 struct rx_call *call;
2631 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2632 struct rx_call *cp; /* Call pointer temp */
2633 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2634 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2636 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2638 /* Grab an existing call structure, or allocate a new one.
2639 * Existing call structures are assumed to have been left reset by
2641 MUTEX_ENTER(&rx_freeCallQueue_lock);
2643 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2645 * EXCEPT that the TQ might not yet be cleared out.
2646 * Skip over those with in-use TQs.
2649 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2650 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2656 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2657 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2658 call = queue_First(&rx_freeCallQueue, rx_call);
2659 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2661 if (rx_stats_active)
2662 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2663 MUTEX_EXIT(&rx_freeCallQueue_lock);
2664 MUTEX_ENTER(&call->lock);
2665 CLEAR_CALL_QUEUE_LOCK(call);
2666 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2667 /* Now, if TQ wasn't cleared earlier, do it now. */
2668 rxi_WaitforTQBusy(call);
2669 if (call->flags & RX_CALL_TQ_CLEARME) {
2670 rxi_ClearTransmitQueue(call, 1);
2671 /*queue_Init(&call->tq);*/
2673 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2674 /* Bind the call to its connection structure */
2676 rxi_ResetCall(call, 1);
2679 call = rxi_Alloc(sizeof(struct rx_call));
2680 #ifdef RXDEBUG_PACKET
2681 call->allNextp = rx_allCallsp;
2682 rx_allCallsp = call;
2684 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2685 #else /* RXDEBUG_PACKET */
2686 rx_atomic_inc(&rx_stats.nCallStructs);
2687 #endif /* RXDEBUG_PACKET */
2689 MUTEX_EXIT(&rx_freeCallQueue_lock);
2690 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2691 MUTEX_ENTER(&call->lock);
2692 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2693 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2694 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2696 /* Initialize once-only items */
2697 queue_Init(&call->tq);
2698 queue_Init(&call->rq);
2699 queue_Init(&call->iovq);
2700 #ifdef RXDEBUG_PACKET
2701 call->rqc = call->tqc = call->iovqc = 0;
2702 #endif /* RXDEBUG_PACKET */
2703 /* Bind the call to its connection structure (prereq for reset) */
2705 rxi_ResetCall(call, 1);
2707 call->channel = channel;
2708 call->callNumber = &conn->callNumber[channel];
2709 call->rwind = conn->rwind[channel];
2710 call->twind = conn->twind[channel];
2711 /* Note that the next expected call number is retained (in
2712 * conn->callNumber[i]), even if we reallocate the call structure
2714 conn->call[channel] = call;
2715 /* if the channel's never been used (== 0), we should start at 1, otherwise
2716 * the call number is valid from the last time this channel was used */
2717 if (*call->callNumber == 0)
2718 *call->callNumber = 1;
2723 /* A call has been inactive long enough that so we can throw away
2724 * state, including the call structure, which is placed on the call
2727 * call->lock amd rx_refcnt_mutex are held upon entry.
2728 * haveCTLock is set when called from rxi_ReapConnections.
2730 * return 1 if the call is freed, 0 if not.
2733 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2735 int channel = call->channel;
2736 struct rx_connection *conn = call->conn;
2737 u_char state = call->state;
2740 * We are setting the state to RX_STATE_RESET to
2741 * ensure that no one else will attempt to use this
2742 * call once we drop the refcnt lock. We must drop
2743 * the refcnt lock before calling rxi_ResetCall
2744 * because it cannot be held across acquiring the
2745 * freepktQ lock. NewCall does the same.
2747 call->state = RX_STATE_RESET;
2748 MUTEX_EXIT(&rx_refcnt_mutex);
2749 rxi_ResetCall(call, 0);
2751 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2753 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2754 (*call->callNumber)++;
2756 if (call->conn->call[channel] == call)
2757 call->conn->call[channel] = 0;
2758 MUTEX_EXIT(&conn->conn_call_lock);
2761 * We couldn't obtain the conn_call_lock so we can't
2762 * disconnect the call from the connection. Set the
2763 * call state to dally so that the call can be reused.
2765 MUTEX_ENTER(&rx_refcnt_mutex);
2766 call->state = RX_STATE_DALLY;
2770 MUTEX_ENTER(&rx_freeCallQueue_lock);
2771 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2772 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2773 /* A call may be free even though its transmit queue is still in use.
2774 * Since we search the call list from head to tail, put busy calls at
2775 * the head of the list, and idle calls at the tail.
2777 if (call->flags & RX_CALL_TQ_BUSY)
2778 queue_Prepend(&rx_freeCallQueue, call);
2780 queue_Append(&rx_freeCallQueue, call);
2781 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2782 queue_Append(&rx_freeCallQueue, call);
2783 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2784 if (rx_stats_active)
2785 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2786 MUTEX_EXIT(&rx_freeCallQueue_lock);
2788 /* Destroy the connection if it was previously slated for
2789 * destruction, i.e. the Rx client code previously called
2790 * rx_DestroyConnection (client connections), or
2791 * rxi_ReapConnections called the same routine (server
2792 * connections). Only do this, however, if there are no
2793 * outstanding calls. Note that for fine grain locking, there appears
2794 * to be a deadlock in that rxi_FreeCall has a call locked and
2795 * DestroyConnectionNoLock locks each call in the conn. But note a
2796 * few lines up where we have removed this call from the conn.
2797 * If someone else destroys a connection, they either have no
2798 * call lock held or are going through this section of code.
2800 MUTEX_ENTER(&conn->conn_data_lock);
2801 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2802 MUTEX_ENTER(&rx_refcnt_mutex);
2804 MUTEX_EXIT(&rx_refcnt_mutex);
2805 MUTEX_EXIT(&conn->conn_data_lock);
2806 #ifdef RX_ENABLE_LOCKS
2808 rxi_DestroyConnectionNoLock(conn);
2810 rxi_DestroyConnection(conn);
2811 #else /* RX_ENABLE_LOCKS */
2812 rxi_DestroyConnection(conn);
2813 #endif /* RX_ENABLE_LOCKS */
2815 MUTEX_EXIT(&conn->conn_data_lock);
2817 MUTEX_ENTER(&rx_refcnt_mutex);
2821 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2822 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2825 rxi_Alloc(size_t size)
2829 if (rx_stats_active) {
2830 rx_atomic_add(&rxi_Allocsize, (int) size);
2831 rx_atomic_inc(&rxi_Alloccnt);
2835 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2836 afs_osi_Alloc_NoSleep(size);
2841 osi_Panic("rxi_Alloc error");
2847 rxi_Free(void *addr, size_t size)
2849 if (rx_stats_active) {
2850 rx_atomic_sub(&rxi_Allocsize, (int) size);
2851 rx_atomic_dec(&rxi_Alloccnt);
2853 osi_Free(addr, size);
2857 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2859 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2860 struct rx_peer *next = NULL;
2864 MUTEX_ENTER(&rx_peerHashTable_lock);
2866 peer_ptr = &rx_peerHashTable[0];
2867 peer_end = &rx_peerHashTable[rx_hashTableSize];
2870 for ( ; peer_ptr < peer_end; peer_ptr++) {
2873 for ( ; peer; peer = next) {
2875 if (host == peer->host)
2880 hashIndex = PEER_HASH(host, port);
2881 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2882 if ((peer->host == host) && (peer->port == port))
2887 MUTEX_ENTER(&rx_peerHashTable_lock);
2892 MUTEX_EXIT(&rx_peerHashTable_lock);
2894 MUTEX_ENTER(&peer->peer_lock);
2895 /* We don't handle dropping below min, so don't */
2896 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2897 peer->ifMTU=MIN(mtu, peer->ifMTU);
2898 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2899 /* if we tweaked this down, need to tune our peer MTU too */
2900 peer->MTU = MIN(peer->MTU, peer->natMTU);
2901 /* if we discovered a sub-1500 mtu, degrade */
2902 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2903 peer->maxDgramPackets = 1;
2904 /* We no longer have valid peer packet information */
2905 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2906 peer->maxPacketSize = 0;
2907 MUTEX_EXIT(&peer->peer_lock);
2909 MUTEX_ENTER(&rx_peerHashTable_lock);
2911 if (host && !port) {
2913 /* pick up where we left off */
2917 MUTEX_EXIT(&rx_peerHashTable_lock);
2920 #ifdef AFS_RXERRQ_ENV
2922 rxi_SetPeerDead(afs_uint32 host, afs_uint16 port)
2924 int hashIndex = PEER_HASH(host, port);
2925 struct rx_peer *peer;
2927 MUTEX_ENTER(&rx_peerHashTable_lock);
2929 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2930 if (peer->host == host && peer->port == port) {
2936 rx_atomic_inc(&peer->neterrs);
2939 MUTEX_EXIT(&rx_peerHashTable_lock);
2943 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2945 # ifdef AFS_ADAPT_PMTU
2946 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2947 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2951 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2952 switch (err->ee_code) {
2953 case ICMP_NET_UNREACH:
2954 case ICMP_HOST_UNREACH:
2955 case ICMP_PORT_UNREACH:
2958 rxi_SetPeerDead(addr, port);
2963 #endif /* AFS_RXERRQ_ENV */
2965 /* Find the peer process represented by the supplied (host,port)
2966 * combination. If there is no appropriate active peer structure, a
2967 * new one will be allocated and initialized
2968 * The origPeer, if set, is a pointer to a peer structure on which the
2969 * refcount will be be decremented. This is used to replace the peer
2970 * structure hanging off a connection structure */
2972 rxi_FindPeer(afs_uint32 host, u_short port,
2973 struct rx_peer *origPeer, int create)
2977 hashIndex = PEER_HASH(host, port);
2978 MUTEX_ENTER(&rx_peerHashTable_lock);
2979 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2980 if ((pp->host == host) && (pp->port == port))
2985 pp = rxi_AllocPeer(); /* This bzero's *pp */
2986 pp->host = host; /* set here or in InitPeerParams is zero */
2988 #ifdef AFS_RXERRQ_ENV
2989 rx_atomic_set(&pp->neterrs, 0);
2991 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2992 queue_Init(&pp->rpcStats);
2993 pp->next = rx_peerHashTable[hashIndex];
2994 rx_peerHashTable[hashIndex] = pp;
2995 rxi_InitPeerParams(pp);
2996 if (rx_stats_active)
2997 rx_atomic_inc(&rx_stats.nPeerStructs);
3004 origPeer->refCount--;
3005 MUTEX_EXIT(&rx_peerHashTable_lock);
3010 /* Find the connection at (host, port) started at epoch, and with the
3011 * given connection id. Creates the server connection if necessary.
3012 * The type specifies whether a client connection or a server
3013 * connection is desired. In both cases, (host, port) specify the
3014 * peer's (host, pair) pair. Client connections are not made
3015 * automatically by this routine. The parameter socket gives the
3016 * socket descriptor on which the packet was received. This is used,
3017 * in the case of server connections, to check that *new* connections
3018 * come via a valid (port, serviceId). Finally, the securityIndex
3019 * parameter must match the existing index for the connection. If a
3020 * server connection is created, it will be created using the supplied
3021 * index, if the index is valid for this service */
3022 static struct rx_connection *
3023 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3024 u_short port, u_short serviceId, afs_uint32 cid,
3025 afs_uint32 epoch, int type, u_int securityIndex)
3027 int hashindex, flag, i;
3028 struct rx_connection *conn;
3029 hashindex = CONN_HASH(host, port, cid, epoch, type);
3030 MUTEX_ENTER(&rx_connHashTable_lock);
3031 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3032 rx_connHashTable[hashindex],
3035 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3036 && (epoch == conn->epoch)) {
3037 struct rx_peer *pp = conn->peer;
3038 if (securityIndex != conn->securityIndex) {
3039 /* this isn't supposed to happen, but someone could forge a packet
3040 * like this, and there seems to be some CM bug that makes this
3041 * happen from time to time -- in which case, the fileserver
3043 MUTEX_EXIT(&rx_connHashTable_lock);
3044 return (struct rx_connection *)0;
3046 if (pp->host == host && pp->port == port)
3048 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3050 /* So what happens when it's a callback connection? */
3051 if ( /*type == RX_CLIENT_CONNECTION && */
3052 (conn->epoch & 0x80000000))
3056 /* the connection rxLastConn that was used the last time is not the
3057 ** one we are looking for now. Hence, start searching in the hash */
3059 conn = rx_connHashTable[hashindex];
3064 struct rx_service *service;
3065 if (type == RX_CLIENT_CONNECTION) {
3066 MUTEX_EXIT(&rx_connHashTable_lock);
3067 return (struct rx_connection *)0;
3069 service = rxi_FindService(socket, serviceId);
3070 if (!service || (securityIndex >= service->nSecurityObjects)
3071 || (service->securityObjects[securityIndex] == 0)) {
3072 MUTEX_EXIT(&rx_connHashTable_lock);
3073 return (struct rx_connection *)0;
3075 conn = rxi_AllocConnection(); /* This bzero's the connection */
3076 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3077 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3078 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3079 conn->next = rx_connHashTable[hashindex];
3080 rx_connHashTable[hashindex] = conn;
3081 conn->peer = rxi_FindPeer(host, port, 0, 1);
3082 conn->type = RX_SERVER_CONNECTION;
3083 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3084 conn->epoch = epoch;
3085 conn->cid = cid & RX_CIDMASK;
3086 conn->ackRate = RX_FAST_ACK_RATE;
3087 conn->service = service;
3088 conn->serviceId = serviceId;
3089 conn->securityIndex = securityIndex;
3090 conn->securityObject = service->securityObjects[securityIndex];
3091 conn->nSpecific = 0;
3092 conn->specific = NULL;
3093 rx_SetConnDeadTime(conn, service->connDeadTime);
3094 conn->idleDeadTime = service->idleDeadTime;
3095 conn->idleDeadDetection = service->idleDeadErr ? 1 : 0;
3096 for (i = 0; i < RX_MAXCALLS; i++) {
3097 conn->twind[i] = rx_initSendWindow;
3098 conn->rwind[i] = rx_initReceiveWindow;
3100 /* Notify security object of the new connection */
3101 RXS_NewConnection(conn->securityObject, conn);
3102 /* XXXX Connection timeout? */
3103 if (service->newConnProc)
3104 (*service->newConnProc) (conn);
3105 if (rx_stats_active)
3106 rx_atomic_inc(&rx_stats.nServerConns);
3109 MUTEX_ENTER(&rx_refcnt_mutex);
3111 MUTEX_EXIT(&rx_refcnt_mutex);
3113 rxLastConn = conn; /* store this connection as the last conn used */
3114 MUTEX_EXIT(&rx_connHashTable_lock);
3119 * Timeout a call on a busy call channel if appropriate.
3121 * @param[in] call The busy call.
3123 * @pre 'call' is marked as busy (namely,
3124 * call->conn->lastBusy[call->channel] != 0)
3126 * @pre call->lock is held
3127 * @pre rxi_busyChannelError is nonzero
3129 * @note call->lock is dropped and reacquired
3132 rxi_CheckBusy(struct rx_call *call)
3134 struct rx_connection *conn = call->conn;
3135 int channel = call->channel;
3136 int freechannel = 0;
3138 afs_uint32 callNumber;
3140 MUTEX_EXIT(&call->lock);
3142 MUTEX_ENTER(&conn->conn_call_lock);
3143 callNumber = *call->callNumber;
3145 /* Are there any other call slots on this conn that we should try? Look for
3146 * slots that are empty and are either non-busy, or were marked as busy
3147 * longer than conn->secondsUntilDead seconds before this call started. */
3149 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3151 /* only look at channels that aren't us */
3155 if (conn->lastBusy[i]) {
3156 /* if this channel looked busy too recently, don't look at it */
3157 if (conn->lastBusy[i] >= call->startTime.sec) {
3160 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3165 if (conn->call[i]) {
3166 struct rx_call *tcall = conn->call[i];
3167 MUTEX_ENTER(&tcall->lock);
3168 if (tcall->state == RX_STATE_DALLY) {
3171 MUTEX_EXIT(&tcall->lock);
3177 MUTEX_ENTER(&call->lock);
3179 /* Since the call->lock and conn->conn_call_lock have been released it is
3180 * possible that (1) the call may no longer be busy and/or (2) the call may
3181 * have been reused by another waiting thread. Therefore, we must confirm
3182 * that the call state has not changed when deciding whether or not to
3183 * force this application thread to retry by forcing a Timeout error. */
3185 if (freechannel && *call->callNumber == callNumber &&
3186 (call->flags & RX_CALL_PEER_BUSY)) {
3187 /* Since 'freechannel' is set, there exists another channel in this
3188 * rx_conn that the application thread might be able to use. We know
3189 * that we have the correct call since callNumber is unchanged, and we
3190 * know that the call is still busy. So, set the call error state to
3191 * rxi_busyChannelError so the application can retry the request,
3192 * presumably on a less-busy call channel. */
3194 rxi_CallError(call, RX_CALL_BUSY);
3196 MUTEX_EXIT(&conn->conn_call_lock);
3199 /* There are two packet tracing routines available for testing and monitoring
3200 * Rx. One is called just after every packet is received and the other is
3201 * called just before every packet is sent. Received packets, have had their
3202 * headers decoded, and packets to be sent have not yet had their headers
3203 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3204 * containing the network address. Both can be modified. The return value, if
3205 * non-zero, indicates that the packet should be dropped. */
3207 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3208 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3210 /* A packet has been received off the interface. Np is the packet, socket is
3211 * the socket number it was received from (useful in determining which service
3212 * this packet corresponds to), and (host, port) reflect the host,port of the
3213 * sender. This call returns the packet to the caller if it is finished with
3214 * it, rather than de-allocating it, just as a small performance hack */
3217 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3218 afs_uint32 host, u_short port, int *tnop,
3219 struct rx_call **newcallp)
3221 struct rx_call *call;
3222 struct rx_connection *conn;
3224 afs_uint32 currentCallNumber;
3229 struct rx_packet *tnp;
3232 /* We don't print out the packet until now because (1) the time may not be
3233 * accurate enough until now in the lwp implementation (rx_Listener only gets
3234 * the time after the packet is read) and (2) from a protocol point of view,
3235 * this is the first time the packet has been seen */
3236 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3237 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3238 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3239 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3240 np->header.epoch, np->header.cid, np->header.callNumber,
3241 np->header.seq, np->header.flags, np));
3244 /* Account for connectionless packets */
3245 if (rx_stats_active &&
3246 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3247 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3248 struct rx_peer *peer;
3250 /* Try to look up the peer structure, but don't create one */
3251 peer = rxi_FindPeer(host, port, 0, 0);
3253 /* Since this may not be associated with a connection, it may have
3254 * no refCount, meaning we could race with ReapConnections
3257 if (peer && (peer->refCount > 0)) {
3258 #ifdef AFS_RXERRQ_ENV
3259 if (rx_atomic_read(&peer->neterrs)) {
3260 rx_atomic_set(&peer->neterrs, 0);
3263 MUTEX_ENTER(&peer->peer_lock);
3264 peer->bytesReceived += np->length;
3265 MUTEX_EXIT(&peer->peer_lock);
3269 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3270 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3273 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3274 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3277 /* If an input tracer function is defined, call it with the packet and
3278 * network address. Note this function may modify its arguments. */
3279 if (rx_justReceived) {
3280 struct sockaddr_in addr;
3282 addr.sin_family = AF_INET;
3283 addr.sin_port = port;
3284 addr.sin_addr.s_addr = host;
3285 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3286 addr.sin_len = sizeof(addr);
3287 #endif /* AFS_OSF_ENV */
3288 drop = (*rx_justReceived) (np, &addr);
3289 /* drop packet if return value is non-zero */
3292 port = addr.sin_port; /* in case fcn changed addr */
3293 host = addr.sin_addr.s_addr;
3297 /* If packet was not sent by the client, then *we* must be the client */
3298 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3299 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3301 /* Find the connection (or fabricate one, if we're the server & if
3302 * necessary) associated with this packet */
3304 rxi_FindConnection(socket, host, port, np->header.serviceId,
3305 np->header.cid, np->header.epoch, type,
3306 np->header.securityIndex);
3308 /* To avoid having 2 connections just abort at each other,
3309 don't abort an abort. */
3311 if (np->header.type != RX_PACKET_TYPE_ABORT)
3312 rxi_SendRawAbort(socket, host, port, RX_INVALID_OPERATION,
3317 #ifdef AFS_RXERRQ_ENV
3318 if (rx_atomic_read(&conn->peer->neterrs)) {
3319 rx_atomic_set(&conn->peer->neterrs, 0);
3323 /* If we're doing statistics, then account for the incoming packet */
3324 if (rx_stats_active) {
3325 MUTEX_ENTER(&conn->peer->peer_lock);
3326 conn->peer->bytesReceived += np->length;
3327 MUTEX_EXIT(&conn->peer->peer_lock);
3330 /* If the connection is in an error state, send an abort packet and ignore
3331 * the incoming packet */
3333 /* Don't respond to an abort packet--we don't want loops! */
3334 MUTEX_ENTER(&conn->conn_data_lock);
3335 if (np->header.type != RX_PACKET_TYPE_ABORT)
3336 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3337 putConnection(conn);
3338 MUTEX_EXIT(&conn->conn_data_lock);
3342 /* Check for connection-only requests (i.e. not call specific). */
3343 if (np->header.callNumber == 0) {
3344 switch (np->header.type) {
3345 case RX_PACKET_TYPE_ABORT: {
3346 /* What if the supplied error is zero? */
3347 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3348 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3349 rxi_ConnectionError(conn, errcode);
3350 putConnection(conn);
3353 case RX_PACKET_TYPE_CHALLENGE:
3354 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3355 putConnection(conn);
3357 case RX_PACKET_TYPE_RESPONSE:
3358 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3359 putConnection(conn);
3361 case RX_PACKET_TYPE_PARAMS:
3362 case RX_PACKET_TYPE_PARAMS + 1:
3363 case RX_PACKET_TYPE_PARAMS + 2:
3364 /* ignore these packet types for now */
3365 putConnection(conn);
3369 /* Should not reach here, unless the peer is broken: send an
3371 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3372 MUTEX_ENTER(&conn->conn_data_lock);
3373 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3374 putConnection(conn);
3375 MUTEX_EXIT(&conn->conn_data_lock);
3380 channel = np->header.cid & RX_CHANNELMASK;
3381 MUTEX_ENTER(&conn->conn_call_lock);
3382 call = conn->call[channel];
3385 MUTEX_ENTER(&call->lock);
3386 currentCallNumber = conn->callNumber[channel];
3387 MUTEX_EXIT(&conn->conn_call_lock);
3388 } else if (type == RX_SERVER_CONNECTION) { /* No call allocated */
3389 call = conn->call[channel];
3391 MUTEX_ENTER(&call->lock);
3392 currentCallNumber = conn->callNumber[channel];
3393 MUTEX_EXIT(&conn->conn_call_lock);
3395 call = rxi_NewCall(conn, channel); /* returns locked call */
3396 *call->callNumber = currentCallNumber = np->header.callNumber;
3397 MUTEX_EXIT(&conn->conn_call_lock);
3399 if (np->header.callNumber == 0)
3400 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3401 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3402 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3403 np->header.flags, np, np->length));
3405 call->state = RX_STATE_PRECALL;
3406 clock_GetTime(&call->queueTime);
3407 call->bytesSent = 0;
3408 call->bytesRcvd = 0;
3410 * If the number of queued calls exceeds the overload
3411 * threshold then abort this call.
3413 if ((rx_BusyThreshold > 0) &&
3414 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3415 struct rx_packet *tp;
3417 rxi_CallError(call, rx_BusyError);
3418 tp = rxi_SendCallAbort(call, np, 1, 0);
3419 MUTEX_EXIT(&call->lock);
3420 putConnection(conn);
3421 if (rx_stats_active)
3422 rx_atomic_inc(&rx_stats.nBusies);
3425 rxi_KeepAliveOn(call);
3427 } else { /* RX_CLIENT_CONNECTION and No call allocated */
3428 /* This packet can't be for this call. If the new call address is
3429 * 0 then no call is running on this channel. If there is a call
3430 * then, since this is a client connection we're getting data for
3431 * it must be for the previous call.
3433 MUTEX_EXIT(&conn->conn_call_lock);
3434 if (rx_stats_active)
3435 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3436 putConnection(conn);
3440 /* There is a non-NULL locked call at this point */
3441 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3442 if (np->header.callNumber < currentCallNumber) {
3443 MUTEX_EXIT(&call->lock);
3444 if (rx_stats_active)
3445 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3446 putConnection(conn);
3448 } else if (np->header.callNumber != currentCallNumber) {
3449 /* Wait until the transmit queue is idle before deciding
3450 * whether to reset the current call. Chances are that the
3451 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3454 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3455 if (call->state == RX_STATE_ACTIVE) {
3456 rxi_WaitforTQBusy(call);
3458 * If we entered error state while waiting,
3459 * must call rxi_CallError to permit rxi_ResetCall
3460 * to processed when the tqWaiter count hits zero.
3463 rxi_CallError(call, call->error);
3464 MUTEX_EXIT(&call->lock);
3465 putConnection(conn);
3469 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3470 /* If the new call cannot be taken right now send a busy and set
3471 * the error condition in this call, so that it terminates as
3472 * quickly as possible */
3473 if (call->state == RX_STATE_ACTIVE) {
3474 struct rx_packet *tp;
3476 rxi_CallError(call, RX_CALL_DEAD);
3477 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3479 MUTEX_EXIT(&call->lock);
3480 putConnection(conn);
3483 rxi_ResetCall(call, 0);
3485 * The conn_call_lock is not held but no one else should be
3486 * using this call channel while we are processing this incoming
3487 * packet. This assignment should be safe.
3489 *call->callNumber = np->header.callNumber;
3491 if (np->header.callNumber == 0)
3492 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3493 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3494 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3495 np->header.flags, np, np->length));
3497 call->state = RX_STATE_PRECALL;
3498 clock_GetTime(&call->queueTime);
3499 call->bytesSent = 0;
3500 call->bytesRcvd = 0;
3502 * If the number of queued calls exceeds the overload
3503 * threshold then abort this call.
3505 if ((rx_BusyThreshold > 0) &&
3506 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3507 struct rx_packet *tp;
3509 rxi_CallError(call, rx_BusyError);
3510 tp = rxi_SendCallAbort(call, np, 1, 0);
3511 MUTEX_EXIT(&call->lock);
3512 putConnection(conn);
3513 if (rx_stats_active)
3514 rx_atomic_inc(&rx_stats.nBusies);
3517 rxi_KeepAliveOn(call);
3519 /* Continuing call; do nothing here. */
3521 } else { /* we're the client */
3522 /* Ignore all incoming acknowledgements for calls in DALLY state */
3523 if ((call->state == RX_STATE_DALLY)
3524 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3525 if (rx_stats_active)
3526 rx_atomic_inc(&rx_stats.ignorePacketDally);
3527 MUTEX_EXIT(&call->lock);
3528 putConnection(conn);
3532 /* Ignore anything that's not relevant to the current call. If there
3533 * isn't a current call, then no packet is relevant. */
3534 if (np->header.callNumber != currentCallNumber) {
3535 if (rx_stats_active)
3536 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3537 MUTEX_EXIT(&call->lock);
3538 putConnection(conn);
3541 /* If the service security object index stamped in the packet does not
3542 * match the connection's security index, ignore the packet */
3543 if (np->header.securityIndex != conn->securityIndex) {
3544 MUTEX_EXIT(&call->lock);
3545 putConnection(conn);
3549 /* If we're receiving the response, then all transmit packets are
3550 * implicitly acknowledged. Get rid of them. */
3551 if (np->header.type == RX_PACKET_TYPE_DATA) {
3552 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3553 /* XXX Hack. Because we must release the global rx lock when
3554 * sending packets (osi_NetSend) we drop all acks while we're
3555 * traversing the tq in rxi_Start sending packets out because
3556 * packets may move to the freePacketQueue as result of being here!
3557 * So we drop these packets until we're safely out of the
3558 * traversing. Really ugly!
3559 * For fine grain RX locking, we set the acked field in the
3560 * packets and let rxi_Start remove them from the transmit queue.
3562 if (call->flags & RX_CALL_TQ_BUSY) {
3563 #ifdef RX_ENABLE_LOCKS
3564 rxi_SetAcksInTransmitQueue(call);
3566 putConnection(conn);
3567 return np; /* xmitting; drop packet */
3570 rxi_ClearTransmitQueue(call, 0);
3572 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3573 rxi_ClearTransmitQueue(call, 0);
3574 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3576 if (np->header.type == RX_PACKET_TYPE_ACK) {
3577 /* now check to see if this is an ack packet acknowledging that the
3578 * server actually *lost* some hard-acked data. If this happens we
3579 * ignore this packet, as it may indicate that the server restarted in
3580 * the middle of a call. It is also possible that this is an old ack
3581 * packet. We don't abort the connection in this case, because this
3582 * *might* just be an old ack packet. The right way to detect a server
3583 * restart in the midst of a call is to notice that the server epoch
3585 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3586 * XXX unacknowledged. I think that this is off-by-one, but
3587 * XXX I don't dare change it just yet, since it will
3588 * XXX interact badly with the server-restart detection
3589 * XXX code in receiveackpacket. */
3590 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3591 if (rx_stats_active)
3592 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3593 MUTEX_EXIT(&call->lock);
3594 putConnection(conn);
3598 } /* else not a data packet */
3601 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3602 /* Set remote user defined status from packet */
3603 call->remoteStatus = np->header.userStatus;
3605 /* Now do packet type-specific processing */
3606 switch (np->header.type) {
3607 case RX_PACKET_TYPE_DATA:
3608 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3611 case RX_PACKET_TYPE_ACK:
3612 /* Respond immediately to ack packets requesting acknowledgement
3614 if (np->header.flags & RX_REQUEST_ACK) {
3616 (void)rxi_SendCallAbort(call, 0, 1, 0);
3618 (void)rxi_SendAck(call, 0, np->header.serial,
3619 RX_ACK_PING_RESPONSE, 1);
3621 np = rxi_ReceiveAckPacket(call, np, 1);
3623 case RX_PACKET_TYPE_ABORT: {
3624 /* An abort packet: reset the call, passing the error up to the user. */
3625 /* What if error is zero? */
3626 /* What if the error is -1? the application will treat it as a timeout. */
3627 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3628 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3629 rxi_CallError(call, errdata);
3630 MUTEX_EXIT(&call->lock);
3631 putConnection(conn);
3632 return np; /* xmitting; drop packet */
3634 case RX_PACKET_TYPE_BUSY: {
3635 struct clock busyTime;
3637 clock_GetTime(&busyTime);
3639 MUTEX_EXIT(&call->lock);
3641 MUTEX_ENTER(&conn->conn_call_lock);
3642 MUTEX_ENTER(&call->lock);
3643 conn->lastBusy[call->channel] = busyTime.sec;
3644 call->flags |= RX_CALL_PEER_BUSY;
3645 MUTEX_EXIT(&call->lock);
3646 MUTEX_EXIT(&conn->conn_call_lock);
3648 putConnection(conn);
3652 case RX_PACKET_TYPE_ACKALL:
3653 /* All packets acknowledged, so we can drop all packets previously
3654 * readied for sending */
3655 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3656 /* XXX Hack. We because we can't release the global rx lock when
3657 * sending packets (osi_NetSend) we drop all ack pkts while we're
3658 * traversing the tq in rxi_Start sending packets out because
3659 * packets may move to the freePacketQueue as result of being
3660 * here! So we drop these packets until we're safely out of the
3661 * traversing. Really ugly!
3662 * For fine grain RX locking, we set the acked field in the packets
3663 * and let rxi_Start remove the packets from the transmit queue.
3665 if (call->flags & RX_CALL_TQ_BUSY) {
3666 #ifdef RX_ENABLE_LOCKS
3667 rxi_SetAcksInTransmitQueue(call);
3669 #else /* RX_ENABLE_LOCKS */
3670 MUTEX_EXIT(&call->lock);
3671 putConnection(conn);
3672 return np; /* xmitting; drop packet */
3673 #endif /* RX_ENABLE_LOCKS */
3675 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3676 rxi_ClearTransmitQueue(call, 0);
3679 /* Should not reach here, unless the peer is broken: send an abort
3681 rxi_CallError(call, RX_PROTOCOL_ERROR);
3682 np = rxi_SendCallAbort(call, np, 1, 0);
3685 /* Note when this last legitimate packet was received, for keep-alive
3686 * processing. Note, we delay getting the time until now in the hope that
3687 * the packet will be delivered to the user before any get time is required
3688 * (if not, then the time won't actually be re-evaluated here). */
3689 call->lastReceiveTime = clock_Sec();
3690 /* we've received a legit packet, so the channel is not busy */
3691 call->flags &= ~RX_CALL_PEER_BUSY;
3692 MUTEX_EXIT(&call->lock);
3693 putConnection(conn);
3697 /* return true if this is an "interesting" connection from the point of view
3698 of someone trying to debug the system */
3700 rxi_IsConnInteresting(struct rx_connection *aconn)
3703 struct rx_call *tcall;
3705 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3708 for (i = 0; i < RX_MAXCALLS; i++) {
3709 tcall = aconn->call[i];
3711 if ((tcall->state == RX_STATE_PRECALL)
3712 || (tcall->state == RX_STATE_ACTIVE))
3714 if ((tcall->mode == RX_MODE_SENDING)
3715 || (tcall->mode == RX_MODE_RECEIVING))
3723 /* if this is one of the last few packets AND it wouldn't be used by the
3724 receiving call to immediately satisfy a read request, then drop it on
3725 the floor, since accepting it might prevent a lock-holding thread from
3726 making progress in its reading. If a call has been cleared while in
3727 the precall state then ignore all subsequent packets until the call
3728 is assigned to a thread. */
3731 TooLow(struct rx_packet *ap, struct rx_call *acall)
3735 MUTEX_ENTER(&rx_quota_mutex);
3736 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3737 && (acall->state == RX_STATE_PRECALL))
3738 || ((rx_nFreePackets < rxi_dataQuota + 2)
3739 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3740 && (acall->flags & RX_CALL_READER_WAIT)))) {
3743 MUTEX_EXIT(&rx_quota_mutex);
3749 * Clear the attach wait flag on a connection and proceed.
3751 * Any processing waiting for a connection to be attached should be
3752 * unblocked. We clear the flag and do any other needed tasks.
3755 * the conn to unmark waiting for attach
3757 * @pre conn's conn_data_lock must be locked before calling this function
3761 rxi_ConnClearAttachWait(struct rx_connection *conn)
3763 /* Indicate that rxi_CheckReachEvent is no longer running by
3764 * clearing the flag. Must be atomic under conn_data_lock to
3765 * avoid a new call slipping by: rxi_CheckConnReach holds
3766 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3768 conn->flags &= ~RX_CONN_ATTACHWAIT;
3769 if (conn->flags & RX_CONN_NAT_PING) {
3770 conn->flags &= ~RX_CONN_NAT_PING;
3771 rxi_ScheduleNatKeepAliveEvent(conn);
3776 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3778 struct rx_connection *conn = arg1;
3779 struct rx_call *acall = arg2;
3780 struct rx_call *call = acall;
3781 struct clock when, now;
3784 MUTEX_ENTER(&conn->conn_data_lock);
3787 rxevent_Put(conn->checkReachEvent);
3788 conn->checkReachEvent = NULL;
3791 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3793 putConnection(conn);
3795 MUTEX_EXIT(&conn->conn_data_lock);
3799 MUTEX_ENTER(&conn->conn_call_lock);
3800 MUTEX_ENTER(&conn->conn_data_lock);
3801 for (i = 0; i < RX_MAXCALLS; i++) {
3802 struct rx_call *tc = conn->call[i];
3803 if (tc && tc->state == RX_STATE_PRECALL) {
3809 rxi_ConnClearAttachWait(conn);
3810 MUTEX_EXIT(&conn->conn_data_lock);
3811 MUTEX_EXIT(&conn->conn_call_lock);
3816 MUTEX_ENTER(&call->lock);
3817 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3819 MUTEX_EXIT(&call->lock);
3821 clock_GetTime(&now);
3823 when.sec += RX_CHECKREACH_TIMEOUT;
3824 MUTEX_ENTER(&conn->conn_data_lock);
3825 if (!conn->checkReachEvent) {
3826 MUTEX_ENTER(&rx_refcnt_mutex);
3828 MUTEX_EXIT(&rx_refcnt_mutex);
3829 conn->checkReachEvent = rxevent_Post(&when, &now,
3830 rxi_CheckReachEvent, conn,
3833 MUTEX_EXIT(&conn->conn_data_lock);
3839 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3841 struct rx_service *service = conn->service;
3842 struct rx_peer *peer = conn->peer;
3843 afs_uint32 now, lastReach;
3845 if (service->checkReach == 0)
3849 MUTEX_ENTER(&peer->peer_lock);
3850 lastReach = peer->lastReachTime;
3851 MUTEX_EXIT(&peer->peer_lock);
3852 if (now - lastReach < RX_CHECKREACH_TTL)
3855 MUTEX_ENTER(&conn->conn_data_lock);
3856 if (conn->flags & RX_CONN_ATTACHWAIT) {
3857 MUTEX_EXIT(&conn->conn_data_lock);
3860 conn->flags |= RX_CONN_ATTACHWAIT;
3861 MUTEX_EXIT(&conn->conn_data_lock);
3862 if (!conn->checkReachEvent)
3863 rxi_CheckReachEvent(NULL, conn, call, 0);
3868 /* try to attach call, if authentication is complete */
3870 TryAttach(struct rx_call *acall, osi_socket socket,
3871 int *tnop, struct rx_call **newcallp,
3874 struct rx_connection *conn = acall->conn;
3876 if (conn->type == RX_SERVER_CONNECTION
3877 && acall->state == RX_STATE_PRECALL) {
3878 /* Don't attach until we have any req'd. authentication. */
3879 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3880 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3881 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3882 /* Note: this does not necessarily succeed; there
3883 * may not any proc available
3886 rxi_ChallengeOn(acall->conn);
3891 /* A data packet has been received off the interface. This packet is
3892 * appropriate to the call (the call is in the right state, etc.). This
3893 * routine can return a packet to the caller, for re-use */
3895 static struct rx_packet *
3896 rxi_ReceiveDataPacket(struct rx_call *call,
3897 struct rx_packet *np, int istack,
3898 osi_socket socket, afs_uint32 host, u_short port,
3899 int *tnop, struct rx_call **newcallp)
3901 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3906 afs_uint32 serial=0, flags=0;
3908 struct rx_packet *tnp;
3909 if (rx_stats_active)
3910 rx_atomic_inc(&rx_stats.dataPacketsRead);
3913 /* If there are no packet buffers, drop this new packet, unless we can find
3914 * packet buffers from inactive calls */
3916 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3917 MUTEX_ENTER(&rx_freePktQ_lock);
3918 rxi_NeedMorePackets = TRUE;
3919 MUTEX_EXIT(&rx_freePktQ_lock);
3920 if (rx_stats_active)
3921 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3922 rxi_calltrace(RX_TRACE_DROP, call);
3923 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3924 /* We used to clear the receive queue here, in an attempt to free
3925 * packets. However this is unsafe if the queue has received a
3926 * soft ACK for the final packet */
3927 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3933 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3934 * packet is one of several packets transmitted as a single
3935 * datagram. Do not send any soft or hard acks until all packets
3936 * in a jumbogram have been processed. Send negative acks right away.
3938 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3939 /* tnp is non-null when there are more packets in the
3940 * current jumbo gram */
3947 seq = np->header.seq;
3948 serial = np->header.serial;
3949 flags = np->header.flags;
3951 /* If the call is in an error state, send an abort message */
3953 return rxi_SendCallAbort(call, np, istack, 0);
3955 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3956 * AFS 3.5 jumbogram. */
3957 if (flags & RX_JUMBO_PACKET) {
3958 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3963 if (np->header.spare != 0) {
3964 MUTEX_ENTER(&call->conn->conn_data_lock);
3965 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3966 MUTEX_EXIT(&call->conn->conn_data_lock);
3969 /* The usual case is that this is the expected next packet */
3970 if (seq == call->rnext) {
3972 /* Check to make sure it is not a duplicate of one already queued */
3973 if (queue_IsNotEmpty(&call->rq)
3974 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3975 if (rx_stats_active)
3976 rx_atomic_inc(&rx_stats.dupPacketsRead);
3977 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3978 rxevent_Cancel(&call->delayedAckEvent, call,
3979 RX_CALL_REFCOUNT_DELAY);
3980 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3986 /* It's the next packet. Stick it on the receive queue
3987 * for this call. Set newPackets to make sure we wake
3988 * the reader once all packets have been processed */
3989 #ifdef RX_TRACK_PACKETS
3990 np->flags |= RX_PKTFLAG_RQ;
3992 queue_Prepend(&call->rq, np);
3993 #ifdef RXDEBUG_PACKET
3995 #endif /* RXDEBUG_PACKET */
3997 np = NULL; /* We can't use this anymore */
4000 /* If an ack is requested then set a flag to make sure we
4001 * send an acknowledgement for this packet */
4002 if (flags & RX_REQUEST_ACK) {
4003 ackNeeded = RX_ACK_REQUESTED;
4006 /* Keep track of whether we have received the last packet */
4007 if (flags & RX_LAST_PACKET) {
4008 call->flags |= RX_CALL_HAVE_LAST;
4012 /* Check whether we have all of the packets for this call */
4013 if (call->flags & RX_CALL_HAVE_LAST) {
4014 afs_uint32 tseq; /* temporary sequence number */
4015 struct rx_packet *tp; /* Temporary packet pointer */
4016 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
4018 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4019 if (tseq != tp->header.seq)
4021 if (tp->header.flags & RX_LAST_PACKET) {
4022 call->flags |= RX_CALL_RECEIVE_DONE;
4029 /* Provide asynchronous notification for those who want it
4030 * (e.g. multi rx) */
4031 if (call->arrivalProc) {
4032 (*call->arrivalProc) (call, call->arrivalProcHandle,
4033 call->arrivalProcArg);
4034 call->arrivalProc = (void (*)())0;
4037 /* Update last packet received */
4040 /* If there is no server process serving this call, grab
4041 * one, if available. We only need to do this once. If a
4042 * server thread is available, this thread becomes a server
4043 * thread and the server thread becomes a listener thread. */
4045 TryAttach(call, socket, tnop, newcallp, 0);
4048 /* This is not the expected next packet. */
4050 /* Determine whether this is a new or old packet, and if it's
4051 * a new one, whether it fits into the current receive window.
4052 * Also figure out whether the packet was delivered in sequence.
4053 * We use the prev variable to determine whether the new packet
4054 * is the successor of its immediate predecessor in the
4055 * receive queue, and the missing flag to determine whether
4056 * any of this packets predecessors are missing. */
4058 afs_uint32 prev; /* "Previous packet" sequence number */
4059 struct rx_packet *tp; /* Temporary packet pointer */
4060 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
4061 int missing; /* Are any predecessors missing? */
4063 /* If the new packet's sequence number has been sent to the
4064 * application already, then this is a duplicate */
4065 if (seq < call->rnext) {
4066 if (rx_stats_active)
4067 rx_atomic_inc(&rx_stats.dupPacketsRead);
4068 rxevent_Cancel(&call->delayedAckEvent, call,
4069 RX_CALL_REFCOUNT_DELAY);
4070 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4076 /* If the sequence number is greater than what can be
4077 * accomodated by the current window, then send a negative
4078 * acknowledge and drop the packet */
4079 if ((call->rnext + call->rwind) <= seq) {
4080 rxevent_Cancel(&call->delayedAckEvent, call,
4081 RX_CALL_REFCOUNT_DELAY);
4082 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4089 /* Look for the packet in the queue of old received packets */
4090 for (prev = call->rnext - 1, missing =
4091 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4092 /*Check for duplicate packet */
4093 if (seq == tp->header.seq) {
4094 if (rx_stats_active)
4095 rx_atomic_inc(&rx_stats.dupPacketsRead);
4096 rxevent_Cancel(&call->delayedAckEvent, call,
4097 RX_CALL_REFCOUNT_DELAY);
4098 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4104 /* If we find a higher sequence packet, break out and
4105 * insert the new packet here. */
4106 if (seq < tp->header.seq)
4108 /* Check for missing packet */
4109 if (tp->header.seq != prev + 1) {
4113 prev = tp->header.seq;
4116 /* Keep track of whether we have received the last packet. */
4117 if (flags & RX_LAST_PACKET) {
4118 call->flags |= RX_CALL_HAVE_LAST;
4121 /* It's within the window: add it to the the receive queue.
4122 * tp is left by the previous loop either pointing at the
4123 * packet before which to insert the new packet, or at the
4124 * queue head if the queue is empty or the packet should be
4126 #ifdef RX_TRACK_PACKETS
4127 np->flags |= RX_PKTFLAG_RQ;
4129 #ifdef RXDEBUG_PACKET
4131 #endif /* RXDEBUG_PACKET */
4132 queue_InsertBefore(tp, np);
4136 /* Check whether we have all of the packets for this call */
4137 if ((call->flags & RX_CALL_HAVE_LAST)
4138 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4139 afs_uint32 tseq; /* temporary sequence number */
4142 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4143 if (tseq != tp->header.seq)
4145 if (tp->header.flags & RX_LAST_PACKET) {
4146 call->flags |= RX_CALL_RECEIVE_DONE;
4153 /* We need to send an ack of the packet is out of sequence,
4154 * or if an ack was requested by the peer. */
4155 if (seq != prev + 1 || missing) {
4156 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4157 } else if (flags & RX_REQUEST_ACK) {
4158 ackNeeded = RX_ACK_REQUESTED;
4161 /* Acknowledge the last packet for each call */
4162 if (flags & RX_LAST_PACKET) {
4173 * If the receiver is waiting for an iovec, fill the iovec
4174 * using the data from the receive queue */
4175 if (call->flags & RX_CALL_IOVEC_WAIT) {
4176 didHardAck = rxi_FillReadVec(call, serial);
4177 /* the call may have been aborted */
4186 /* Wakeup the reader if any */
4187 if ((call->flags & RX_CALL_READER_WAIT)
4188 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4189 || (call->iovNext >= call->iovMax)
4190 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4191 call->flags &= ~RX_CALL_READER_WAIT;
4192 #ifdef RX_ENABLE_LOCKS
4193 CV_BROADCAST(&call->cv_rq);
4195 osi_rxWakeup(&call->rq);
4201 * Send an ack when requested by the peer, or once every
4202 * rxi_SoftAckRate packets until the last packet has been
4203 * received. Always send a soft ack for the last packet in
4204 * the server's reply. */
4206 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4207 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4208 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4209 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4210 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4211 } else if (call->nSoftAcks) {
4212 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4213 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4215 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4216 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4217 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4224 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4226 struct rx_peer *peer = conn->peer;
4228 MUTEX_ENTER(&peer->peer_lock);
4229 peer->lastReachTime = clock_Sec();
4230 MUTEX_EXIT(&peer->peer_lock);
4232 MUTEX_ENTER(&conn->conn_data_lock);
4233 if (conn->flags & RX_CONN_ATTACHWAIT) {
4236 rxi_ConnClearAttachWait(conn);
4237 MUTEX_EXIT(&conn->conn_data_lock);
4239 for (i = 0; i < RX_MAXCALLS; i++) {
4240 struct rx_call *call = conn->call[i];
4243 MUTEX_ENTER(&call->lock);
4244 /* tnop can be null if newcallp is null */
4245 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4247 MUTEX_EXIT(&call->lock);
4251 MUTEX_EXIT(&conn->conn_data_lock);
4254 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4256 rx_ack_reason(int reason)
4259 case RX_ACK_REQUESTED:
4261 case RX_ACK_DUPLICATE:
4263 case RX_ACK_OUT_OF_SEQUENCE:
4265 case RX_ACK_EXCEEDS_WINDOW:
4267 case RX_ACK_NOSPACE:
4271 case RX_ACK_PING_RESPONSE:
4284 /* The real smarts of the whole thing. */
4285 static struct rx_packet *
4286 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4289 struct rx_ackPacket *ap;
4291 struct rx_packet *tp;
4292 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4293 struct rx_connection *conn = call->conn;
4294 struct rx_peer *peer = conn->peer;
4295 struct clock now; /* Current time, for RTT calculations */
4303 int newAckCount = 0;
4304 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4305 int pktsize = 0; /* Set if we need to update the peer mtu */
4306 int conn_data_locked = 0;
4308 if (rx_stats_active)
4309 rx_atomic_inc(&rx_stats.ackPacketsRead);
4310 ap = (struct rx_ackPacket *)rx_DataOf(np);
4311 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4313 return np; /* truncated ack packet */
4315 /* depends on ack packet struct */
4316 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4317 first = ntohl(ap->firstPacket);
4318 prev = ntohl(ap->previousPacket);
4319 serial = ntohl(ap->serial);
4322 * Ignore ack packets received out of order while protecting
4323 * against peers that set the previousPacket field to a packet
4324 * serial number instead of a sequence number.
4326 if (first < call->tfirst ||
4327 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4334 if (np->header.flags & RX_SLOW_START_OK) {
4335 call->flags |= RX_CALL_SLOW_START_OK;
4338 if (ap->reason == RX_ACK_PING_RESPONSE)
4339 rxi_UpdatePeerReach(conn, call);
4341 if (conn->lastPacketSizeSeq) {
4342 MUTEX_ENTER(&conn->conn_data_lock);
4343 conn_data_locked = 1;
4344 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4345 pktsize = conn->lastPacketSize;
4346 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4349 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4350 if (!conn_data_locked) {
4351 MUTEX_ENTER(&conn->conn_data_lock);
4352 conn_data_locked = 1;
4354 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4355 /* process mtu ping ack */
4356 pktsize = conn->lastPingSize;
4357 conn->lastPingSizeSer = conn->lastPingSize = 0;
4361 if (conn_data_locked) {
4362 MUTEX_EXIT(&conn->conn_data_lock);
4363 conn_data_locked = 0;
4367 if (rxdebug_active) {
4371 len = _snprintf(msg, sizeof(msg),
4372 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4373 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4374 ntohl(ap->serial), ntohl(ap->previousPacket),
4375 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4376 ap->nAcks, ntohs(ap->bufferSpace) );
4380 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4381 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4385 OutputDebugString(msg);
4387 #else /* AFS_NT40_ENV */
4390 "RACK: reason %x previous %u seq %u serial %u first %u",
4391 ap->reason, ntohl(ap->previousPacket),
4392 (unsigned int)np->header.seq, (unsigned int)serial,
4393 ntohl(ap->firstPacket));
4396 for (offset = 0; offset < nAcks; offset++)
4397 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4402 #endif /* AFS_NT40_ENV */
4405 MUTEX_ENTER(&peer->peer_lock);
4408 * Start somewhere. Can't assume we can send what we can receive,
4409 * but we are clearly receiving.
4411 if (!peer->maxPacketSize)
4412 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4414 if (pktsize > peer->maxPacketSize) {
4415 peer->maxPacketSize = pktsize;
4416 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4417 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4418 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4419 rxi_ScheduleGrowMTUEvent(call, 1);
4424 clock_GetTime(&now);
4426 /* The transmit queue splits into 4 sections.
4428 * The first section is packets which have now been acknowledged
4429 * by a window size change in the ack. These have reached the
4430 * application layer, and may be discarded. These are packets
4431 * with sequence numbers < ap->firstPacket.
4433 * The second section is packets which have sequence numbers in
4434 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4435 * contents of the packet's ack array determines whether these
4436 * packets are acknowledged or not.
4438 * The third section is packets which fall above the range
4439 * addressed in the ack packet. These have not yet been received
4442 * The four section is packets which have not yet been transmitted.
4443 * These packets will have a header.serial of 0.
4446 /* First section - implicitly acknowledged packets that can be
4450 tp = queue_First(&call->tq, rx_packet);
4451 while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4452 struct rx_packet *next;
4454 next = queue_Next(tp, rx_packet);
4455 call->tfirst = tp->header.seq + 1;
4457 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4459 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4462 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4463 /* XXX Hack. Because we have to release the global rx lock when sending
4464 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4465 * in rxi_Start sending packets out because packets may move to the
4466 * freePacketQueue as result of being here! So we drop these packets until
4467 * we're safely out of the traversing. Really ugly!
4468 * To make it even uglier, if we're using fine grain locking, we can
4469 * set the ack bits in the packets and have rxi_Start remove the packets
4470 * when it's done transmitting.
4472 if (call->flags & RX_CALL_TQ_BUSY) {
4473 #ifdef RX_ENABLE_LOCKS
4474 tp->flags |= RX_PKTFLAG_ACKED;
4475 call->flags |= RX_CALL_TQ_SOME_ACKED;
4476 #else /* RX_ENABLE_LOCKS */
4478 #endif /* RX_ENABLE_LOCKS */
4480 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4483 #ifdef RX_TRACK_PACKETS
4484 tp->flags &= ~RX_PKTFLAG_TQ;
4486 #ifdef RXDEBUG_PACKET
4488 #endif /* RXDEBUG_PACKET */
4489 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4494 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4496 /* Second section of the queue - packets for which we are receiving
4499 * Go through the explicit acks/nacks and record the results in
4500 * the waiting packets. These are packets that can't be released
4501 * yet, even with a positive acknowledge. This positive
4502 * acknowledge only means the packet has been received by the
4503 * peer, not that it will be retained long enough to be sent to
4504 * the peer's upper level. In addition, reset the transmit timers
4505 * of any missing packets (those packets that must be missing
4506 * because this packet was out of sequence) */
4508 call->nSoftAcked = 0;
4510 while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4511 /* Set the acknowledge flag per packet based on the
4512 * information in the ack packet. An acknowlegded packet can
4513 * be downgraded when the server has discarded a packet it
4514 * soacked previously, or when an ack packet is received
4515 * out of sequence. */
4516 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4517 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4519 tp->flags |= RX_PKTFLAG_ACKED;
4520 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4527 } else /* RX_ACK_TYPE_NACK */ {
4528 tp->flags &= ~RX_PKTFLAG_ACKED;
4532 tp = queue_Next(tp, rx_packet);
4535 /* We don't need to take any action with the 3rd or 4th section in the
4536 * queue - they're not addressed by the contents of this ACK packet.
4539 /* If the window has been extended by this acknowledge packet,
4540 * then wakeup a sender waiting in alloc for window space, or try
4541 * sending packets now, if he's been sitting on packets due to
4542 * lack of window space */
4543 if (call->tnext < (call->tfirst + call->twind)) {
4544 #ifdef RX_ENABLE_LOCKS
4545 CV_SIGNAL(&call->cv_twind);
4547 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4548 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4549 osi_rxWakeup(&call->twind);
4552 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4553 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4557 /* if the ack packet has a receivelen field hanging off it,
4558 * update our state */
4559 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4562 /* If the ack packet has a "recommended" size that is less than
4563 * what I am using now, reduce my size to match */
4564 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4565 (int)sizeof(afs_int32), &tSize);
4566 tSize = (afs_uint32) ntohl(tSize);
4567 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4569 /* Get the maximum packet size to send to this peer */
4570 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4572 tSize = (afs_uint32) ntohl(tSize);
4573 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4574 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4576 /* sanity check - peer might have restarted with different params.
4577 * If peer says "send less", dammit, send less... Peer should never
4578 * be unable to accept packets of the size that prior AFS versions would
4579 * send without asking. */
4580 if (peer->maxMTU != tSize) {
4581 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4583 peer->maxMTU = tSize;
4584 peer->MTU = MIN(tSize, peer->MTU);
4585 call->MTU = MIN(call->MTU, tSize);
4588 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4591 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4592 (int)sizeof(afs_int32), &tSize);
4593 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4594 if (tSize < call->twind) { /* smaller than our send */
4595 call->twind = tSize; /* window, we must send less... */
4596 call->ssthresh = MIN(call->twind, call->ssthresh);
4597 call->conn->twind[call->channel] = call->twind;
4600 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4601 * network MTU confused with the loopback MTU. Calculate the
4602 * maximum MTU here for use in the slow start code below.
4604 /* Did peer restart with older RX version? */
4605 if (peer->maxDgramPackets > 1) {
4606 peer->maxDgramPackets = 1;
4608 } else if (np->length >=
4609 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4612 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4613 sizeof(afs_int32), &tSize);
4614 tSize = (afs_uint32) ntohl(tSize);
4616 * As of AFS 3.5 we set the send window to match the receive window.
4618 if (tSize < call->twind) {
4619 call->twind = tSize;
4620 call->conn->twind[call->channel] = call->twind;
4621 call->ssthresh = MIN(call->twind, call->ssthresh);
4622 } else if (tSize > call->twind) {
4623 call->twind = tSize;
4624 call->conn->twind[call->channel] = call->twind;
4628 * As of AFS 3.5, a jumbogram is more than one fixed size
4629 * packet transmitted in a single UDP datagram. If the remote
4630 * MTU is smaller than our local MTU then never send a datagram
4631 * larger than the natural MTU.
4634 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4635 (int)sizeof(afs_int32), &tSize);
4636 maxDgramPackets = (afs_uint32) ntohl(tSize);
4637 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4639 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4640 if (maxDgramPackets > 1) {
4641 peer->maxDgramPackets = maxDgramPackets;
4642 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4644 peer->maxDgramPackets = 1;
4645 call->MTU = peer->natMTU;
4647 } else if (peer->maxDgramPackets > 1) {
4648 /* Restarted with lower version of RX */
4649 peer->maxDgramPackets = 1;
4651 } else if (peer->maxDgramPackets > 1
4652 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4653 /* Restarted with lower version of RX */
4654 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4655 peer->natMTU = OLD_MAX_PACKET_SIZE;
4656 peer->MTU = OLD_MAX_PACKET_SIZE;
4657 peer->maxDgramPackets = 1;
4658 peer->nDgramPackets = 1;
4660 call->MTU = OLD_MAX_PACKET_SIZE;
4665 * Calculate how many datagrams were successfully received after
4666 * the first missing packet and adjust the negative ack counter
4671 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4672 if (call->nNacks < nNacked) {
4673 call->nNacks = nNacked;
4676 call->nAcks += newAckCount;
4680 /* If the packet contained new acknowledgements, rather than just
4681 * being a duplicate of one we have previously seen, then we can restart
4684 if (newAckCount > 0)
4685 rxi_rto_packet_acked(call, istack);
4687 if (call->flags & RX_CALL_FAST_RECOVER) {
4688 if (newAckCount == 0) {
4689 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4691 call->flags &= ~RX_CALL_FAST_RECOVER;
4692 call->cwind = call->nextCwind;
4693 call->nextCwind = 0;
4696 call->nCwindAcks = 0;
4697 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4698 /* Three negative acks in a row trigger congestion recovery */
4699 call->flags |= RX_CALL_FAST_RECOVER;
4700 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4702 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4703 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4704 call->nextCwind = call->ssthresh;
4707 peer->MTU = call->MTU;
4708 peer->cwind = call->nextCwind;
4709 peer->nDgramPackets = call->nDgramPackets;
4711 call->congestSeq = peer->congestSeq;
4713 /* Reset the resend times on the packets that were nacked
4714 * so we will retransmit as soon as the window permits
4717 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4719 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4720 tp->flags &= ~RX_PKTFLAG_SENT;
4722 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4727 /* If cwind is smaller than ssthresh, then increase
4728 * the window one packet for each ack we receive (exponential
4730 * If cwind is greater than or equal to ssthresh then increase
4731 * the congestion window by one packet for each cwind acks we
4732 * receive (linear growth). */
4733 if (call->cwind < call->ssthresh) {
4735 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4736 call->nCwindAcks = 0;
4738 call->nCwindAcks += newAckCount;
4739 if (call->nCwindAcks >= call->cwind) {
4740 call->nCwindAcks = 0;
4741 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4745 * If we have received several acknowledgements in a row then
4746 * it is time to increase the size of our datagrams
4748 if ((int)call->nAcks > rx_nDgramThreshold) {
4749 if (peer->maxDgramPackets > 1) {
4750 if (call->nDgramPackets < peer->maxDgramPackets) {
4751 call->nDgramPackets++;
4753 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4754 } else if (call->MTU < peer->maxMTU) {
4755 /* don't upgrade if we can't handle it */
4756 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4757 call->MTU = peer->ifMTU;
4759 call->MTU += peer->natMTU;
4760 call->MTU = MIN(call->MTU, peer->maxMTU);
4767 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4769 /* Servers need to hold the call until all response packets have
4770 * been acknowledged. Soft acks are good enough since clients
4771 * are not allowed to clear their receive queues. */
4772 if (call->state == RX_STATE_HOLD
4773 && call->tfirst + call->nSoftAcked >= call->tnext) {
4774 call->state = RX_STATE_DALLY;
4775 rxi_ClearTransmitQueue(call, 0);
4776 rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4777 } else if (!queue_IsEmpty(&call->tq)) {
4778 rxi_Start(call, istack);
4783 /* Received a response to a challenge packet */
4784 static struct rx_packet *
4785 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4786 struct rx_packet *np, int istack)
4790 /* Ignore the packet if we're the client */
4791 if (conn->type == RX_CLIENT_CONNECTION)
4794 /* If already authenticated, ignore the packet (it's probably a retry) */
4795 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4798 /* Otherwise, have the security object evaluate the response packet */
4799 error = RXS_CheckResponse(conn->securityObject, conn, np);
4801 /* If the response is invalid, reset the connection, sending
4802 * an abort to the peer */
4806 rxi_ConnectionError(conn, error);
4807 MUTEX_ENTER(&conn->conn_data_lock);
4808 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4809 MUTEX_EXIT(&conn->conn_data_lock);
4812 /* If the response is valid, any calls waiting to attach
4813 * servers can now do so */
4816 for (i = 0; i < RX_MAXCALLS; i++) {
4817 struct rx_call *call = conn->call[i];
4819 MUTEX_ENTER(&call->lock);
4820 if (call->state == RX_STATE_PRECALL)
4821 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4822 /* tnop can be null if newcallp is null */
4823 MUTEX_EXIT(&call->lock);
4827 /* Update the peer reachability information, just in case
4828 * some calls went into attach-wait while we were waiting
4829 * for authentication..
4831 rxi_UpdatePeerReach(conn, NULL);
4836 /* A client has received an authentication challenge: the security
4837 * object is asked to cough up a respectable response packet to send
4838 * back to the server. The server is responsible for retrying the
4839 * challenge if it fails to get a response. */
4841 static struct rx_packet *
4842 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4843 struct rx_packet *np, int istack)
4847 /* Ignore the challenge if we're the server */
4848 if (conn->type == RX_SERVER_CONNECTION)
4851 /* Ignore the challenge if the connection is otherwise idle; someone's
4852 * trying to use us as an oracle. */
4853 if (!rxi_HasActiveCalls(conn))
4856 /* Send the security object the challenge packet. It is expected to fill
4857 * in the response. */
4858 error = RXS_GetResponse(conn->securityObject, conn, np);
4860 /* If the security object is unable to return a valid response, reset the
4861 * connection and send an abort to the peer. Otherwise send the response
4862 * packet to the peer connection. */
4864 rxi_ConnectionError(conn, error);
4865 MUTEX_ENTER(&conn->conn_data_lock);
4866 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4867 MUTEX_EXIT(&conn->conn_data_lock);
4869 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4870 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4876 /* Find an available server process to service the current request in
4877 * the given call structure. If one isn't available, queue up this
4878 * call so it eventually gets one */
4880 rxi_AttachServerProc(struct rx_call *call,
4881 osi_socket socket, int *tnop,
4882 struct rx_call **newcallp)
4884 struct rx_serverQueueEntry *sq;
4885 struct rx_service *service = call->conn->service;
4888 /* May already be attached */
4889 if (call->state == RX_STATE_ACTIVE)
4892 MUTEX_ENTER(&rx_serverPool_lock);
4894 haveQuota = QuotaOK(service);
4895 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4896 /* If there are no processes available to service this call,
4897 * put the call on the incoming call queue (unless it's
4898 * already on the queue).
4900 #ifdef RX_ENABLE_LOCKS
4902 ReturnToServerPool(service);
4903 #endif /* RX_ENABLE_LOCKS */
4905 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4906 call->flags |= RX_CALL_WAIT_PROC;
4907 rx_atomic_inc(&rx_nWaiting);
4908 rx_atomic_inc(&rx_nWaited);
4909 rxi_calltrace(RX_CALL_ARRIVAL, call);
4910 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4911 queue_Append(&rx_incomingCallQueue, call);
4914 sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4916 /* If hot threads are enabled, and both newcallp and sq->socketp
4917 * are non-null, then this thread will process the call, and the
4918 * idle server thread will start listening on this threads socket.
4921 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4924 *sq->socketp = socket;
4925 clock_GetTime(&call->startTime);
4926 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4930 if (call->flags & RX_CALL_WAIT_PROC) {
4931 /* Conservative: I don't think this should happen */
4932 call->flags &= ~RX_CALL_WAIT_PROC;
4933 rx_atomic_dec(&rx_nWaiting);
4934 if (queue_IsOnQueue(call)) {
4938 call->state = RX_STATE_ACTIVE;
4939 call->mode = RX_MODE_RECEIVING;
4940 #ifdef RX_KERNEL_TRACE
4942 int glockOwner = ISAFS_GLOCK();
4945 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4946 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4952 if (call->flags & RX_CALL_CLEARED) {
4953 /* send an ack now to start the packet flow up again */
4954 call->flags &= ~RX_CALL_CLEARED;
4955 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4957 #ifdef RX_ENABLE_LOCKS
4960 service->nRequestsRunning++;
4961 MUTEX_ENTER(&rx_quota_mutex);
4962 if (service->nRequestsRunning <= service->minProcs)
4965 MUTEX_EXIT(&rx_quota_mutex);
4969 MUTEX_EXIT(&rx_serverPool_lock);
4972 /* Delay the sending of an acknowledge event for a short while, while
4973 * a new call is being prepared (in the case of a client) or a reply
4974 * is being prepared (in the case of a server). Rather than sending
4975 * an ack packet, an ACKALL packet is sent. */
4977 rxi_AckAll(struct rx_call *call)
4979 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4981 call->flags |= RX_CALL_ACKALL_SENT;
4985 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4988 struct rx_call *call = arg1;
4989 #ifdef RX_ENABLE_LOCKS
4991 MUTEX_ENTER(&call->lock);
4992 if (event == call->delayedAckEvent) {
4993 rxevent_Put(call->delayedAckEvent);
4994 call->delayedAckEvent = NULL;
4996 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4998 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5000 MUTEX_EXIT(&call->lock);
5001 #else /* RX_ENABLE_LOCKS */
5003 rxevent_Put(call->delayedAckEvent);
5004 call->delayedAckEvent = NULL;
5006 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5007 #endif /* RX_ENABLE_LOCKS */
5011 #ifdef RX_ENABLE_LOCKS
5012 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5013 * clearing them out.
5016 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5018 struct rx_packet *p, *tp;
5021 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
5022 p->flags |= RX_PKTFLAG_ACKED;
5026 call->flags |= RX_CALL_TQ_CLEARME;
5027 call->flags |= RX_CALL_TQ_SOME_ACKED;
5030 rxi_rto_cancel(call);
5032 call->tfirst = call->tnext;
5033 call->nSoftAcked = 0;
5035 if (call->flags & RX_CALL_FAST_RECOVER) {
5036 call->flags &= ~RX_CALL_FAST_RECOVER;
5037 call->cwind = call->nextCwind;
5038 call->nextCwind = 0;
5041 CV_SIGNAL(&call->cv_twind);
5043 #endif /* RX_ENABLE_LOCKS */
5045 /* Clear out the transmit queue for the current call (all packets have
5046 * been received by peer) */
5048 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5050 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5051 struct rx_packet *p, *tp;
5053 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5055 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
5056 p->flags |= RX_PKTFLAG_ACKED;
5060 call->flags |= RX_CALL_TQ_CLEARME;
5061 call->flags |= RX_CALL_TQ_SOME_ACKED;
5064 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5065 #ifdef RXDEBUG_PACKET
5067 #endif /* RXDEBUG_PACKET */
5068 rxi_FreePackets(0, &call->tq);
5069 rxi_WakeUpTransmitQueue(call);
5070 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5071 call->flags &= ~RX_CALL_TQ_CLEARME;
5073 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5075 rxi_rto_cancel(call);
5076 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5077 call->nSoftAcked = 0;
5079 if (call->flags & RX_CALL_FAST_RECOVER) {
5080 call->flags &= ~RX_CALL_FAST_RECOVER;
5081 call->cwind = call->nextCwind;
5083 #ifdef RX_ENABLE_LOCKS
5084 CV_SIGNAL(&call->cv_twind);
5086 osi_rxWakeup(&call->twind);
5091 rxi_ClearReceiveQueue(struct rx_call *call)
5093 if (queue_IsNotEmpty(&call->rq)) {
5096 count = rxi_FreePackets(0, &call->rq);
5097 rx_packetReclaims += count;
5098 #ifdef RXDEBUG_PACKET
5100 if ( call->rqc != 0 )
5101 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5103 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5105 if (call->state == RX_STATE_PRECALL) {
5106 call->flags |= RX_CALL_CLEARED;
5110 /* Send an abort packet for the specified call */
5111 static struct rx_packet *
5112 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5113 int istack, int force)
5115 afs_int32 error, cerror;
5116 struct clock when, now;
5121 switch (call->error) {
5124 cerror = RX_CALL_TIMEOUT;
5127 cerror = call->error;
5130 /* Clients should never delay abort messages */
5131 if (rx_IsClientConn(call->conn))
5134 if (call->abortCode != cerror) {
5135 call->abortCode = cerror;
5136 call->abortCount = 0;
5139 if (force || rxi_callAbortThreshhold == 0
5140 || call->abortCount < rxi_callAbortThreshhold) {
5141 if (call->delayedAbortEvent) {
5142 rxevent_Cancel(&call->delayedAbortEvent, call,
5143 RX_CALL_REFCOUNT_ABORT);
5145 error = htonl(cerror);
5148 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5149 (char *)&error, sizeof(error), istack);
5150 } else if (!call->delayedAbortEvent) {
5151 clock_GetTime(&now);
5153 clock_Addmsec(&when, rxi_callAbortDelay);
5154 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5155 call->delayedAbortEvent =
5156 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5161 /* Send an abort packet for the specified connection. Packet is an
5162 * optional pointer to a packet that can be used to send the abort.
5163 * Once the number of abort messages reaches the threshhold, an
5164 * event is scheduled to send the abort. Setting the force flag
5165 * overrides sending delayed abort messages.
5167 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5168 * to send the abort packet.
5171 rxi_SendConnectionAbort(struct rx_connection *conn,
5172 struct rx_packet *packet, int istack, int force)
5175 struct clock when, now;
5180 /* Clients should never delay abort messages */
5181 if (rx_IsClientConn(conn))
5184 if (force || rxi_connAbortThreshhold == 0
5185 || conn->abortCount < rxi_connAbortThreshhold) {
5187 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5188 error = htonl(conn->error);
5190 MUTEX_EXIT(&conn->conn_data_lock);
5192 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5193 RX_PACKET_TYPE_ABORT, (char *)&error,
5194 sizeof(error), istack);
5195 MUTEX_ENTER(&conn->conn_data_lock);
5196 } else if (!conn->delayedAbortEvent) {
5197 clock_GetTime(&now);
5199 clock_Addmsec(&when, rxi_connAbortDelay);
5200 conn->delayedAbortEvent =
5201 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5206 /* Associate an error all of the calls owned by a connection. Called
5207 * with error non-zero. This is only for really fatal things, like
5208 * bad authentication responses. The connection itself is set in
5209 * error at this point, so that future packets received will be
5212 rxi_ConnectionError(struct rx_connection *conn,
5218 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5220 MUTEX_ENTER(&conn->conn_data_lock);
5221 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5222 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5223 if (conn->checkReachEvent) {
5224 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5225 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5226 putConnection(conn);
5228 MUTEX_EXIT(&conn->conn_data_lock);
5229 for (i = 0; i < RX_MAXCALLS; i++) {
5230 struct rx_call *call = conn->call[i];
5232 MUTEX_ENTER(&call->lock);
5233 rxi_CallError(call, error);
5234 MUTEX_EXIT(&call->lock);
5237 conn->error = error;
5238 if (rx_stats_active)
5239 rx_atomic_inc(&rx_stats.fatalErrors);
5244 * Interrupt an in-progress call with the specified error and wakeup waiters.
5246 * @param[in] call The call to interrupt
5247 * @param[in] error The error code to send to the peer
5250 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5252 MUTEX_ENTER(&call->lock);
5253 rxi_CallError(call, error);
5254 rxi_SendCallAbort(call, NULL, 0, 1);
5255 MUTEX_EXIT(&call->lock);
5259 rxi_CallError(struct rx_call *call, afs_int32 error)
5262 osirx_AssertMine(&call->lock, "rxi_CallError");
5264 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5266 error = call->error;
5268 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5269 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5270 rxi_ResetCall(call, 0);
5273 rxi_ResetCall(call, 0);
5275 call->error = error;
5278 /* Reset various fields in a call structure, and wakeup waiting
5279 * processes. Some fields aren't changed: state & mode are not
5280 * touched (these must be set by the caller), and bufptr, nLeft, and
5281 * nFree are not reset, since these fields are manipulated by
5282 * unprotected macros, and may only be reset by non-interrupting code.
5286 rxi_ResetCall(struct rx_call *call, int newcall)
5289 struct rx_peer *peer;
5290 struct rx_packet *packet;
5292 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5294 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5296 /* Notify anyone who is waiting for asynchronous packet arrival */
5297 if (call->arrivalProc) {
5298 (*call->arrivalProc) (call, call->arrivalProcHandle,
5299 call->arrivalProcArg);
5300 call->arrivalProc = (void (*)())0;
5304 rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_MTU);
5306 if (call->delayedAbortEvent) {
5307 rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5308 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5310 rxi_SendCallAbort(call, packet, 0, 1);
5311 rxi_FreePacket(packet);
5316 * Update the peer with the congestion information in this call
5317 * so other calls on this connection can pick up where this call
5318 * left off. If the congestion sequence numbers don't match then
5319 * another call experienced a retransmission.
5321 peer = call->conn->peer;
5322 MUTEX_ENTER(&peer->peer_lock);
5324 if (call->congestSeq == peer->congestSeq) {
5325 peer->cwind = MAX(peer->cwind, call->cwind);
5326 peer->MTU = MAX(peer->MTU, call->MTU);
5327 peer->nDgramPackets =
5328 MAX(peer->nDgramPackets, call->nDgramPackets);
5331 call->abortCode = 0;
5332 call->abortCount = 0;
5334 if (peer->maxDgramPackets > 1) {
5335 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5337 call->MTU = peer->MTU;
5339 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5340 call->ssthresh = rx_maxSendWindow;
5341 call->nDgramPackets = peer->nDgramPackets;
5342 call->congestSeq = peer->congestSeq;
5343 call->rtt = peer->rtt;
5344 call->rtt_dev = peer->rtt_dev;
5345 clock_Zero(&call->rto);
5346 clock_Addmsec(&call->rto,
5347 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5348 MUTEX_EXIT(&peer->peer_lock);
5350 flags = call->flags;
5351 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5352 rxi_WaitforTQBusy(call);
5353 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5355 rxi_ClearTransmitQueue(call, 1);
5356 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5357 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5361 if (!newcall && (flags & RX_CALL_PEER_BUSY)) {
5362 /* The call channel is still busy; resetting the call doesn't change
5363 * that. However, if 'newcall' is set, we are processing a call
5364 * structure that has either been recycled from the free list, or has
5365 * been newly allocated. So, RX_CALL_PEER_BUSY is not relevant if
5366 * 'newcall' is set, since it describes a completely different call
5367 * channel which we do not care about. */
5368 call->flags |= RX_CALL_PEER_BUSY;
5371 rxi_ClearReceiveQueue(call);
5372 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5376 call->twind = call->conn->twind[call->channel];
5377 call->rwind = call->conn->rwind[call->channel];
5378 call->nSoftAcked = 0;
5379 call->nextCwind = 0;
5382 call->nCwindAcks = 0;
5383 call->nSoftAcks = 0;
5384 call->nHardAcks = 0;
5386 call->tfirst = call->rnext = call->tnext = 1;
5389 call->lastAcked = 0;
5390 call->localStatus = call->remoteStatus = 0;
5392 if (flags & RX_CALL_READER_WAIT) {
5393 #ifdef RX_ENABLE_LOCKS
5394 CV_BROADCAST(&call->cv_rq);
5396 osi_rxWakeup(&call->rq);
5399 if (flags & RX_CALL_WAIT_PACKETS) {
5400 MUTEX_ENTER(&rx_freePktQ_lock);
5401 rxi_PacketsUnWait(); /* XXX */
5402 MUTEX_EXIT(&rx_freePktQ_lock);
5404 #ifdef RX_ENABLE_LOCKS
5405 CV_SIGNAL(&call->cv_twind);
5407 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5408 osi_rxWakeup(&call->twind);
5411 if (flags & RX_CALL_WAIT_PROC) {
5412 rx_atomic_dec(&rx_nWaiting);
5414 #ifdef RX_ENABLE_LOCKS
5415 /* The following ensures that we don't mess with any queue while some
5416 * other thread might also be doing so. The call_queue_lock field is
5417 * is only modified under the call lock. If the call is in the process
5418 * of being removed from a queue, the call is not locked until the
5419 * the queue lock is dropped and only then is the call_queue_lock field
5420 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5421 * Note that any other routine which removes a call from a queue has to
5422 * obtain the queue lock before examing the queue and removing the call.
5424 if (call->call_queue_lock) {
5425 MUTEX_ENTER(call->call_queue_lock);
5426 if (queue_IsOnQueue(call)) {
5429 MUTEX_EXIT(call->call_queue_lock);
5430 CLEAR_CALL_QUEUE_LOCK(call);
5432 #else /* RX_ENABLE_LOCKS */
5433 if (queue_IsOnQueue(call)) {
5436 #endif /* RX_ENABLE_LOCKS */
5438 rxi_KeepAliveOff(call);
5439 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5442 /* Send an acknowledge for the indicated packet (seq,serial) of the
5443 * indicated call, for the indicated reason (reason). This
5444 * acknowledge will specifically acknowledge receiving the packet, and
5445 * will also specify which other packets for this call have been
5446 * received. This routine returns the packet that was used to the
5447 * caller. The caller is responsible for freeing it or re-using it.
5448 * This acknowledgement also returns the highest sequence number
5449 * actually read out by the higher level to the sender; the sender
5450 * promises to keep around packets that have not been read by the
5451 * higher level yet (unless, of course, the sender decides to abort
5452 * the call altogether). Any of p, seq, serial, pflags, or reason may
5453 * be set to zero without ill effect. That is, if they are zero, they
5454 * will not convey any information.
5455 * NOW there is a trailer field, after the ack where it will safely be
5456 * ignored by mundanes, which indicates the maximum size packet this
5457 * host can swallow. */
5459 struct rx_packet *optionalPacket; use to send ack (or null)
5460 int seq; Sequence number of the packet we are acking
5461 int serial; Serial number of the packet
5462 int pflags; Flags field from packet header
5463 int reason; Reason an acknowledge was prompted
5467 rxi_SendAck(struct rx_call *call,
5468 struct rx_packet *optionalPacket, int serial, int reason,
5471 struct rx_ackPacket *ap;
5472 struct rx_packet *rqp;
5473 struct rx_packet *nxp; /* For queue_Scan */
5474 struct rx_packet *p;
5477 afs_uint32 padbytes = 0;
5478 #ifdef RX_ENABLE_TSFPQ
5479 struct rx_ts_info_t * rx_ts_info;
5483 * Open the receive window once a thread starts reading packets
5485 if (call->rnext > 1) {
5486 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5489 /* Don't attempt to grow MTU if this is a critical ping */
5490 if (reason == RX_ACK_MTU) {
5491 /* keep track of per-call attempts, if we're over max, do in small
5492 * otherwise in larger? set a size to increment by, decrease
5495 if (call->conn->peer->maxPacketSize &&
5496 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5498 padbytes = call->conn->peer->maxPacketSize+16;
5500 padbytes = call->conn->peer->maxMTU + 128;
5502 /* do always try a minimum size ping */
5503 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5505 /* subtract the ack payload */
5506 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5507 reason = RX_ACK_PING;
5510 call->nHardAcks = 0;
5511 call->nSoftAcks = 0;
5512 if (call->rnext > call->lastAcked)
5513 call->lastAcked = call->rnext;
5517 rx_computelen(p, p->length); /* reset length, you never know */
5518 } /* where that's been... */
5519 #ifdef RX_ENABLE_TSFPQ
5521 RX_TS_INFO_GET(rx_ts_info);
5522 if ((p = rx_ts_info->local_special_packet)) {
5523 rx_computelen(p, p->length);
5524 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5525 rx_ts_info->local_special_packet = p;
5526 } else { /* We won't send the ack, but don't panic. */
5527 return optionalPacket;
5531 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5532 /* We won't send the ack, but don't panic. */
5533 return optionalPacket;
5538 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5541 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5542 #ifndef RX_ENABLE_TSFPQ
5543 if (!optionalPacket)
5546 return optionalPacket;
5548 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5549 if (rx_Contiguous(p) < templ) {
5550 #ifndef RX_ENABLE_TSFPQ
5551 if (!optionalPacket)
5554 return optionalPacket;
5559 /* MTUXXX failing to send an ack is very serious. We should */
5560 /* try as hard as possible to send even a partial ack; it's */
5561 /* better than nothing. */
5562 ap = (struct rx_ackPacket *)rx_DataOf(p);
5563 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5564 ap->reason = reason;
5566 /* The skew computation used to be bogus, I think it's better now. */
5567 /* We should start paying attention to skew. XXX */
5568 ap->serial = htonl(serial);
5569 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5572 * First packet not yet forwarded to reader. When ACKALL has been
5573 * sent the peer has been told that all received packets will be
5574 * delivered to the reader. The value 'rnext' is used internally
5575 * to refer to the next packet in the receive queue that must be
5576 * delivered to the reader. From the perspective of the peer it
5577 * already has so report the last sequence number plus one if there
5578 * are packets in the receive queue awaiting processing.
5580 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5581 !queue_IsEmpty(&call->rq)) {
5582 ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5584 ap->firstPacket = htonl(call->rnext);
5586 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5588 /* No fear of running out of ack packet here because there can only be at most
5589 * one window full of unacknowledged packets. The window size must be constrained
5590 * to be less than the maximum ack size, of course. Also, an ack should always
5591 * fit into a single packet -- it should not ever be fragmented. */
5592 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5593 if (!rqp || !call->rq.next
5594 || (rqp->header.seq > (call->rnext + call->rwind))) {
5595 #ifndef RX_ENABLE_TSFPQ
5596 if (!optionalPacket)
5599 rxi_CallError(call, RX_CALL_DEAD);
5600 return optionalPacket;
5603 while (rqp->header.seq > call->rnext + offset)
5604 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5605 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5607 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5608 #ifndef RX_ENABLE_TSFPQ
5609 if (!optionalPacket)
5612 rxi_CallError(call, RX_CALL_DEAD);
5613 return optionalPacket;
5619 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5621 /* these are new for AFS 3.3 */
5622 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5623 templ = htonl(templ);
5624 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5625 templ = htonl(call->conn->peer->ifMTU);
5626 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5627 sizeof(afs_int32), &templ);
5629 /* new for AFS 3.4 */
5630 templ = htonl(call->rwind);
5631 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5632 sizeof(afs_int32), &templ);
5634 /* new for AFS 3.5 */
5635 templ = htonl(call->conn->peer->ifDgramPackets);
5636 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5637 sizeof(afs_int32), &templ);
5639 p->header.serviceId = call->conn->serviceId;
5640 p->header.cid = (call->conn->cid | call->channel);
5641 p->header.callNumber = *call->callNumber;
5643 p->header.securityIndex = call->conn->securityIndex;
5644 p->header.epoch = call->conn->epoch;
5645 p->header.type = RX_PACKET_TYPE_ACK;
5646 p->header.flags = RX_SLOW_START_OK;
5647 if (reason == RX_ACK_PING) {
5648 p->header.flags |= RX_REQUEST_ACK;
5650 p->length = padbytes +
5651 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5654 /* not fast but we can potentially use this if truncated
5655 * fragments are delivered to figure out the mtu.
5657 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5658 sizeof(afs_int32), sizeof(afs_int32),
5662 if (call->conn->type == RX_CLIENT_CONNECTION)
5663 p->header.flags |= RX_CLIENT_INITIATED;
5667 if (rxdebug_active) {
5671 len = _snprintf(msg, sizeof(msg),
5672 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5673 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5674 ntohl(ap->serial), ntohl(ap->previousPacket),
5675 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5676 ap->nAcks, ntohs(ap->bufferSpace) );
5680 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5681 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5685 OutputDebugString(msg);
5687 #else /* AFS_NT40_ENV */
5689 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5690 ap->reason, ntohl(ap->previousPacket),
5691 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5693 for (offset = 0; offset < ap->nAcks; offset++)
5694 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5699 #endif /* AFS_NT40_ENV */
5702 int i, nbytes = p->length;
5704 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5705 if (nbytes <= p->wirevec[i].iov_len) {
5708 savelen = p->wirevec[i].iov_len;
5710 p->wirevec[i].iov_len = nbytes;
5712 rxi_Send(call, p, istack);
5713 p->wirevec[i].iov_len = savelen;
5717 nbytes -= p->wirevec[i].iov_len;
5720 if (rx_stats_active)
5721 rx_atomic_inc(&rx_stats.ackPacketsSent);
5722 #ifndef RX_ENABLE_TSFPQ
5723 if (!optionalPacket)
5726 return optionalPacket; /* Return packet for re-use by caller */
5730 struct rx_packet **list;
5735 /* Send all of the packets in the list in single datagram */
5737 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5738 int istack, int moreFlag)
5744 struct rx_connection *conn = call->conn;
5745 struct rx_peer *peer = conn->peer;
5747 MUTEX_ENTER(&peer->peer_lock);
5748 peer->nSent += xmit->len;
5749 if (xmit->resending)
5750 peer->reSends += xmit->len;
5751 MUTEX_EXIT(&peer->peer_lock);
5753 if (rx_stats_active) {
5754 if (xmit->resending)
5755 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5757 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5760 clock_GetTime(&now);
5762 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5766 /* Set the packet flags and schedule the resend events */
5767 /* Only request an ack for the last packet in the list */
5768 for (i = 0; i < xmit->len; i++) {
5769 struct rx_packet *packet = xmit->list[i];
5771 /* Record the time sent */
5772 packet->timeSent = now;
5773 packet->flags |= RX_PKTFLAG_SENT;
5775 /* Ask for an ack on retransmitted packets, on every other packet
5776 * if the peer doesn't support slow start. Ask for an ack on every
5777 * packet until the congestion window reaches the ack rate. */
5778 if (packet->header.serial) {
5781 packet->firstSent = now;
5782 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5783 || (!(call->flags & RX_CALL_SLOW_START_OK)
5784 && (packet->header.seq & 1)))) {
5789 /* Tag this packet as not being the last in this group,
5790 * for the receiver's benefit */
5791 if (i < xmit->len - 1 || moreFlag) {
5792 packet->header.flags |= RX_MORE_PACKETS;
5797 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5800 /* Since we're about to send a data packet to the peer, it's
5801 * safe to nuke any scheduled end-of-packets ack */
5802 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5804 MUTEX_EXIT(&call->lock);
5805 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5806 if (xmit->len > 1) {
5807 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5809 rxi_SendPacket(call, conn, xmit->list[0], istack);
5811 MUTEX_ENTER(&call->lock);
5812 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5814 /* Tell the RTO calculation engine that we have sent a packet, and
5815 * if it was the last one */
5816 rxi_rto_packet_sent(call, lastPacket, istack);
5818 /* Update last send time for this call (for keep-alive
5819 * processing), and for the connection (so that we can discover
5820 * idle connections) */
5821 conn->lastSendTime = call->lastSendTime = clock_Sec();
5822 /* Let a set of retransmits trigger an idle timeout */
5823 if (!xmit->resending)
5824 call->lastSendData = call->lastSendTime;
5827 /* When sending packets we need to follow these rules:
5828 * 1. Never send more than maxDgramPackets in a jumbogram.
5829 * 2. Never send a packet with more than two iovecs in a jumbogram.
5830 * 3. Never send a retransmitted packet in a jumbogram.
5831 * 4. Never send more than cwind/4 packets in a jumbogram
5832 * We always keep the last list we should have sent so we
5833 * can set the RX_MORE_PACKETS flags correctly.
5837 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5842 struct xmitlist working;
5843 struct xmitlist last;
5845 struct rx_peer *peer = call->conn->peer;
5846 int morePackets = 0;
5848 memset(&last, 0, sizeof(struct xmitlist));
5849 working.list = &list[0];
5851 working.resending = 0;
5853 recovery = call->flags & RX_CALL_FAST_RECOVER;
5855 for (i = 0; i < len; i++) {
5856 /* Does the current packet force us to flush the current list? */
5858 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5859 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5861 /* This sends the 'last' list and then rolls the current working
5862 * set into the 'last' one, and resets the working set */
5865 rxi_SendList(call, &last, istack, 1);
5866 /* If the call enters an error state stop sending, or if
5867 * we entered congestion recovery mode, stop sending */
5869 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5874 working.resending = 0;
5875 working.list = &list[i];
5877 /* Add the current packet to the list if it hasn't been acked.
5878 * Otherwise adjust the list pointer to skip the current packet. */
5879 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5882 if (list[i]->header.serial)
5883 working.resending = 1;
5885 /* Do we need to flush the list? */
5886 if (working.len >= (int)peer->maxDgramPackets
5887 || working.len >= (int)call->nDgramPackets
5888 || working.len >= (int)call->cwind
5889 || list[i]->header.serial
5890 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5892 rxi_SendList(call, &last, istack, 1);
5893 /* If the call enters an error state stop sending, or if
5894 * we entered congestion recovery mode, stop sending */
5896 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5901 working.resending = 0;
5902 working.list = &list[i + 1];
5905 if (working.len != 0) {
5906 osi_Panic("rxi_SendList error");
5908 working.list = &list[i + 1];
5912 /* Send the whole list when the call is in receive mode, when
5913 * the call is in eof mode, when we are in fast recovery mode,
5914 * and when we have the last packet */
5915 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5916 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5917 || (call->flags & RX_CALL_FAST_RECOVER)) {
5918 /* Check for the case where the current list contains
5919 * an acked packet. Since we always send retransmissions
5920 * in a separate packet, we only need to check the first
5921 * packet in the list */
5922 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5926 rxi_SendList(call, &last, istack, morePackets);
5927 /* If the call enters an error state stop sending, or if
5928 * we entered congestion recovery mode, stop sending */
5930 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5934 rxi_SendList(call, &working, istack, 0);
5936 } else if (last.len > 0) {
5937 rxi_SendList(call, &last, istack, 0);
5938 /* Packets which are in 'working' are not sent by this call */
5943 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5945 struct rx_call *call = arg0;
5946 struct rx_peer *peer;
5947 struct rx_packet *p, *nxp;
5948 struct clock maxTimeout = { 60, 0 };
5950 MUTEX_ENTER(&call->lock);
5952 peer = call->conn->peer;
5954 /* Make sure that the event pointer is removed from the call
5955 * structure, since there is no longer a per-call retransmission
5957 if (event == call->resendEvent) {
5958 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5959 rxevent_Put(call->resendEvent);
5960 call->resendEvent = NULL;
5963 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5964 rxi_CheckBusy(call);
5967 if (queue_IsEmpty(&call->tq)) {
5968 /* Nothing to do. This means that we've been raced, and that an
5969 * ACK has come in between when we were triggered, and when we
5970 * actually got to run. */
5974 /* We're in loss recovery */
5975 call->flags |= RX_CALL_FAST_RECOVER;
5977 /* Mark all of the pending packets in the queue as being lost */
5978 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5979 if (!(p->flags & RX_PKTFLAG_ACKED))
5980 p->flags &= ~RX_PKTFLAG_SENT;
5983 /* We're resending, so we double the timeout of the call. This will be
5984 * dropped back down by the first successful ACK that we receive.
5986 * We apply a maximum value here of 60 seconds
5988 clock_Add(&call->rto, &call->rto);
5989 if (clock_Gt(&call->rto, &maxTimeout))
5990 call->rto = maxTimeout;
5992 /* Packet loss is most likely due to congestion, so drop our window size
5993 * and start again from the beginning */
5994 if (peer->maxDgramPackets >1) {
5995 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5996 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5998 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5999 call->nDgramPackets = 1;
6001 call->nextCwind = 1;
6004 MUTEX_ENTER(&peer->peer_lock);
6005 peer->MTU = call->MTU;
6006 peer->cwind = call->cwind;
6007 peer->nDgramPackets = 1;
6009 call->congestSeq = peer->congestSeq;
6010 MUTEX_EXIT(&peer->peer_lock);
6012 rxi_Start(call, istack);
6015 MUTEX_EXIT(&call->lock);
6018 /* This routine is called when new packets are readied for
6019 * transmission and when retransmission may be necessary, or when the
6020 * transmission window or burst count are favourable. This should be
6021 * better optimized for new packets, the usual case, now that we've
6022 * got rid of queues of send packets. XXXXXXXXXXX */
6024 rxi_Start(struct rx_call *call, int istack)
6027 struct rx_packet *p;
6028 struct rx_packet *nxp; /* Next pointer for queue_Scan */
6033 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6034 if (rx_stats_active)
6035 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6040 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
6042 /* Send (or resend) any packets that need it, subject to
6043 * window restrictions and congestion burst control
6044 * restrictions. Ask for an ack on the last packet sent in
6045 * this burst. For now, we're relying upon the window being
6046 * considerably bigger than the largest number of packets that
6047 * are typically sent at once by one initial call to
6048 * rxi_Start. This is probably bogus (perhaps we should ask
6049 * for an ack when we're half way through the current
6050 * window?). Also, for non file transfer applications, this
6051 * may end up asking for an ack for every packet. Bogus. XXXX
6054 * But check whether we're here recursively, and let the other guy
6057 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6058 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6059 call->flags |= RX_CALL_TQ_BUSY;
6061 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6063 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6064 call->flags &= ~RX_CALL_NEED_START;
6065 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6067 maxXmitPackets = MIN(call->twind, call->cwind);
6068 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
6069 #ifdef RX_TRACK_PACKETS
6070 if ((p->flags & RX_PKTFLAG_FREE)
6071 || (!queue_IsEnd(&call->tq, nxp)
6072 && (nxp->flags & RX_PKTFLAG_FREE))
6073 || (p == (struct rx_packet *)&rx_freePacketQueue)
6074 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
6075 osi_Panic("rxi_Start: xmit queue clobbered");
6078 if (p->flags & RX_PKTFLAG_ACKED) {
6079 /* Since we may block, don't trust this */
6080 if (rx_stats_active)
6081 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6082 continue; /* Ignore this packet if it has been acknowledged */
6085 /* Turn off all flags except these ones, which are the same
6086 * on each transmission */
6087 p->header.flags &= RX_PRESET_FLAGS;
6089 if (p->header.seq >=
6090 call->tfirst + MIN((int)call->twind,
6091 (int)(call->nSoftAcked +
6093 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6094 /* Note: if we're waiting for more window space, we can
6095 * still send retransmits; hence we don't return here, but
6096 * break out to schedule a retransmit event */
6097 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6098 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6103 /* Transmit the packet if it needs to be sent. */
6104 if (!(p->flags & RX_PKTFLAG_SENT)) {
6105 if (nXmitPackets == maxXmitPackets) {
6106 rxi_SendXmitList(call, call->xmitList,
6107 nXmitPackets, istack);
6110 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6111 *(call->callNumber), p));
6112 call->xmitList[nXmitPackets++] = p;
6116 /* xmitList now hold pointers to all of the packets that are
6117 * ready to send. Now we loop to send the packets */
6118 if (nXmitPackets > 0) {
6119 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6123 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6125 /* We went into the error state while sending packets. Now is
6126 * the time to reset the call. This will also inform the using
6127 * process that the call is in an error state.
6129 if (rx_stats_active)
6130 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6131 call->flags &= ~RX_CALL_TQ_BUSY;
6132 rxi_WakeUpTransmitQueue(call);
6133 rxi_CallError(call, call->error);
6136 #ifdef RX_ENABLE_LOCKS
6137 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6139 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6140 /* Some packets have received acks. If they all have, we can clear
6141 * the transmit queue.
6144 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6145 if (p->header.seq < call->tfirst
6146 && (p->flags & RX_PKTFLAG_ACKED)) {
6148 #ifdef RX_TRACK_PACKETS
6149 p->flags &= ~RX_PKTFLAG_TQ;
6151 #ifdef RXDEBUG_PACKET
6159 call->flags |= RX_CALL_TQ_CLEARME;
6161 #endif /* RX_ENABLE_LOCKS */
6162 if (call->flags & RX_CALL_TQ_CLEARME)
6163 rxi_ClearTransmitQueue(call, 1);
6164 } while (call->flags & RX_CALL_NEED_START);
6166 * TQ references no longer protected by this flag; they must remain
6167 * protected by the global lock.
6169 call->flags &= ~RX_CALL_TQ_BUSY;
6170 rxi_WakeUpTransmitQueue(call);
6172 call->flags |= RX_CALL_NEED_START;
6174 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6176 rxi_rto_cancel(call);
6180 /* Also adjusts the keep alive parameters for the call, to reflect
6181 * that we have just sent a packet (so keep alives aren't sent
6184 rxi_Send(struct rx_call *call, struct rx_packet *p,
6187 struct rx_connection *conn = call->conn;
6189 /* Stamp each packet with the user supplied status */
6190 p->header.userStatus = call->localStatus;
6192 /* Allow the security object controlling this call's security to
6193 * make any last-minute changes to the packet */
6194 RXS_SendPacket(conn->securityObject, call, p);
6196 /* Since we're about to send SOME sort of packet to the peer, it's
6197 * safe to nuke any scheduled end-of-packets ack */
6198 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6200 /* Actually send the packet, filling in more connection-specific fields */
6201 MUTEX_EXIT(&call->lock);
6202 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6203 rxi_SendPacket(call, conn, p, istack);
6204 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6205 MUTEX_ENTER(&call->lock);
6207 /* Update last send time for this call (for keep-alive
6208 * processing), and for the connection (so that we can discover
6209 * idle connections) */
6210 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6211 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6212 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6214 conn->lastSendTime = call->lastSendTime = clock_Sec();
6215 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6216 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6217 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6218 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6219 RX_ACK_PING_RESPONSE)))
6220 call->lastSendData = call->lastSendTime;
6224 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6225 * that things are fine. Also called periodically to guarantee that nothing
6226 * falls through the cracks (e.g. (error + dally) connections have keepalive
6227 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6229 * haveCTLock Set if calling from rxi_ReapConnections
6231 #ifdef RX_ENABLE_LOCKS
6233 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6234 #else /* RX_ENABLE_LOCKS */
6236 rxi_CheckCall(struct rx_call *call)
6237 #endif /* RX_ENABLE_LOCKS */
6239 struct rx_connection *conn = call->conn;
6241 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6242 afs_uint32 fudgeFactor;
6245 int idle_timeout = 0;
6246 afs_int32 clock_diff = 0;
6248 #ifdef AFS_RXERRQ_ENV
6249 int peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6250 if (call->neterr_gen < peererrs) {
6251 /* we have received network errors since this call started; kill
6253 if (call->state == RX_STATE_ACTIVE) {
6254 rxi_CallError(call, RX_CALL_DEAD);
6258 if (call->neterr_gen > peererrs) {
6259 /* someone has reset the number of peer errors; set the call error gen
6260 * so we can detect if more errors are encountered */
6261 call->neterr_gen = peererrs;
6267 /* Large swings in the clock can have a significant impact on
6268 * the performance of RX call processing. Forward clock shifts
6269 * will result in premature event triggering or timeouts.
6270 * Backward shifts can result in calls not completing until
6271 * the clock catches up with the original start clock value.
6273 * If a backward clock shift of more than five minutes is noticed,
6274 * just fail the call.
6276 if (now < call->lastSendTime)
6277 clock_diff = call->lastSendTime - now;
6278 if (now < call->startWait)
6279 clock_diff = MAX(clock_diff, call->startWait - now);
6280 if (now < call->lastReceiveTime)
6281 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6282 if (clock_diff > 5 * 60)
6284 if (call->state == RX_STATE_ACTIVE)
6285 rxi_CallError(call, RX_CALL_TIMEOUT);
6289 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6290 if (call->flags & RX_CALL_TQ_BUSY) {
6291 /* Call is active and will be reset by rxi_Start if it's
6292 * in an error state.
6297 /* RTT + 8*MDEV, rounded up to the next second. */
6298 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6299 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6301 deadTime = conn->secondsUntilDead + fudgeFactor;
6302 /* These are computed to the second (+- 1 second). But that's
6303 * good enough for these values, which should be a significant
6304 * number of seconds. */
6305 if (now > (call->lastReceiveTime + deadTime)) {
6306 if (call->state == RX_STATE_ACTIVE) {
6307 #ifdef AFS_ADAPT_PMTU
6308 # if defined(KERNEL) && defined(AFS_SUN5_ENV)
6310 # if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6311 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6312 ip_stack_t *ipst = ns->netstack_ip;
6314 ire = ire_cache_lookup(conn->peer->host
6315 # if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6317 # if defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID)
6319 # if defined(GLOBAL_NETSTACKID)
6326 if (ire && ire->ire_max_frag > 0)
6327 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6329 # if defined(GLOBAL_NETSTACKID)
6333 #endif /* AFS_ADAPT_PMTU */
6334 cerror = RX_CALL_DEAD;
6337 #ifdef RX_ENABLE_LOCKS
6338 /* Cancel pending events */
6339 rxevent_Cancel(&call->delayedAckEvent, call,
6340 RX_CALL_REFCOUNT_DELAY);
6341 rxi_rto_cancel(call);
6342 rxevent_Cancel(&call->keepAliveEvent, call,
6343 RX_CALL_REFCOUNT_ALIVE);
6344 rxevent_Cancel(&call->growMTUEvent, call,
6345 RX_CALL_REFCOUNT_MTU);
6346 MUTEX_ENTER(&rx_refcnt_mutex);
6347 /* if rxi_FreeCall returns 1 it has freed the call */
6348 if (call->refCount == 0 &&
6349 rxi_FreeCall(call, haveCTLock))
6351 MUTEX_EXIT(&rx_refcnt_mutex);
6354 MUTEX_EXIT(&rx_refcnt_mutex);
6356 #else /* RX_ENABLE_LOCKS */
6357 rxi_FreeCall(call, 0);
6359 #endif /* RX_ENABLE_LOCKS */
6361 /* Non-active calls are destroyed if they are not responding
6362 * to pings; active calls are simply flagged in error, so the
6363 * attached process can die reasonably gracefully. */
6366 if (conn->idleDeadDetection) {
6367 if (conn->idleDeadTime) {
6368 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6372 /* see if we have a non-activity timeout */
6373 if (call->startWait && ((call->startWait + idleDeadTime) < now) &&
6374 (call->flags & RX_CALL_READER_WAIT)) {
6375 if (call->state == RX_STATE_ACTIVE) {
6376 cerror = RX_CALL_TIMEOUT;
6381 if (call->lastSendData && ((call->lastSendData + idleDeadTime) < now)) {
6382 if (call->state == RX_STATE_ACTIVE) {
6383 cerror = conn->service ? conn->service->idleDeadErr : RX_CALL_IDLE;
6391 if (conn->hardDeadTime) {
6392 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6395 /* see if we have a hard timeout */
6397 && (now > (hardDeadTime + call->startTime.sec))) {
6398 if (call->state == RX_STATE_ACTIVE)
6399 rxi_CallError(call, RX_CALL_TIMEOUT);
6404 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6405 call->lastReceiveTime) {
6406 int oldMTU = conn->peer->ifMTU;
6408 /* if we thought we could send more, perhaps things got worse */
6409 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6410 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6411 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6412 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6414 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6416 /* minimum capped in SetPeerMtu */
6417 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6420 conn->lastPacketSize = 0;
6422 /* needed so ResetCall doesn't clobber us. */
6423 call->MTU = conn->peer->ifMTU;
6425 /* if we never succeeded, let the error pass out as-is */
6426 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6427 cerror = conn->msgsizeRetryErr;
6430 rxi_CallError(call, cerror);
6435 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6436 void *dummy, int dummy2)
6438 struct rx_connection *conn = arg1;
6439 struct rx_header theader;
6440 char tbuffer[1 + sizeof(struct rx_header)];
6441 struct sockaddr_in taddr;
6444 struct iovec tmpiov[2];
6447 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6450 tp = &tbuffer[sizeof(struct rx_header)];
6451 taddr.sin_family = AF_INET;
6452 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6453 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6454 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6455 taddr.sin_len = sizeof(struct sockaddr_in);
6457 memset(&theader, 0, sizeof(theader));
6458 theader.epoch = htonl(999);
6460 theader.callNumber = 0;
6463 theader.type = RX_PACKET_TYPE_VERSION;
6464 theader.flags = RX_LAST_PACKET;
6465 theader.serviceId = 0;
6467 memcpy(tbuffer, &theader, sizeof(theader));
6468 memcpy(tp, &a, sizeof(a));
6469 tmpiov[0].iov_base = tbuffer;
6470 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6472 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6474 MUTEX_ENTER(&conn->conn_data_lock);
6475 MUTEX_ENTER(&rx_refcnt_mutex);
6476 /* Only reschedule ourselves if the connection would not be destroyed */
6477 if (conn->refCount <= 1) {
6478 rxevent_Put(conn->natKeepAliveEvent);
6479 conn->natKeepAliveEvent = NULL;
6480 MUTEX_EXIT(&rx_refcnt_mutex);
6481 MUTEX_EXIT(&conn->conn_data_lock);
6482 rx_DestroyConnection(conn); /* drop the reference for this */
6484 conn->refCount--; /* drop the reference for this */
6485 MUTEX_EXIT(&rx_refcnt_mutex);
6486 rxevent_Put(conn->natKeepAliveEvent);
6487 conn->natKeepAliveEvent = NULL;
6488 rxi_ScheduleNatKeepAliveEvent(conn);
6489 MUTEX_EXIT(&conn->conn_data_lock);
6494 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6496 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6497 struct clock when, now;
6498 clock_GetTime(&now);
6500 when.sec += conn->secondsUntilNatPing;
6501 MUTEX_ENTER(&rx_refcnt_mutex);
6502 conn->refCount++; /* hold a reference for this */
6503 MUTEX_EXIT(&rx_refcnt_mutex);
6504 conn->natKeepAliveEvent =
6505 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6510 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6512 MUTEX_ENTER(&conn->conn_data_lock);
6513 conn->secondsUntilNatPing = seconds;
6515 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6516 rxi_ScheduleNatKeepAliveEvent(conn);
6518 conn->flags |= RX_CONN_NAT_PING;
6520 MUTEX_EXIT(&conn->conn_data_lock);
6523 /* When a call is in progress, this routine is called occasionally to
6524 * make sure that some traffic has arrived (or been sent to) the peer.
6525 * If nothing has arrived in a reasonable amount of time, the call is
6526 * declared dead; if nothing has been sent for a while, we send a
6527 * keep-alive packet (if we're actually trying to keep the call alive)
6530 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6533 struct rx_call *call = arg1;
6534 struct rx_connection *conn;
6537 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6538 MUTEX_ENTER(&call->lock);
6540 if (event == call->keepAliveEvent) {
6541 rxevent_Put(call->keepAliveEvent);
6542 call->keepAliveEvent = NULL;
6547 #ifdef RX_ENABLE_LOCKS
6548 if (rxi_CheckCall(call, 0)) {
6549 MUTEX_EXIT(&call->lock);
6552 #else /* RX_ENABLE_LOCKS */
6553 if (rxi_CheckCall(call))
6555 #endif /* RX_ENABLE_LOCKS */
6557 /* Don't try to keep alive dallying calls */
6558 if (call->state == RX_STATE_DALLY) {
6559 MUTEX_EXIT(&call->lock);
6564 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6565 /* Don't try to send keepalives if there is unacknowledged data */
6566 /* the rexmit code should be good enough, this little hack
6567 * doesn't quite work XXX */
6568 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6570 rxi_ScheduleKeepAliveEvent(call);
6571 MUTEX_EXIT(&call->lock);
6574 /* Does what's on the nameplate. */
6576 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6578 struct rx_call *call = arg1;
6579 struct rx_connection *conn;
6581 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6582 MUTEX_ENTER(&call->lock);
6584 if (event == call->growMTUEvent) {
6585 rxevent_Put(call->growMTUEvent);
6586 call->growMTUEvent = NULL;
6589 #ifdef RX_ENABLE_LOCKS
6590 if (rxi_CheckCall(call, 0)) {
6591 MUTEX_EXIT(&call->lock);
6594 #else /* RX_ENABLE_LOCKS */
6595 if (rxi_CheckCall(call))
6597 #endif /* RX_ENABLE_LOCKS */
6599 /* Don't bother with dallying calls */
6600 if (call->state == RX_STATE_DALLY) {
6601 MUTEX_EXIT(&call->lock);
6608 * keep being scheduled, just don't do anything if we're at peak,
6609 * or we're not set up to be properly handled (idle timeout required)
6611 if ((conn->peer->maxPacketSize != 0) &&
6612 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6613 conn->idleDeadDetection)
6614 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6615 rxi_ScheduleGrowMTUEvent(call, 0);
6616 MUTEX_EXIT(&call->lock);
6620 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6622 if (!call->keepAliveEvent) {
6623 struct clock when, now;
6624 clock_GetTime(&now);
6626 when.sec += call->conn->secondsUntilPing;
6627 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6628 call->keepAliveEvent =
6629 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6634 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6636 if (!call->growMTUEvent) {
6637 struct clock when, now;
6639 clock_GetTime(&now);
6642 if (call->conn->secondsUntilPing)
6643 secs = (6*call->conn->secondsUntilPing)-1;
6645 if (call->conn->secondsUntilDead)
6646 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6650 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6651 call->growMTUEvent =
6652 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6656 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6658 rxi_KeepAliveOn(struct rx_call *call)
6660 /* Pretend last packet received was received now--i.e. if another
6661 * packet isn't received within the keep alive time, then the call
6662 * will die; Initialize last send time to the current time--even
6663 * if a packet hasn't been sent yet. This will guarantee that a
6664 * keep-alive is sent within the ping time */
6665 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6666 rxi_ScheduleKeepAliveEvent(call);
6670 * Solely in order that callers not need to include rx_call.h
6673 rx_KeepAliveOff(struct rx_call *call)
6675 rxi_KeepAliveOff(call);
6678 rx_KeepAliveOn(struct rx_call *call)
6680 rxi_KeepAliveOn(call);
6684 rxi_GrowMTUOn(struct rx_call *call)
6686 struct rx_connection *conn = call->conn;
6687 MUTEX_ENTER(&conn->conn_data_lock);
6688 conn->lastPingSizeSer = conn->lastPingSize = 0;
6689 MUTEX_EXIT(&conn->conn_data_lock);
6690 rxi_ScheduleGrowMTUEvent(call, 1);
6693 /* This routine is called to send connection abort messages
6694 * that have been delayed to throttle looping clients. */
6696 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6699 struct rx_connection *conn = arg1;
6702 struct rx_packet *packet;
6704 MUTEX_ENTER(&conn->conn_data_lock);
6705 rxevent_Put(conn->delayedAbortEvent);
6706 conn->delayedAbortEvent = NULL;
6707 error = htonl(conn->error);
6709 MUTEX_EXIT(&conn->conn_data_lock);
6710 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6713 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6714 RX_PACKET_TYPE_ABORT, (char *)&error,
6716 rxi_FreePacket(packet);
6720 /* This routine is called to send call abort messages
6721 * that have been delayed to throttle looping clients. */
6723 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6726 struct rx_call *call = arg1;
6729 struct rx_packet *packet;
6731 MUTEX_ENTER(&call->lock);
6732 rxevent_Put(call->delayedAbortEvent);
6733 call->delayedAbortEvent = NULL;
6734 error = htonl(call->error);
6736 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6739 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6740 (char *)&error, sizeof(error), 0);
6741 rxi_FreePacket(packet);
6743 MUTEX_EXIT(&call->lock);
6744 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6747 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6748 * seconds) to ask the client to authenticate itself. The routine
6749 * issues a challenge to the client, which is obtained from the
6750 * security object associated with the connection */
6752 rxi_ChallengeEvent(struct rxevent *event,
6753 void *arg0, void *arg1, int tries)
6755 struct rx_connection *conn = arg0;
6758 rxevent_Put(conn->challengeEvent);
6759 conn->challengeEvent = NULL;
6762 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6763 struct rx_packet *packet;
6764 struct clock when, now;
6767 /* We've failed to authenticate for too long.
6768 * Reset any calls waiting for authentication;
6769 * they are all in RX_STATE_PRECALL.
6773 MUTEX_ENTER(&conn->conn_call_lock);
6774 for (i = 0; i < RX_MAXCALLS; i++) {
6775 struct rx_call *call = conn->call[i];
6777 MUTEX_ENTER(&call->lock);
6778 if (call->state == RX_STATE_PRECALL) {
6779 rxi_CallError(call, RX_CALL_DEAD);
6780 rxi_SendCallAbort(call, NULL, 0, 0);
6782 MUTEX_EXIT(&call->lock);
6785 MUTEX_EXIT(&conn->conn_call_lock);
6789 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6791 /* If there's no packet available, do this later. */
6792 RXS_GetChallenge(conn->securityObject, conn, packet);
6793 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6794 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6795 rxi_FreePacket(packet);
6797 clock_GetTime(&now);
6799 when.sec += RX_CHALLENGE_TIMEOUT;
6800 conn->challengeEvent =
6801 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6806 /* Call this routine to start requesting the client to authenticate
6807 * itself. This will continue until authentication is established,
6808 * the call times out, or an invalid response is returned. The
6809 * security object associated with the connection is asked to create
6810 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6811 * defined earlier. */
6813 rxi_ChallengeOn(struct rx_connection *conn)
6815 if (!conn->challengeEvent) {
6816 RXS_CreateChallenge(conn->securityObject, conn);
6817 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6822 /* rxi_ComputeRoundTripTime is called with peer locked. */
6823 /* peer may be null */
6825 rxi_ComputeRoundTripTime(struct rx_packet *p,
6826 struct rx_ackPacket *ack,
6827 struct rx_call *call,
6828 struct rx_peer *peer,
6831 struct clock thisRtt, *sentp;
6835 /* If the ACK is delayed, then do nothing */
6836 if (ack->reason == RX_ACK_DELAY)
6839 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6840 * their RTT multiple times, so only include the RTT of the last packet
6842 if (p->flags & RX_JUMBO_PACKET)
6845 /* Use the serial number to determine which transmission the ACK is for,
6846 * and set the sent time to match this. If we have no serial number, then
6847 * only use the ACK for RTT calculations if the packet has not been
6851 serial = ntohl(ack->serial);
6853 if (serial == p->header.serial) {
6854 sentp = &p->timeSent;
6855 } else if (serial == p->firstSerial) {
6856 sentp = &p->firstSent;
6857 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6858 sentp = &p->firstSent;
6862 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6863 sentp = &p->firstSent;
6870 if (clock_Lt(&thisRtt, sentp))
6871 return; /* somebody set the clock back, don't count this time. */
6873 clock_Sub(&thisRtt, sentp);
6874 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6875 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6877 if (clock_IsZero(&thisRtt)) {
6879 * The actual round trip time is shorter than the
6880 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6881 * Since we can't tell which at the moment we will assume 1ms.
6883 thisRtt.usec = 1000;
6886 if (rx_stats_active) {
6887 MUTEX_ENTER(&rx_stats_mutex);
6888 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6889 rx_stats.minRtt = thisRtt;
6890 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6891 if (thisRtt.sec > 60) {
6892 MUTEX_EXIT(&rx_stats_mutex);
6893 return; /* somebody set the clock ahead */
6895 rx_stats.maxRtt = thisRtt;
6897 clock_Add(&rx_stats.totalRtt, &thisRtt);
6898 rx_atomic_inc(&rx_stats.nRttSamples);
6899 MUTEX_EXIT(&rx_stats_mutex);
6902 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6904 /* Apply VanJacobson round-trip estimations */
6909 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6910 * srtt is stored as fixed point with 3 bits after the binary
6911 * point (i.e., scaled by 8). The following magic is
6912 * equivalent to the smoothing algorithm in rfc793 with an
6913 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6914 * srtt'*8 = rtt + srtt*7
6915 * srtt'*8 = srtt*8 + rtt - srtt
6916 * srtt' = srtt + rtt/8 - srtt/8
6917 * srtt' = srtt + (rtt - srtt)/8
6920 delta = _8THMSEC(&thisRtt) - call->rtt;
6921 call->rtt += (delta >> 3);
6924 * We accumulate a smoothed rtt variance (actually, a smoothed
6925 * mean difference), then set the retransmit timer to smoothed
6926 * rtt + 4 times the smoothed variance (was 2x in van's original
6927 * paper, but 4x works better for me, and apparently for him as
6929 * rttvar is stored as
6930 * fixed point with 2 bits after the binary point (scaled by
6931 * 4). The following is equivalent to rfc793 smoothing with
6932 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6933 * rttvar'*4 = rttvar*3 + |delta|
6934 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6935 * rttvar' = rttvar + |delta|/4 - rttvar/4
6936 * rttvar' = rttvar + (|delta| - rttvar)/4
6937 * This replaces rfc793's wired-in beta.
6938 * dev*4 = dev*4 + (|actual - expected| - dev)
6944 delta -= (call->rtt_dev << 1);
6945 call->rtt_dev += (delta >> 3);
6947 /* I don't have a stored RTT so I start with this value. Since I'm
6948 * probably just starting a call, and will be pushing more data down
6949 * this, I expect congestion to increase rapidly. So I fudge a
6950 * little, and I set deviance to half the rtt. In practice,
6951 * deviance tends to approach something a little less than
6952 * half the smoothed rtt. */
6953 call->rtt = _8THMSEC(&thisRtt) + 8;
6954 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6956 /* the smoothed RTT time is RTT + 4*MDEV
6958 * We allow a user specified minimum to be set for this, to allow clamping
6959 * at a minimum value in the same way as TCP. In addition, we have to allow
6960 * for the possibility that this packet is answered by a delayed ACK, so we
6961 * add on a fixed 200ms to account for that timer expiring.
6964 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6965 rx_minPeerTimeout) + 200;
6966 clock_Zero(&call->rto);
6967 clock_Addmsec(&call->rto, rtt_timeout);
6969 /* Update the peer, so any new calls start with our values */
6970 peer->rtt_dev = call->rtt_dev;
6971 peer->rtt = call->rtt;
6973 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6974 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6978 /* Find all server connections that have not been active for a long time, and
6981 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6984 struct clock now, when;
6985 clock_GetTime(&now);
6987 /* Find server connection structures that haven't been used for
6988 * greater than rx_idleConnectionTime */
6990 struct rx_connection **conn_ptr, **conn_end;
6991 int i, havecalls = 0;
6992 MUTEX_ENTER(&rx_connHashTable_lock);
6993 for (conn_ptr = &rx_connHashTable[0], conn_end =
6994 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6996 struct rx_connection *conn, *next;
6997 struct rx_call *call;
7001 for (conn = *conn_ptr; conn; conn = next) {
7002 /* XXX -- Shouldn't the connection be locked? */
7005 for (i = 0; i < RX_MAXCALLS; i++) {
7006 call = conn->call[i];
7010 code = MUTEX_TRYENTER(&call->lock);
7013 #ifdef RX_ENABLE_LOCKS
7014 result = rxi_CheckCall(call, 1);
7015 #else /* RX_ENABLE_LOCKS */
7016 result = rxi_CheckCall(call);
7017 #endif /* RX_ENABLE_LOCKS */
7018 MUTEX_EXIT(&call->lock);
7020 /* If CheckCall freed the call, it might
7021 * have destroyed the connection as well,
7022 * which screws up the linked lists.
7028 if (conn->type == RX_SERVER_CONNECTION) {
7029 /* This only actually destroys the connection if
7030 * there are no outstanding calls */
7031 MUTEX_ENTER(&conn->conn_data_lock);
7032 MUTEX_ENTER(&rx_refcnt_mutex);
7033 if (!havecalls && !conn->refCount
7034 && ((conn->lastSendTime + rx_idleConnectionTime) <
7036 conn->refCount++; /* it will be decr in rx_DestroyConn */
7037 MUTEX_EXIT(&rx_refcnt_mutex);
7038 MUTEX_EXIT(&conn->conn_data_lock);
7039 #ifdef RX_ENABLE_LOCKS
7040 rxi_DestroyConnectionNoLock(conn);
7041 #else /* RX_ENABLE_LOCKS */
7042 rxi_DestroyConnection(conn);
7043 #endif /* RX_ENABLE_LOCKS */
7045 #ifdef RX_ENABLE_LOCKS
7047 MUTEX_EXIT(&rx_refcnt_mutex);
7048 MUTEX_EXIT(&conn->conn_data_lock);
7050 #endif /* RX_ENABLE_LOCKS */
7054 #ifdef RX_ENABLE_LOCKS
7055 while (rx_connCleanup_list) {
7056 struct rx_connection *conn;
7057 conn = rx_connCleanup_list;
7058 rx_connCleanup_list = rx_connCleanup_list->next;
7059 MUTEX_EXIT(&rx_connHashTable_lock);
7060 rxi_CleanupConnection(conn);
7061 MUTEX_ENTER(&rx_connHashTable_lock);
7063 MUTEX_EXIT(&rx_connHashTable_lock);
7064 #endif /* RX_ENABLE_LOCKS */
7067 /* Find any peer structures that haven't been used (haven't had an
7068 * associated connection) for greater than rx_idlePeerTime */
7070 struct rx_peer **peer_ptr, **peer_end;
7074 * Why do we need to hold the rx_peerHashTable_lock across
7075 * the incrementing of peer_ptr since the rx_peerHashTable
7076 * array is not changing? We don't.
7078 * By dropping the lock periodically we can permit other
7079 * activities to be performed while a rxi_ReapConnections
7080 * call is in progress. The goal of reap connections
7081 * is to clean up quickly without causing large amounts
7082 * of contention. Therefore, it is important that global
7083 * mutexes not be held for extended periods of time.
7085 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7086 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7088 struct rx_peer *peer, *next, *prev;
7090 MUTEX_ENTER(&rx_peerHashTable_lock);
7091 for (prev = peer = *peer_ptr; peer; peer = next) {
7093 code = MUTEX_TRYENTER(&peer->peer_lock);
7094 if ((code) && (peer->refCount == 0)
7095 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7096 rx_interface_stat_p rpc_stat, nrpc_stat;
7100 * now know that this peer object is one to be
7101 * removed from the hash table. Once it is removed
7102 * it can't be referenced by other threads.
7103 * Lets remove it first and decrement the struct
7104 * nPeerStructs count.
7106 if (peer == *peer_ptr) {
7112 if (rx_stats_active)
7113 rx_atomic_dec(&rx_stats.nPeerStructs);
7116 * Now if we hold references on 'prev' and 'next'
7117 * we can safely drop the rx_peerHashTable_lock
7118 * while we destroy this 'peer' object.
7124 MUTEX_EXIT(&rx_peerHashTable_lock);
7126 MUTEX_EXIT(&peer->peer_lock);
7127 MUTEX_DESTROY(&peer->peer_lock);
7129 (&peer->rpcStats, rpc_stat, nrpc_stat,
7130 rx_interface_stat)) {
7131 unsigned int num_funcs;
7134 queue_Remove(&rpc_stat->queue_header);
7135 queue_Remove(&rpc_stat->all_peers);
7136 num_funcs = rpc_stat->stats[0].func_total;
7138 sizeof(rx_interface_stat_t) +
7139 rpc_stat->stats[0].func_total *
7140 sizeof(rx_function_entry_v1_t);
7142 rxi_Free(rpc_stat, space);
7144 MUTEX_ENTER(&rx_rpc_stats);
7145 rxi_rpc_peer_stat_cnt -= num_funcs;
7146 MUTEX_EXIT(&rx_rpc_stats);
7151 * Regain the rx_peerHashTable_lock and
7152 * decrement the reference count on 'prev'
7155 MUTEX_ENTER(&rx_peerHashTable_lock);
7162 MUTEX_EXIT(&peer->peer_lock);
7167 MUTEX_EXIT(&rx_peerHashTable_lock);
7171 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7172 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7173 * GC, just below. Really, we shouldn't have to keep moving packets from
7174 * one place to another, but instead ought to always know if we can
7175 * afford to hold onto a packet in its particular use. */
7176 MUTEX_ENTER(&rx_freePktQ_lock);
7177 if (rx_waitingForPackets) {
7178 rx_waitingForPackets = 0;
7179 #ifdef RX_ENABLE_LOCKS
7180 CV_BROADCAST(&rx_waitingForPackets_cv);
7182 osi_rxWakeup(&rx_waitingForPackets);
7185 MUTEX_EXIT(&rx_freePktQ_lock);
7188 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7189 rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7193 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7194 * rx.h is sort of strange this is better. This is called with a security
7195 * object before it is discarded. Each connection using a security object has
7196 * its own refcount to the object so it won't actually be freed until the last
7197 * connection is destroyed.
7199 * This is the only rxs module call. A hold could also be written but no one
7203 rxs_Release(struct rx_securityClass *aobj)
7205 return RXS_Close(aobj);
7213 #define TRACE_OPTION_RX_DEBUG 16
7221 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7222 0, KEY_QUERY_VALUE, &parmKey);
7223 if (code != ERROR_SUCCESS)
7226 dummyLen = sizeof(TraceOption);
7227 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7228 (BYTE *) &TraceOption, &dummyLen);
7229 if (code == ERROR_SUCCESS) {
7230 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7232 RegCloseKey (parmKey);
7233 #endif /* AFS_NT40_ENV */
7238 rx_DebugOnOff(int on)
7242 rxdebug_active = on;
7248 rx_StatsOnOff(int on)
7250 rx_stats_active = on;
7254 /* Don't call this debugging routine directly; use dpf */
7256 rxi_DebugPrint(char *format, ...)
7265 va_start(ap, format);
7267 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7270 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7272 OutputDebugString(msg);
7278 va_start(ap, format);
7280 clock_GetTime(&now);
7281 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7282 (unsigned int)now.usec);
7283 vfprintf(rx_Log, format, ap);
7291 * This function is used to process the rx_stats structure that is local
7292 * to a process as well as an rx_stats structure received from a remote
7293 * process (via rxdebug). Therefore, it needs to do minimal version
7297 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7298 afs_int32 freePackets, char version)
7302 if (size != sizeof(struct rx_statistics)) {
7304 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7305 size, sizeof(struct rx_statistics));
7308 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7311 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7312 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7313 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7314 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7315 s->specialPktAllocFailures);
7317 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7318 s->receivePktAllocFailures, s->sendPktAllocFailures,
7319 s->specialPktAllocFailures);
7323 " greedy %u, " "bogusReads %u (last from host %x), "
7324 "noPackets %u, " "noBuffers %u, " "selects %u, "
7325 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7326 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7327 s->selects, s->sendSelects);
7329 fprintf(file, " packets read: ");
7330 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7331 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7333 fprintf(file, "\n");
7336 " other read counters: data %u, " "ack %u, " "dup %u "
7337 "spurious %u " "dally %u\n", s->dataPacketsRead,
7338 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7339 s->ignorePacketDally);
7341 fprintf(file, " packets sent: ");
7342 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7343 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7345 fprintf(file, "\n");
7348 " other send counters: ack %u, " "data %u (not resends), "
7349 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7350 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7351 s->dataPacketsPushed, s->ignoreAckedPacket);
7354 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7355 s->netSendFailures, (int)s->fatalErrors);
7357 if (s->nRttSamples) {
7358 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7359 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7361 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7362 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7366 " %d server connections, " "%d client connections, "
7367 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7368 s->nServerConns, s->nClientConns, s->nPeerStructs,
7369 s->nCallStructs, s->nFreeCallStructs);
7371 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7372 fprintf(file, " %d clock updates\n", clock_nUpdates);
7376 /* for backward compatibility */
7378 rx_PrintStats(FILE * file)
7380 MUTEX_ENTER(&rx_stats_mutex);
7381 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7382 sizeof(rx_stats), rx_nFreePackets,
7384 MUTEX_EXIT(&rx_stats_mutex);
7388 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7390 fprintf(file, "Peer %x.%d.\n",
7391 ntohl(peer->host), (int)ntohs(peer->port));
7394 " Rtt %d, " "total sent %d, " "resent %d\n",
7395 peer->rtt, peer->nSent, peer->reSends);
7397 fprintf(file, " Packet size %d\n", peer->ifMTU);
7401 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7403 * This mutex protects the following static variables:
7407 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7408 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7410 #define LOCK_RX_DEBUG
7411 #define UNLOCK_RX_DEBUG
7412 #endif /* AFS_PTHREAD_ENV */
7414 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7416 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7417 u_char type, void *inputData, size_t inputLength,
7418 void *outputData, size_t outputLength)
7420 static afs_int32 counter = 100;
7421 time_t waitTime, waitCount;
7422 struct rx_header theader;
7425 struct timeval tv_now, tv_wake, tv_delta;
7426 struct sockaddr_in taddr, faddr;
7440 tp = &tbuffer[sizeof(struct rx_header)];
7441 taddr.sin_family = AF_INET;
7442 taddr.sin_port = remotePort;
7443 taddr.sin_addr.s_addr = remoteAddr;
7444 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7445 taddr.sin_len = sizeof(struct sockaddr_in);
7448 memset(&theader, 0, sizeof(theader));
7449 theader.epoch = htonl(999);
7451 theader.callNumber = htonl(counter);
7454 theader.type = type;
7455 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7456 theader.serviceId = 0;
7458 memcpy(tbuffer, &theader, sizeof(theader));
7459 memcpy(tp, inputData, inputLength);
7461 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7462 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7464 /* see if there's a packet available */
7465 gettimeofday(&tv_wake, NULL);
7466 tv_wake.tv_sec += waitTime;
7469 FD_SET(socket, &imask);
7470 tv_delta.tv_sec = tv_wake.tv_sec;
7471 tv_delta.tv_usec = tv_wake.tv_usec;
7472 gettimeofday(&tv_now, NULL);
7474 if (tv_delta.tv_usec < tv_now.tv_usec) {
7476 tv_delta.tv_usec += 1000000;
7479 tv_delta.tv_usec -= tv_now.tv_usec;
7481 if (tv_delta.tv_sec < tv_now.tv_sec) {
7485 tv_delta.tv_sec -= tv_now.tv_sec;
7488 code = select(0, &imask, 0, 0, &tv_delta);
7489 #else /* AFS_NT40_ENV */
7490 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7491 #endif /* AFS_NT40_ENV */
7492 if (code == 1 && FD_ISSET(socket, &imask)) {
7493 /* now receive a packet */
7494 faddrLen = sizeof(struct sockaddr_in);
7496 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7497 (struct sockaddr *)&faddr, &faddrLen);
7500 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7501 if (counter == ntohl(theader.callNumber))
7509 /* see if we've timed out */
7517 code -= sizeof(struct rx_header);
7518 if (code > outputLength)
7519 code = outputLength;
7520 memcpy(outputData, tp, code);
7523 #endif /* RXDEBUG */
7526 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7527 afs_uint16 remotePort, struct rx_debugStats * stat,
7528 afs_uint32 * supportedValues)
7530 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7532 struct rx_debugIn in;
7534 *supportedValues = 0;
7535 in.type = htonl(RX_DEBUGI_GETSTATS);
7538 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7539 &in, sizeof(in), stat, sizeof(*stat));
7542 * If the call was successful, fixup the version and indicate
7543 * what contents of the stat structure are valid.
7544 * Also do net to host conversion of fields here.
7548 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7549 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7551 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7552 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7554 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7555 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7557 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7558 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7560 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7561 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7563 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7564 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7566 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7567 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7569 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7570 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7572 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7573 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7575 stat->nFreePackets = ntohl(stat->nFreePackets);
7576 stat->packetReclaims = ntohl(stat->packetReclaims);
7577 stat->callsExecuted = ntohl(stat->callsExecuted);
7578 stat->nWaiting = ntohl(stat->nWaiting);
7579 stat->idleThreads = ntohl(stat->idleThreads);
7580 stat->nWaited = ntohl(stat->nWaited);
7581 stat->nPackets = ntohl(stat->nPackets);
7590 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7591 afs_uint16 remotePort, struct rx_statistics * stat,
7592 afs_uint32 * supportedValues)
7594 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7596 struct rx_debugIn in;
7597 afs_int32 *lp = (afs_int32 *) stat;
7601 * supportedValues is currently unused, but added to allow future
7602 * versioning of this function.
7605 *supportedValues = 0;
7606 in.type = htonl(RX_DEBUGI_RXSTATS);
7608 memset(stat, 0, sizeof(*stat));
7610 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7611 &in, sizeof(in), stat, sizeof(*stat));
7616 * Do net to host conversion here
7619 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7630 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7631 afs_uint16 remotePort, size_t version_length,
7634 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7636 return MakeDebugCall(socket, remoteAddr, remotePort,
7637 RX_PACKET_TYPE_VERSION, a, 1, version,
7645 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7646 afs_uint16 remotePort, afs_int32 * nextConnection,
7647 int allConnections, afs_uint32 debugSupportedValues,
7648 struct rx_debugConn * conn,
7649 afs_uint32 * supportedValues)
7651 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7653 struct rx_debugIn in;
7657 * supportedValues is currently unused, but added to allow future
7658 * versioning of this function.
7661 *supportedValues = 0;
7662 if (allConnections) {
7663 in.type = htonl(RX_DEBUGI_GETALLCONN);
7665 in.type = htonl(RX_DEBUGI_GETCONN);
7667 in.index = htonl(*nextConnection);
7668 memset(conn, 0, sizeof(*conn));
7670 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7671 &in, sizeof(in), conn, sizeof(*conn));
7674 *nextConnection += 1;
7677 * Convert old connection format to new structure.
7680 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7681 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7682 #define MOVEvL(a) (conn->a = vL->a)
7684 /* any old or unrecognized version... */
7685 for (i = 0; i < RX_MAXCALLS; i++) {
7686 MOVEvL(callState[i]);
7687 MOVEvL(callMode[i]);
7688 MOVEvL(callFlags[i]);
7689 MOVEvL(callOther[i]);
7691 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7692 MOVEvL(secStats.type);
7693 MOVEvL(secStats.level);
7694 MOVEvL(secStats.flags);
7695 MOVEvL(secStats.expires);
7696 MOVEvL(secStats.packetsReceived);
7697 MOVEvL(secStats.packetsSent);
7698 MOVEvL(secStats.bytesReceived);
7699 MOVEvL(secStats.bytesSent);
7704 * Do net to host conversion here
7706 * I don't convert host or port since we are most likely
7707 * going to want these in NBO.
7709 conn->cid = ntohl(conn->cid);
7710 conn->serial = ntohl(conn->serial);
7711 for (i = 0; i < RX_MAXCALLS; i++) {
7712 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7714 conn->error = ntohl(conn->error);
7715 conn->secStats.flags = ntohl(conn->secStats.flags);
7716 conn->secStats.expires = ntohl(conn->secStats.expires);
7717 conn->secStats.packetsReceived =
7718 ntohl(conn->secStats.packetsReceived);
7719 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7720 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7721 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7722 conn->epoch = ntohl(conn->epoch);
7723 conn->natMTU = ntohl(conn->natMTU);
7732 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7733 afs_uint16 remotePort, afs_int32 * nextPeer,
7734 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7735 afs_uint32 * supportedValues)
7737 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7739 struct rx_debugIn in;
7742 * supportedValues is currently unused, but added to allow future
7743 * versioning of this function.
7746 *supportedValues = 0;
7747 in.type = htonl(RX_DEBUGI_GETPEER);
7748 in.index = htonl(*nextPeer);
7749 memset(peer, 0, sizeof(*peer));
7751 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7752 &in, sizeof(in), peer, sizeof(*peer));
7758 * Do net to host conversion here
7760 * I don't convert host or port since we are most likely
7761 * going to want these in NBO.
7763 peer->ifMTU = ntohs(peer->ifMTU);
7764 peer->idleWhen = ntohl(peer->idleWhen);
7765 peer->refCount = ntohs(peer->refCount);
7766 peer->rtt = ntohl(peer->rtt);
7767 peer->rtt_dev = ntohl(peer->rtt_dev);
7768 peer->timeout.sec = 0;
7769 peer->timeout.usec = 0;
7770 peer->nSent = ntohl(peer->nSent);
7771 peer->reSends = ntohl(peer->reSends);
7772 peer->natMTU = ntohs(peer->natMTU);
7773 peer->maxMTU = ntohs(peer->maxMTU);
7774 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7775 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7776 peer->MTU = ntohs(peer->MTU);
7777 peer->cwind = ntohs(peer->cwind);
7778 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7779 peer->congestSeq = ntohs(peer->congestSeq);
7780 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7781 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7782 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7783 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7792 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7793 struct rx_debugPeer * peerStats)
7796 afs_int32 error = 1; /* default to "did not succeed" */
7797 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7799 MUTEX_ENTER(&rx_peerHashTable_lock);
7800 for(tp = rx_peerHashTable[hashValue];
7801 tp != NULL; tp = tp->next) {
7802 if (tp->host == peerHost)
7808 MUTEX_EXIT(&rx_peerHashTable_lock);
7812 MUTEX_ENTER(&tp->peer_lock);
7813 peerStats->host = tp->host;
7814 peerStats->port = tp->port;
7815 peerStats->ifMTU = tp->ifMTU;
7816 peerStats->idleWhen = tp->idleWhen;
7817 peerStats->refCount = tp->refCount;
7818 peerStats->burstSize = 0;
7819 peerStats->burst = 0;
7820 peerStats->burstWait.sec = 0;
7821 peerStats->burstWait.usec = 0;
7822 peerStats->rtt = tp->rtt;
7823 peerStats->rtt_dev = tp->rtt_dev;
7824 peerStats->timeout.sec = 0;
7825 peerStats->timeout.usec = 0;
7826 peerStats->nSent = tp->nSent;
7827 peerStats->reSends = tp->reSends;
7828 peerStats->natMTU = tp->natMTU;
7829 peerStats->maxMTU = tp->maxMTU;
7830 peerStats->maxDgramPackets = tp->maxDgramPackets;
7831 peerStats->ifDgramPackets = tp->ifDgramPackets;
7832 peerStats->MTU = tp->MTU;
7833 peerStats->cwind = tp->cwind;
7834 peerStats->nDgramPackets = tp->nDgramPackets;
7835 peerStats->congestSeq = tp->congestSeq;
7836 peerStats->bytesSent.high = tp->bytesSent >> 32;
7837 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7838 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7839 peerStats->bytesReceived.low
7840 = tp->bytesReceived & MAX_AFS_UINT32;
7841 MUTEX_EXIT(&tp->peer_lock);
7843 MUTEX_ENTER(&rx_peerHashTable_lock);
7846 MUTEX_EXIT(&rx_peerHashTable_lock);
7854 struct rx_serverQueueEntry *np;
7857 struct rx_call *call;
7858 struct rx_serverQueueEntry *sq;
7862 if (rxinit_status == 1) {
7864 return; /* Already shutdown. */
7868 #ifndef AFS_PTHREAD_ENV
7869 FD_ZERO(&rx_selectMask);
7870 #endif /* AFS_PTHREAD_ENV */
7871 rxi_dataQuota = RX_MAX_QUOTA;
7872 #ifndef AFS_PTHREAD_ENV
7874 #endif /* AFS_PTHREAD_ENV */
7877 #ifndef AFS_PTHREAD_ENV
7878 #ifndef AFS_USE_GETTIMEOFDAY
7880 #endif /* AFS_USE_GETTIMEOFDAY */
7881 #endif /* AFS_PTHREAD_ENV */
7883 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7884 call = queue_First(&rx_freeCallQueue, rx_call);
7886 rxi_Free(call, sizeof(struct rx_call));
7889 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7890 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7896 struct rx_peer **peer_ptr, **peer_end;
7897 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7898 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7900 struct rx_peer *peer, *next;
7902 MUTEX_ENTER(&rx_peerHashTable_lock);
7903 for (peer = *peer_ptr; peer; peer = next) {
7904 rx_interface_stat_p rpc_stat, nrpc_stat;
7907 MUTEX_ENTER(&rx_rpc_stats);
7908 MUTEX_ENTER(&peer->peer_lock);
7910 (&peer->rpcStats, rpc_stat, nrpc_stat,
7911 rx_interface_stat)) {
7912 unsigned int num_funcs;
7915 queue_Remove(&rpc_stat->queue_header);
7916 queue_Remove(&rpc_stat->all_peers);
7917 num_funcs = rpc_stat->stats[0].func_total;
7919 sizeof(rx_interface_stat_t) +
7920 rpc_stat->stats[0].func_total *
7921 sizeof(rx_function_entry_v1_t);
7923 rxi_Free(rpc_stat, space);
7925 /* rx_rpc_stats must be held */
7926 rxi_rpc_peer_stat_cnt -= num_funcs;
7928 MUTEX_EXIT(&peer->peer_lock);
7929 MUTEX_EXIT(&rx_rpc_stats);
7933 if (rx_stats_active)
7934 rx_atomic_dec(&rx_stats.nPeerStructs);
7936 MUTEX_EXIT(&rx_peerHashTable_lock);
7939 for (i = 0; i < RX_MAX_SERVICES; i++) {
7941 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7943 for (i = 0; i < rx_hashTableSize; i++) {
7944 struct rx_connection *tc, *ntc;
7945 MUTEX_ENTER(&rx_connHashTable_lock);
7946 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7948 for (j = 0; j < RX_MAXCALLS; j++) {
7950 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7953 rxi_Free(tc, sizeof(*tc));
7955 MUTEX_EXIT(&rx_connHashTable_lock);
7958 MUTEX_ENTER(&freeSQEList_lock);
7960 while ((np = rx_FreeSQEList)) {
7961 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7962 MUTEX_DESTROY(&np->lock);
7963 rxi_Free(np, sizeof(*np));
7966 MUTEX_EXIT(&freeSQEList_lock);
7967 MUTEX_DESTROY(&freeSQEList_lock);
7968 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7969 MUTEX_DESTROY(&rx_connHashTable_lock);
7970 MUTEX_DESTROY(&rx_peerHashTable_lock);
7971 MUTEX_DESTROY(&rx_serverPool_lock);
7973 osi_Free(rx_connHashTable,
7974 rx_hashTableSize * sizeof(struct rx_connection *));
7975 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7977 UNPIN(rx_connHashTable,
7978 rx_hashTableSize * sizeof(struct rx_connection *));
7979 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7981 rxi_FreeAllPackets();
7983 MUTEX_ENTER(&rx_quota_mutex);
7984 rxi_dataQuota = RX_MAX_QUOTA;
7985 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7986 MUTEX_EXIT(&rx_quota_mutex);
7991 #ifdef RX_ENABLE_LOCKS
7993 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7995 if (!MUTEX_ISMINE(lockaddr))
7996 osi_Panic("Lock not held: %s", msg);
7998 #endif /* RX_ENABLE_LOCKS */
8003 * Routines to implement connection specific data.
8007 rx_KeyCreate(rx_destructor_t rtn)
8010 MUTEX_ENTER(&rxi_keyCreate_lock);
8011 key = rxi_keyCreate_counter++;
8012 rxi_keyCreate_destructor = (rx_destructor_t *)
8013 realloc((void *)rxi_keyCreate_destructor,
8014 (key + 1) * sizeof(rx_destructor_t));
8015 rxi_keyCreate_destructor[key] = rtn;
8016 MUTEX_EXIT(&rxi_keyCreate_lock);
8021 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8024 MUTEX_ENTER(&conn->conn_data_lock);
8025 if (!conn->specific) {
8026 conn->specific = malloc((key + 1) * sizeof(void *));
8027 for (i = 0; i < key; i++)
8028 conn->specific[i] = NULL;
8029 conn->nSpecific = key + 1;
8030 conn->specific[key] = ptr;
8031 } else if (key >= conn->nSpecific) {
8032 conn->specific = (void **)
8033 realloc(conn->specific, (key + 1) * sizeof(void *));
8034 for (i = conn->nSpecific; i < key; i++)
8035 conn->specific[i] = NULL;
8036 conn->nSpecific = key + 1;
8037 conn->specific[key] = ptr;
8039 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8040 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8041 conn->specific[key] = ptr;
8043 MUTEX_EXIT(&conn->conn_data_lock);
8047 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8050 MUTEX_ENTER(&svc->svc_data_lock);
8051 if (!svc->specific) {
8052 svc->specific = malloc((key + 1) * sizeof(void *));
8053 for (i = 0; i < key; i++)
8054 svc->specific[i] = NULL;
8055 svc->nSpecific = key + 1;
8056 svc->specific[key] = ptr;
8057 } else if (key >= svc->nSpecific) {
8058 svc->specific = (void **)
8059 realloc(svc->specific, (key + 1) * sizeof(void *));
8060 for (i = svc->nSpecific; i < key; i++)
8061 svc->specific[i] = NULL;
8062 svc->nSpecific = key + 1;
8063 svc->specific[key] = ptr;
8065 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8066 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8067 svc->specific[key] = ptr;
8069 MUTEX_EXIT(&svc->svc_data_lock);
8073 rx_GetSpecific(struct rx_connection *conn, int key)
8076 MUTEX_ENTER(&conn->conn_data_lock);
8077 if (key >= conn->nSpecific)
8080 ptr = conn->specific[key];
8081 MUTEX_EXIT(&conn->conn_data_lock);
8086 rx_GetServiceSpecific(struct rx_service *svc, int key)
8089 MUTEX_ENTER(&svc->svc_data_lock);
8090 if (key >= svc->nSpecific)
8093 ptr = svc->specific[key];
8094 MUTEX_EXIT(&svc->svc_data_lock);
8099 #endif /* !KERNEL */
8102 * processStats is a queue used to store the statistics for the local
8103 * process. Its contents are similar to the contents of the rpcStats
8104 * queue on a rx_peer structure, but the actual data stored within
8105 * this queue contains totals across the lifetime of the process (assuming
8106 * the stats have not been reset) - unlike the per peer structures
8107 * which can come and go based upon the peer lifetime.
8110 static struct rx_queue processStats = { &processStats, &processStats };
8113 * peerStats is a queue used to store the statistics for all peer structs.
8114 * Its contents are the union of all the peer rpcStats queues.
8117 static struct rx_queue peerStats = { &peerStats, &peerStats };
8120 * rxi_monitor_processStats is used to turn process wide stat collection
8124 static int rxi_monitor_processStats = 0;
8127 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8130 static int rxi_monitor_peerStats = 0;
8134 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8136 rpc_stat->invocations = 0;
8137 rpc_stat->bytes_sent = 0;
8138 rpc_stat->bytes_rcvd = 0;
8139 rpc_stat->queue_time_sum.sec = 0;
8140 rpc_stat->queue_time_sum.usec = 0;
8141 rpc_stat->queue_time_sum_sqr.sec = 0;
8142 rpc_stat->queue_time_sum_sqr.usec = 0;
8143 rpc_stat->queue_time_min.sec = 9999999;
8144 rpc_stat->queue_time_min.usec = 9999999;
8145 rpc_stat->queue_time_max.sec = 0;
8146 rpc_stat->queue_time_max.usec = 0;
8147 rpc_stat->execution_time_sum.sec = 0;
8148 rpc_stat->execution_time_sum.usec = 0;
8149 rpc_stat->execution_time_sum_sqr.sec = 0;
8150 rpc_stat->execution_time_sum_sqr.usec = 0;
8151 rpc_stat->execution_time_min.sec = 9999999;
8152 rpc_stat->execution_time_min.usec = 9999999;
8153 rpc_stat->execution_time_max.sec = 0;
8154 rpc_stat->execution_time_max.usec = 0;
8158 * Given all of the information for a particular rpc
8159 * call, find or create (if requested) the stat structure for the rpc.
8162 * the queue of stats that will be updated with the new value
8164 * @param rxInterface
8165 * a unique number that identifies the rpc interface
8168 * the total number of functions in this interface. this is only
8169 * required if create is true
8172 * if true, this invocation was made to a server
8175 * the ip address of the remote host. this is only required if create
8176 * and addToPeerList are true
8179 * the port of the remote host. this is only required if create
8180 * and addToPeerList are true
8182 * @param addToPeerList
8183 * if != 0, add newly created stat to the global peer list
8186 * if a new stats structure is allocated, the counter will
8187 * be updated with the new number of allocated stat structures.
8188 * only required if create is true
8191 * if no stats structure exists, allocate one
8195 static rx_interface_stat_p
8196 rxi_FindRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8197 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8198 afs_uint32 remotePort, int addToPeerList,
8199 unsigned int *counter, int create)
8201 rx_interface_stat_p rpc_stat, nrpc_stat;
8204 * See if there's already a structure for this interface
8207 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8208 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8209 && (rpc_stat->stats[0].remote_is_server == isServer))
8213 /* if they didn't ask us to create, we're done */
8215 if (queue_IsEnd(stats, rpc_stat))
8221 /* can't proceed without these */
8222 if (!totalFunc || !counter)
8226 * Didn't find a match so allocate a new structure and add it to the
8230 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8231 || (rpc_stat->stats[0].interfaceId != rxInterface)
8232 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8237 sizeof(rx_interface_stat_t) +
8238 totalFunc * sizeof(rx_function_entry_v1_t);
8240 rpc_stat = rxi_Alloc(space);
8241 if (rpc_stat == NULL)
8244 *counter += totalFunc;
8245 for (i = 0; i < totalFunc; i++) {
8246 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8247 rpc_stat->stats[i].remote_peer = remoteHost;
8248 rpc_stat->stats[i].remote_port = remotePort;
8249 rpc_stat->stats[i].remote_is_server = isServer;
8250 rpc_stat->stats[i].interfaceId = rxInterface;
8251 rpc_stat->stats[i].func_total = totalFunc;
8252 rpc_stat->stats[i].func_index = i;
8254 queue_Prepend(stats, rpc_stat);
8255 if (addToPeerList) {
8256 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8263 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8265 rx_interface_stat_p rpc_stat;
8268 if (rxInterface == -1)
8271 MUTEX_ENTER(&rx_rpc_stats);
8272 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8275 totalFunc = rpc_stat->stats[0].func_total;
8276 for (i = 0; i < totalFunc; i++)
8277 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8279 MUTEX_EXIT(&rx_rpc_stats);
8284 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8286 rx_interface_stat_p rpc_stat;
8288 struct rx_peer * peer;
8290 if (rxInterface == -1)
8293 peer = rxi_FindPeer(peerHost, peerPort, 0, 0);
8297 MUTEX_ENTER(&rx_rpc_stats);
8298 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8301 totalFunc = rpc_stat->stats[0].func_total;
8302 for (i = 0; i < totalFunc; i++)
8303 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8305 MUTEX_EXIT(&rx_rpc_stats);
8310 rx_CopyProcessRPCStats(afs_uint64 op)
8312 rx_interface_stat_p rpc_stat;
8313 rx_function_entry_v1_p rpcop_stat =
8314 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8315 int currentFunc = (op & MAX_AFS_UINT32);
8316 afs_int32 rxInterface = (op >> 32);
8318 if (!rxi_monitor_processStats)
8321 if (rxInterface == -1)
8324 if (rpcop_stat == NULL)
8327 MUTEX_ENTER(&rx_rpc_stats);
8328 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8331 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8332 sizeof(rx_function_entry_v1_t));
8333 MUTEX_EXIT(&rx_rpc_stats);
8335 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8342 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8344 rx_interface_stat_p rpc_stat;
8345 rx_function_entry_v1_p rpcop_stat =
8346 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8347 int currentFunc = (op & MAX_AFS_UINT32);
8348 afs_int32 rxInterface = (op >> 32);
8349 struct rx_peer *peer;
8351 if (!rxi_monitor_peerStats)
8354 if (rxInterface == -1)
8357 if (rpcop_stat == NULL)
8360 peer = rxi_FindPeer(peerHost, peerPort, 0, 0);
8364 MUTEX_ENTER(&rx_rpc_stats);
8365 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8368 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8369 sizeof(rx_function_entry_v1_t));
8370 MUTEX_EXIT(&rx_rpc_stats);
8372 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8379 rx_ReleaseRPCStats(void *stats)
8382 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8386 * Given all of the information for a particular rpc
8387 * call, create (if needed) and update the stat totals for the rpc.
8390 * the queue of stats that will be updated with the new value
8392 * @param rxInterface
8393 * a unique number that identifies the rpc interface
8395 * @param currentFunc
8396 * the index of the function being invoked
8399 * the total number of functions in this interface
8402 * the amount of time this function waited for a thread
8405 * the amount of time this function invocation took to execute
8408 * the number bytes sent by this invocation
8411 * the number bytes received by this invocation
8414 * if true, this invocation was made to a server
8417 * the ip address of the remote host
8420 * the port of the remote host
8422 * @param addToPeerList
8423 * if != 0, add newly created stat to the global peer list
8426 * if a new stats structure is allocated, the counter will
8427 * be updated with the new number of allocated stat structures
8432 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8433 afs_uint32 currentFunc, afs_uint32 totalFunc,
8434 struct clock *queueTime, struct clock *execTime,
8435 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8436 afs_uint32 remoteHost, afs_uint32 remotePort,
8437 int addToPeerList, unsigned int *counter)
8440 rx_interface_stat_p rpc_stat;
8442 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8443 remoteHost, remotePort, addToPeerList, counter,
8451 * Increment the stats for this function
8454 rpc_stat->stats[currentFunc].invocations++;
8455 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8456 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8457 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8458 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8459 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8460 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8462 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8463 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8465 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8466 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8468 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8469 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8471 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8472 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8480 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8481 afs_uint32 currentFunc, afs_uint32 totalFunc,
8482 struct clock *queueTime, struct clock *execTime,
8483 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8487 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8490 MUTEX_ENTER(&rx_rpc_stats);
8492 if (rxi_monitor_peerStats) {
8493 MUTEX_ENTER(&peer->peer_lock);
8494 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8495 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8496 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8497 MUTEX_EXIT(&peer->peer_lock);
8500 if (rxi_monitor_processStats) {
8501 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8502 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8503 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8506 MUTEX_EXIT(&rx_rpc_stats);
8510 * Increment the times and count for a particular rpc function.
8512 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8513 * call rx_RecordCallStatistics instead, so the public version of this
8514 * function is left purely for legacy callers.
8517 * The peer who invoked the rpc
8519 * @param rxInterface
8520 * A unique number that identifies the rpc interface
8522 * @param currentFunc
8523 * The index of the function being invoked
8526 * The total number of functions in this interface
8529 * The amount of time this function waited for a thread
8532 * The amount of time this function invocation took to execute
8535 * The number bytes sent by this invocation
8538 * The number bytes received by this invocation
8541 * If true, this invocation was made to a server
8545 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8546 afs_uint32 currentFunc, afs_uint32 totalFunc,
8547 struct clock *queueTime, struct clock *execTime,
8548 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8554 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8555 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8557 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8558 queueTime, execTime, sent64, rcvd64,
8565 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8569 * IN callerVersion - the rpc stat version of the caller.
8571 * IN count - the number of entries to marshall.
8573 * IN stats - pointer to stats to be marshalled.
8575 * OUT ptr - Where to store the marshalled data.
8582 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8583 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8589 * We only support the first version
8591 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8592 *(ptr++) = stats->remote_peer;
8593 *(ptr++) = stats->remote_port;
8594 *(ptr++) = stats->remote_is_server;
8595 *(ptr++) = stats->interfaceId;
8596 *(ptr++) = stats->func_total;
8597 *(ptr++) = stats->func_index;
8598 *(ptr++) = stats->invocations >> 32;
8599 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8600 *(ptr++) = stats->bytes_sent >> 32;
8601 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8602 *(ptr++) = stats->bytes_rcvd >> 32;
8603 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8604 *(ptr++) = stats->queue_time_sum.sec;
8605 *(ptr++) = stats->queue_time_sum.usec;
8606 *(ptr++) = stats->queue_time_sum_sqr.sec;
8607 *(ptr++) = stats->queue_time_sum_sqr.usec;
8608 *(ptr++) = stats->queue_time_min.sec;
8609 *(ptr++) = stats->queue_time_min.usec;
8610 *(ptr++) = stats->queue_time_max.sec;
8611 *(ptr++) = stats->queue_time_max.usec;
8612 *(ptr++) = stats->execution_time_sum.sec;
8613 *(ptr++) = stats->execution_time_sum.usec;
8614 *(ptr++) = stats->execution_time_sum_sqr.sec;
8615 *(ptr++) = stats->execution_time_sum_sqr.usec;
8616 *(ptr++) = stats->execution_time_min.sec;
8617 *(ptr++) = stats->execution_time_min.usec;
8618 *(ptr++) = stats->execution_time_max.sec;
8619 *(ptr++) = stats->execution_time_max.usec;
8625 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8630 * IN callerVersion - the rpc stat version of the caller
8632 * OUT myVersion - the rpc stat version of this function
8634 * OUT clock_sec - local time seconds
8636 * OUT clock_usec - local time microseconds
8638 * OUT allocSize - the number of bytes allocated to contain stats
8640 * OUT statCount - the number stats retrieved from this process.
8642 * OUT stats - the actual stats retrieved from this process.
8646 * Returns void. If successful, stats will != NULL.
8650 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8651 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8652 size_t * allocSize, afs_uint32 * statCount,
8653 afs_uint32 ** stats)
8663 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8666 * Check to see if stats are enabled
8669 MUTEX_ENTER(&rx_rpc_stats);
8670 if (!rxi_monitor_processStats) {
8671 MUTEX_EXIT(&rx_rpc_stats);
8675 clock_GetTime(&now);
8676 *clock_sec = now.sec;
8677 *clock_usec = now.usec;
8680 * Allocate the space based upon the caller version
8682 * If the client is at an older version than we are,
8683 * we return the statistic data in the older data format, but
8684 * we still return our version number so the client knows we
8685 * are maintaining more data than it can retrieve.
8688 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8689 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8690 *statCount = rxi_rpc_process_stat_cnt;
8693 * This can't happen yet, but in the future version changes
8694 * can be handled by adding additional code here
8698 if (space > (size_t) 0) {
8700 ptr = *stats = rxi_Alloc(space);
8703 rx_interface_stat_p rpc_stat, nrpc_stat;
8707 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8709 * Copy the data based upon the caller version
8711 rx_MarshallProcessRPCStats(callerVersion,
8712 rpc_stat->stats[0].func_total,
8713 rpc_stat->stats, &ptr);
8719 MUTEX_EXIT(&rx_rpc_stats);
8724 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8728 * IN callerVersion - the rpc stat version of the caller
8730 * OUT myVersion - the rpc stat version of this function
8732 * OUT clock_sec - local time seconds
8734 * OUT clock_usec - local time microseconds
8736 * OUT allocSize - the number of bytes allocated to contain stats
8738 * OUT statCount - the number of stats retrieved from the individual
8741 * OUT stats - the actual stats retrieved from the individual peer structures.
8745 * Returns void. If successful, stats will != NULL.
8749 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8750 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8751 size_t * allocSize, afs_uint32 * statCount,
8752 afs_uint32 ** stats)
8762 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8765 * Check to see if stats are enabled
8768 MUTEX_ENTER(&rx_rpc_stats);
8769 if (!rxi_monitor_peerStats) {
8770 MUTEX_EXIT(&rx_rpc_stats);
8774 clock_GetTime(&now);
8775 *clock_sec = now.sec;
8776 *clock_usec = now.usec;
8779 * Allocate the space based upon the caller version
8781 * If the client is at an older version than we are,
8782 * we return the statistic data in the older data format, but
8783 * we still return our version number so the client knows we
8784 * are maintaining more data than it can retrieve.
8787 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8788 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8789 *statCount = rxi_rpc_peer_stat_cnt;
8792 * This can't happen yet, but in the future version changes
8793 * can be handled by adding additional code here
8797 if (space > (size_t) 0) {
8799 ptr = *stats = rxi_Alloc(space);
8802 rx_interface_stat_p rpc_stat, nrpc_stat;
8806 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8808 * We have to fix the offset of rpc_stat since we are
8809 * keeping this structure on two rx_queues. The rx_queue
8810 * package assumes that the rx_queue member is the first
8811 * member of the structure. That is, rx_queue assumes that
8812 * any one item is only on one queue at a time. We are
8813 * breaking that assumption and so we have to do a little
8814 * math to fix our pointers.
8817 fix_offset = (char *)rpc_stat;
8818 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8819 rpc_stat = (rx_interface_stat_p) fix_offset;
8822 * Copy the data based upon the caller version
8824 rx_MarshallProcessRPCStats(callerVersion,
8825 rpc_stat->stats[0].func_total,
8826 rpc_stat->stats, &ptr);
8832 MUTEX_EXIT(&rx_rpc_stats);
8837 * rx_FreeRPCStats - free memory allocated by
8838 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8842 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8843 * rx_RetrievePeerRPCStats
8845 * IN allocSize - the number of bytes in stats.
8853 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8855 rxi_Free(stats, allocSize);
8859 * rx_queryProcessRPCStats - see if process rpc stat collection is
8860 * currently enabled.
8866 * Returns 0 if stats are not enabled != 0 otherwise
8870 rx_queryProcessRPCStats(void)
8873 MUTEX_ENTER(&rx_rpc_stats);
8874 rc = rxi_monitor_processStats;
8875 MUTEX_EXIT(&rx_rpc_stats);
8880 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8886 * Returns 0 if stats are not enabled != 0 otherwise
8890 rx_queryPeerRPCStats(void)
8893 MUTEX_ENTER(&rx_rpc_stats);
8894 rc = rxi_monitor_peerStats;
8895 MUTEX_EXIT(&rx_rpc_stats);
8900 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8910 rx_enableProcessRPCStats(void)
8912 MUTEX_ENTER(&rx_rpc_stats);
8913 rx_enable_stats = 1;
8914 rxi_monitor_processStats = 1;
8915 MUTEX_EXIT(&rx_rpc_stats);
8919 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8929 rx_enablePeerRPCStats(void)
8931 MUTEX_ENTER(&rx_rpc_stats);
8932 rx_enable_stats = 1;
8933 rxi_monitor_peerStats = 1;
8934 MUTEX_EXIT(&rx_rpc_stats);
8938 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8948 rx_disableProcessRPCStats(void)
8950 rx_interface_stat_p rpc_stat, nrpc_stat;
8953 MUTEX_ENTER(&rx_rpc_stats);
8956 * Turn off process statistics and if peer stats is also off, turn
8960 rxi_monitor_processStats = 0;
8961 if (rxi_monitor_peerStats == 0) {
8962 rx_enable_stats = 0;
8965 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8966 unsigned int num_funcs = 0;
8969 queue_Remove(rpc_stat);
8970 num_funcs = rpc_stat->stats[0].func_total;
8972 sizeof(rx_interface_stat_t) +
8973 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8975 rxi_Free(rpc_stat, space);
8976 rxi_rpc_process_stat_cnt -= num_funcs;
8978 MUTEX_EXIT(&rx_rpc_stats);
8982 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8992 rx_disablePeerRPCStats(void)
8994 struct rx_peer **peer_ptr, **peer_end;
8998 * Turn off peer statistics and if process stats is also off, turn
9002 rxi_monitor_peerStats = 0;
9003 if (rxi_monitor_processStats == 0) {
9004 rx_enable_stats = 0;
9007 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9008 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9010 struct rx_peer *peer, *next, *prev;
9012 MUTEX_ENTER(&rx_peerHashTable_lock);
9013 MUTEX_ENTER(&rx_rpc_stats);
9014 for (prev = peer = *peer_ptr; peer; peer = next) {
9016 code = MUTEX_TRYENTER(&peer->peer_lock);
9018 rx_interface_stat_p rpc_stat, nrpc_stat;
9021 if (prev == *peer_ptr) {
9032 MUTEX_EXIT(&rx_peerHashTable_lock);
9035 (&peer->rpcStats, rpc_stat, nrpc_stat,
9036 rx_interface_stat)) {
9037 unsigned int num_funcs = 0;
9040 queue_Remove(&rpc_stat->queue_header);
9041 queue_Remove(&rpc_stat->all_peers);
9042 num_funcs = rpc_stat->stats[0].func_total;
9044 sizeof(rx_interface_stat_t) +
9045 rpc_stat->stats[0].func_total *
9046 sizeof(rx_function_entry_v1_t);
9048 rxi_Free(rpc_stat, space);
9049 rxi_rpc_peer_stat_cnt -= num_funcs;
9051 MUTEX_EXIT(&peer->peer_lock);
9053 MUTEX_ENTER(&rx_peerHashTable_lock);
9063 MUTEX_EXIT(&rx_rpc_stats);
9064 MUTEX_EXIT(&rx_peerHashTable_lock);
9069 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9074 * IN clearFlag - flag indicating which stats to clear
9082 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9084 rx_interface_stat_p rpc_stat, nrpc_stat;
9086 MUTEX_ENTER(&rx_rpc_stats);
9088 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
9089 unsigned int num_funcs = 0, i;
9090 num_funcs = rpc_stat->stats[0].func_total;
9091 for (i = 0; i < num_funcs; i++) {
9092 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9093 rpc_stat->stats[i].invocations = 0;
9095 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9096 rpc_stat->stats[i].bytes_sent = 0;
9098 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9099 rpc_stat->stats[i].bytes_rcvd = 0;
9101 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9102 rpc_stat->stats[i].queue_time_sum.sec = 0;
9103 rpc_stat->stats[i].queue_time_sum.usec = 0;
9105 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9106 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9107 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9109 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9110 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9111 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9113 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9114 rpc_stat->stats[i].queue_time_max.sec = 0;
9115 rpc_stat->stats[i].queue_time_max.usec = 0;
9117 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9118 rpc_stat->stats[i].execution_time_sum.sec = 0;
9119 rpc_stat->stats[i].execution_time_sum.usec = 0;
9121 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9122 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9123 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9125 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9126 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9127 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9129 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9130 rpc_stat->stats[i].execution_time_max.sec = 0;
9131 rpc_stat->stats[i].execution_time_max.usec = 0;
9136 MUTEX_EXIT(&rx_rpc_stats);
9140 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9145 * IN clearFlag - flag indicating which stats to clear
9153 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9155 rx_interface_stat_p rpc_stat, nrpc_stat;
9157 MUTEX_ENTER(&rx_rpc_stats);
9159 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
9160 unsigned int num_funcs = 0, i;
9163 * We have to fix the offset of rpc_stat since we are
9164 * keeping this structure on two rx_queues. The rx_queue
9165 * package assumes that the rx_queue member is the first
9166 * member of the structure. That is, rx_queue assumes that
9167 * any one item is only on one queue at a time. We are
9168 * breaking that assumption and so we have to do a little
9169 * math to fix our pointers.
9172 fix_offset = (char *)rpc_stat;
9173 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
9174 rpc_stat = (rx_interface_stat_p) fix_offset;
9176 num_funcs = rpc_stat->stats[0].func_total;
9177 for (i = 0; i < num_funcs; i++) {
9178 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9179 rpc_stat->stats[i].invocations = 0;
9181 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9182 rpc_stat->stats[i].bytes_sent = 0;
9184 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9185 rpc_stat->stats[i].bytes_rcvd = 0;
9187 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9188 rpc_stat->stats[i].queue_time_sum.sec = 0;
9189 rpc_stat->stats[i].queue_time_sum.usec = 0;
9191 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9192 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9193 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9195 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9196 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9197 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9199 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9200 rpc_stat->stats[i].queue_time_max.sec = 0;
9201 rpc_stat->stats[i].queue_time_max.usec = 0;
9203 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9204 rpc_stat->stats[i].execution_time_sum.sec = 0;
9205 rpc_stat->stats[i].execution_time_sum.usec = 0;
9207 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9208 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9209 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9211 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9212 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9213 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9215 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9216 rpc_stat->stats[i].execution_time_max.sec = 0;
9217 rpc_stat->stats[i].execution_time_max.usec = 0;
9222 MUTEX_EXIT(&rx_rpc_stats);
9226 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9227 * is authorized to enable/disable/clear RX statistics.
9229 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9232 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9234 rxi_rxstat_userok = proc;
9238 rx_RxStatUserOk(struct rx_call *call)
9240 if (!rxi_rxstat_userok)
9242 return rxi_rxstat_userok(call);
9247 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9248 * function in the MSVC runtime DLL (msvcrt.dll).
9250 * Note: the system serializes calls to this function.
9253 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9254 DWORD reason, /* reason function is being called */
9255 LPVOID reserved) /* reserved for future use */
9258 case DLL_PROCESS_ATTACH:
9259 /* library is being attached to a process */
9263 case DLL_PROCESS_DETACH:
9270 #endif /* AFS_NT40_ENV */
9273 int rx_DumpCalls(FILE *outputFile, char *cookie)
9275 #ifdef RXDEBUG_PACKET
9276 #ifdef KDUMP_RX_LOCK
9277 struct rx_call_rx_lock *c;
9284 #define RXDPRINTF sprintf
9285 #define RXDPRINTOUT output
9287 #define RXDPRINTF fprintf
9288 #define RXDPRINTOUT outputFile
9291 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9293 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9296 for (c = rx_allCallsp; c; c = c->allNextp) {
9297 u_short rqc, tqc, iovqc;
9298 struct rx_packet *p, *np;
9300 MUTEX_ENTER(&c->lock);
9301 queue_Count(&c->rq, p, np, rx_packet, rqc);
9302 queue_Count(&c->tq, p, np, rx_packet, tqc);
9303 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9305 RXDPRINTF(RXDPRINTOUT, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
9306 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9307 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9308 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9309 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9310 #ifdef RX_ENABLE_LOCKS
9313 #ifdef RX_REFCOUNT_CHECK
9314 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9315 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9318 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
9319 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9320 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9321 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9322 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9323 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9324 #ifdef RX_ENABLE_LOCKS
9325 , (afs_uint32)c->refCount
9327 #ifdef RX_REFCOUNT_CHECK
9328 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9331 MUTEX_EXIT(&c->lock);
9334 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9337 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9339 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9341 #endif /* RXDEBUG_PACKET */