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"
85 #include "rx_packet.h"
87 #include <afs/rxgen_consts.h>
90 #ifdef AFS_PTHREAD_ENV
92 int (*registerProgram) (pid_t, char *) = 0;
93 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
96 int (*registerProgram) (PROCESS, char *) = 0;
97 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
101 /* Local static routines */
102 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
103 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
104 struct rx_call *, struct rx_peer *,
106 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
108 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
109 void *dummy, int dummy2);
110 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
111 void *dummy, int dummy2);
112 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
113 void *unused, int unused2);
114 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
115 void *unused2, int unused3);
116 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
117 struct rx_packet *packet,
118 int istack, int force);
119 static void rxi_AckAll(struct rx_call *call);
120 static struct rx_connection
121 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
122 u_short serviceId, afs_uint32 cid,
123 afs_uint32 epoch, int type, u_int securityIndex);
124 static struct rx_packet
125 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
126 int istack, osi_socket socket,
127 afs_uint32 host, u_short port, int *tnop,
128 struct rx_call **newcallp);
129 static struct rx_packet
130 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
132 static struct rx_packet
133 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
134 struct rx_packet *np, int istack);
135 static struct rx_packet
136 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
137 struct rx_packet *np, int istack);
138 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
139 int *tnop, struct rx_call **newcallp);
140 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
141 static void rxi_ClearReceiveQueue(struct rx_call *call);
142 static void rxi_ResetCall(struct rx_call *call, int newcall);
143 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
144 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
145 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
146 static void rxi_KeepAliveOn(struct rx_call *call);
147 static void rxi_GrowMTUOn(struct rx_call *call);
148 static void rxi_ChallengeOn(struct rx_connection *conn);
150 #ifdef RX_ENABLE_LOCKS
151 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
152 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
154 static int rxi_CheckCall(struct rx_call *call);
157 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
159 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
160 rx_atomic_t rxi_start_in_error;
162 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
164 /* Constant delay time before sending an acknowledge of the last packet
165 * received. This is to avoid sending an extra acknowledge when the
166 * client is about to make another call, anyway, or the server is
169 * The lastAckDelay may not exceeed 400ms without causing peers to
170 * unecessarily timeout.
172 struct clock rx_lastAckDelay = {0, 400000};
174 /* Constant delay time before sending a soft ack when none was requested.
175 * This is to make sure we send soft acks before the sender times out,
176 * Normally we wait and send a hard ack when the receiver consumes the packet
178 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
179 * will require changes to the peer's RTT calculations.
181 struct clock rx_softAckDelay = {0, 100000};
184 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
185 * currently allocated within rx. This number is used to allocate the
186 * memory required to return the statistics when queried.
187 * Protected by the rx_rpc_stats mutex.
190 static unsigned int rxi_rpc_peer_stat_cnt;
193 * rxi_rpc_process_stat_cnt counts the total number of local process stat
194 * structures currently allocated within rx. The number is used to allocate
195 * the memory required to return the statistics when queried.
196 * Protected by the rx_rpc_stats mutex.
199 static unsigned int rxi_rpc_process_stat_cnt;
202 * rxi_busyChannelError is a boolean. It indicates whether or not RX_CALL_BUSY
203 * errors should be reported to the application when a call channel appears busy
204 * (inferred from the receipt of RX_PACKET_TYPE_BUSY packets on the channel),
205 * and there are other call channels in the connection that are not busy.
206 * If 0, we do not return errors upon receiving busy packets; we just keep
207 * trying on the same call channel until we hit a timeout.
209 static afs_int32 rxi_busyChannelError = 0;
211 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
212 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
214 #if !defined(offsetof)
215 #include <stddef.h> /* for definition of offsetof() */
218 #ifdef RX_ENABLE_LOCKS
219 afs_kmutex_t rx_atomic_mutex;
222 /* Forward prototypes */
223 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
226 putConnection (struct rx_connection *conn) {
227 MUTEX_ENTER(&rx_refcnt_mutex);
229 MUTEX_EXIT(&rx_refcnt_mutex);
232 #ifdef AFS_PTHREAD_ENV
235 * Use procedural initialization of mutexes/condition variables
239 extern afs_kmutex_t rx_quota_mutex;
240 extern afs_kmutex_t rx_pthread_mutex;
241 extern afs_kmutex_t rx_packets_mutex;
242 extern afs_kmutex_t rx_refcnt_mutex;
243 extern afs_kmutex_t des_init_mutex;
244 extern afs_kmutex_t des_random_mutex;
245 extern afs_kmutex_t rx_clock_mutex;
246 extern afs_kmutex_t rxi_connCacheMutex;
247 extern afs_kmutex_t event_handler_mutex;
248 extern afs_kmutex_t listener_mutex;
249 extern afs_kmutex_t rx_if_init_mutex;
250 extern afs_kmutex_t rx_if_mutex;
252 extern afs_kcondvar_t rx_event_handler_cond;
253 extern afs_kcondvar_t rx_listener_cond;
255 static afs_kmutex_t epoch_mutex;
256 static afs_kmutex_t rx_init_mutex;
257 static afs_kmutex_t rx_debug_mutex;
258 static afs_kmutex_t rx_rpc_stats;
261 rxi_InitPthread(void)
263 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
264 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
265 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
266 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
267 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
268 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
269 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
270 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
271 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
272 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
273 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
274 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
275 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
279 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
280 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
282 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
283 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
285 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
287 #ifdef RX_ENABLE_LOCKS
290 #endif /* RX_LOCKS_DB */
291 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
294 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
296 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
298 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
300 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
301 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
302 #endif /* RX_ENABLE_LOCKS */
305 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
306 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
308 * The rx_stats_mutex mutex protects the following global variables:
309 * rxi_lowConnRefCount
310 * rxi_lowPeerRefCount
319 * The rx_quota_mutex mutex protects the following global variables:
327 * The rx_freePktQ_lock protects the following global variables:
332 * The rx_packets_mutex mutex protects the following global variables:
340 * The rx_pthread_mutex mutex protects the following global variables:
341 * rxi_fcfs_thread_num
344 #define INIT_PTHREAD_LOCKS
348 /* Variables for handling the minProcs implementation. availProcs gives the
349 * number of threads available in the pool at this moment (not counting dudes
350 * executing right now). totalMin gives the total number of procs required
351 * for handling all minProcs requests. minDeficit is a dynamic variable
352 * tracking the # of procs required to satisfy all of the remaining minProcs
354 * For fine grain locking to work, the quota check and the reservation of
355 * a server thread has to come while rxi_availProcs and rxi_minDeficit
356 * are locked. To this end, the code has been modified under #ifdef
357 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
358 * same time. A new function, ReturnToServerPool() returns the allocation.
360 * A call can be on several queue's (but only one at a time). When
361 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
362 * that no one else is touching the queue. To this end, we store the address
363 * of the queue lock in the call structure (under the call lock) when we
364 * put the call on a queue, and we clear the call_queue_lock when the
365 * call is removed from a queue (once the call lock has been obtained).
366 * This allows rxi_ResetCall to safely synchronize with others wishing
367 * to manipulate the queue.
370 #if defined(RX_ENABLE_LOCKS)
371 static afs_kmutex_t rx_rpc_stats;
374 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
375 ** pretty good that the next packet coming in is from the same connection
376 ** as the last packet, since we're send multiple packets in a transmit window.
378 struct rx_connection *rxLastConn = 0;
380 #ifdef RX_ENABLE_LOCKS
381 /* The locking hierarchy for rx fine grain locking is composed of these
384 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
385 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
386 * call->lock - locks call data fields.
387 * These are independent of each other:
388 * rx_freeCallQueue_lock
393 * serverQueueEntry->lock
394 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
396 * peer->lock - locks peer data fields.
397 * conn_data_lock - that more than one thread is not updating a conn data
398 * field at the same time.
409 * Do we need a lock to protect the peer field in the conn structure?
410 * conn->peer was previously a constant for all intents and so has no
411 * lock protecting this field. The multihomed client delta introduced
412 * a RX code change : change the peer field in the connection structure
413 * to that remote interface from which the last packet for this
414 * connection was sent out. This may become an issue if further changes
417 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
418 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
420 /* rxdb_fileID is used to identify the lock location, along with line#. */
421 static int rxdb_fileID = RXDB_FILE_RX;
422 #endif /* RX_LOCKS_DB */
423 #else /* RX_ENABLE_LOCKS */
424 #define SET_CALL_QUEUE_LOCK(C, L)
425 #define CLEAR_CALL_QUEUE_LOCK(C)
426 #endif /* RX_ENABLE_LOCKS */
427 struct rx_serverQueueEntry *rx_waitForPacket = 0;
428 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
430 /* ------------Exported Interfaces------------- */
432 /* This function allows rxkad to set the epoch to a suitably random number
433 * which rx_NewConnection will use in the future. The principle purpose is to
434 * get rxnull connections to use the same epoch as the rxkad connections do, at
435 * least once the first rxkad connection is established. This is important now
436 * that the host/port addresses aren't used in FindConnection: the uniqueness
437 * of epoch/cid matters and the start time won't do. */
439 #ifdef AFS_PTHREAD_ENV
441 * This mutex protects the following global variables:
445 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
446 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
450 #endif /* AFS_PTHREAD_ENV */
453 rx_SetEpoch(afs_uint32 epoch)
460 /* Initialize rx. A port number may be mentioned, in which case this
461 * becomes the default port number for any service installed later.
462 * If 0 is provided for the port number, a random port will be chosen
463 * by the kernel. Whether this will ever overlap anything in
464 * /etc/services is anybody's guess... Returns 0 on success, -1 on
469 int rxinit_status = 1;
470 #ifdef AFS_PTHREAD_ENV
472 * This mutex protects the following global variables:
476 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
477 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
480 #define UNLOCK_RX_INIT
484 rx_InitHost(u_int host, u_int port)
491 char *htable, *ptable;
498 if (rxinit_status == 0) {
499 tmp_status = rxinit_status;
501 return tmp_status; /* Already started; return previous error code. */
507 if (afs_winsockInit() < 0)
513 * Initialize anything necessary to provide a non-premptive threading
516 rxi_InitializeThreadSupport();
519 /* Allocate and initialize a socket for client and perhaps server
522 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
523 if (rx_socket == OSI_NULLSOCKET) {
527 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
530 #endif /* RX_LOCKS_DB */
531 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
539 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
541 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
543 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
545 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
547 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
548 #if defined(AFS_HPUX110_ENV)
550 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
551 #endif /* AFS_HPUX110_ENV */
552 #endif /* RX_ENABLE_LOCKS && KERNEL */
555 rx_connDeadTime = 12;
556 rx_tranquil = 0; /* reset flag */
557 rxi_ResetStatistics();
559 osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
560 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
561 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
562 ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
563 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
564 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
566 /* Malloc up a bunch of packets & buffers */
568 queue_Init(&rx_freePacketQueue);
569 rxi_NeedMorePackets = FALSE;
570 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
572 /* enforce a minimum number of allocated packets */
573 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
574 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
576 /* allocate the initial free packet pool */
577 #ifdef RX_ENABLE_TSFPQ
578 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
579 #else /* RX_ENABLE_TSFPQ */
580 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
581 #endif /* RX_ENABLE_TSFPQ */
588 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
589 tv.tv_sec = clock_now.sec;
590 tv.tv_usec = clock_now.usec;
591 srand((unsigned int)tv.tv_usec);
598 #if defined(KERNEL) && !defined(UKERNEL)
599 /* Really, this should never happen in a real kernel */
602 struct sockaddr_in addr;
604 int addrlen = sizeof(addr);
606 socklen_t addrlen = sizeof(addr);
608 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
612 rx_port = addr.sin_port;
615 rx_stats.minRtt.sec = 9999999;
617 rx_SetEpoch(tv.tv_sec | 0x80000000);
619 rx_SetEpoch(tv.tv_sec); /* Start time of this package, rxkad
620 * will provide a randomer value. */
622 MUTEX_ENTER(&rx_quota_mutex);
623 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
624 MUTEX_EXIT(&rx_quota_mutex);
625 /* *Slightly* random start time for the cid. This is just to help
626 * out with the hashing function at the peer */
627 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
628 rx_connHashTable = (struct rx_connection **)htable;
629 rx_peerHashTable = (struct rx_peer **)ptable;
631 rx_hardAckDelay.sec = 0;
632 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
634 rxevent_Init(20, rxi_ReScheduleEvents);
636 /* Initialize various global queues */
637 queue_Init(&rx_idleServerQueue);
638 queue_Init(&rx_incomingCallQueue);
639 queue_Init(&rx_freeCallQueue);
641 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
642 /* Initialize our list of usable IP addresses. */
646 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
647 /* Start listener process (exact function is dependent on the
648 * implementation environment--kernel or user space) */
653 tmp_status = rxinit_status = 0;
661 return rx_InitHost(htonl(INADDR_ANY), port);
667 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
668 * maintaing the round trip timer.
673 * Start a new RTT timer for a given call and packet.
675 * There must be no resendEvent already listed for this call, otherwise this
676 * will leak events - intended for internal use within the RTO code only
679 * the RX call to start the timer for
680 * @param[in] lastPacket
681 * a flag indicating whether the last packet has been sent or not
683 * @pre call must be locked before calling this function
687 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
689 struct clock now, retryTime;
694 clock_Add(&retryTime, &call->rto);
696 /* If we're sending the last packet, and we're the client, then the server
697 * may wait for an additional 400ms before returning the ACK, wait for it
698 * rather than hitting a timeout */
699 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
700 clock_Addmsec(&retryTime, 400);
702 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
703 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
708 * Cancel an RTT timer for a given call.
712 * the RX call to cancel the timer for
714 * @pre call must be locked before calling this function
719 rxi_rto_cancel(struct rx_call *call)
721 rxevent_Cancel(&call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
725 * Tell the RTO timer that we have sent a packet.
727 * If the timer isn't already running, then start it. If the timer is running,
731 * the RX call that the packet has been sent on
732 * @param[in] lastPacket
733 * A flag which is true if this is the last packet for the call
735 * @pre The call must be locked before calling this function
740 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
742 if (call->resendEvent)
745 rxi_rto_startTimer(call, lastPacket, istack);
749 * Tell the RTO timer that we have received an new ACK message
751 * This function should be called whenever a call receives an ACK that
752 * acknowledges new packets. Whatever happens, we stop the current timer.
753 * If there are unacked packets in the queue which have been sent, then
754 * we restart the timer from now. Otherwise, we leave it stopped.
757 * the RX call that the ACK has been received on
761 rxi_rto_packet_acked(struct rx_call *call, int istack)
763 struct rx_packet *p, *nxp;
765 rxi_rto_cancel(call);
767 if (queue_IsEmpty(&call->tq))
770 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
771 if (p->header.seq > call->tfirst + call->twind)
774 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
775 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
783 * Set an initial round trip timeout for a peer connection
785 * @param[in] secs The timeout to set in seconds
789 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
790 peer->rtt = secs * 8000;
794 * Enables or disables the busy call channel error (RX_CALL_BUSY).
796 * @param[in] onoff Non-zero to enable busy call channel errors.
798 * @pre Neither rx_Init nor rx_InitHost have been called yet
801 rx_SetBusyChannelError(afs_int32 onoff)
803 osi_Assert(rxinit_status != 0);
804 rxi_busyChannelError = onoff ? 1 : 0;
808 * Set a delayed ack event on the specified call for the given time
810 * @param[in] call - the call on which to set the event
811 * @param[in] offset - the delay from now after which the event fires
814 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
816 struct clock now, when;
820 clock_Add(&when, offset);
822 if (!call->delayedAckEvent
823 || clock_Gt(&call->delayedAckTime, &when)) {
825 rxevent_Cancel(&call->delayedAckEvent, call,
826 RX_CALL_REFCOUNT_DELAY);
827 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
829 call->delayedAckEvent = rxevent_Post(&when, &now,
832 call->delayedAckTime = when;
836 /* called with unincremented nRequestsRunning to see if it is OK to start
837 * a new thread in this service. Could be "no" for two reasons: over the
838 * max quota, or would prevent others from reaching their min quota.
840 #ifdef RX_ENABLE_LOCKS
841 /* This verion of QuotaOK reserves quota if it's ok while the
842 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
845 QuotaOK(struct rx_service *aservice)
847 /* check if over max quota */
848 if (aservice->nRequestsRunning >= aservice->maxProcs) {
852 /* under min quota, we're OK */
853 /* otherwise, can use only if there are enough to allow everyone
854 * to go to their min quota after this guy starts.
857 MUTEX_ENTER(&rx_quota_mutex);
858 if ((aservice->nRequestsRunning < aservice->minProcs)
859 || (rxi_availProcs > rxi_minDeficit)) {
860 aservice->nRequestsRunning++;
861 /* just started call in minProcs pool, need fewer to maintain
863 if (aservice->nRequestsRunning <= aservice->minProcs)
866 MUTEX_EXIT(&rx_quota_mutex);
869 MUTEX_EXIT(&rx_quota_mutex);
875 ReturnToServerPool(struct rx_service *aservice)
877 aservice->nRequestsRunning--;
878 MUTEX_ENTER(&rx_quota_mutex);
879 if (aservice->nRequestsRunning < aservice->minProcs)
882 MUTEX_EXIT(&rx_quota_mutex);
885 #else /* RX_ENABLE_LOCKS */
887 QuotaOK(struct rx_service *aservice)
890 /* under min quota, we're OK */
891 if (aservice->nRequestsRunning < aservice->minProcs)
894 /* check if over max quota */
895 if (aservice->nRequestsRunning >= aservice->maxProcs)
898 /* otherwise, can use only if there are enough to allow everyone
899 * to go to their min quota after this guy starts.
901 MUTEX_ENTER(&rx_quota_mutex);
902 if (rxi_availProcs > rxi_minDeficit)
904 MUTEX_EXIT(&rx_quota_mutex);
907 #endif /* RX_ENABLE_LOCKS */
910 /* Called by rx_StartServer to start up lwp's to service calls.
911 NExistingProcs gives the number of procs already existing, and which
912 therefore needn't be created. */
914 rxi_StartServerProcs(int nExistingProcs)
916 struct rx_service *service;
921 /* For each service, reserve N processes, where N is the "minimum"
922 * number of processes that MUST be able to execute a request in parallel,
923 * at any time, for that process. Also compute the maximum difference
924 * between any service's maximum number of processes that can run
925 * (i.e. the maximum number that ever will be run, and a guarantee
926 * that this number will run if other services aren't running), and its
927 * minimum number. The result is the extra number of processes that
928 * we need in order to provide the latter guarantee */
929 for (i = 0; i < RX_MAX_SERVICES; i++) {
931 service = rx_services[i];
932 if (service == (struct rx_service *)0)
934 nProcs += service->minProcs;
935 diff = service->maxProcs - service->minProcs;
939 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
940 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
941 for (i = 0; i < nProcs; i++) {
942 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
948 /* This routine is only required on Windows */
950 rx_StartClientThread(void)
952 #ifdef AFS_PTHREAD_ENV
954 pid = pthread_self();
955 #endif /* AFS_PTHREAD_ENV */
957 #endif /* AFS_NT40_ENV */
959 /* This routine must be called if any services are exported. If the
960 * donateMe flag is set, the calling process is donated to the server
963 rx_StartServer(int donateMe)
965 struct rx_service *service;
971 /* Start server processes, if necessary (exact function is dependent
972 * on the implementation environment--kernel or user space). DonateMe
973 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
974 * case, one less new proc will be created rx_StartServerProcs.
976 rxi_StartServerProcs(donateMe);
978 /* count up the # of threads in minProcs, and add set the min deficit to
979 * be that value, too.
981 for (i = 0; i < RX_MAX_SERVICES; i++) {
982 service = rx_services[i];
983 if (service == (struct rx_service *)0)
985 MUTEX_ENTER(&rx_quota_mutex);
986 rxi_totalMin += service->minProcs;
987 /* below works even if a thread is running, since minDeficit would
988 * still have been decremented and later re-incremented.
990 rxi_minDeficit += service->minProcs;
991 MUTEX_EXIT(&rx_quota_mutex);
994 /* Turn on reaping of idle server connections */
995 rxi_ReapConnections(NULL, NULL, NULL, 0);
1000 #ifndef AFS_NT40_ENV
1004 #ifdef AFS_PTHREAD_ENV
1006 pid = afs_pointer_to_int(pthread_self());
1007 #else /* AFS_PTHREAD_ENV */
1009 LWP_CurrentProcess(&pid);
1010 #endif /* AFS_PTHREAD_ENV */
1012 sprintf(name, "srv_%d", ++nProcs);
1013 if (registerProgram)
1014 (*registerProgram) (pid, name);
1016 #endif /* AFS_NT40_ENV */
1017 rx_ServerProc(NULL); /* Never returns */
1019 #ifdef RX_ENABLE_TSFPQ
1020 /* no use leaving packets around in this thread's local queue if
1021 * it isn't getting donated to the server thread pool.
1023 rxi_FlushLocalPacketsTSFPQ();
1024 #endif /* RX_ENABLE_TSFPQ */
1028 /* Create a new client connection to the specified service, using the
1029 * specified security object to implement the security model for this
1031 struct rx_connection *
1032 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1033 struct rx_securityClass *securityObject,
1034 int serviceSecurityIndex)
1038 struct rx_connection *conn;
1043 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1044 "serviceSecurityIndex %d)\n",
1045 ntohl(shost), ntohs(sport), sservice, securityObject,
1046 serviceSecurityIndex));
1048 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1049 * the case of kmem_alloc? */
1050 conn = rxi_AllocConnection();
1051 #ifdef RX_ENABLE_LOCKS
1052 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1053 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1054 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1057 MUTEX_ENTER(&rx_connHashTable_lock);
1058 cid = (rx_nextCid += RX_MAXCALLS);
1059 conn->type = RX_CLIENT_CONNECTION;
1061 conn->epoch = rx_epoch;
1062 conn->peer = rxi_FindPeer(shost, sport, 0, 1);
1063 conn->serviceId = sservice;
1064 conn->securityObject = securityObject;
1065 conn->securityData = (void *) 0;
1066 conn->securityIndex = serviceSecurityIndex;
1067 rx_SetConnDeadTime(conn, rx_connDeadTime);
1068 rx_SetConnSecondsUntilNatPing(conn, 0);
1069 conn->ackRate = RX_FAST_ACK_RATE;
1070 conn->nSpecific = 0;
1071 conn->specific = NULL;
1072 conn->challengeEvent = NULL;
1073 conn->delayedAbortEvent = NULL;
1074 conn->abortCount = 0;
1076 for (i = 0; i < RX_MAXCALLS; i++) {
1077 conn->twind[i] = rx_initSendWindow;
1078 conn->rwind[i] = rx_initReceiveWindow;
1079 conn->lastBusy[i] = 0;
1082 RXS_NewConnection(securityObject, conn);
1084 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1086 conn->refCount++; /* no lock required since only this thread knows... */
1087 conn->next = rx_connHashTable[hashindex];
1088 rx_connHashTable[hashindex] = conn;
1089 if (rx_stats_active)
1090 rx_atomic_inc(&rx_stats.nClientConns);
1091 MUTEX_EXIT(&rx_connHashTable_lock);
1097 * Ensure a connection's timeout values are valid.
1099 * @param[in] conn The connection to check
1101 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1102 * unless idleDeadTime and/or hardDeadTime are not set
1106 rxi_CheckConnTimeouts(struct rx_connection *conn)
1108 /* a connection's timeouts must have the relationship
1109 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1110 * total loss of network to a peer may cause an idle timeout instead of a
1111 * dead timeout, simply because the idle timeout gets hit first. Also set
1112 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1113 /* this logic is slightly complicated by the fact that
1114 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1116 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1117 if (conn->idleDeadTime) {
1118 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1120 if (conn->hardDeadTime) {
1121 if (conn->idleDeadTime) {
1122 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1124 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1130 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1132 /* The idea is to set the dead time to a value that allows several
1133 * keepalives to be dropped without timing out the connection. */
1134 conn->secondsUntilDead = seconds;
1135 rxi_CheckConnTimeouts(conn);
1136 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1140 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1142 conn->hardDeadTime = seconds;
1143 rxi_CheckConnTimeouts(conn);
1147 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1149 conn->idleDeadTime = seconds;
1150 conn->idleDeadDetection = (seconds ? 1 : 0);
1151 rxi_CheckConnTimeouts(conn);
1154 int rxi_lowPeerRefCount = 0;
1155 int rxi_lowConnRefCount = 0;
1158 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1159 * NOTE: must not be called with rx_connHashTable_lock held.
1162 rxi_CleanupConnection(struct rx_connection *conn)
1164 /* Notify the service exporter, if requested, that this connection
1165 * is being destroyed */
1166 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1167 (*conn->service->destroyConnProc) (conn);
1169 /* Notify the security module that this connection is being destroyed */
1170 RXS_DestroyConnection(conn->securityObject, conn);
1172 /* If this is the last connection using the rx_peer struct, set its
1173 * idle time to now. rxi_ReapConnections will reap it if it's still
1174 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1176 MUTEX_ENTER(&rx_peerHashTable_lock);
1177 if (conn->peer->refCount < 2) {
1178 conn->peer->idleWhen = clock_Sec();
1179 if (conn->peer->refCount < 1) {
1180 conn->peer->refCount = 1;
1181 if (rx_stats_active) {
1182 MUTEX_ENTER(&rx_stats_mutex);
1183 rxi_lowPeerRefCount++;
1184 MUTEX_EXIT(&rx_stats_mutex);
1188 conn->peer->refCount--;
1189 MUTEX_EXIT(&rx_peerHashTable_lock);
1191 if (rx_stats_active)
1193 if (conn->type == RX_SERVER_CONNECTION)
1194 rx_atomic_dec(&rx_stats.nServerConns);
1196 rx_atomic_dec(&rx_stats.nClientConns);
1199 if (conn->specific) {
1201 for (i = 0; i < conn->nSpecific; i++) {
1202 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1203 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1204 conn->specific[i] = NULL;
1206 free(conn->specific);
1208 conn->specific = NULL;
1209 conn->nSpecific = 0;
1210 #endif /* !KERNEL */
1212 MUTEX_DESTROY(&conn->conn_call_lock);
1213 MUTEX_DESTROY(&conn->conn_data_lock);
1214 CV_DESTROY(&conn->conn_call_cv);
1216 rxi_FreeConnection(conn);
1219 /* Destroy the specified connection */
1221 rxi_DestroyConnection(struct rx_connection *conn)
1223 MUTEX_ENTER(&rx_connHashTable_lock);
1224 rxi_DestroyConnectionNoLock(conn);
1225 /* conn should be at the head of the cleanup list */
1226 if (conn == rx_connCleanup_list) {
1227 rx_connCleanup_list = rx_connCleanup_list->next;
1228 MUTEX_EXIT(&rx_connHashTable_lock);
1229 rxi_CleanupConnection(conn);
1231 #ifdef RX_ENABLE_LOCKS
1233 MUTEX_EXIT(&rx_connHashTable_lock);
1235 #endif /* RX_ENABLE_LOCKS */
1239 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1241 struct rx_connection **conn_ptr;
1243 struct rx_packet *packet;
1250 MUTEX_ENTER(&conn->conn_data_lock);
1251 MUTEX_ENTER(&rx_refcnt_mutex);
1252 if (conn->refCount > 0)
1255 if (rx_stats_active) {
1256 MUTEX_ENTER(&rx_stats_mutex);
1257 rxi_lowConnRefCount++;
1258 MUTEX_EXIT(&rx_stats_mutex);
1262 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1263 /* Busy; wait till the last guy before proceeding */
1264 MUTEX_EXIT(&rx_refcnt_mutex);
1265 MUTEX_EXIT(&conn->conn_data_lock);
1270 /* If the client previously called rx_NewCall, but it is still
1271 * waiting, treat this as a running call, and wait to destroy the
1272 * connection later when the call completes. */
1273 if ((conn->type == RX_CLIENT_CONNECTION)
1274 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1275 conn->flags |= RX_CONN_DESTROY_ME;
1276 MUTEX_EXIT(&conn->conn_data_lock);
1280 MUTEX_EXIT(&rx_refcnt_mutex);
1281 MUTEX_EXIT(&conn->conn_data_lock);
1283 /* Check for extant references to this connection */
1284 MUTEX_ENTER(&conn->conn_call_lock);
1285 for (i = 0; i < RX_MAXCALLS; i++) {
1286 struct rx_call *call = conn->call[i];
1289 if (conn->type == RX_CLIENT_CONNECTION) {
1290 MUTEX_ENTER(&call->lock);
1291 if (call->delayedAckEvent) {
1292 /* Push the final acknowledgment out now--there
1293 * won't be a subsequent call to acknowledge the
1294 * last reply packets */
1295 rxevent_Cancel(&call->delayedAckEvent, call,
1296 RX_CALL_REFCOUNT_DELAY);
1297 if (call->state == RX_STATE_PRECALL
1298 || call->state == RX_STATE_ACTIVE) {
1299 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1304 MUTEX_EXIT(&call->lock);
1308 MUTEX_EXIT(&conn->conn_call_lock);
1310 #ifdef RX_ENABLE_LOCKS
1312 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1313 MUTEX_EXIT(&conn->conn_data_lock);
1315 /* Someone is accessing a packet right now. */
1319 #endif /* RX_ENABLE_LOCKS */
1322 /* Don't destroy the connection if there are any call
1323 * structures still in use */
1324 MUTEX_ENTER(&conn->conn_data_lock);
1325 conn->flags |= RX_CONN_DESTROY_ME;
1326 MUTEX_EXIT(&conn->conn_data_lock);
1331 if (conn->natKeepAliveEvent) {
1332 rxi_NatKeepAliveOff(conn);
1335 if (conn->delayedAbortEvent) {
1336 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1337 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1339 MUTEX_ENTER(&conn->conn_data_lock);
1340 rxi_SendConnectionAbort(conn, packet, 0, 1);
1341 MUTEX_EXIT(&conn->conn_data_lock);
1342 rxi_FreePacket(packet);
1346 /* Remove from connection hash table before proceeding */
1348 &rx_connHashTable[CONN_HASH
1349 (peer->host, peer->port, conn->cid, conn->epoch,
1351 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1352 if (*conn_ptr == conn) {
1353 *conn_ptr = conn->next;
1357 /* if the conn that we are destroying was the last connection, then we
1358 * clear rxLastConn as well */
1359 if (rxLastConn == conn)
1362 /* Make sure the connection is completely reset before deleting it. */
1363 /* get rid of pending events that could zap us later */
1364 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1365 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1366 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1368 /* Add the connection to the list of destroyed connections that
1369 * need to be cleaned up. This is necessary to avoid deadlocks
1370 * in the routines we call to inform others that this connection is
1371 * being destroyed. */
1372 conn->next = rx_connCleanup_list;
1373 rx_connCleanup_list = conn;
1376 /* Externally available version */
1378 rx_DestroyConnection(struct rx_connection *conn)
1383 rxi_DestroyConnection(conn);
1388 rx_GetConnection(struct rx_connection *conn)
1393 MUTEX_ENTER(&rx_refcnt_mutex);
1395 MUTEX_EXIT(&rx_refcnt_mutex);
1399 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1400 /* Wait for the transmit queue to no longer be busy.
1401 * requires the call->lock to be held */
1403 rxi_WaitforTQBusy(struct rx_call *call) {
1404 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1405 call->flags |= RX_CALL_TQ_WAIT;
1407 #ifdef RX_ENABLE_LOCKS
1408 osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1409 CV_WAIT(&call->cv_tq, &call->lock);
1410 #else /* RX_ENABLE_LOCKS */
1411 osi_rxSleep(&call->tq);
1412 #endif /* RX_ENABLE_LOCKS */
1414 if (call->tqWaiters == 0) {
1415 call->flags &= ~RX_CALL_TQ_WAIT;
1422 rxi_WakeUpTransmitQueue(struct rx_call *call)
1424 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1425 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1426 call, call->tqWaiters, call->flags));
1427 #ifdef RX_ENABLE_LOCKS
1428 osirx_AssertMine(&call->lock, "rxi_Start start");
1429 CV_BROADCAST(&call->cv_tq);
1430 #else /* RX_ENABLE_LOCKS */
1431 osi_rxWakeup(&call->tq);
1432 #endif /* RX_ENABLE_LOCKS */
1436 /* Start a new rx remote procedure call, on the specified connection.
1437 * If wait is set to 1, wait for a free call channel; otherwise return
1438 * 0. Maxtime gives the maximum number of seconds this call may take,
1439 * after rx_NewCall returns. After this time interval, a call to any
1440 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1441 * For fine grain locking, we hold the conn_call_lock in order to
1442 * to ensure that we don't get signalle after we found a call in an active
1443 * state and before we go to sleep.
1446 rx_NewCall(struct rx_connection *conn)
1448 int i, wait, ignoreBusy = 1;
1449 struct rx_call *call;
1450 struct clock queueTime;
1451 afs_uint32 leastBusy = 0;
1455 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1458 clock_GetTime(&queueTime);
1460 * Check if there are others waiting for a new call.
1461 * If so, let them go first to avoid starving them.
1462 * This is a fairly simple scheme, and might not be
1463 * a complete solution for large numbers of waiters.
1465 * makeCallWaiters keeps track of the number of
1466 * threads waiting to make calls and the
1467 * RX_CONN_MAKECALL_WAITING flag bit is used to
1468 * indicate that there are indeed calls waiting.
1469 * The flag is set when the waiter is incremented.
1470 * It is only cleared when makeCallWaiters is 0.
1471 * This prevents us from accidently destroying the
1472 * connection while it is potentially about to be used.
1474 MUTEX_ENTER(&conn->conn_call_lock);
1475 MUTEX_ENTER(&conn->conn_data_lock);
1476 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1477 conn->flags |= RX_CONN_MAKECALL_WAITING;
1478 conn->makeCallWaiters++;
1479 MUTEX_EXIT(&conn->conn_data_lock);
1481 #ifdef RX_ENABLE_LOCKS
1482 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1486 MUTEX_ENTER(&conn->conn_data_lock);
1487 conn->makeCallWaiters--;
1488 if (conn->makeCallWaiters == 0)
1489 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1492 /* We are now the active thread in rx_NewCall */
1493 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1494 MUTEX_EXIT(&conn->conn_data_lock);
1499 for (i = 0; i < RX_MAXCALLS; i++) {
1500 call = conn->call[i];
1502 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1503 /* we're not ignoring busy call slots; only look at the
1504 * call slot that is the "least" busy */
1508 if (call->state == RX_STATE_DALLY) {
1509 MUTEX_ENTER(&call->lock);
1510 if (call->state == RX_STATE_DALLY) {
1511 if (ignoreBusy && conn->lastBusy[i]) {
1512 /* if we're ignoring busy call slots, skip any ones that
1513 * have lastBusy set */
1514 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1515 leastBusy = conn->lastBusy[i];
1517 MUTEX_EXIT(&call->lock);
1522 * We are setting the state to RX_STATE_RESET to
1523 * ensure that no one else will attempt to use this
1524 * call once we drop the conn->conn_call_lock and
1525 * call->lock. We must drop the conn->conn_call_lock
1526 * before calling rxi_ResetCall because the process
1527 * of clearing the transmit queue can block for an
1528 * extended period of time. If we block while holding
1529 * the conn->conn_call_lock, then all rx_EndCall
1530 * processing will block as well. This has a detrimental
1531 * effect on overall system performance.
1533 call->state = RX_STATE_RESET;
1534 (*call->callNumber)++;
1535 MUTEX_EXIT(&conn->conn_call_lock);
1536 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1537 rxi_ResetCall(call, 0);
1538 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1542 * If we failed to be able to safely obtain the
1543 * conn->conn_call_lock we will have to drop the
1544 * call->lock to avoid a deadlock. When the call->lock
1545 * is released the state of the call can change. If it
1546 * is no longer RX_STATE_RESET then some other thread is
1549 MUTEX_EXIT(&call->lock);
1550 MUTEX_ENTER(&conn->conn_call_lock);
1551 MUTEX_ENTER(&call->lock);
1553 if (call->state == RX_STATE_RESET)
1557 * If we get here it means that after dropping
1558 * the conn->conn_call_lock and call->lock that
1559 * the call is no longer ours. If we can't find
1560 * a free call in the remaining slots we should
1561 * not go immediately to RX_CONN_MAKECALL_WAITING
1562 * because by dropping the conn->conn_call_lock
1563 * we have given up synchronization with rx_EndCall.
1564 * Instead, cycle through one more time to see if
1565 * we can find a call that can call our own.
1567 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1570 MUTEX_EXIT(&call->lock);
1573 if (ignoreBusy && conn->lastBusy[i]) {
1574 /* if we're ignoring busy call slots, skip any ones that
1575 * have lastBusy set */
1576 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1577 leastBusy = conn->lastBusy[i];
1582 /* rxi_NewCall returns with mutex locked */
1583 call = rxi_NewCall(conn, i);
1584 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1588 if (i < RX_MAXCALLS) {
1589 conn->lastBusy[i] = 0;
1590 call->flags &= ~RX_CALL_PEER_BUSY;
1595 if (leastBusy && ignoreBusy) {
1596 /* we didn't find a useable call slot, but we did see at least one
1597 * 'busy' slot; look again and only use a slot with the 'least
1603 MUTEX_ENTER(&conn->conn_data_lock);
1604 conn->flags |= RX_CONN_MAKECALL_WAITING;
1605 conn->makeCallWaiters++;
1606 MUTEX_EXIT(&conn->conn_data_lock);
1608 #ifdef RX_ENABLE_LOCKS
1609 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1613 MUTEX_ENTER(&conn->conn_data_lock);
1614 conn->makeCallWaiters--;
1615 if (conn->makeCallWaiters == 0)
1616 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1617 MUTEX_EXIT(&conn->conn_data_lock);
1619 /* Client is initially in send mode */
1620 call->state = RX_STATE_ACTIVE;
1621 call->error = conn->error;
1623 call->mode = RX_MODE_ERROR;
1625 call->mode = RX_MODE_SENDING;
1627 /* remember start time for call in case we have hard dead time limit */
1628 call->queueTime = queueTime;
1629 clock_GetTime(&call->startTime);
1630 hzero(call->bytesSent);
1631 hzero(call->bytesRcvd);
1633 /* Turn on busy protocol. */
1634 rxi_KeepAliveOn(call);
1636 /* Attempt MTU discovery */
1637 rxi_GrowMTUOn(call);
1640 * We are no longer the active thread in rx_NewCall
1642 MUTEX_ENTER(&conn->conn_data_lock);
1643 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1644 MUTEX_EXIT(&conn->conn_data_lock);
1647 * Wake up anyone else who might be giving us a chance to
1648 * run (see code above that avoids resource starvation).
1650 #ifdef RX_ENABLE_LOCKS
1651 CV_BROADCAST(&conn->conn_call_cv);
1655 MUTEX_EXIT(&conn->conn_call_lock);
1657 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1658 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1659 osi_Panic("rx_NewCall call about to be used without an empty tq");
1661 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1663 MUTEX_EXIT(&call->lock);
1666 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1671 rxi_HasActiveCalls(struct rx_connection *aconn)
1674 struct rx_call *tcall;
1678 for (i = 0; i < RX_MAXCALLS; i++) {
1679 if ((tcall = aconn->call[i])) {
1680 if ((tcall->state == RX_STATE_ACTIVE)
1681 || (tcall->state == RX_STATE_PRECALL)) {
1692 rxi_GetCallNumberVector(struct rx_connection *aconn,
1693 afs_int32 * aint32s)
1696 struct rx_call *tcall;
1700 MUTEX_ENTER(&aconn->conn_call_lock);
1701 for (i = 0; i < RX_MAXCALLS; i++) {
1702 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1703 aint32s[i] = aconn->callNumber[i] + 1;
1705 aint32s[i] = aconn->callNumber[i];
1707 MUTEX_EXIT(&aconn->conn_call_lock);
1713 rxi_SetCallNumberVector(struct rx_connection *aconn,
1714 afs_int32 * aint32s)
1717 struct rx_call *tcall;
1721 MUTEX_ENTER(&aconn->conn_call_lock);
1722 for (i = 0; i < RX_MAXCALLS; i++) {
1723 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1724 aconn->callNumber[i] = aint32s[i] - 1;
1726 aconn->callNumber[i] = aint32s[i];
1728 MUTEX_EXIT(&aconn->conn_call_lock);
1733 /* Advertise a new service. A service is named locally by a UDP port
1734 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1737 char *serviceName; Name for identification purposes (e.g. the
1738 service name might be used for probing for
1741 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1742 char *serviceName, struct rx_securityClass **securityObjects,
1743 int nSecurityObjects,
1744 afs_int32(*serviceProc) (struct rx_call * acall))
1746 osi_socket socket = OSI_NULLSOCKET;
1747 struct rx_service *tservice;
1753 if (serviceId == 0) {
1755 "rx_NewService: service id for service %s is not non-zero.\n",
1762 "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",
1770 tservice = rxi_AllocService();
1773 #ifdef RX_ENABLE_LOCKS
1774 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1777 for (i = 0; i < RX_MAX_SERVICES; i++) {
1778 struct rx_service *service = rx_services[i];
1780 if (port == service->servicePort && host == service->serviceHost) {
1781 if (service->serviceId == serviceId) {
1782 /* The identical service has already been
1783 * installed; if the caller was intending to
1784 * change the security classes used by this
1785 * service, he/she loses. */
1787 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1788 serviceName, serviceId, service->serviceName);
1790 rxi_FreeService(tservice);
1793 /* Different service, same port: re-use the socket
1794 * which is bound to the same port */
1795 socket = service->socket;
1798 if (socket == OSI_NULLSOCKET) {
1799 /* If we don't already have a socket (from another
1800 * service on same port) get a new one */
1801 socket = rxi_GetHostUDPSocket(host, port);
1802 if (socket == OSI_NULLSOCKET) {
1804 rxi_FreeService(tservice);
1809 service->socket = socket;
1810 service->serviceHost = host;
1811 service->servicePort = port;
1812 service->serviceId = serviceId;
1813 service->serviceName = serviceName;
1814 service->nSecurityObjects = nSecurityObjects;
1815 service->securityObjects = securityObjects;
1816 service->minProcs = 0;
1817 service->maxProcs = 1;
1818 service->idleDeadTime = 60;
1819 service->idleDeadErr = 0;
1820 service->connDeadTime = rx_connDeadTime;
1821 service->executeRequestProc = serviceProc;
1822 service->checkReach = 0;
1823 service->nSpecific = 0;
1824 service->specific = NULL;
1825 rx_services[i] = service; /* not visible until now */
1831 rxi_FreeService(tservice);
1832 (osi_Msg "rx_NewService: cannot support > %d services\n",
1837 /* Set configuration options for all of a service's security objects */
1840 rx_SetSecurityConfiguration(struct rx_service *service,
1841 rx_securityConfigVariables type,
1845 for (i = 0; i<service->nSecurityObjects; i++) {
1846 if (service->securityObjects[i]) {
1847 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1855 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1856 struct rx_securityClass **securityObjects, int nSecurityObjects,
1857 afs_int32(*serviceProc) (struct rx_call * acall))
1859 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1862 /* Generic request processing loop. This routine should be called
1863 * by the implementation dependent rx_ServerProc. If socketp is
1864 * non-null, it will be set to the file descriptor that this thread
1865 * is now listening on. If socketp is null, this routine will never
1868 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1870 struct rx_call *call;
1872 struct rx_service *tservice = NULL;
1879 call = rx_GetCall(threadID, tservice, socketp);
1880 if (socketp && *socketp != OSI_NULLSOCKET) {
1881 /* We are now a listener thread */
1887 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1888 #ifdef RX_ENABLE_LOCKS
1890 #endif /* RX_ENABLE_LOCKS */
1891 afs_termState = AFSOP_STOP_AFS;
1892 afs_osi_Wakeup(&afs_termState);
1893 #ifdef RX_ENABLE_LOCKS
1895 #endif /* RX_ENABLE_LOCKS */
1900 /* if server is restarting( typically smooth shutdown) then do not
1901 * allow any new calls.
1904 if (rx_tranquil && (call != NULL)) {
1908 MUTEX_ENTER(&call->lock);
1910 rxi_CallError(call, RX_RESTARTING);
1911 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1913 MUTEX_EXIT(&call->lock);
1918 tservice = call->conn->service;
1920 if (tservice->beforeProc)
1921 (*tservice->beforeProc) (call);
1923 code = tservice->executeRequestProc(call);
1925 if (tservice->afterProc)
1926 (*tservice->afterProc) (call, code);
1928 rx_EndCall(call, code);
1930 if (tservice->postProc)
1931 (*tservice->postProc) (code);
1933 if (rx_stats_active) {
1934 MUTEX_ENTER(&rx_stats_mutex);
1936 MUTEX_EXIT(&rx_stats_mutex);
1943 rx_WakeupServerProcs(void)
1945 struct rx_serverQueueEntry *np, *tqp;
1949 MUTEX_ENTER(&rx_serverPool_lock);
1951 #ifdef RX_ENABLE_LOCKS
1952 if (rx_waitForPacket)
1953 CV_BROADCAST(&rx_waitForPacket->cv);
1954 #else /* RX_ENABLE_LOCKS */
1955 if (rx_waitForPacket)
1956 osi_rxWakeup(rx_waitForPacket);
1957 #endif /* RX_ENABLE_LOCKS */
1958 MUTEX_ENTER(&freeSQEList_lock);
1959 for (np = rx_FreeSQEList; np; np = tqp) {
1960 tqp = *(struct rx_serverQueueEntry **)np;
1961 #ifdef RX_ENABLE_LOCKS
1962 CV_BROADCAST(&np->cv);
1963 #else /* RX_ENABLE_LOCKS */
1965 #endif /* RX_ENABLE_LOCKS */
1967 MUTEX_EXIT(&freeSQEList_lock);
1968 for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1969 #ifdef RX_ENABLE_LOCKS
1970 CV_BROADCAST(&np->cv);
1971 #else /* RX_ENABLE_LOCKS */
1973 #endif /* RX_ENABLE_LOCKS */
1975 MUTEX_EXIT(&rx_serverPool_lock);
1980 * One thing that seems to happen is that all the server threads get
1981 * tied up on some empty or slow call, and then a whole bunch of calls
1982 * arrive at once, using up the packet pool, so now there are more
1983 * empty calls. The most critical resources here are server threads
1984 * and the free packet pool. The "doreclaim" code seems to help in
1985 * general. I think that eventually we arrive in this state: there
1986 * are lots of pending calls which do have all their packets present,
1987 * so they won't be reclaimed, are multi-packet calls, so they won't
1988 * be scheduled until later, and thus are tying up most of the free
1989 * packet pool for a very long time.
1991 * 1. schedule multi-packet calls if all the packets are present.
1992 * Probably CPU-bound operation, useful to return packets to pool.
1993 * Do what if there is a full window, but the last packet isn't here?
1994 * 3. preserve one thread which *only* runs "best" calls, otherwise
1995 * it sleeps and waits for that type of call.
1996 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1997 * the current dataquota business is badly broken. The quota isn't adjusted
1998 * to reflect how many packets are presently queued for a running call.
1999 * So, when we schedule a queued call with a full window of packets queued
2000 * up for it, that *should* free up a window full of packets for other 2d-class
2001 * calls to be able to use from the packet pool. But it doesn't.
2003 * NB. Most of the time, this code doesn't run -- since idle server threads
2004 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2005 * as a new call arrives.
2007 /* Sleep until a call arrives. Returns a pointer to the call, ready
2008 * for an rx_Read. */
2009 #ifdef RX_ENABLE_LOCKS
2011 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2013 struct rx_serverQueueEntry *sq;
2014 struct rx_call *call = (struct rx_call *)0;
2015 struct rx_service *service = NULL;
2017 MUTEX_ENTER(&freeSQEList_lock);
2019 if ((sq = rx_FreeSQEList)) {
2020 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2021 MUTEX_EXIT(&freeSQEList_lock);
2022 } else { /* otherwise allocate a new one and return that */
2023 MUTEX_EXIT(&freeSQEList_lock);
2024 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2025 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2026 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2029 MUTEX_ENTER(&rx_serverPool_lock);
2030 if (cur_service != NULL) {
2031 ReturnToServerPool(cur_service);
2034 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2035 struct rx_call *tcall, *ncall, *choice2 = NULL;
2037 /* Scan for eligible incoming calls. A call is not eligible
2038 * if the maximum number of calls for its service type are
2039 * already executing */
2040 /* One thread will process calls FCFS (to prevent starvation),
2041 * while the other threads may run ahead looking for calls which
2042 * have all their input data available immediately. This helps
2043 * keep threads from blocking, waiting for data from the client. */
2044 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2045 service = tcall->conn->service;
2046 if (!QuotaOK(service)) {
2049 MUTEX_ENTER(&rx_pthread_mutex);
2050 if (tno == rxi_fcfs_thread_num
2051 || queue_IsLast(&rx_incomingCallQueue, tcall)) {
2052 MUTEX_EXIT(&rx_pthread_mutex);
2053 /* If we're the fcfs thread , then we'll just use
2054 * this call. If we haven't been able to find an optimal
2055 * choice, and we're at the end of the list, then use a
2056 * 2d choice if one has been identified. Otherwise... */
2057 call = (choice2 ? choice2 : tcall);
2058 service = call->conn->service;
2060 MUTEX_EXIT(&rx_pthread_mutex);
2061 if (!queue_IsEmpty(&tcall->rq)) {
2062 struct rx_packet *rp;
2063 rp = queue_First(&tcall->rq, rx_packet);
2064 if (rp->header.seq == 1) {
2066 || (rp->header.flags & RX_LAST_PACKET)) {
2068 } else if (rxi_2dchoice && !choice2
2069 && !(tcall->flags & RX_CALL_CLEARED)
2070 && (tcall->rprev > rxi_HardAckRate)) {
2080 ReturnToServerPool(service);
2087 MUTEX_EXIT(&rx_serverPool_lock);
2088 MUTEX_ENTER(&call->lock);
2090 if (call->flags & RX_CALL_WAIT_PROC) {
2091 call->flags &= ~RX_CALL_WAIT_PROC;
2092 rx_atomic_dec(&rx_nWaiting);
2095 if (call->state != RX_STATE_PRECALL || call->error) {
2096 MUTEX_EXIT(&call->lock);
2097 MUTEX_ENTER(&rx_serverPool_lock);
2098 ReturnToServerPool(service);
2103 if (queue_IsEmpty(&call->rq)
2104 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2105 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2107 CLEAR_CALL_QUEUE_LOCK(call);
2110 /* If there are no eligible incoming calls, add this process
2111 * to the idle server queue, to wait for one */
2115 *socketp = OSI_NULLSOCKET;
2117 sq->socketp = socketp;
2118 queue_Append(&rx_idleServerQueue, sq);
2119 #ifndef AFS_AIX41_ENV
2120 rx_waitForPacket = sq;
2122 rx_waitingForPacket = sq;
2123 #endif /* AFS_AIX41_ENV */
2125 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2127 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2128 MUTEX_EXIT(&rx_serverPool_lock);
2129 return (struct rx_call *)0;
2132 } while (!(call = sq->newcall)
2133 && !(socketp && *socketp != OSI_NULLSOCKET));
2134 MUTEX_EXIT(&rx_serverPool_lock);
2136 MUTEX_ENTER(&call->lock);
2142 MUTEX_ENTER(&freeSQEList_lock);
2143 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2144 rx_FreeSQEList = sq;
2145 MUTEX_EXIT(&freeSQEList_lock);
2148 clock_GetTime(&call->startTime);
2149 call->state = RX_STATE_ACTIVE;
2150 call->mode = RX_MODE_RECEIVING;
2151 #ifdef RX_KERNEL_TRACE
2152 if (ICL_SETACTIVE(afs_iclSetp)) {
2153 int glockOwner = ISAFS_GLOCK();
2156 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2157 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2164 rxi_calltrace(RX_CALL_START, call);
2165 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2166 call->conn->service->servicePort, call->conn->service->serviceId,
2169 MUTEX_EXIT(&call->lock);
2170 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2172 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2177 #else /* RX_ENABLE_LOCKS */
2179 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2181 struct rx_serverQueueEntry *sq;
2182 struct rx_call *call = (struct rx_call *)0, *choice2;
2183 struct rx_service *service = NULL;
2187 MUTEX_ENTER(&freeSQEList_lock);
2189 if ((sq = rx_FreeSQEList)) {
2190 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2191 MUTEX_EXIT(&freeSQEList_lock);
2192 } else { /* otherwise allocate a new one and return that */
2193 MUTEX_EXIT(&freeSQEList_lock);
2194 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2195 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2196 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2198 MUTEX_ENTER(&sq->lock);
2200 if (cur_service != NULL) {
2201 cur_service->nRequestsRunning--;
2202 MUTEX_ENTER(&rx_quota_mutex);
2203 if (cur_service->nRequestsRunning < cur_service->minProcs)
2206 MUTEX_EXIT(&rx_quota_mutex);
2208 if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2209 struct rx_call *tcall, *ncall;
2210 /* Scan for eligible incoming calls. A call is not eligible
2211 * if the maximum number of calls for its service type are
2212 * already executing */
2213 /* One thread will process calls FCFS (to prevent starvation),
2214 * while the other threads may run ahead looking for calls which
2215 * have all their input data available immediately. This helps
2216 * keep threads from blocking, waiting for data from the client. */
2217 choice2 = (struct rx_call *)0;
2218 for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2219 service = tcall->conn->service;
2220 if (QuotaOK(service)) {
2221 MUTEX_ENTER(&rx_pthread_mutex);
2222 if (tno == rxi_fcfs_thread_num
2223 || !tcall->queue_item_header.next) {
2224 MUTEX_EXIT(&rx_pthread_mutex);
2225 /* If we're the fcfs thread, then we'll just use
2226 * this call. If we haven't been able to find an optimal
2227 * choice, and we're at the end of the list, then use a
2228 * 2d choice if one has been identified. Otherwise... */
2229 call = (choice2 ? choice2 : tcall);
2230 service = call->conn->service;
2232 MUTEX_EXIT(&rx_pthread_mutex);
2233 if (!queue_IsEmpty(&tcall->rq)) {
2234 struct rx_packet *rp;
2235 rp = queue_First(&tcall->rq, rx_packet);
2236 if (rp->header.seq == 1
2238 || (rp->header.flags & RX_LAST_PACKET))) {
2240 } else if (rxi_2dchoice && !choice2
2241 && !(tcall->flags & RX_CALL_CLEARED)
2242 && (tcall->rprev > rxi_HardAckRate)) {
2256 /* we can't schedule a call if there's no data!!! */
2257 /* send an ack if there's no data, if we're missing the
2258 * first packet, or we're missing something between first
2259 * and last -- there's a "hole" in the incoming data. */
2260 if (queue_IsEmpty(&call->rq)
2261 || queue_First(&call->rq, rx_packet)->header.seq != 1
2262 || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2263 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2265 call->flags &= (~RX_CALL_WAIT_PROC);
2266 service->nRequestsRunning++;
2267 /* just started call in minProcs pool, need fewer to maintain
2269 MUTEX_ENTER(&rx_quota_mutex);
2270 if (service->nRequestsRunning <= service->minProcs)
2273 MUTEX_EXIT(&rx_quota_mutex);
2274 rx_atomic_dec(&rx_nWaiting);
2275 /* MUTEX_EXIT(&call->lock); */
2277 /* If there are no eligible incoming calls, add this process
2278 * to the idle server queue, to wait for one */
2281 *socketp = OSI_NULLSOCKET;
2283 sq->socketp = socketp;
2284 queue_Append(&rx_idleServerQueue, sq);
2288 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2290 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2291 return (struct rx_call *)0;
2294 } while (!(call = sq->newcall)
2295 && !(socketp && *socketp != OSI_NULLSOCKET));
2297 MUTEX_EXIT(&sq->lock);
2299 MUTEX_ENTER(&freeSQEList_lock);
2300 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2301 rx_FreeSQEList = sq;
2302 MUTEX_EXIT(&freeSQEList_lock);
2305 clock_GetTime(&call->startTime);
2306 call->state = RX_STATE_ACTIVE;
2307 call->mode = RX_MODE_RECEIVING;
2308 #ifdef RX_KERNEL_TRACE
2309 if (ICL_SETACTIVE(afs_iclSetp)) {
2310 int glockOwner = ISAFS_GLOCK();
2313 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2314 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2321 rxi_calltrace(RX_CALL_START, call);
2322 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2323 call->conn->service->servicePort, call->conn->service->serviceId,
2326 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2333 #endif /* RX_ENABLE_LOCKS */
2337 /* Establish a procedure to be called when a packet arrives for a
2338 * call. This routine will be called at most once after each call,
2339 * and will also be called if there is an error condition on the or
2340 * the call is complete. Used by multi rx to build a selection
2341 * function which determines which of several calls is likely to be a
2342 * good one to read from.
2343 * NOTE: the way this is currently implemented it is probably only a
2344 * good idea to (1) use it immediately after a newcall (clients only)
2345 * and (2) only use it once. Other uses currently void your warranty
2348 rx_SetArrivalProc(struct rx_call *call,
2349 void (*proc) (struct rx_call * call,
2352 void * handle, int arg)
2354 call->arrivalProc = proc;
2355 call->arrivalProcHandle = handle;
2356 call->arrivalProcArg = arg;
2359 /* Call is finished (possibly prematurely). Return rc to the peer, if
2360 * appropriate, and return the final error code from the conversation
2364 rx_EndCall(struct rx_call *call, afs_int32 rc)
2366 struct rx_connection *conn = call->conn;
2370 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2371 call, rc, call->error, call->abortCode));
2374 MUTEX_ENTER(&call->lock);
2376 if (rc == 0 && call->error == 0) {
2377 call->abortCode = 0;
2378 call->abortCount = 0;
2381 call->arrivalProc = (void (*)())0;
2382 if (rc && call->error == 0) {
2383 rxi_CallError(call, rc);
2384 call->mode = RX_MODE_ERROR;
2385 /* Send an abort message to the peer if this error code has
2386 * only just been set. If it was set previously, assume the
2387 * peer has already been sent the error code or will request it
2389 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2391 if (conn->type == RX_SERVER_CONNECTION) {
2392 /* Make sure reply or at least dummy reply is sent */
2393 if (call->mode == RX_MODE_RECEIVING) {
2394 MUTEX_EXIT(&call->lock);
2395 rxi_WriteProc(call, 0, 0);
2396 MUTEX_ENTER(&call->lock);
2398 if (call->mode == RX_MODE_SENDING) {
2399 MUTEX_EXIT(&call->lock);
2400 rxi_FlushWrite(call);
2401 MUTEX_ENTER(&call->lock);
2403 rxi_calltrace(RX_CALL_END, call);
2404 /* Call goes to hold state until reply packets are acknowledged */
2405 if (call->tfirst + call->nSoftAcked < call->tnext) {
2406 call->state = RX_STATE_HOLD;
2408 call->state = RX_STATE_DALLY;
2409 rxi_ClearTransmitQueue(call, 0);
2410 rxi_rto_cancel(call);
2411 rxevent_Cancel(&call->keepAliveEvent, call,
2412 RX_CALL_REFCOUNT_ALIVE);
2414 } else { /* Client connection */
2416 /* Make sure server receives input packets, in the case where
2417 * no reply arguments are expected */
2418 if ((call->mode == RX_MODE_SENDING)
2419 || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2420 MUTEX_EXIT(&call->lock);
2421 (void)rxi_ReadProc(call, &dummy, 1);
2422 MUTEX_ENTER(&call->lock);
2425 /* If we had an outstanding delayed ack, be nice to the server
2426 * and force-send it now.
2428 if (call->delayedAckEvent) {
2429 rxevent_Cancel(&call->delayedAckEvent, call,
2430 RX_CALL_REFCOUNT_DELAY);
2431 rxi_SendDelayedAck(NULL, call, NULL, 0);
2434 /* We need to release the call lock since it's lower than the
2435 * conn_call_lock and we don't want to hold the conn_call_lock
2436 * over the rx_ReadProc call. The conn_call_lock needs to be held
2437 * here for the case where rx_NewCall is perusing the calls on
2438 * the connection structure. We don't want to signal until
2439 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2440 * have checked this call, found it active and by the time it
2441 * goes to sleep, will have missed the signal.
2443 MUTEX_EXIT(&call->lock);
2444 MUTEX_ENTER(&conn->conn_call_lock);
2445 MUTEX_ENTER(&call->lock);
2447 if (!(call->flags & RX_CALL_PEER_BUSY)) {
2448 conn->lastBusy[call->channel] = 0;
2451 MUTEX_ENTER(&conn->conn_data_lock);
2452 conn->flags |= RX_CONN_BUSY;
2453 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2454 MUTEX_EXIT(&conn->conn_data_lock);
2455 #ifdef RX_ENABLE_LOCKS
2456 CV_BROADCAST(&conn->conn_call_cv);
2461 #ifdef RX_ENABLE_LOCKS
2463 MUTEX_EXIT(&conn->conn_data_lock);
2465 #endif /* RX_ENABLE_LOCKS */
2466 call->state = RX_STATE_DALLY;
2468 error = call->error;
2470 /* currentPacket, nLeft, and NFree must be zeroed here, because
2471 * ResetCall cannot: ResetCall may be called at splnet(), in the
2472 * kernel version, and may interrupt the macros rx_Read or
2473 * rx_Write, which run at normal priority for efficiency. */
2474 if (call->currentPacket) {
2475 #ifdef RX_TRACK_PACKETS
2476 call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2478 rxi_FreePacket(call->currentPacket);
2479 call->currentPacket = (struct rx_packet *)0;
2482 call->nLeft = call->nFree = call->curlen = 0;
2484 /* Free any packets from the last call to ReadvProc/WritevProc */
2485 #ifdef RXDEBUG_PACKET
2487 #endif /* RXDEBUG_PACKET */
2488 rxi_FreePackets(0, &call->iovq);
2489 MUTEX_EXIT(&call->lock);
2491 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2492 if (conn->type == RX_CLIENT_CONNECTION) {
2493 MUTEX_ENTER(&conn->conn_data_lock);
2494 conn->flags &= ~RX_CONN_BUSY;
2495 MUTEX_EXIT(&conn->conn_data_lock);
2496 MUTEX_EXIT(&conn->conn_call_lock);
2500 * Map errors to the local host's errno.h format.
2502 error = ntoh_syserr_conv(error);
2506 #if !defined(KERNEL)
2508 /* Call this routine when shutting down a server or client (especially
2509 * clients). This will allow Rx to gracefully garbage collect server
2510 * connections, and reduce the number of retries that a server might
2511 * make to a dead client.
2512 * This is not quite right, since some calls may still be ongoing and
2513 * we can't lock them to destroy them. */
2517 struct rx_connection **conn_ptr, **conn_end;
2521 if (rxinit_status == 1) {
2523 return; /* Already shutdown. */
2525 rxi_DeleteCachedConnections();
2526 if (rx_connHashTable) {
2527 MUTEX_ENTER(&rx_connHashTable_lock);
2528 for (conn_ptr = &rx_connHashTable[0], conn_end =
2529 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2531 struct rx_connection *conn, *next;
2532 for (conn = *conn_ptr; conn; conn = next) {
2534 if (conn->type == RX_CLIENT_CONNECTION) {
2535 MUTEX_ENTER(&rx_refcnt_mutex);
2537 MUTEX_EXIT(&rx_refcnt_mutex);
2538 #ifdef RX_ENABLE_LOCKS
2539 rxi_DestroyConnectionNoLock(conn);
2540 #else /* RX_ENABLE_LOCKS */
2541 rxi_DestroyConnection(conn);
2542 #endif /* RX_ENABLE_LOCKS */
2546 #ifdef RX_ENABLE_LOCKS
2547 while (rx_connCleanup_list) {
2548 struct rx_connection *conn;
2549 conn = rx_connCleanup_list;
2550 rx_connCleanup_list = rx_connCleanup_list->next;
2551 MUTEX_EXIT(&rx_connHashTable_lock);
2552 rxi_CleanupConnection(conn);
2553 MUTEX_ENTER(&rx_connHashTable_lock);
2555 MUTEX_EXIT(&rx_connHashTable_lock);
2556 #endif /* RX_ENABLE_LOCKS */
2561 afs_winsockCleanup();
2569 /* if we wakeup packet waiter too often, can get in loop with two
2570 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2572 rxi_PacketsUnWait(void)
2574 if (!rx_waitingForPackets) {
2578 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2579 return; /* still over quota */
2582 rx_waitingForPackets = 0;
2583 #ifdef RX_ENABLE_LOCKS
2584 CV_BROADCAST(&rx_waitingForPackets_cv);
2586 osi_rxWakeup(&rx_waitingForPackets);
2592 /* ------------------Internal interfaces------------------------- */
2594 /* Return this process's service structure for the
2595 * specified socket and service */
2596 static struct rx_service *
2597 rxi_FindService(osi_socket socket, u_short serviceId)
2599 struct rx_service **sp;
2600 for (sp = &rx_services[0]; *sp; sp++) {
2601 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2607 #ifdef RXDEBUG_PACKET
2608 #ifdef KDUMP_RX_LOCK
2609 static struct rx_call_rx_lock *rx_allCallsp = 0;
2611 static struct rx_call *rx_allCallsp = 0;
2613 #endif /* RXDEBUG_PACKET */
2615 /* Allocate a call structure, for the indicated channel of the
2616 * supplied connection. The mode and state of the call must be set by
2617 * the caller. Returns the call with mutex locked. */
2618 static struct rx_call *
2619 rxi_NewCall(struct rx_connection *conn, int channel)
2621 struct rx_call *call;
2622 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2623 struct rx_call *cp; /* Call pointer temp */
2624 struct rx_call *nxp; /* Next call pointer, for queue_Scan */
2625 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2627 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2629 /* Grab an existing call structure, or allocate a new one.
2630 * Existing call structures are assumed to have been left reset by
2632 MUTEX_ENTER(&rx_freeCallQueue_lock);
2634 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2636 * EXCEPT that the TQ might not yet be cleared out.
2637 * Skip over those with in-use TQs.
2640 for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2641 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2647 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2648 if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2649 call = queue_First(&rx_freeCallQueue, rx_call);
2650 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2652 if (rx_stats_active)
2653 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2654 MUTEX_EXIT(&rx_freeCallQueue_lock);
2655 MUTEX_ENTER(&call->lock);
2656 CLEAR_CALL_QUEUE_LOCK(call);
2657 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2658 /* Now, if TQ wasn't cleared earlier, do it now. */
2659 rxi_WaitforTQBusy(call);
2660 if (call->flags & RX_CALL_TQ_CLEARME) {
2661 rxi_ClearTransmitQueue(call, 1);
2662 /*queue_Init(&call->tq);*/
2664 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2665 /* Bind the call to its connection structure */
2667 rxi_ResetCall(call, 1);
2670 call = rxi_Alloc(sizeof(struct rx_call));
2671 #ifdef RXDEBUG_PACKET
2672 call->allNextp = rx_allCallsp;
2673 rx_allCallsp = call;
2675 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2676 #else /* RXDEBUG_PACKET */
2677 rx_atomic_inc(&rx_stats.nCallStructs);
2678 #endif /* RXDEBUG_PACKET */
2680 MUTEX_EXIT(&rx_freeCallQueue_lock);
2681 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2682 MUTEX_ENTER(&call->lock);
2683 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2684 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2685 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2687 /* Initialize once-only items */
2688 queue_Init(&call->tq);
2689 queue_Init(&call->rq);
2690 queue_Init(&call->iovq);
2691 #ifdef RXDEBUG_PACKET
2692 call->rqc = call->tqc = call->iovqc = 0;
2693 #endif /* RXDEBUG_PACKET */
2694 /* Bind the call to its connection structure (prereq for reset) */
2696 rxi_ResetCall(call, 1);
2698 call->channel = channel;
2699 call->callNumber = &conn->callNumber[channel];
2700 call->rwind = conn->rwind[channel];
2701 call->twind = conn->twind[channel];
2702 /* Note that the next expected call number is retained (in
2703 * conn->callNumber[i]), even if we reallocate the call structure
2705 conn->call[channel] = call;
2706 /* if the channel's never been used (== 0), we should start at 1, otherwise
2707 * the call number is valid from the last time this channel was used */
2708 if (*call->callNumber == 0)
2709 *call->callNumber = 1;
2714 /* A call has been inactive long enough that so we can throw away
2715 * state, including the call structure, which is placed on the call
2718 * call->lock amd rx_refcnt_mutex are held upon entry.
2719 * haveCTLock is set when called from rxi_ReapConnections.
2721 * return 1 if the call is freed, 0 if not.
2724 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2726 int channel = call->channel;
2727 struct rx_connection *conn = call->conn;
2728 u_char state = call->state;
2731 * We are setting the state to RX_STATE_RESET to
2732 * ensure that no one else will attempt to use this
2733 * call once we drop the refcnt lock. We must drop
2734 * the refcnt lock before calling rxi_ResetCall
2735 * because it cannot be held across acquiring the
2736 * freepktQ lock. NewCall does the same.
2738 call->state = RX_STATE_RESET;
2739 MUTEX_EXIT(&rx_refcnt_mutex);
2740 rxi_ResetCall(call, 0);
2742 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2744 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2745 (*call->callNumber)++;
2747 if (call->conn->call[channel] == call)
2748 call->conn->call[channel] = 0;
2749 MUTEX_EXIT(&conn->conn_call_lock);
2752 * We couldn't obtain the conn_call_lock so we can't
2753 * disconnect the call from the connection. Set the
2754 * call state to dally so that the call can be reused.
2756 MUTEX_ENTER(&rx_refcnt_mutex);
2757 call->state = RX_STATE_DALLY;
2761 MUTEX_ENTER(&rx_freeCallQueue_lock);
2762 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2763 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2764 /* A call may be free even though its transmit queue is still in use.
2765 * Since we search the call list from head to tail, put busy calls at
2766 * the head of the list, and idle calls at the tail.
2768 if (call->flags & RX_CALL_TQ_BUSY)
2769 queue_Prepend(&rx_freeCallQueue, call);
2771 queue_Append(&rx_freeCallQueue, call);
2772 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2773 queue_Append(&rx_freeCallQueue, call);
2774 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2775 if (rx_stats_active)
2776 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2777 MUTEX_EXIT(&rx_freeCallQueue_lock);
2779 /* Destroy the connection if it was previously slated for
2780 * destruction, i.e. the Rx client code previously called
2781 * rx_DestroyConnection (client connections), or
2782 * rxi_ReapConnections called the same routine (server
2783 * connections). Only do this, however, if there are no
2784 * outstanding calls. Note that for fine grain locking, there appears
2785 * to be a deadlock in that rxi_FreeCall has a call locked and
2786 * DestroyConnectionNoLock locks each call in the conn. But note a
2787 * few lines up where we have removed this call from the conn.
2788 * If someone else destroys a connection, they either have no
2789 * call lock held or are going through this section of code.
2791 MUTEX_ENTER(&conn->conn_data_lock);
2792 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2793 MUTEX_ENTER(&rx_refcnt_mutex);
2795 MUTEX_EXIT(&rx_refcnt_mutex);
2796 MUTEX_EXIT(&conn->conn_data_lock);
2797 #ifdef RX_ENABLE_LOCKS
2799 rxi_DestroyConnectionNoLock(conn);
2801 rxi_DestroyConnection(conn);
2802 #else /* RX_ENABLE_LOCKS */
2803 rxi_DestroyConnection(conn);
2804 #endif /* RX_ENABLE_LOCKS */
2806 MUTEX_EXIT(&conn->conn_data_lock);
2808 MUTEX_ENTER(&rx_refcnt_mutex);
2812 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2813 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2816 rxi_Alloc(size_t size)
2820 if (rx_stats_active) {
2821 rx_atomic_add(&rxi_Allocsize, (int) size);
2822 rx_atomic_inc(&rxi_Alloccnt);
2826 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2827 afs_osi_Alloc_NoSleep(size);
2832 osi_Panic("rxi_Alloc error");
2838 rxi_Free(void *addr, size_t size)
2840 if (rx_stats_active) {
2841 rx_atomic_sub(&rxi_Allocsize, (int) size);
2842 rx_atomic_dec(&rxi_Alloccnt);
2844 osi_Free(addr, size);
2848 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2850 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2851 struct rx_peer *next = NULL;
2855 MUTEX_ENTER(&rx_peerHashTable_lock);
2857 peer_ptr = &rx_peerHashTable[0];
2858 peer_end = &rx_peerHashTable[rx_hashTableSize];
2861 for ( ; peer_ptr < peer_end; peer_ptr++) {
2864 for ( ; peer; peer = next) {
2866 if (host == peer->host)
2871 hashIndex = PEER_HASH(host, port);
2872 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2873 if ((peer->host == host) && (peer->port == port))
2878 MUTEX_ENTER(&rx_peerHashTable_lock);
2883 MUTEX_EXIT(&rx_peerHashTable_lock);
2885 MUTEX_ENTER(&peer->peer_lock);
2886 /* We don't handle dropping below min, so don't */
2887 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2888 peer->ifMTU=MIN(mtu, peer->ifMTU);
2889 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2890 /* if we tweaked this down, need to tune our peer MTU too */
2891 peer->MTU = MIN(peer->MTU, peer->natMTU);
2892 /* if we discovered a sub-1500 mtu, degrade */
2893 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2894 peer->maxDgramPackets = 1;
2895 /* We no longer have valid peer packet information */
2896 if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2897 peer->maxPacketSize = 0;
2898 MUTEX_EXIT(&peer->peer_lock);
2900 MUTEX_ENTER(&rx_peerHashTable_lock);
2902 if (host && !port) {
2904 /* pick up where we left off */
2908 MUTEX_EXIT(&rx_peerHashTable_lock);
2911 /* Find the peer process represented by the supplied (host,port)
2912 * combination. If there is no appropriate active peer structure, a
2913 * new one will be allocated and initialized
2914 * The origPeer, if set, is a pointer to a peer structure on which the
2915 * refcount will be be decremented. This is used to replace the peer
2916 * structure hanging off a connection structure */
2918 rxi_FindPeer(afs_uint32 host, u_short port,
2919 struct rx_peer *origPeer, int create)
2923 hashIndex = PEER_HASH(host, port);
2924 MUTEX_ENTER(&rx_peerHashTable_lock);
2925 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2926 if ((pp->host == host) && (pp->port == port))
2931 pp = rxi_AllocPeer(); /* This bzero's *pp */
2932 pp->host = host; /* set here or in InitPeerParams is zero */
2934 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2935 queue_Init(&pp->congestionQueue);
2936 queue_Init(&pp->rpcStats);
2937 pp->next = rx_peerHashTable[hashIndex];
2938 rx_peerHashTable[hashIndex] = pp;
2939 rxi_InitPeerParams(pp);
2940 if (rx_stats_active)
2941 rx_atomic_inc(&rx_stats.nPeerStructs);
2948 origPeer->refCount--;
2949 MUTEX_EXIT(&rx_peerHashTable_lock);
2954 /* Find the connection at (host, port) started at epoch, and with the
2955 * given connection id. Creates the server connection if necessary.
2956 * The type specifies whether a client connection or a server
2957 * connection is desired. In both cases, (host, port) specify the
2958 * peer's (host, pair) pair. Client connections are not made
2959 * automatically by this routine. The parameter socket gives the
2960 * socket descriptor on which the packet was received. This is used,
2961 * in the case of server connections, to check that *new* connections
2962 * come via a valid (port, serviceId). Finally, the securityIndex
2963 * parameter must match the existing index for the connection. If a
2964 * server connection is created, it will be created using the supplied
2965 * index, if the index is valid for this service */
2966 static struct rx_connection *
2967 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2968 u_short port, u_short serviceId, afs_uint32 cid,
2969 afs_uint32 epoch, int type, u_int securityIndex)
2971 int hashindex, flag, i;
2972 struct rx_connection *conn;
2973 hashindex = CONN_HASH(host, port, cid, epoch, type);
2974 MUTEX_ENTER(&rx_connHashTable_lock);
2975 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2976 rx_connHashTable[hashindex],
2979 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2980 && (epoch == conn->epoch)) {
2981 struct rx_peer *pp = conn->peer;
2982 if (securityIndex != conn->securityIndex) {
2983 /* this isn't supposed to happen, but someone could forge a packet
2984 * like this, and there seems to be some CM bug that makes this
2985 * happen from time to time -- in which case, the fileserver
2987 MUTEX_EXIT(&rx_connHashTable_lock);
2988 return (struct rx_connection *)0;
2990 if (pp->host == host && pp->port == port)
2992 if (type == RX_CLIENT_CONNECTION && pp->port == port)
2994 /* So what happens when it's a callback connection? */
2995 if ( /*type == RX_CLIENT_CONNECTION && */
2996 (conn->epoch & 0x80000000))
3000 /* the connection rxLastConn that was used the last time is not the
3001 ** one we are looking for now. Hence, start searching in the hash */
3003 conn = rx_connHashTable[hashindex];
3008 struct rx_service *service;
3009 if (type == RX_CLIENT_CONNECTION) {
3010 MUTEX_EXIT(&rx_connHashTable_lock);
3011 return (struct rx_connection *)0;
3013 service = rxi_FindService(socket, serviceId);
3014 if (!service || (securityIndex >= service->nSecurityObjects)
3015 || (service->securityObjects[securityIndex] == 0)) {
3016 MUTEX_EXIT(&rx_connHashTable_lock);
3017 return (struct rx_connection *)0;
3019 conn = rxi_AllocConnection(); /* This bzero's the connection */
3020 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3021 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3022 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3023 conn->next = rx_connHashTable[hashindex];
3024 rx_connHashTable[hashindex] = conn;
3025 conn->peer = rxi_FindPeer(host, port, 0, 1);
3026 conn->type = RX_SERVER_CONNECTION;
3027 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3028 conn->epoch = epoch;
3029 conn->cid = cid & RX_CIDMASK;
3030 /* conn->serial = conn->lastSerial = 0; */
3031 /* conn->timeout = 0; */
3032 conn->ackRate = RX_FAST_ACK_RATE;
3033 conn->service = service;
3034 conn->serviceId = serviceId;
3035 conn->securityIndex = securityIndex;
3036 conn->securityObject = service->securityObjects[securityIndex];
3037 conn->nSpecific = 0;
3038 conn->specific = NULL;
3039 rx_SetConnDeadTime(conn, service->connDeadTime);
3040 conn->idleDeadTime = service->idleDeadTime;
3041 conn->idleDeadDetection = service->idleDeadErr ? 1 : 0;
3042 for (i = 0; i < RX_MAXCALLS; i++) {
3043 conn->twind[i] = rx_initSendWindow;
3044 conn->rwind[i] = rx_initReceiveWindow;
3046 /* Notify security object of the new connection */
3047 RXS_NewConnection(conn->securityObject, conn);
3048 /* XXXX Connection timeout? */
3049 if (service->newConnProc)
3050 (*service->newConnProc) (conn);
3051 if (rx_stats_active)
3052 rx_atomic_inc(&rx_stats.nServerConns);
3055 MUTEX_ENTER(&rx_refcnt_mutex);
3057 MUTEX_EXIT(&rx_refcnt_mutex);
3059 rxLastConn = conn; /* store this connection as the last conn used */
3060 MUTEX_EXIT(&rx_connHashTable_lock);
3065 * Timeout a call on a busy call channel if appropriate.
3067 * @param[in] call The busy call.
3069 * @pre 'call' is marked as busy (namely,
3070 * call->conn->lastBusy[call->channel] != 0)
3072 * @pre call->lock is held
3073 * @pre rxi_busyChannelError is nonzero
3075 * @note call->lock is dropped and reacquired
3078 rxi_CheckBusy(struct rx_call *call)
3080 struct rx_connection *conn = call->conn;
3081 int channel = call->channel;
3082 int freechannel = 0;
3084 afs_uint32 callNumber;
3086 MUTEX_EXIT(&call->lock);
3088 MUTEX_ENTER(&conn->conn_call_lock);
3089 callNumber = *call->callNumber;
3091 /* Are there any other call slots on this conn that we should try? Look for
3092 * slots that are empty and are either non-busy, or were marked as busy
3093 * longer than conn->secondsUntilDead seconds before this call started. */
3095 for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3097 /* only look at channels that aren't us */
3101 if (conn->lastBusy[i]) {
3102 /* if this channel looked busy too recently, don't look at it */
3103 if (conn->lastBusy[i] >= call->startTime.sec) {
3106 if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3111 if (conn->call[i]) {
3112 struct rx_call *tcall = conn->call[i];
3113 MUTEX_ENTER(&tcall->lock);
3114 if (tcall->state == RX_STATE_DALLY) {
3117 MUTEX_EXIT(&tcall->lock);
3123 MUTEX_ENTER(&call->lock);
3125 /* Since the call->lock and conn->conn_call_lock have been released it is
3126 * possible that (1) the call may no longer be busy and/or (2) the call may
3127 * have been reused by another waiting thread. Therefore, we must confirm
3128 * that the call state has not changed when deciding whether or not to
3129 * force this application thread to retry by forcing a Timeout error. */
3131 if (freechannel && *call->callNumber == callNumber &&
3132 (call->flags & RX_CALL_PEER_BUSY)) {
3133 /* Since 'freechannel' is set, there exists another channel in this
3134 * rx_conn that the application thread might be able to use. We know
3135 * that we have the correct call since callNumber is unchanged, and we
3136 * know that the call is still busy. So, set the call error state to
3137 * rxi_busyChannelError so the application can retry the request,
3138 * presumably on a less-busy call channel. */
3140 rxi_CallError(call, RX_CALL_BUSY);
3142 MUTEX_EXIT(&conn->conn_call_lock);
3145 /* There are two packet tracing routines available for testing and monitoring
3146 * Rx. One is called just after every packet is received and the other is
3147 * called just before every packet is sent. Received packets, have had their
3148 * headers decoded, and packets to be sent have not yet had their headers
3149 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3150 * containing the network address. Both can be modified. The return value, if
3151 * non-zero, indicates that the packet should be dropped. */
3153 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3154 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3156 /* A packet has been received off the interface. Np is the packet, socket is
3157 * the socket number it was received from (useful in determining which service
3158 * this packet corresponds to), and (host, port) reflect the host,port of the
3159 * sender. This call returns the packet to the caller if it is finished with
3160 * it, rather than de-allocating it, just as a small performance hack */
3163 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3164 afs_uint32 host, u_short port, int *tnop,
3165 struct rx_call **newcallp)
3167 struct rx_call *call;
3168 struct rx_connection *conn;
3170 afs_uint32 currentCallNumber;
3176 struct rx_packet *tnp;
3179 /* We don't print out the packet until now because (1) the time may not be
3180 * accurate enough until now in the lwp implementation (rx_Listener only gets
3181 * the time after the packet is read) and (2) from a protocol point of view,
3182 * this is the first time the packet has been seen */
3183 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3184 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3185 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3186 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3187 np->header.epoch, np->header.cid, np->header.callNumber,
3188 np->header.seq, np->header.flags, np));
3191 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3192 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3195 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3196 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3199 /* If an input tracer function is defined, call it with the packet and
3200 * network address. Note this function may modify its arguments. */
3201 if (rx_justReceived) {
3202 struct sockaddr_in addr;
3204 addr.sin_family = AF_INET;
3205 addr.sin_port = port;
3206 addr.sin_addr.s_addr = host;
3207 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3208 addr.sin_len = sizeof(addr);
3209 #endif /* AFS_OSF_ENV */
3210 drop = (*rx_justReceived) (np, &addr);
3211 /* drop packet if return value is non-zero */
3214 port = addr.sin_port; /* in case fcn changed addr */
3215 host = addr.sin_addr.s_addr;
3219 /* If packet was not sent by the client, then *we* must be the client */
3220 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3221 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3223 /* Find the connection (or fabricate one, if we're the server & if
3224 * necessary) associated with this packet */
3226 rxi_FindConnection(socket, host, port, np->header.serviceId,
3227 np->header.cid, np->header.epoch, type,
3228 np->header.securityIndex);
3231 /* If no connection found or fabricated, just ignore the packet.
3232 * (An argument could be made for sending an abort packet for
3237 /* If the connection is in an error state, send an abort packet and ignore
3238 * the incoming packet */
3240 /* Don't respond to an abort packet--we don't want loops! */
3241 MUTEX_ENTER(&conn->conn_data_lock);
3242 if (np->header.type != RX_PACKET_TYPE_ABORT)
3243 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3244 putConnection(conn);
3245 MUTEX_EXIT(&conn->conn_data_lock);
3249 /* Check for connection-only requests (i.e. not call specific). */
3250 if (np->header.callNumber == 0) {
3251 switch (np->header.type) {
3252 case RX_PACKET_TYPE_ABORT: {
3253 /* What if the supplied error is zero? */
3254 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3255 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3256 rxi_ConnectionError(conn, errcode);
3257 putConnection(conn);
3260 case RX_PACKET_TYPE_CHALLENGE:
3261 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3262 putConnection(conn);
3264 case RX_PACKET_TYPE_RESPONSE:
3265 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3266 putConnection(conn);
3268 case RX_PACKET_TYPE_PARAMS:
3269 case RX_PACKET_TYPE_PARAMS + 1:
3270 case RX_PACKET_TYPE_PARAMS + 2:
3271 /* ignore these packet types for now */
3272 putConnection(conn);
3276 /* Should not reach here, unless the peer is broken: send an
3278 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3279 MUTEX_ENTER(&conn->conn_data_lock);
3280 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3281 putConnection(conn);
3282 MUTEX_EXIT(&conn->conn_data_lock);
3287 channel = np->header.cid & RX_CHANNELMASK;
3288 MUTEX_ENTER(&conn->conn_call_lock);
3289 call = conn->call[channel];
3292 MUTEX_ENTER(&call->lock);
3293 currentCallNumber = conn->callNumber[channel];
3294 MUTEX_EXIT(&conn->conn_call_lock);
3295 } else if (type == RX_SERVER_CONNECTION) { /* No call allocated */
3296 call = conn->call[channel];
3298 MUTEX_ENTER(&call->lock);
3299 currentCallNumber = conn->callNumber[channel];
3300 MUTEX_EXIT(&conn->conn_call_lock);
3302 call = rxi_NewCall(conn, channel); /* returns locked call */
3303 *call->callNumber = currentCallNumber = np->header.callNumber;
3304 MUTEX_EXIT(&conn->conn_call_lock);
3306 if (np->header.callNumber == 0)
3307 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3308 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3309 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3310 np->header.flags, np, np->length));
3312 call->state = RX_STATE_PRECALL;
3313 clock_GetTime(&call->queueTime);
3314 hzero(call->bytesSent);
3315 hzero(call->bytesRcvd);
3317 * If the number of queued calls exceeds the overload
3318 * threshold then abort this call.
3320 if ((rx_BusyThreshold > 0) &&
3321 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3322 struct rx_packet *tp;
3324 rxi_CallError(call, rx_BusyError);
3325 tp = rxi_SendCallAbort(call, np, 1, 0);
3326 MUTEX_EXIT(&call->lock);
3327 putConnection(conn);
3328 if (rx_stats_active)
3329 rx_atomic_inc(&rx_stats.nBusies);
3332 rxi_KeepAliveOn(call);
3334 } else { /* RX_CLIENT_CONNECTION and No call allocated */
3335 /* This packet can't be for this call. If the new call address is
3336 * 0 then no call is running on this channel. If there is a call
3337 * then, since this is a client connection we're getting data for
3338 * it must be for the previous call.
3340 if (rx_stats_active)
3341 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3342 putConnection(conn);
3346 /* There is a non-NULL locked call at this point */
3347 if (type == RX_SERVER_CONNECTION) { /* We're the server */
3348 if (np->header.callNumber < currentCallNumber) {
3349 MUTEX_EXIT(&call->lock);
3350 if (rx_stats_active)
3351 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3352 putConnection(conn);
3354 } else if (np->header.callNumber != currentCallNumber) {
3355 /* Wait until the transmit queue is idle before deciding
3356 * whether to reset the current call. Chances are that the
3357 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3360 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3361 if (call->state == RX_STATE_ACTIVE) {
3362 rxi_WaitforTQBusy(call);
3364 * If we entered error state while waiting,
3365 * must call rxi_CallError to permit rxi_ResetCall
3366 * to processed when the tqWaiter count hits zero.
3369 rxi_CallError(call, call->error);
3370 MUTEX_EXIT(&call->lock);
3371 putConnection(conn);
3375 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3376 /* If the new call cannot be taken right now send a busy and set
3377 * the error condition in this call, so that it terminates as
3378 * quickly as possible */
3379 if (call->state == RX_STATE_ACTIVE) {
3380 struct rx_packet *tp;
3382 rxi_CallError(call, RX_CALL_DEAD);
3383 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3385 MUTEX_EXIT(&call->lock);
3386 putConnection(conn);
3389 rxi_ResetCall(call, 0);
3391 * The conn_call_lock is not held but no one else should be
3392 * using this call channel while we are processing this incoming
3393 * packet. This assignment should be safe.
3395 *call->callNumber = np->header.callNumber;
3397 if (np->header.callNumber == 0)
3398 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3399 np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3400 np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3401 np->header.flags, np, np->length));
3403 call->state = RX_STATE_PRECALL;
3404 clock_GetTime(&call->queueTime);
3405 hzero(call->bytesSent);
3406 hzero(call->bytesRcvd);
3408 * If the number of queued calls exceeds the overload
3409 * threshold then abort this call.
3411 if ((rx_BusyThreshold > 0) &&
3412 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3413 struct rx_packet *tp;
3415 rxi_CallError(call, rx_BusyError);
3416 tp = rxi_SendCallAbort(call, np, 1, 0);
3417 MUTEX_EXIT(&call->lock);
3418 putConnection(conn);
3419 if (rx_stats_active)
3420 rx_atomic_inc(&rx_stats.nBusies);
3423 rxi_KeepAliveOn(call);
3425 /* Continuing call; do nothing here. */
3427 } else { /* we're the client */
3428 /* Ignore all incoming acknowledgements for calls in DALLY state */
3429 if ((call->state == RX_STATE_DALLY)
3430 && (np->header.type == RX_PACKET_TYPE_ACK)) {
3431 if (rx_stats_active)
3432 rx_atomic_inc(&rx_stats.ignorePacketDally);
3433 MUTEX_EXIT(&call->lock);
3434 putConnection(conn);
3438 /* Ignore anything that's not relevant to the current call. If there
3439 * isn't a current call, then no packet is relevant. */
3440 if (np->header.callNumber != currentCallNumber) {
3441 if (rx_stats_active)
3442 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3443 MUTEX_EXIT(&call->lock);
3444 putConnection(conn);
3447 /* If the service security object index stamped in the packet does not
3448 * match the connection's security index, ignore the packet */
3449 if (np->header.securityIndex != conn->securityIndex) {
3450 MUTEX_EXIT(&call->lock);
3451 putConnection(conn);
3455 /* If we're receiving the response, then all transmit packets are
3456 * implicitly acknowledged. Get rid of them. */
3457 if (np->header.type == RX_PACKET_TYPE_DATA) {
3458 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3459 /* XXX Hack. Because we must release the global rx lock when
3460 * sending packets (osi_NetSend) we drop all acks while we're
3461 * traversing the tq in rxi_Start sending packets out because
3462 * packets may move to the freePacketQueue as result of being here!
3463 * So we drop these packets until we're safely out of the
3464 * traversing. Really ugly!
3465 * For fine grain RX locking, we set the acked field in the
3466 * packets and let rxi_Start remove them from the transmit queue.
3468 if (call->flags & RX_CALL_TQ_BUSY) {
3469 #ifdef RX_ENABLE_LOCKS
3470 rxi_SetAcksInTransmitQueue(call);
3472 putConnection(conn);
3473 return np; /* xmitting; drop packet */
3476 rxi_ClearTransmitQueue(call, 0);
3478 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3479 rxi_ClearTransmitQueue(call, 0);
3480 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3482 if (np->header.type == RX_PACKET_TYPE_ACK) {
3483 /* now check to see if this is an ack packet acknowledging that the
3484 * server actually *lost* some hard-acked data. If this happens we
3485 * ignore this packet, as it may indicate that the server restarted in
3486 * the middle of a call. It is also possible that this is an old ack
3487 * packet. We don't abort the connection in this case, because this
3488 * *might* just be an old ack packet. The right way to detect a server
3489 * restart in the midst of a call is to notice that the server epoch
3491 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3492 * XXX unacknowledged. I think that this is off-by-one, but
3493 * XXX I don't dare change it just yet, since it will
3494 * XXX interact badly with the server-restart detection
3495 * XXX code in receiveackpacket. */
3496 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3497 if (rx_stats_active)
3498 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3499 MUTEX_EXIT(&call->lock);
3500 putConnection(conn);
3504 } /* else not a data packet */
3507 osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3508 /* Set remote user defined status from packet */
3509 call->remoteStatus = np->header.userStatus;
3511 /* Note the gap between the expected next packet and the actual
3512 * packet that arrived, when the new packet has a smaller serial number
3513 * than expected. Rioses frequently reorder packets all by themselves,
3514 * so this will be quite important with very large window sizes.
3515 * Skew is checked against 0 here to avoid any dependence on the type of
3516 * inPacketSkew (which may be unsigned). In C, -1 > (unsigned) 0 is always
3518 * The inPacketSkew should be a smoothed running value, not just a maximum. MTUXXX
3519 * see CalculateRoundTripTime for an example of how to keep smoothed values.
3520 * I think using a beta of 1/8 is probably appropriate. 93.04.21
3522 MUTEX_ENTER(&conn->conn_data_lock);
3523 skew = conn->lastSerial - np->header.serial;
3524 conn->lastSerial = np->header.serial;
3525 MUTEX_EXIT(&conn->conn_data_lock);
3527 struct rx_peer *peer;
3529 if (skew > peer->inPacketSkew) {
3530 dpf(("*** In skew changed from %d to %d\n",
3531 peer->inPacketSkew, skew));
3532 peer->inPacketSkew = skew;
3536 /* Now do packet type-specific processing */
3537 switch (np->header.type) {
3538 case RX_PACKET_TYPE_DATA:
3539 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3542 case RX_PACKET_TYPE_ACK:
3543 /* Respond immediately to ack packets requesting acknowledgement
3545 if (np->header.flags & RX_REQUEST_ACK) {
3547 (void)rxi_SendCallAbort(call, 0, 1, 0);
3549 (void)rxi_SendAck(call, 0, np->header.serial,
3550 RX_ACK_PING_RESPONSE, 1);
3552 np = rxi_ReceiveAckPacket(call, np, 1);
3554 case RX_PACKET_TYPE_ABORT: {
3555 /* An abort packet: reset the call, passing the error up to the user. */
3556 /* What if error is zero? */
3557 /* What if the error is -1? the application will treat it as a timeout. */
3558 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3559 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3560 rxi_CallError(call, errdata);
3561 MUTEX_EXIT(&call->lock);
3562 putConnection(conn);
3563 return np; /* xmitting; drop packet */
3565 case RX_PACKET_TYPE_BUSY: {
3566 struct clock busyTime;
3568 clock_GetTime(&busyTime);
3570 MUTEX_EXIT(&call->lock);
3572 MUTEX_ENTER(&conn->conn_call_lock);
3573 MUTEX_ENTER(&call->lock);
3574 conn->lastBusy[call->channel] = busyTime.sec;
3575 call->flags |= RX_CALL_PEER_BUSY;
3576 MUTEX_EXIT(&call->lock);
3577 MUTEX_EXIT(&conn->conn_call_lock);
3579 putConnection(conn);
3583 case RX_PACKET_TYPE_ACKALL:
3584 /* All packets acknowledged, so we can drop all packets previously
3585 * readied for sending */
3586 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3587 /* XXX Hack. We because we can't release the global rx lock when
3588 * sending packets (osi_NetSend) we drop all ack pkts while we're
3589 * traversing the tq in rxi_Start sending packets out because
3590 * packets may move to the freePacketQueue as result of being
3591 * here! So we drop these packets until we're safely out of the
3592 * traversing. Really ugly!
3593 * For fine grain RX locking, we set the acked field in the packets
3594 * and let rxi_Start remove the packets from the transmit queue.
3596 if (call->flags & RX_CALL_TQ_BUSY) {
3597 #ifdef RX_ENABLE_LOCKS
3598 rxi_SetAcksInTransmitQueue(call);
3600 #else /* RX_ENABLE_LOCKS */
3601 MUTEX_EXIT(&call->lock);
3602 putConnection(conn);
3603 return np; /* xmitting; drop packet */
3604 #endif /* RX_ENABLE_LOCKS */
3606 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3607 rxi_ClearTransmitQueue(call, 0);
3610 /* Should not reach here, unless the peer is broken: send an abort
3612 rxi_CallError(call, RX_PROTOCOL_ERROR);
3613 np = rxi_SendCallAbort(call, np, 1, 0);
3616 /* Note when this last legitimate packet was received, for keep-alive
3617 * processing. Note, we delay getting the time until now in the hope that
3618 * the packet will be delivered to the user before any get time is required
3619 * (if not, then the time won't actually be re-evaluated here). */
3620 call->lastReceiveTime = clock_Sec();
3621 /* we've received a legit packet, so the channel is not busy */
3622 call->flags &= ~RX_CALL_PEER_BUSY;
3623 MUTEX_EXIT(&call->lock);
3624 putConnection(conn);
3628 /* return true if this is an "interesting" connection from the point of view
3629 of someone trying to debug the system */
3631 rxi_IsConnInteresting(struct rx_connection *aconn)
3634 struct rx_call *tcall;
3636 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3639 for (i = 0; i < RX_MAXCALLS; i++) {
3640 tcall = aconn->call[i];
3642 if ((tcall->state == RX_STATE_PRECALL)
3643 || (tcall->state == RX_STATE_ACTIVE))
3645 if ((tcall->mode == RX_MODE_SENDING)
3646 || (tcall->mode == RX_MODE_RECEIVING))
3654 /* if this is one of the last few packets AND it wouldn't be used by the
3655 receiving call to immediately satisfy a read request, then drop it on
3656 the floor, since accepting it might prevent a lock-holding thread from
3657 making progress in its reading. If a call has been cleared while in
3658 the precall state then ignore all subsequent packets until the call
3659 is assigned to a thread. */
3662 TooLow(struct rx_packet *ap, struct rx_call *acall)
3666 MUTEX_ENTER(&rx_quota_mutex);
3667 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3668 && (acall->state == RX_STATE_PRECALL))
3669 || ((rx_nFreePackets < rxi_dataQuota + 2)
3670 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3671 && (acall->flags & RX_CALL_READER_WAIT)))) {
3674 MUTEX_EXIT(&rx_quota_mutex);
3680 * Clear the attach wait flag on a connection and proceed.
3682 * Any processing waiting for a connection to be attached should be
3683 * unblocked. We clear the flag and do any other needed tasks.
3686 * the conn to unmark waiting for attach
3688 * @pre conn's conn_data_lock must be locked before calling this function
3692 rxi_ConnClearAttachWait(struct rx_connection *conn)
3694 /* Indicate that rxi_CheckReachEvent is no longer running by
3695 * clearing the flag. Must be atomic under conn_data_lock to
3696 * avoid a new call slipping by: rxi_CheckConnReach holds
3697 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3699 conn->flags &= ~RX_CONN_ATTACHWAIT;
3700 if (conn->flags & RX_CONN_NAT_PING) {
3701 conn->flags &= ~RX_CONN_NAT_PING;
3702 rxi_ScheduleNatKeepAliveEvent(conn);
3707 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3709 struct rx_connection *conn = arg1;
3710 struct rx_call *acall = arg2;
3711 struct rx_call *call = acall;
3712 struct clock when, now;
3715 MUTEX_ENTER(&conn->conn_data_lock);
3718 rxevent_Put(conn->checkReachEvent);
3719 conn->checkReachEvent = NULL;
3722 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3724 putConnection(conn);
3726 MUTEX_EXIT(&conn->conn_data_lock);
3730 MUTEX_ENTER(&conn->conn_call_lock);
3731 MUTEX_ENTER(&conn->conn_data_lock);
3732 for (i = 0; i < RX_MAXCALLS; i++) {
3733 struct rx_call *tc = conn->call[i];
3734 if (tc && tc->state == RX_STATE_PRECALL) {
3740 rxi_ConnClearAttachWait(conn);
3741 MUTEX_EXIT(&conn->conn_data_lock);
3742 MUTEX_EXIT(&conn->conn_call_lock);
3747 MUTEX_ENTER(&call->lock);
3748 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3750 MUTEX_EXIT(&call->lock);
3752 clock_GetTime(&now);
3754 when.sec += RX_CHECKREACH_TIMEOUT;
3755 MUTEX_ENTER(&conn->conn_data_lock);
3756 if (!conn->checkReachEvent) {
3757 MUTEX_ENTER(&rx_refcnt_mutex);
3759 MUTEX_EXIT(&rx_refcnt_mutex);
3760 conn->checkReachEvent = rxevent_Post(&when, &now,
3761 rxi_CheckReachEvent, conn,
3764 MUTEX_EXIT(&conn->conn_data_lock);
3770 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3772 struct rx_service *service = conn->service;
3773 struct rx_peer *peer = conn->peer;
3774 afs_uint32 now, lastReach;
3776 if (service->checkReach == 0)
3780 MUTEX_ENTER(&peer->peer_lock);
3781 lastReach = peer->lastReachTime;
3782 MUTEX_EXIT(&peer->peer_lock);
3783 if (now - lastReach < RX_CHECKREACH_TTL)
3786 MUTEX_ENTER(&conn->conn_data_lock);
3787 if (conn->flags & RX_CONN_ATTACHWAIT) {
3788 MUTEX_EXIT(&conn->conn_data_lock);
3791 conn->flags |= RX_CONN_ATTACHWAIT;
3792 MUTEX_EXIT(&conn->conn_data_lock);
3793 if (!conn->checkReachEvent)
3794 rxi_CheckReachEvent(NULL, conn, call, 0);
3799 /* try to attach call, if authentication is complete */
3801 TryAttach(struct rx_call *acall, osi_socket socket,
3802 int *tnop, struct rx_call **newcallp,
3805 struct rx_connection *conn = acall->conn;
3807 if (conn->type == RX_SERVER_CONNECTION
3808 && acall->state == RX_STATE_PRECALL) {
3809 /* Don't attach until we have any req'd. authentication. */
3810 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3811 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3812 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3813 /* Note: this does not necessarily succeed; there
3814 * may not any proc available
3817 rxi_ChallengeOn(acall->conn);
3822 /* A data packet has been received off the interface. This packet is
3823 * appropriate to the call (the call is in the right state, etc.). This
3824 * routine can return a packet to the caller, for re-use */
3826 static struct rx_packet *
3827 rxi_ReceiveDataPacket(struct rx_call *call,
3828 struct rx_packet *np, int istack,
3829 osi_socket socket, afs_uint32 host, u_short port,
3830 int *tnop, struct rx_call **newcallp)
3832 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3837 afs_uint32 serial=0, flags=0;
3839 struct rx_packet *tnp;
3840 if (rx_stats_active)
3841 rx_atomic_inc(&rx_stats.dataPacketsRead);
3844 /* If there are no packet buffers, drop this new packet, unless we can find
3845 * packet buffers from inactive calls */
3847 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3848 MUTEX_ENTER(&rx_freePktQ_lock);
3849 rxi_NeedMorePackets = TRUE;
3850 MUTEX_EXIT(&rx_freePktQ_lock);
3851 if (rx_stats_active)
3852 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3853 call->rprev = np->header.serial;
3854 rxi_calltrace(RX_TRACE_DROP, call);
3855 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3856 /* We used to clear the receive queue here, in an attempt to free
3857 * packets. However this is unsafe if the queue has received a
3858 * soft ACK for the final packet */
3859 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3861 /* we've damaged this call already, might as well do it in. */
3867 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3868 * packet is one of several packets transmitted as a single
3869 * datagram. Do not send any soft or hard acks until all packets
3870 * in a jumbogram have been processed. Send negative acks right away.
3872 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3873 /* tnp is non-null when there are more packets in the
3874 * current jumbo gram */
3881 seq = np->header.seq;
3882 serial = np->header.serial;
3883 flags = np->header.flags;
3885 /* If the call is in an error state, send an abort message */
3887 return rxi_SendCallAbort(call, np, istack, 0);
3889 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3890 * AFS 3.5 jumbogram. */
3891 if (flags & RX_JUMBO_PACKET) {
3892 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3897 if (np->header.spare != 0) {
3898 MUTEX_ENTER(&call->conn->conn_data_lock);
3899 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3900 MUTEX_EXIT(&call->conn->conn_data_lock);
3903 /* The usual case is that this is the expected next packet */
3904 if (seq == call->rnext) {
3906 /* Check to make sure it is not a duplicate of one already queued */
3907 if (queue_IsNotEmpty(&call->rq)
3908 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3909 if (rx_stats_active)
3910 rx_atomic_inc(&rx_stats.dupPacketsRead);
3911 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3912 rxevent_Cancel(&call->delayedAckEvent, call,
3913 RX_CALL_REFCOUNT_DELAY);
3914 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3920 /* It's the next packet. Stick it on the receive queue
3921 * for this call. Set newPackets to make sure we wake
3922 * the reader once all packets have been processed */
3923 #ifdef RX_TRACK_PACKETS
3924 np->flags |= RX_PKTFLAG_RQ;
3926 queue_Prepend(&call->rq, np);
3927 #ifdef RXDEBUG_PACKET
3929 #endif /* RXDEBUG_PACKET */
3931 np = NULL; /* We can't use this anymore */
3934 /* If an ack is requested then set a flag to make sure we
3935 * send an acknowledgement for this packet */
3936 if (flags & RX_REQUEST_ACK) {
3937 ackNeeded = RX_ACK_REQUESTED;
3940 /* Keep track of whether we have received the last packet */
3941 if (flags & RX_LAST_PACKET) {
3942 call->flags |= RX_CALL_HAVE_LAST;
3946 /* Check whether we have all of the packets for this call */
3947 if (call->flags & RX_CALL_HAVE_LAST) {
3948 afs_uint32 tseq; /* temporary sequence number */
3949 struct rx_packet *tp; /* Temporary packet pointer */
3950 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3952 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3953 if (tseq != tp->header.seq)
3955 if (tp->header.flags & RX_LAST_PACKET) {
3956 call->flags |= RX_CALL_RECEIVE_DONE;
3963 /* Provide asynchronous notification for those who want it
3964 * (e.g. multi rx) */
3965 if (call->arrivalProc) {
3966 (*call->arrivalProc) (call, call->arrivalProcHandle,
3967 call->arrivalProcArg);
3968 call->arrivalProc = (void (*)())0;
3971 /* Update last packet received */
3974 /* If there is no server process serving this call, grab
3975 * one, if available. We only need to do this once. If a
3976 * server thread is available, this thread becomes a server
3977 * thread and the server thread becomes a listener thread. */
3979 TryAttach(call, socket, tnop, newcallp, 0);
3982 /* This is not the expected next packet. */
3984 /* Determine whether this is a new or old packet, and if it's
3985 * a new one, whether it fits into the current receive window.
3986 * Also figure out whether the packet was delivered in sequence.
3987 * We use the prev variable to determine whether the new packet
3988 * is the successor of its immediate predecessor in the
3989 * receive queue, and the missing flag to determine whether
3990 * any of this packets predecessors are missing. */
3992 afs_uint32 prev; /* "Previous packet" sequence number */
3993 struct rx_packet *tp; /* Temporary packet pointer */
3994 struct rx_packet *nxp; /* Next pointer, for queue_Scan */
3995 int missing; /* Are any predecessors missing? */
3997 /* If the new packet's sequence number has been sent to the
3998 * application already, then this is a duplicate */
3999 if (seq < call->rnext) {
4000 if (rx_stats_active)
4001 rx_atomic_inc(&rx_stats.dupPacketsRead);
4002 rxevent_Cancel(&call->delayedAckEvent, call,
4003 RX_CALL_REFCOUNT_DELAY);
4004 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4010 /* If the sequence number is greater than what can be
4011 * accomodated by the current window, then send a negative
4012 * acknowledge and drop the packet */
4013 if ((call->rnext + call->rwind) <= seq) {
4014 rxevent_Cancel(&call->delayedAckEvent, call,
4015 RX_CALL_REFCOUNT_DELAY);
4016 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4023 /* Look for the packet in the queue of old received packets */
4024 for (prev = call->rnext - 1, missing =
4025 0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4026 /*Check for duplicate packet */
4027 if (seq == tp->header.seq) {
4028 if (rx_stats_active)
4029 rx_atomic_inc(&rx_stats.dupPacketsRead);
4030 rxevent_Cancel(&call->delayedAckEvent, call,
4031 RX_CALL_REFCOUNT_DELAY);
4032 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4038 /* If we find a higher sequence packet, break out and
4039 * insert the new packet here. */
4040 if (seq < tp->header.seq)
4042 /* Check for missing packet */
4043 if (tp->header.seq != prev + 1) {
4047 prev = tp->header.seq;
4050 /* Keep track of whether we have received the last packet. */
4051 if (flags & RX_LAST_PACKET) {
4052 call->flags |= RX_CALL_HAVE_LAST;
4055 /* It's within the window: add it to the the receive queue.
4056 * tp is left by the previous loop either pointing at the
4057 * packet before which to insert the new packet, or at the
4058 * queue head if the queue is empty or the packet should be
4060 #ifdef RX_TRACK_PACKETS
4061 np->flags |= RX_PKTFLAG_RQ;
4063 #ifdef RXDEBUG_PACKET
4065 #endif /* RXDEBUG_PACKET */
4066 queue_InsertBefore(tp, np);
4070 /* Check whether we have all of the packets for this call */
4071 if ((call->flags & RX_CALL_HAVE_LAST)
4072 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4073 afs_uint32 tseq; /* temporary sequence number */
4076 call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4077 if (tseq != tp->header.seq)
4079 if (tp->header.flags & RX_LAST_PACKET) {
4080 call->flags |= RX_CALL_RECEIVE_DONE;
4087 /* We need to send an ack of the packet is out of sequence,
4088 * or if an ack was requested by the peer. */
4089 if (seq != prev + 1 || missing) {
4090 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4091 } else if (flags & RX_REQUEST_ACK) {
4092 ackNeeded = RX_ACK_REQUESTED;
4095 /* Acknowledge the last packet for each call */
4096 if (flags & RX_LAST_PACKET) {
4107 * If the receiver is waiting for an iovec, fill the iovec
4108 * using the data from the receive queue */
4109 if (call->flags & RX_CALL_IOVEC_WAIT) {
4110 didHardAck = rxi_FillReadVec(call, serial);
4111 /* the call may have been aborted */
4120 /* Wakeup the reader if any */
4121 if ((call->flags & RX_CALL_READER_WAIT)
4122 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4123 || (call->iovNext >= call->iovMax)
4124 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4125 call->flags &= ~RX_CALL_READER_WAIT;
4126 #ifdef RX_ENABLE_LOCKS
4127 CV_BROADCAST(&call->cv_rq);
4129 osi_rxWakeup(&call->rq);
4135 * Send an ack when requested by the peer, or once every
4136 * rxi_SoftAckRate packets until the last packet has been
4137 * received. Always send a soft ack for the last packet in
4138 * the server's reply. */
4140 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4141 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4142 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4143 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4144 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4145 } else if (call->nSoftAcks) {
4146 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4147 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4149 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4150 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4151 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4158 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4160 struct rx_peer *peer = conn->peer;
4162 MUTEX_ENTER(&peer->peer_lock);
4163 peer->lastReachTime = clock_Sec();
4164 MUTEX_EXIT(&peer->peer_lock);
4166 MUTEX_ENTER(&conn->conn_data_lock);
4167 if (conn->flags & RX_CONN_ATTACHWAIT) {
4170 rxi_ConnClearAttachWait(conn);
4171 MUTEX_EXIT(&conn->conn_data_lock);
4173 for (i = 0; i < RX_MAXCALLS; i++) {
4174 struct rx_call *call = conn->call[i];
4177 MUTEX_ENTER(&call->lock);
4178 /* tnop can be null if newcallp is null */
4179 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4181 MUTEX_EXIT(&call->lock);
4185 MUTEX_EXIT(&conn->conn_data_lock);
4188 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4190 rx_ack_reason(int reason)
4193 case RX_ACK_REQUESTED:
4195 case RX_ACK_DUPLICATE:
4197 case RX_ACK_OUT_OF_SEQUENCE:
4199 case RX_ACK_EXCEEDS_WINDOW:
4201 case RX_ACK_NOSPACE:
4205 case RX_ACK_PING_RESPONSE:
4218 /* The real smarts of the whole thing. */
4219 static struct rx_packet *
4220 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4223 struct rx_ackPacket *ap;
4225 struct rx_packet *tp;
4226 struct rx_packet *nxp; /* Next packet pointer for queue_Scan */
4227 struct rx_connection *conn = call->conn;
4228 struct rx_peer *peer = conn->peer;
4229 struct clock now; /* Current time, for RTT calculations */
4233 /* because there are CM's that are bogus, sending weird values for this. */
4234 afs_uint32 skew = 0;
4239 int newAckCount = 0;
4240 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4241 int pktsize = 0; /* Set if we need to update the peer mtu */
4242 int conn_data_locked = 0;
4244 if (rx_stats_active)
4245 rx_atomic_inc(&rx_stats.ackPacketsRead);
4246 ap = (struct rx_ackPacket *)rx_DataOf(np);
4247 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4249 return np; /* truncated ack packet */
4251 /* depends on ack packet struct */
4252 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4253 first = ntohl(ap->firstPacket);
4254 prev = ntohl(ap->previousPacket);
4255 serial = ntohl(ap->serial);
4256 /* temporarily disabled -- needs to degrade over time
4257 * skew = ntohs(ap->maxSkew); */
4259 /* Ignore ack packets received out of order */
4260 if (first < call->tfirst ||
4261 (first == call->tfirst && prev < call->tprev)) {
4267 if (np->header.flags & RX_SLOW_START_OK) {
4268 call->flags |= RX_CALL_SLOW_START_OK;
4271 if (ap->reason == RX_ACK_PING_RESPONSE)
4272 rxi_UpdatePeerReach(conn, call);
4274 if (conn->lastPacketSizeSeq) {
4275 MUTEX_ENTER(&conn->conn_data_lock);
4276 conn_data_locked = 1;
4277 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4278 pktsize = conn->lastPacketSize;
4279 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4282 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4283 if (!conn_data_locked) {
4284 MUTEX_ENTER(&conn->conn_data_lock);
4285 conn_data_locked = 1;
4287 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4288 /* process mtu ping ack */
4289 pktsize = conn->lastPingSize;
4290 conn->lastPingSizeSer = conn->lastPingSize = 0;
4294 if (conn_data_locked) {
4295 MUTEX_EXIT(&conn->conn_data_lock);
4296 conn_data_locked = 0;
4300 if (rxdebug_active) {
4304 len = _snprintf(msg, sizeof(msg),
4305 "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4306 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4307 ntohl(ap->serial), ntohl(ap->previousPacket),
4308 (unsigned int)np->header.seq, (unsigned int)skew,
4309 ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4313 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4314 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4318 OutputDebugString(msg);
4320 #else /* AFS_NT40_ENV */
4323 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4324 ap->reason, ntohl(ap->previousPacket),
4325 (unsigned int)np->header.seq, (unsigned int)serial,
4326 (unsigned int)skew, ntohl(ap->firstPacket));
4329 for (offset = 0; offset < nAcks; offset++)
4330 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4335 #endif /* AFS_NT40_ENV */
4338 MUTEX_ENTER(&peer->peer_lock);
4341 * Start somewhere. Can't assume we can send what we can receive,
4342 * but we are clearly receiving.
4344 if (!peer->maxPacketSize)
4345 peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4347 if (pktsize > peer->maxPacketSize) {
4348 peer->maxPacketSize = pktsize;
4349 if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4350 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4351 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4352 rxi_ScheduleGrowMTUEvent(call, 1);
4357 /* Update the outgoing packet skew value to the latest value of
4358 * the peer's incoming packet skew value. The ack packet, of
4359 * course, could arrive out of order, but that won't affect things
4361 peer->outPacketSkew = skew;
4364 clock_GetTime(&now);
4366 /* The transmit queue splits into 4 sections.
4368 * The first section is packets which have now been acknowledged
4369 * by a window size change in the ack. These have reached the
4370 * application layer, and may be discarded. These are packets
4371 * with sequence numbers < ap->firstPacket.
4373 * The second section is packets which have sequence numbers in
4374 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4375 * contents of the packet's ack array determines whether these
4376 * packets are acknowledged or not.
4378 * The third section is packets which fall above the range
4379 * addressed in the ack packet. These have not yet been received
4382 * The four section is packets which have not yet been transmitted.
4383 * These packets will have a header.serial of 0.
4386 /* First section - implicitly acknowledged packets that can be
4390 tp = queue_First(&call->tq, rx_packet);
4391 while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4392 struct rx_packet *next;
4394 next = queue_Next(tp, rx_packet);
4395 call->tfirst = tp->header.seq + 1;
4397 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4399 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4402 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4403 /* XXX Hack. Because we have to release the global rx lock when sending
4404 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4405 * in rxi_Start sending packets out because packets may move to the
4406 * freePacketQueue as result of being here! So we drop these packets until
4407 * we're safely out of the traversing. Really ugly!
4408 * To make it even uglier, if we're using fine grain locking, we can
4409 * set the ack bits in the packets and have rxi_Start remove the packets
4410 * when it's done transmitting.
4412 if (call->flags & RX_CALL_TQ_BUSY) {
4413 #ifdef RX_ENABLE_LOCKS
4414 tp->flags |= RX_PKTFLAG_ACKED;
4415 call->flags |= RX_CALL_TQ_SOME_ACKED;
4416 #else /* RX_ENABLE_LOCKS */
4418 #endif /* RX_ENABLE_LOCKS */
4420 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4423 #ifdef RX_TRACK_PACKETS
4424 tp->flags &= ~RX_PKTFLAG_TQ;
4426 #ifdef RXDEBUG_PACKET
4428 #endif /* RXDEBUG_PACKET */
4429 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4434 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4436 /* Second section of the queue - packets for which we are receiving
4439 * Go through the explicit acks/nacks and record the results in
4440 * the waiting packets. These are packets that can't be released
4441 * yet, even with a positive acknowledge. This positive
4442 * acknowledge only means the packet has been received by the
4443 * peer, not that it will be retained long enough to be sent to
4444 * the peer's upper level. In addition, reset the transmit timers
4445 * of any missing packets (those packets that must be missing
4446 * because this packet was out of sequence) */
4448 call->nSoftAcked = 0;
4450 while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4451 /* Set the acknowledge flag per packet based on the
4452 * information in the ack packet. An acknowlegded packet can
4453 * be downgraded when the server has discarded a packet it
4454 * soacked previously, or when an ack packet is received
4455 * out of sequence. */
4456 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4457 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4459 tp->flags |= RX_PKTFLAG_ACKED;
4460 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4467 } else /* RX_ACK_TYPE_NACK */ {
4468 tp->flags &= ~RX_PKTFLAG_ACKED;
4472 tp = queue_Next(tp, rx_packet);
4475 /* We don't need to take any action with the 3rd or 4th section in the
4476 * queue - they're not addressed by the contents of this ACK packet.
4479 /* If the window has been extended by this acknowledge packet,
4480 * then wakeup a sender waiting in alloc for window space, or try
4481 * sending packets now, if he's been sitting on packets due to
4482 * lack of window space */
4483 if (call->tnext < (call->tfirst + call->twind)) {
4484 #ifdef RX_ENABLE_LOCKS
4485 CV_SIGNAL(&call->cv_twind);
4487 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4488 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4489 osi_rxWakeup(&call->twind);
4492 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4493 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4497 /* if the ack packet has a receivelen field hanging off it,
4498 * update our state */
4499 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4502 /* If the ack packet has a "recommended" size that is less than
4503 * what I am using now, reduce my size to match */
4504 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4505 (int)sizeof(afs_int32), &tSize);
4506 tSize = (afs_uint32) ntohl(tSize);
4507 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4509 /* Get the maximum packet size to send to this peer */
4510 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4512 tSize = (afs_uint32) ntohl(tSize);
4513 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4514 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4516 /* sanity check - peer might have restarted with different params.
4517 * If peer says "send less", dammit, send less... Peer should never
4518 * be unable to accept packets of the size that prior AFS versions would
4519 * send without asking. */
4520 if (peer->maxMTU != tSize) {
4521 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4523 peer->maxMTU = tSize;
4524 peer->MTU = MIN(tSize, peer->MTU);
4525 call->MTU = MIN(call->MTU, tSize);
4528 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4531 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4532 (int)sizeof(afs_int32), &tSize);
4533 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4534 if (tSize < call->twind) { /* smaller than our send */
4535 call->twind = tSize; /* window, we must send less... */
4536 call->ssthresh = MIN(call->twind, call->ssthresh);
4537 call->conn->twind[call->channel] = call->twind;
4540 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4541 * network MTU confused with the loopback MTU. Calculate the
4542 * maximum MTU here for use in the slow start code below.
4544 /* Did peer restart with older RX version? */
4545 if (peer->maxDgramPackets > 1) {
4546 peer->maxDgramPackets = 1;
4548 } else if (np->length >=
4549 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4552 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4553 sizeof(afs_int32), &tSize);
4554 tSize = (afs_uint32) ntohl(tSize);
4556 * As of AFS 3.5 we set the send window to match the receive window.
4558 if (tSize < call->twind) {
4559 call->twind = tSize;
4560 call->conn->twind[call->channel] = call->twind;
4561 call->ssthresh = MIN(call->twind, call->ssthresh);
4562 } else if (tSize > call->twind) {
4563 call->twind = tSize;
4564 call->conn->twind[call->channel] = call->twind;
4568 * As of AFS 3.5, a jumbogram is more than one fixed size
4569 * packet transmitted in a single UDP datagram. If the remote
4570 * MTU is smaller than our local MTU then never send a datagram
4571 * larger than the natural MTU.
4574 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4575 (int)sizeof(afs_int32), &tSize);
4576 maxDgramPackets = (afs_uint32) ntohl(tSize);
4577 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4579 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4580 if (maxDgramPackets > 1) {
4581 peer->maxDgramPackets = maxDgramPackets;
4582 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4584 peer->maxDgramPackets = 1;
4585 call->MTU = peer->natMTU;
4587 } else if (peer->maxDgramPackets > 1) {
4588 /* Restarted with lower version of RX */
4589 peer->maxDgramPackets = 1;
4591 } else if (peer->maxDgramPackets > 1
4592 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4593 /* Restarted with lower version of RX */
4594 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4595 peer->natMTU = OLD_MAX_PACKET_SIZE;
4596 peer->MTU = OLD_MAX_PACKET_SIZE;
4597 peer->maxDgramPackets = 1;
4598 peer->nDgramPackets = 1;
4600 call->MTU = OLD_MAX_PACKET_SIZE;
4605 * Calculate how many datagrams were successfully received after
4606 * the first missing packet and adjust the negative ack counter
4611 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4612 if (call->nNacks < nNacked) {
4613 call->nNacks = nNacked;
4616 call->nAcks += newAckCount;
4620 /* If the packet contained new acknowledgements, rather than just
4621 * being a duplicate of one we have previously seen, then we can restart
4624 if (newAckCount > 0)
4625 rxi_rto_packet_acked(call, istack);
4627 if (call->flags & RX_CALL_FAST_RECOVER) {
4628 if (newAckCount == 0) {
4629 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4631 call->flags &= ~RX_CALL_FAST_RECOVER;
4632 call->cwind = call->nextCwind;
4633 call->nextCwind = 0;
4636 call->nCwindAcks = 0;
4637 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4638 /* Three negative acks in a row trigger congestion recovery */
4639 call->flags |= RX_CALL_FAST_RECOVER;
4640 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4642 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4643 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4644 call->nextCwind = call->ssthresh;
4647 peer->MTU = call->MTU;
4648 peer->cwind = call->nextCwind;
4649 peer->nDgramPackets = call->nDgramPackets;
4651 call->congestSeq = peer->congestSeq;
4653 /* Reset the resend times on the packets that were nacked
4654 * so we will retransmit as soon as the window permits
4657 for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4659 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4660 tp->flags &= ~RX_PKTFLAG_SENT;
4662 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4667 /* If cwind is smaller than ssthresh, then increase
4668 * the window one packet for each ack we receive (exponential
4670 * If cwind is greater than or equal to ssthresh then increase
4671 * the congestion window by one packet for each cwind acks we
4672 * receive (linear growth). */
4673 if (call->cwind < call->ssthresh) {
4675 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4676 call->nCwindAcks = 0;
4678 call->nCwindAcks += newAckCount;
4679 if (call->nCwindAcks >= call->cwind) {
4680 call->nCwindAcks = 0;
4681 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4685 * If we have received several acknowledgements in a row then
4686 * it is time to increase the size of our datagrams
4688 if ((int)call->nAcks > rx_nDgramThreshold) {
4689 if (peer->maxDgramPackets > 1) {
4690 if (call->nDgramPackets < peer->maxDgramPackets) {
4691 call->nDgramPackets++;
4693 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4694 } else if (call->MTU < peer->maxMTU) {
4695 /* don't upgrade if we can't handle it */
4696 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4697 call->MTU = peer->ifMTU;
4699 call->MTU += peer->natMTU;
4700 call->MTU = MIN(call->MTU, peer->maxMTU);
4707 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4709 /* Servers need to hold the call until all response packets have
4710 * been acknowledged. Soft acks are good enough since clients
4711 * are not allowed to clear their receive queues. */
4712 if (call->state == RX_STATE_HOLD
4713 && call->tfirst + call->nSoftAcked >= call->tnext) {
4714 call->state = RX_STATE_DALLY;
4715 rxi_ClearTransmitQueue(call, 0);
4716 rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4717 } else if (!queue_IsEmpty(&call->tq)) {
4718 rxi_Start(call, istack);
4723 /* Received a response to a challenge packet */
4724 static struct rx_packet *
4725 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4726 struct rx_packet *np, int istack)
4730 /* Ignore the packet if we're the client */
4731 if (conn->type == RX_CLIENT_CONNECTION)
4734 /* If already authenticated, ignore the packet (it's probably a retry) */
4735 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4738 /* Otherwise, have the security object evaluate the response packet */
4739 error = RXS_CheckResponse(conn->securityObject, conn, np);
4741 /* If the response is invalid, reset the connection, sending
4742 * an abort to the peer */
4746 rxi_ConnectionError(conn, error);
4747 MUTEX_ENTER(&conn->conn_data_lock);
4748 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4749 MUTEX_EXIT(&conn->conn_data_lock);
4752 /* If the response is valid, any calls waiting to attach
4753 * servers can now do so */
4756 for (i = 0; i < RX_MAXCALLS; i++) {
4757 struct rx_call *call = conn->call[i];
4759 MUTEX_ENTER(&call->lock);
4760 if (call->state == RX_STATE_PRECALL)
4761 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4762 /* tnop can be null if newcallp is null */
4763 MUTEX_EXIT(&call->lock);
4767 /* Update the peer reachability information, just in case
4768 * some calls went into attach-wait while we were waiting
4769 * for authentication..
4771 rxi_UpdatePeerReach(conn, NULL);
4776 /* A client has received an authentication challenge: the security
4777 * object is asked to cough up a respectable response packet to send
4778 * back to the server. The server is responsible for retrying the
4779 * challenge if it fails to get a response. */
4781 static struct rx_packet *
4782 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4783 struct rx_packet *np, int istack)
4787 /* Ignore the challenge if we're the server */
4788 if (conn->type == RX_SERVER_CONNECTION)
4791 /* Ignore the challenge if the connection is otherwise idle; someone's
4792 * trying to use us as an oracle. */
4793 if (!rxi_HasActiveCalls(conn))
4796 /* Send the security object the challenge packet. It is expected to fill
4797 * in the response. */
4798 error = RXS_GetResponse(conn->securityObject, conn, np);
4800 /* If the security object is unable to return a valid response, reset the
4801 * connection and send an abort to the peer. Otherwise send the response
4802 * packet to the peer connection. */
4804 rxi_ConnectionError(conn, error);
4805 MUTEX_ENTER(&conn->conn_data_lock);
4806 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4807 MUTEX_EXIT(&conn->conn_data_lock);
4809 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4810 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4816 /* Find an available server process to service the current request in
4817 * the given call structure. If one isn't available, queue up this
4818 * call so it eventually gets one */
4820 rxi_AttachServerProc(struct rx_call *call,
4821 osi_socket socket, int *tnop,
4822 struct rx_call **newcallp)
4824 struct rx_serverQueueEntry *sq;
4825 struct rx_service *service = call->conn->service;
4828 /* May already be attached */
4829 if (call->state == RX_STATE_ACTIVE)
4832 MUTEX_ENTER(&rx_serverPool_lock);
4834 haveQuota = QuotaOK(service);
4835 if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4836 /* If there are no processes available to service this call,
4837 * put the call on the incoming call queue (unless it's
4838 * already on the queue).
4840 #ifdef RX_ENABLE_LOCKS
4842 ReturnToServerPool(service);
4843 #endif /* RX_ENABLE_LOCKS */
4845 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4846 call->flags |= RX_CALL_WAIT_PROC;
4847 rx_atomic_inc(&rx_nWaiting);
4848 rx_atomic_inc(&rx_nWaited);
4849 rxi_calltrace(RX_CALL_ARRIVAL, call);
4850 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4851 queue_Append(&rx_incomingCallQueue, call);
4854 sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4856 /* If hot threads are enabled, and both newcallp and sq->socketp
4857 * are non-null, then this thread will process the call, and the
4858 * idle server thread will start listening on this threads socket.
4861 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4864 *sq->socketp = socket;
4865 clock_GetTime(&call->startTime);
4866 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4870 if (call->flags & RX_CALL_WAIT_PROC) {
4871 /* Conservative: I don't think this should happen */
4872 call->flags &= ~RX_CALL_WAIT_PROC;
4873 if (queue_IsOnQueue(call)) {
4876 rx_atomic_dec(&rx_nWaiting);
4879 call->state = RX_STATE_ACTIVE;
4880 call->mode = RX_MODE_RECEIVING;
4881 #ifdef RX_KERNEL_TRACE
4883 int glockOwner = ISAFS_GLOCK();
4886 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4887 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4893 if (call->flags & RX_CALL_CLEARED) {
4894 /* send an ack now to start the packet flow up again */
4895 call->flags &= ~RX_CALL_CLEARED;
4896 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4898 #ifdef RX_ENABLE_LOCKS
4901 service->nRequestsRunning++;
4902 MUTEX_ENTER(&rx_quota_mutex);
4903 if (service->nRequestsRunning <= service->minProcs)
4906 MUTEX_EXIT(&rx_quota_mutex);
4910 MUTEX_EXIT(&rx_serverPool_lock);
4913 /* Delay the sending of an acknowledge event for a short while, while
4914 * a new call is being prepared (in the case of a client) or a reply
4915 * is being prepared (in the case of a server). Rather than sending
4916 * an ack packet, an ACKALL packet is sent. */
4918 rxi_AckAll(struct rx_call *call)
4920 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4922 call->flags |= RX_CALL_ACKALL_SENT;
4926 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4929 struct rx_call *call = arg1;
4930 #ifdef RX_ENABLE_LOCKS
4932 MUTEX_ENTER(&call->lock);
4933 if (event == call->delayedAckEvent) {
4934 rxevent_Put(call->delayedAckEvent);
4935 call->delayedAckEvent = NULL;
4937 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4939 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4941 MUTEX_EXIT(&call->lock);
4942 #else /* RX_ENABLE_LOCKS */
4944 rxevent_Put(call->delayedAckEvent);
4945 call->delayedAckEvent = NULL;
4947 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4948 #endif /* RX_ENABLE_LOCKS */
4952 #ifdef RX_ENABLE_LOCKS
4953 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4954 * clearing them out.
4957 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4959 struct rx_packet *p, *tp;
4962 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4963 p->flags |= RX_PKTFLAG_ACKED;
4967 call->flags |= RX_CALL_TQ_CLEARME;
4968 call->flags |= RX_CALL_TQ_SOME_ACKED;
4971 rxi_rto_cancel(call);
4973 call->tfirst = call->tnext;
4974 call->nSoftAcked = 0;
4976 if (call->flags & RX_CALL_FAST_RECOVER) {
4977 call->flags &= ~RX_CALL_FAST_RECOVER;
4978 call->cwind = call->nextCwind;
4979 call->nextCwind = 0;
4982 CV_SIGNAL(&call->cv_twind);
4984 #endif /* RX_ENABLE_LOCKS */
4986 /* Clear out the transmit queue for the current call (all packets have
4987 * been received by peer) */
4989 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4991 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
4992 struct rx_packet *p, *tp;
4994 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4996 for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4997 p->flags |= RX_PKTFLAG_ACKED;
5001 call->flags |= RX_CALL_TQ_CLEARME;
5002 call->flags |= RX_CALL_TQ_SOME_ACKED;
5005 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5006 #ifdef RXDEBUG_PACKET
5008 #endif /* RXDEBUG_PACKET */
5009 rxi_FreePackets(0, &call->tq);
5010 rxi_WakeUpTransmitQueue(call);
5011 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5012 call->flags &= ~RX_CALL_TQ_CLEARME;
5014 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5016 rxi_rto_cancel(call);
5017 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5018 call->nSoftAcked = 0;
5020 if (call->flags & RX_CALL_FAST_RECOVER) {
5021 call->flags &= ~RX_CALL_FAST_RECOVER;
5022 call->cwind = call->nextCwind;
5024 #ifdef RX_ENABLE_LOCKS
5025 CV_SIGNAL(&call->cv_twind);
5027 osi_rxWakeup(&call->twind);
5032 rxi_ClearReceiveQueue(struct rx_call *call)
5034 if (queue_IsNotEmpty(&call->rq)) {
5037 count = rxi_FreePackets(0, &call->rq);
5038 rx_packetReclaims += count;
5039 #ifdef RXDEBUG_PACKET
5041 if ( call->rqc != 0 )
5042 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5044 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5046 if (call->state == RX_STATE_PRECALL) {
5047 call->flags |= RX_CALL_CLEARED;
5051 /* Send an abort packet for the specified call */
5052 static struct rx_packet *
5053 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5054 int istack, int force)
5056 afs_int32 error, cerror;
5057 struct clock when, now;
5062 switch (call->error) {
5065 cerror = RX_CALL_TIMEOUT;
5068 cerror = call->error;
5071 /* Clients should never delay abort messages */
5072 if (rx_IsClientConn(call->conn))
5075 if (call->abortCode != cerror) {
5076 call->abortCode = cerror;
5077 call->abortCount = 0;
5080 if (force || rxi_callAbortThreshhold == 0
5081 || call->abortCount < rxi_callAbortThreshhold) {
5082 if (call->delayedAbortEvent) {
5083 rxevent_Cancel(&call->delayedAbortEvent, call,
5084 RX_CALL_REFCOUNT_ABORT);
5086 error = htonl(cerror);
5089 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5090 (char *)&error, sizeof(error), istack);
5091 } else if (!call->delayedAbortEvent) {
5092 clock_GetTime(&now);
5094 clock_Addmsec(&when, rxi_callAbortDelay);
5095 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5096 call->delayedAbortEvent =
5097 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5102 /* Send an abort packet for the specified connection. Packet is an
5103 * optional pointer to a packet that can be used to send the abort.
5104 * Once the number of abort messages reaches the threshhold, an
5105 * event is scheduled to send the abort. Setting the force flag
5106 * overrides sending delayed abort messages.
5108 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5109 * to send the abort packet.
5112 rxi_SendConnectionAbort(struct rx_connection *conn,
5113 struct rx_packet *packet, int istack, int force)
5116 struct clock when, now;
5121 /* Clients should never delay abort messages */
5122 if (rx_IsClientConn(conn))
5125 if (force || rxi_connAbortThreshhold == 0
5126 || conn->abortCount < rxi_connAbortThreshhold) {
5128 rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5129 error = htonl(conn->error);
5131 MUTEX_EXIT(&conn->conn_data_lock);
5133 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5134 RX_PACKET_TYPE_ABORT, (char *)&error,
5135 sizeof(error), istack);
5136 MUTEX_ENTER(&conn->conn_data_lock);
5137 } else if (!conn->delayedAbortEvent) {
5138 clock_GetTime(&now);
5140 clock_Addmsec(&when, rxi_connAbortDelay);
5141 conn->delayedAbortEvent =
5142 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5147 /* Associate an error all of the calls owned by a connection. Called
5148 * with error non-zero. This is only for really fatal things, like
5149 * bad authentication responses. The connection itself is set in
5150 * error at this point, so that future packets received will be
5153 rxi_ConnectionError(struct rx_connection *conn,
5159 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5161 MUTEX_ENTER(&conn->conn_data_lock);
5162 rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5163 rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5164 if (conn->checkReachEvent) {
5165 rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5166 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5167 putConnection(conn);
5169 MUTEX_EXIT(&conn->conn_data_lock);
5170 for (i = 0; i < RX_MAXCALLS; i++) {
5171 struct rx_call *call = conn->call[i];
5173 MUTEX_ENTER(&call->lock);
5174 rxi_CallError(call, error);
5175 MUTEX_EXIT(&call->lock);
5178 conn->error = error;
5179 if (rx_stats_active)
5180 rx_atomic_inc(&rx_stats.fatalErrors);
5185 * Interrupt an in-progress call with the specified error and wakeup waiters.
5187 * @param[in] call The call to interrupt
5188 * @param[in] error The error code to send to the peer
5191 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5193 MUTEX_ENTER(&call->lock);
5194 rxi_CallError(call, error);
5195 rxi_SendCallAbort(call, NULL, 0, 1);
5196 MUTEX_EXIT(&call->lock);
5200 rxi_CallError(struct rx_call *call, afs_int32 error)
5203 osirx_AssertMine(&call->lock, "rxi_CallError");
5205 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5207 error = call->error;
5209 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5210 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5211 rxi_ResetCall(call, 0);
5214 rxi_ResetCall(call, 0);
5216 call->error = error;
5219 /* Reset various fields in a call structure, and wakeup waiting
5220 * processes. Some fields aren't changed: state & mode are not
5221 * touched (these must be set by the caller), and bufptr, nLeft, and
5222 * nFree are not reset, since these fields are manipulated by
5223 * unprotected macros, and may only be reset by non-interrupting code.
5227 rxi_ResetCall(struct rx_call *call, int newcall)
5230 struct rx_peer *peer;
5231 struct rx_packet *packet;
5233 osirx_AssertMine(&call->lock, "rxi_ResetCall");
5235 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5237 /* Notify anyone who is waiting for asynchronous packet arrival */
5238 if (call->arrivalProc) {
5239 (*call->arrivalProc) (call, call->arrivalProcHandle,
5240 call->arrivalProcArg);
5241 call->arrivalProc = (void (*)())0;
5245 rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_MTU);
5247 if (call->delayedAbortEvent) {
5248 rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5249 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5251 rxi_SendCallAbort(call, packet, 0, 1);
5252 rxi_FreePacket(packet);
5257 * Update the peer with the congestion information in this call
5258 * so other calls on this connection can pick up where this call
5259 * left off. If the congestion sequence numbers don't match then
5260 * another call experienced a retransmission.
5262 peer = call->conn->peer;
5263 MUTEX_ENTER(&peer->peer_lock);
5265 if (call->congestSeq == peer->congestSeq) {
5266 peer->cwind = MAX(peer->cwind, call->cwind);
5267 peer->MTU = MAX(peer->MTU, call->MTU);
5268 peer->nDgramPackets =
5269 MAX(peer->nDgramPackets, call->nDgramPackets);
5272 call->abortCode = 0;
5273 call->abortCount = 0;
5275 if (peer->maxDgramPackets > 1) {
5276 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5278 call->MTU = peer->MTU;
5280 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5281 call->ssthresh = rx_maxSendWindow;
5282 call->nDgramPackets = peer->nDgramPackets;
5283 call->congestSeq = peer->congestSeq;
5284 call->rtt = peer->rtt;
5285 call->rtt_dev = peer->rtt_dev;
5286 clock_Zero(&call->rto);
5287 clock_Addmsec(&call->rto,
5288 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5289 MUTEX_EXIT(&peer->peer_lock);
5291 flags = call->flags;
5292 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5293 rxi_WaitforTQBusy(call);
5294 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5296 rxi_ClearTransmitQueue(call, 1);
5297 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5298 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5302 if (!newcall && (flags & RX_CALL_PEER_BUSY)) {
5303 /* The call channel is still busy; resetting the call doesn't change
5304 * that. However, if 'newcall' is set, we are processing a call
5305 * structure that has either been recycled from the free list, or has
5306 * been newly allocated. So, RX_CALL_PEER_BUSY is not relevant if
5307 * 'newcall' is set, since it describes a completely different call
5308 * channel which we do not care about. */
5309 call->flags |= RX_CALL_PEER_BUSY;
5312 rxi_ClearReceiveQueue(call);
5313 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5317 call->twind = call->conn->twind[call->channel];
5318 call->rwind = call->conn->rwind[call->channel];
5319 call->nSoftAcked = 0;
5320 call->nextCwind = 0;
5323 call->nCwindAcks = 0;
5324 call->nSoftAcks = 0;
5325 call->nHardAcks = 0;
5327 call->tfirst = call->rnext = call->tnext = 1;
5330 call->lastAcked = 0;
5331 call->localStatus = call->remoteStatus = 0;
5333 if (flags & RX_CALL_READER_WAIT) {
5334 #ifdef RX_ENABLE_LOCKS
5335 CV_BROADCAST(&call->cv_rq);
5337 osi_rxWakeup(&call->rq);
5340 if (flags & RX_CALL_WAIT_PACKETS) {
5341 MUTEX_ENTER(&rx_freePktQ_lock);
5342 rxi_PacketsUnWait(); /* XXX */
5343 MUTEX_EXIT(&rx_freePktQ_lock);
5345 #ifdef RX_ENABLE_LOCKS
5346 CV_SIGNAL(&call->cv_twind);
5348 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5349 osi_rxWakeup(&call->twind);
5352 #ifdef RX_ENABLE_LOCKS
5353 /* The following ensures that we don't mess with any queue while some
5354 * other thread might also be doing so. The call_queue_lock field is
5355 * is only modified under the call lock. If the call is in the process
5356 * of being removed from a queue, the call is not locked until the
5357 * the queue lock is dropped and only then is the call_queue_lock field
5358 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5359 * Note that any other routine which removes a call from a queue has to
5360 * obtain the queue lock before examing the queue and removing the call.
5362 if (call->call_queue_lock) {
5363 MUTEX_ENTER(call->call_queue_lock);
5364 if (queue_IsOnQueue(call)) {
5366 if (flags & RX_CALL_WAIT_PROC) {
5367 rx_atomic_dec(&rx_nWaiting);
5370 MUTEX_EXIT(call->call_queue_lock);
5371 CLEAR_CALL_QUEUE_LOCK(call);
5373 #else /* RX_ENABLE_LOCKS */
5374 if (queue_IsOnQueue(call)) {
5376 if (flags & RX_CALL_WAIT_PROC)
5377 rx_atomic_dec(&rx_nWaiting);
5379 #endif /* RX_ENABLE_LOCKS */
5381 rxi_KeepAliveOff(call);
5382 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5385 /* Send an acknowledge for the indicated packet (seq,serial) of the
5386 * indicated call, for the indicated reason (reason). This
5387 * acknowledge will specifically acknowledge receiving the packet, and
5388 * will also specify which other packets for this call have been
5389 * received. This routine returns the packet that was used to the
5390 * caller. The caller is responsible for freeing it or re-using it.
5391 * This acknowledgement also returns the highest sequence number
5392 * actually read out by the higher level to the sender; the sender
5393 * promises to keep around packets that have not been read by the
5394 * higher level yet (unless, of course, the sender decides to abort
5395 * the call altogether). Any of p, seq, serial, pflags, or reason may
5396 * be set to zero without ill effect. That is, if they are zero, they
5397 * will not convey any information.
5398 * NOW there is a trailer field, after the ack where it will safely be
5399 * ignored by mundanes, which indicates the maximum size packet this
5400 * host can swallow. */
5402 struct rx_packet *optionalPacket; use to send ack (or null)
5403 int seq; Sequence number of the packet we are acking
5404 int serial; Serial number of the packet
5405 int pflags; Flags field from packet header
5406 int reason; Reason an acknowledge was prompted
5410 rxi_SendAck(struct rx_call *call,
5411 struct rx_packet *optionalPacket, int serial, int reason,
5414 struct rx_ackPacket *ap;
5415 struct rx_packet *rqp;
5416 struct rx_packet *nxp; /* For queue_Scan */
5417 struct rx_packet *p;
5420 afs_uint32 padbytes = 0;
5421 #ifdef RX_ENABLE_TSFPQ
5422 struct rx_ts_info_t * rx_ts_info;
5426 * Open the receive window once a thread starts reading packets
5428 if (call->rnext > 1) {
5429 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5432 /* Don't attempt to grow MTU if this is a critical ping */
5433 if (reason == RX_ACK_MTU) {
5434 /* keep track of per-call attempts, if we're over max, do in small
5435 * otherwise in larger? set a size to increment by, decrease
5438 if (call->conn->peer->maxPacketSize &&
5439 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5441 padbytes = call->conn->peer->maxPacketSize+16;
5443 padbytes = call->conn->peer->maxMTU + 128;
5445 /* do always try a minimum size ping */
5446 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5448 /* subtract the ack payload */
5449 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5450 reason = RX_ACK_PING;
5453 call->nHardAcks = 0;
5454 call->nSoftAcks = 0;
5455 if (call->rnext > call->lastAcked)
5456 call->lastAcked = call->rnext;
5460 rx_computelen(p, p->length); /* reset length, you never know */
5461 } /* where that's been... */
5462 #ifdef RX_ENABLE_TSFPQ
5464 RX_TS_INFO_GET(rx_ts_info);
5465 if ((p = rx_ts_info->local_special_packet)) {
5466 rx_computelen(p, p->length);
5467 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5468 rx_ts_info->local_special_packet = p;
5469 } else { /* We won't send the ack, but don't panic. */
5470 return optionalPacket;
5474 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5475 /* We won't send the ack, but don't panic. */
5476 return optionalPacket;
5481 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5484 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5485 #ifndef RX_ENABLE_TSFPQ
5486 if (!optionalPacket)
5489 return optionalPacket;
5491 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5492 if (rx_Contiguous(p) < templ) {
5493 #ifndef RX_ENABLE_TSFPQ
5494 if (!optionalPacket)
5497 return optionalPacket;
5502 /* MTUXXX failing to send an ack is very serious. We should */
5503 /* try as hard as possible to send even a partial ack; it's */
5504 /* better than nothing. */
5505 ap = (struct rx_ackPacket *)rx_DataOf(p);
5506 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5507 ap->reason = reason;
5509 /* The skew computation used to be bogus, I think it's better now. */
5510 /* We should start paying attention to skew. XXX */
5511 ap->serial = htonl(serial);
5512 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5515 * First packet not yet forwarded to reader. When ACKALL has been
5516 * sent the peer has been told that all received packets will be
5517 * delivered to the reader. The value 'rnext' is used internally
5518 * to refer to the next packet in the receive queue that must be
5519 * delivered to the reader. From the perspective of the peer it
5520 * already has so report the last sequence number plus one if there
5521 * are packets in the receive queue awaiting processing.
5523 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5524 !queue_IsEmpty(&call->rq)) {
5525 ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5527 ap->firstPacket = htonl(call->rnext);
5529 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5531 /* No fear of running out of ack packet here because there can only be at most
5532 * one window full of unacknowledged packets. The window size must be constrained
5533 * to be less than the maximum ack size, of course. Also, an ack should always
5534 * fit into a single packet -- it should not ever be fragmented. */
5535 for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5536 if (!rqp || !call->rq.next
5537 || (rqp->header.seq > (call->rnext + call->rwind))) {
5538 #ifndef RX_ENABLE_TSFPQ
5539 if (!optionalPacket)
5542 rxi_CallError(call, RX_CALL_DEAD);
5543 return optionalPacket;
5546 while (rqp->header.seq > call->rnext + offset)
5547 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5548 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5550 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5551 #ifndef RX_ENABLE_TSFPQ
5552 if (!optionalPacket)
5555 rxi_CallError(call, RX_CALL_DEAD);
5556 return optionalPacket;
5562 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5564 /* these are new for AFS 3.3 */
5565 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5566 templ = htonl(templ);
5567 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5568 templ = htonl(call->conn->peer->ifMTU);
5569 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5570 sizeof(afs_int32), &templ);
5572 /* new for AFS 3.4 */
5573 templ = htonl(call->rwind);
5574 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5575 sizeof(afs_int32), &templ);
5577 /* new for AFS 3.5 */
5578 templ = htonl(call->conn->peer->ifDgramPackets);
5579 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5580 sizeof(afs_int32), &templ);
5582 p->header.serviceId = call->conn->serviceId;
5583 p->header.cid = (call->conn->cid | call->channel);
5584 p->header.callNumber = *call->callNumber;
5586 p->header.securityIndex = call->conn->securityIndex;
5587 p->header.epoch = call->conn->epoch;
5588 p->header.type = RX_PACKET_TYPE_ACK;
5589 p->header.flags = RX_SLOW_START_OK;
5590 if (reason == RX_ACK_PING) {
5591 p->header.flags |= RX_REQUEST_ACK;
5593 p->length = padbytes +
5594 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5597 /* not fast but we can potentially use this if truncated
5598 * fragments are delivered to figure out the mtu.
5600 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5601 sizeof(afs_int32), sizeof(afs_int32),
5605 if (call->conn->type == RX_CLIENT_CONNECTION)
5606 p->header.flags |= RX_CLIENT_INITIATED;
5610 if (rxdebug_active) {
5614 len = _snprintf(msg, sizeof(msg),
5615 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5616 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5617 ntohl(ap->serial), ntohl(ap->previousPacket),
5618 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5619 ap->nAcks, ntohs(ap->bufferSpace) );
5623 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5624 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5628 OutputDebugString(msg);
5630 #else /* AFS_NT40_ENV */
5632 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5633 ap->reason, ntohl(ap->previousPacket),
5634 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5636 for (offset = 0; offset < ap->nAcks; offset++)
5637 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5642 #endif /* AFS_NT40_ENV */
5645 int i, nbytes = p->length;
5647 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5648 if (nbytes <= p->wirevec[i].iov_len) {
5651 savelen = p->wirevec[i].iov_len;
5653 p->wirevec[i].iov_len = nbytes;
5655 rxi_Send(call, p, istack);
5656 p->wirevec[i].iov_len = savelen;
5660 nbytes -= p->wirevec[i].iov_len;
5663 if (rx_stats_active)
5664 rx_atomic_inc(&rx_stats.ackPacketsSent);
5665 #ifndef RX_ENABLE_TSFPQ
5666 if (!optionalPacket)
5669 return optionalPacket; /* Return packet for re-use by caller */
5673 struct rx_packet **list;
5678 /* Send all of the packets in the list in single datagram */
5680 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5681 int istack, int moreFlag)
5687 struct rx_connection *conn = call->conn;
5688 struct rx_peer *peer = conn->peer;
5690 MUTEX_ENTER(&peer->peer_lock);
5691 peer->nSent += xmit->len;
5692 if (xmit->resending)
5693 peer->reSends += xmit->len;
5694 MUTEX_EXIT(&peer->peer_lock);
5696 if (rx_stats_active) {
5697 if (xmit->resending)
5698 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5700 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5703 clock_GetTime(&now);
5705 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5709 /* Set the packet flags and schedule the resend events */
5710 /* Only request an ack for the last packet in the list */
5711 for (i = 0; i < xmit->len; i++) {
5712 struct rx_packet *packet = xmit->list[i];
5714 /* Record the time sent */
5715 packet->timeSent = now;
5716 packet->flags |= RX_PKTFLAG_SENT;
5718 /* Ask for an ack on retransmitted packets, on every other packet
5719 * if the peer doesn't support slow start. Ask for an ack on every
5720 * packet until the congestion window reaches the ack rate. */
5721 if (packet->header.serial) {
5724 packet->firstSent = now;
5725 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5726 || (!(call->flags & RX_CALL_SLOW_START_OK)
5727 && (packet->header.seq & 1)))) {
5732 /* Tag this packet as not being the last in this group,
5733 * for the receiver's benefit */
5734 if (i < xmit->len - 1 || moreFlag) {
5735 packet->header.flags |= RX_MORE_PACKETS;
5740 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5743 /* Since we're about to send a data packet to the peer, it's
5744 * safe to nuke any scheduled end-of-packets ack */
5745 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5747 MUTEX_EXIT(&call->lock);
5748 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5749 if (xmit->len > 1) {
5750 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5752 rxi_SendPacket(call, conn, xmit->list[0], istack);
5754 MUTEX_ENTER(&call->lock);
5755 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5757 /* Tell the RTO calculation engine that we have sent a packet, and
5758 * if it was the last one */
5759 rxi_rto_packet_sent(call, lastPacket, istack);
5761 /* Update last send time for this call (for keep-alive
5762 * processing), and for the connection (so that we can discover
5763 * idle connections) */
5764 conn->lastSendTime = call->lastSendTime = clock_Sec();
5765 /* Let a set of retransmits trigger an idle timeout */
5766 if (!xmit->resending)
5767 call->lastSendData = call->lastSendTime;
5770 /* When sending packets we need to follow these rules:
5771 * 1. Never send more than maxDgramPackets in a jumbogram.
5772 * 2. Never send a packet with more than two iovecs in a jumbogram.
5773 * 3. Never send a retransmitted packet in a jumbogram.
5774 * 4. Never send more than cwind/4 packets in a jumbogram
5775 * We always keep the last list we should have sent so we
5776 * can set the RX_MORE_PACKETS flags correctly.
5780 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5785 struct xmitlist working;
5786 struct xmitlist last;
5788 struct rx_peer *peer = call->conn->peer;
5789 int morePackets = 0;
5791 memset(&last, 0, sizeof(struct xmitlist));
5792 working.list = &list[0];
5794 working.resending = 0;
5796 recovery = call->flags & RX_CALL_FAST_RECOVER;
5798 for (i = 0; i < len; i++) {
5799 /* Does the current packet force us to flush the current list? */
5801 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5802 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5804 /* This sends the 'last' list and then rolls the current working
5805 * set into the 'last' one, and resets the working set */
5808 rxi_SendList(call, &last, istack, 1);
5809 /* If the call enters an error state stop sending, or if
5810 * we entered congestion recovery mode, stop sending */
5812 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5817 working.resending = 0;
5818 working.list = &list[i];
5820 /* Add the current packet to the list if it hasn't been acked.
5821 * Otherwise adjust the list pointer to skip the current packet. */
5822 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5825 if (list[i]->header.serial)
5826 working.resending = 1;
5828 /* Do we need to flush the list? */
5829 if (working.len >= (int)peer->maxDgramPackets
5830 || working.len >= (int)call->nDgramPackets
5831 || working.len >= (int)call->cwind
5832 || list[i]->header.serial
5833 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5835 rxi_SendList(call, &last, istack, 1);
5836 /* If the call enters an error state stop sending, or if
5837 * we entered congestion recovery mode, stop sending */
5839 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5844 working.resending = 0;
5845 working.list = &list[i + 1];
5848 if (working.len != 0) {
5849 osi_Panic("rxi_SendList error");
5851 working.list = &list[i + 1];
5855 /* Send the whole list when the call is in receive mode, when
5856 * the call is in eof mode, when we are in fast recovery mode,
5857 * and when we have the last packet */
5858 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5859 || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5860 || (call->flags & RX_CALL_FAST_RECOVER)) {
5861 /* Check for the case where the current list contains
5862 * an acked packet. Since we always send retransmissions
5863 * in a separate packet, we only need to check the first
5864 * packet in the list */
5865 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5869 rxi_SendList(call, &last, istack, morePackets);
5870 /* If the call enters an error state stop sending, or if
5871 * we entered congestion recovery mode, stop sending */
5873 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5877 rxi_SendList(call, &working, istack, 0);
5879 } else if (last.len > 0) {
5880 rxi_SendList(call, &last, istack, 0);
5881 /* Packets which are in 'working' are not sent by this call */
5886 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5888 struct rx_call *call = arg0;
5889 struct rx_peer *peer;
5890 struct rx_packet *p, *nxp;
5891 struct clock maxTimeout = { 60, 0 };
5893 MUTEX_ENTER(&call->lock);
5895 peer = call->conn->peer;
5897 /* Make sure that the event pointer is removed from the call
5898 * structure, since there is no longer a per-call retransmission
5900 if (event == call->resendEvent) {
5901 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5902 rxevent_Put(call->resendEvent);
5903 call->resendEvent = NULL;
5906 if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5907 rxi_CheckBusy(call);
5910 if (queue_IsEmpty(&call->tq)) {
5911 /* Nothing to do. This means that we've been raced, and that an
5912 * ACK has come in between when we were triggered, and when we
5913 * actually got to run. */
5917 /* We're in loss recovery */
5918 call->flags |= RX_CALL_FAST_RECOVER;
5920 /* Mark all of the pending packets in the queue as being lost */
5921 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5922 if (!(p->flags & RX_PKTFLAG_ACKED))
5923 p->flags &= ~RX_PKTFLAG_SENT;
5926 /* We're resending, so we double the timeout of the call. This will be
5927 * dropped back down by the first successful ACK that we receive.
5929 * We apply a maximum value here of 60 seconds
5931 clock_Add(&call->rto, &call->rto);
5932 if (clock_Gt(&call->rto, &maxTimeout))
5933 call->rto = maxTimeout;
5935 /* Packet loss is most likely due to congestion, so drop our window size
5936 * and start again from the beginning */
5937 if (peer->maxDgramPackets >1) {
5938 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5939 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5941 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5942 call->nDgramPackets = 1;
5944 call->nextCwind = 1;
5947 MUTEX_ENTER(&peer->peer_lock);
5948 peer->MTU = call->MTU;
5949 peer->cwind = call->cwind;
5950 peer->nDgramPackets = 1;
5952 call->congestSeq = peer->congestSeq;
5953 MUTEX_EXIT(&peer->peer_lock);
5955 rxi_Start(call, istack);
5958 MUTEX_EXIT(&call->lock);
5961 /* This routine is called when new packets are readied for
5962 * transmission and when retransmission may be necessary, or when the
5963 * transmission window or burst count are favourable. This should be
5964 * better optimized for new packets, the usual case, now that we've
5965 * got rid of queues of send packets. XXXXXXXXXXX */
5967 rxi_Start(struct rx_call *call, int istack)
5970 struct rx_packet *p;
5971 struct rx_packet *nxp; /* Next pointer for queue_Scan */
5976 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5977 if (rx_stats_active)
5978 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5983 if (queue_IsNotEmpty(&call->tq)) { /* If we have anything to send */
5985 /* Send (or resend) any packets that need it, subject to
5986 * window restrictions and congestion burst control
5987 * restrictions. Ask for an ack on the last packet sent in
5988 * this burst. For now, we're relying upon the window being
5989 * considerably bigger than the largest number of packets that
5990 * are typically sent at once by one initial call to
5991 * rxi_Start. This is probably bogus (perhaps we should ask
5992 * for an ack when we're half way through the current
5993 * window?). Also, for non file transfer applications, this
5994 * may end up asking for an ack for every packet. Bogus. XXXX
5997 * But check whether we're here recursively, and let the other guy
6000 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6001 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6002 call->flags |= RX_CALL_TQ_BUSY;
6004 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6006 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6007 call->flags &= ~RX_CALL_NEED_START;
6008 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6010 maxXmitPackets = MIN(call->twind, call->cwind);
6011 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
6012 #ifdef RX_TRACK_PACKETS
6013 if ((p->flags & RX_PKTFLAG_FREE)
6014 || (!queue_IsEnd(&call->tq, nxp)
6015 && (nxp->flags & RX_PKTFLAG_FREE))
6016 || (p == (struct rx_packet *)&rx_freePacketQueue)
6017 || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
6018 osi_Panic("rxi_Start: xmit queue clobbered");
6021 if (p->flags & RX_PKTFLAG_ACKED) {
6022 /* Since we may block, don't trust this */
6023 if (rx_stats_active)
6024 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6025 continue; /* Ignore this packet if it has been acknowledged */
6028 /* Turn off all flags except these ones, which are the same
6029 * on each transmission */
6030 p->header.flags &= RX_PRESET_FLAGS;
6032 if (p->header.seq >=
6033 call->tfirst + MIN((int)call->twind,
6034 (int)(call->nSoftAcked +
6036 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6037 /* Note: if we're waiting for more window space, we can
6038 * still send retransmits; hence we don't return here, but
6039 * break out to schedule a retransmit event */
6040 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6041 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6046 /* Transmit the packet if it needs to be sent. */
6047 if (!(p->flags & RX_PKTFLAG_SENT)) {
6048 if (nXmitPackets == maxXmitPackets) {
6049 rxi_SendXmitList(call, call->xmitList,
6050 nXmitPackets, istack);
6053 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6054 *(call->callNumber), p));
6055 call->xmitList[nXmitPackets++] = p;
6059 /* xmitList now hold pointers to all of the packets that are
6060 * ready to send. Now we loop to send the packets */
6061 if (nXmitPackets > 0) {
6062 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6066 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6068 /* We went into the error state while sending packets. Now is
6069 * the time to reset the call. This will also inform the using
6070 * process that the call is in an error state.
6072 if (rx_stats_active)
6073 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6074 call->flags &= ~RX_CALL_TQ_BUSY;
6075 rxi_WakeUpTransmitQueue(call);
6076 rxi_CallError(call, call->error);
6079 #ifdef RX_ENABLE_LOCKS
6080 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6082 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6083 /* Some packets have received acks. If they all have, we can clear
6084 * the transmit queue.
6087 0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6088 if (p->header.seq < call->tfirst
6089 && (p->flags & RX_PKTFLAG_ACKED)) {
6091 #ifdef RX_TRACK_PACKETS
6092 p->flags &= ~RX_PKTFLAG_TQ;
6094 #ifdef RXDEBUG_PACKET
6102 call->flags |= RX_CALL_TQ_CLEARME;
6104 #endif /* RX_ENABLE_LOCKS */
6105 if (call->flags & RX_CALL_TQ_CLEARME)
6106 rxi_ClearTransmitQueue(call, 1);
6107 } while (call->flags & RX_CALL_NEED_START);
6109 * TQ references no longer protected by this flag; they must remain
6110 * protected by the global lock.
6112 call->flags &= ~RX_CALL_TQ_BUSY;
6113 rxi_WakeUpTransmitQueue(call);
6115 call->flags |= RX_CALL_NEED_START;
6117 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6119 rxi_rto_cancel(call);
6123 /* Also adjusts the keep alive parameters for the call, to reflect
6124 * that we have just sent a packet (so keep alives aren't sent
6127 rxi_Send(struct rx_call *call, struct rx_packet *p,
6130 struct rx_connection *conn = call->conn;
6132 /* Stamp each packet with the user supplied status */
6133 p->header.userStatus = call->localStatus;
6135 /* Allow the security object controlling this call's security to
6136 * make any last-minute changes to the packet */
6137 RXS_SendPacket(conn->securityObject, call, p);
6139 /* Since we're about to send SOME sort of packet to the peer, it's
6140 * safe to nuke any scheduled end-of-packets ack */
6141 rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6143 /* Actually send the packet, filling in more connection-specific fields */
6144 MUTEX_EXIT(&call->lock);
6145 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6146 rxi_SendPacket(call, conn, p, istack);
6147 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6148 MUTEX_ENTER(&call->lock);
6150 /* Update last send time for this call (for keep-alive
6151 * processing), and for the connection (so that we can discover
6152 * idle connections) */
6153 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6154 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6155 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6157 conn->lastSendTime = call->lastSendTime = clock_Sec();
6158 /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6159 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6160 ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6161 (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6162 RX_ACK_PING_RESPONSE)))
6163 call->lastSendData = call->lastSendTime;
6167 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6168 * that things are fine. Also called periodically to guarantee that nothing
6169 * falls through the cracks (e.g. (error + dally) connections have keepalive
6170 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6172 * haveCTLock Set if calling from rxi_ReapConnections
6174 #ifdef RX_ENABLE_LOCKS
6176 static rxi_CheckCall(struct rx_call *call, int haveCTLock)
6177 #else /* RX_ENABLE_LOCKS */
6179 static rxi_CheckCall(struct rx_call *call)
6180 #endif /* RX_ENABLE_LOCKS */
6182 struct rx_connection *conn = call->conn;
6184 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6185 afs_uint32 fudgeFactor;
6188 int idle_timeout = 0;
6189 afs_int32 clock_diff = 0;
6193 /* Large swings in the clock can have a significant impact on
6194 * the performance of RX call processing. Forward clock shifts
6195 * will result in premature event triggering or timeouts.
6196 * Backward shifts can result in calls not completing until
6197 * the clock catches up with the original start clock value.
6199 * If a backward clock shift of more than five minutes is noticed,
6200 * just fail the call.
6202 if (now < call->lastSendTime)
6203 clock_diff = call->lastSendTime - now;
6204 if (now < call->startWait)
6205 clock_diff = MAX(clock_diff, call->startWait - now);
6206 if (now < call->lastReceiveTime)
6207 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6208 if (clock_diff > 5 * 60)
6210 if (call->state == RX_STATE_ACTIVE)
6211 rxi_CallError(call, RX_CALL_TIMEOUT);
6215 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6216 if (call->flags & RX_CALL_TQ_BUSY) {
6217 /* Call is active and will be reset by rxi_Start if it's
6218 * in an error state.
6223 /* RTT + 8*MDEV, rounded up to the next second. */
6224 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6225 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6227 deadTime = conn->secondsUntilDead + fudgeFactor;
6228 /* These are computed to the second (+- 1 second). But that's
6229 * good enough for these values, which should be a significant
6230 * number of seconds. */
6231 if (now > (call->lastReceiveTime + deadTime)) {
6232 if (call->state == RX_STATE_ACTIVE) {
6234 #if defined(KERNEL) && defined(AFS_SUN5_ENV)
6236 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6237 netstack_t *ns = netstack_find_by_stackid(GLOBAL_NETSTACKID);
6238 ip_stack_t *ipst = ns->netstack_ip;
6240 ire = ire_cache_lookup(conn->peer->host
6241 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6243 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6245 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6252 if (ire && ire->ire_max_frag > 0)
6253 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6255 #if defined(GLOBAL_NETSTACKID)
6259 #endif /* ADAPT_PMTU */
6260 cerror = RX_CALL_DEAD;
6263 #ifdef RX_ENABLE_LOCKS
6264 /* Cancel pending events */
6265 rxevent_Cancel(&call->delayedAckEvent, call,
6266 RX_CALL_REFCOUNT_DELAY);
6267 rxi_rto_cancel(call);
6268 rxevent_Cancel(&call->keepAliveEvent, call,
6269 RX_CALL_REFCOUNT_ALIVE);
6270 rxevent_Cancel(&call->growMTUEvent, call,
6271 RX_CALL_REFCOUNT_MTU);
6272 MUTEX_ENTER(&rx_refcnt_mutex);
6273 /* if rxi_FreeCall returns 1 it has freed the call */
6274 if (call->refCount == 0 &&
6275 rxi_FreeCall(call, haveCTLock))
6277 MUTEX_EXIT(&rx_refcnt_mutex);
6280 MUTEX_EXIT(&rx_refcnt_mutex);
6282 #else /* RX_ENABLE_LOCKS */
6283 rxi_FreeCall(call, 0);
6285 #endif /* RX_ENABLE_LOCKS */
6287 /* Non-active calls are destroyed if they are not responding
6288 * to pings; active calls are simply flagged in error, so the
6289 * attached process can die reasonably gracefully. */
6292 if (conn->idleDeadDetection) {
6293 if (conn->idleDeadTime) {
6294 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6298 /* see if we have a non-activity timeout */
6299 if (call->startWait && ((call->startWait + idleDeadTime) < now) &&
6300 (call->flags & RX_CALL_READER_WAIT)) {
6301 if (call->state == RX_STATE_ACTIVE) {
6302 cerror = RX_CALL_TIMEOUT;
6307 if (call->lastSendData && ((call->lastSendData + idleDeadTime) < now)) {
6308 if (call->state == RX_STATE_ACTIVE) {
6309 cerror = conn->service ? conn->service->idleDeadErr : RX_CALL_IDLE;
6317 if (conn->hardDeadTime) {
6318 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6321 /* see if we have a hard timeout */
6323 && (now > (hardDeadTime + call->startTime.sec))) {
6324 if (call->state == RX_STATE_ACTIVE)
6325 rxi_CallError(call, RX_CALL_TIMEOUT);
6330 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6331 call->lastReceiveTime) {
6332 int oldMTU = conn->peer->ifMTU;
6334 /* if we thought we could send more, perhaps things got worse */
6335 if (conn->peer->maxPacketSize > conn->lastPacketSize)
6336 /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6337 newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6338 conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6340 newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6342 /* minimum capped in SetPeerMtu */
6343 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6346 conn->lastPacketSize = 0;
6348 /* needed so ResetCall doesn't clobber us. */
6349 call->MTU = conn->peer->ifMTU;
6351 /* if we never succeeded, let the error pass out as-is */
6352 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6353 cerror = conn->msgsizeRetryErr;
6356 rxi_CallError(call, cerror);
6361 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6362 void *dummy, int dummy2)
6364 struct rx_connection *conn = arg1;
6365 struct rx_header theader;
6366 char tbuffer[1 + sizeof(struct rx_header)];
6367 struct sockaddr_in taddr;
6370 struct iovec tmpiov[2];
6373 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6376 tp = &tbuffer[sizeof(struct rx_header)];
6377 taddr.sin_family = AF_INET;
6378 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6379 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6380 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6381 taddr.sin_len = sizeof(struct sockaddr_in);
6383 memset(&theader, 0, sizeof(theader));
6384 theader.epoch = htonl(999);
6386 theader.callNumber = 0;
6389 theader.type = RX_PACKET_TYPE_VERSION;
6390 theader.flags = RX_LAST_PACKET;
6391 theader.serviceId = 0;
6393 memcpy(tbuffer, &theader, sizeof(theader));
6394 memcpy(tp, &a, sizeof(a));
6395 tmpiov[0].iov_base = tbuffer;
6396 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6398 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6400 MUTEX_ENTER(&conn->conn_data_lock);
6401 MUTEX_ENTER(&rx_refcnt_mutex);
6402 /* Only reschedule ourselves if the connection would not be destroyed */
6403 if (conn->refCount <= 1) {
6404 rxevent_Put(conn->natKeepAliveEvent);
6405 conn->natKeepAliveEvent = NULL;
6406 MUTEX_EXIT(&rx_refcnt_mutex);
6407 MUTEX_EXIT(&conn->conn_data_lock);
6408 rx_DestroyConnection(conn); /* drop the reference for this */
6410 conn->refCount--; /* drop the reference for this */
6411 MUTEX_EXIT(&rx_refcnt_mutex);
6412 rxevent_Put(conn->natKeepAliveEvent);
6413 conn->natKeepAliveEvent = NULL;
6414 rxi_ScheduleNatKeepAliveEvent(conn);
6415 MUTEX_EXIT(&conn->conn_data_lock);
6420 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6422 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6423 struct clock when, now;
6424 clock_GetTime(&now);
6426 when.sec += conn->secondsUntilNatPing;
6427 MUTEX_ENTER(&rx_refcnt_mutex);
6428 conn->refCount++; /* hold a reference for this */
6429 MUTEX_EXIT(&rx_refcnt_mutex);
6430 conn->natKeepAliveEvent =
6431 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6436 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6438 MUTEX_ENTER(&conn->conn_data_lock);
6439 conn->secondsUntilNatPing = seconds;
6441 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6442 rxi_ScheduleNatKeepAliveEvent(conn);
6444 conn->flags |= RX_CONN_NAT_PING;
6446 MUTEX_EXIT(&conn->conn_data_lock);
6449 /* When a call is in progress, this routine is called occasionally to
6450 * make sure that some traffic has arrived (or been sent to) the peer.
6451 * If nothing has arrived in a reasonable amount of time, the call is
6452 * declared dead; if nothing has been sent for a while, we send a
6453 * keep-alive packet (if we're actually trying to keep the call alive)
6456 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6459 struct rx_call *call = arg1;
6460 struct rx_connection *conn;
6463 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6464 MUTEX_ENTER(&call->lock);
6466 if (event == call->keepAliveEvent) {
6467 rxevent_Put(call->keepAliveEvent);
6468 call->keepAliveEvent = NULL;
6473 #ifdef RX_ENABLE_LOCKS
6474 if (rxi_CheckCall(call, 0)) {
6475 MUTEX_EXIT(&call->lock);
6478 #else /* RX_ENABLE_LOCKS */
6479 if (rxi_CheckCall(call))
6481 #endif /* RX_ENABLE_LOCKS */
6483 /* Don't try to keep alive dallying calls */
6484 if (call->state == RX_STATE_DALLY) {
6485 MUTEX_EXIT(&call->lock);
6490 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6491 /* Don't try to send keepalives if there is unacknowledged data */
6492 /* the rexmit code should be good enough, this little hack
6493 * doesn't quite work XXX */
6494 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6496 rxi_ScheduleKeepAliveEvent(call);
6497 MUTEX_EXIT(&call->lock);
6500 /* Does what's on the nameplate. */
6502 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6504 struct rx_call *call = arg1;
6505 struct rx_connection *conn;
6507 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6508 MUTEX_ENTER(&call->lock);
6510 if (event == call->growMTUEvent) {
6511 rxevent_Put(call->growMTUEvent);
6512 call->growMTUEvent = NULL;
6515 #ifdef RX_ENABLE_LOCKS
6516 if (rxi_CheckCall(call, 0)) {
6517 MUTEX_EXIT(&call->lock);
6520 #else /* RX_ENABLE_LOCKS */
6521 if (rxi_CheckCall(call))
6523 #endif /* RX_ENABLE_LOCKS */
6525 /* Don't bother with dallying calls */
6526 if (call->state == RX_STATE_DALLY) {
6527 MUTEX_EXIT(&call->lock);
6534 * keep being scheduled, just don't do anything if we're at peak,
6535 * or we're not set up to be properly handled (idle timeout required)
6537 if ((conn->peer->maxPacketSize != 0) &&
6538 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6539 conn->idleDeadDetection)
6540 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6541 rxi_ScheduleGrowMTUEvent(call, 0);
6542 MUTEX_EXIT(&call->lock);
6546 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6548 if (!call->keepAliveEvent) {
6549 struct clock when, now;
6550 clock_GetTime(&now);
6552 when.sec += call->conn->secondsUntilPing;
6553 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6554 call->keepAliveEvent =
6555 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6560 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6562 if (!call->growMTUEvent) {
6563 struct clock when, now;
6565 clock_GetTime(&now);
6568 if (call->conn->secondsUntilPing)
6569 secs = (6*call->conn->secondsUntilPing)-1;
6571 if (call->conn->secondsUntilDead)
6572 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6576 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6577 call->growMTUEvent =
6578 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6582 /* N.B. rxi_KeepAliveOff: is defined earlier as a macro */
6584 rxi_KeepAliveOn(struct rx_call *call)
6586 /* Pretend last packet received was received now--i.e. if another
6587 * packet isn't received within the keep alive time, then the call
6588 * will die; Initialize last send time to the current time--even
6589 * if a packet hasn't been sent yet. This will guarantee that a
6590 * keep-alive is sent within the ping time */
6591 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6592 rxi_ScheduleKeepAliveEvent(call);
6596 * Solely in order that callers not need to include rx_call.h
6599 rx_KeepAliveOff(struct rx_call *call)
6601 rxi_KeepAliveOff(call);
6604 rx_KeepAliveOn(struct rx_call *call)
6606 rxi_KeepAliveOn(call);
6610 rxi_GrowMTUOn(struct rx_call *call)
6612 struct rx_connection *conn = call->conn;
6613 MUTEX_ENTER(&conn->conn_data_lock);
6614 conn->lastPingSizeSer = conn->lastPingSize = 0;
6615 MUTEX_EXIT(&conn->conn_data_lock);
6616 rxi_ScheduleGrowMTUEvent(call, 1);
6619 /* This routine is called to send connection abort messages
6620 * that have been delayed to throttle looping clients. */
6622 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6625 struct rx_connection *conn = arg1;
6628 struct rx_packet *packet;
6630 MUTEX_ENTER(&conn->conn_data_lock);
6631 rxevent_Put(conn->delayedAbortEvent);
6632 conn->delayedAbortEvent = NULL;
6633 error = htonl(conn->error);
6635 MUTEX_EXIT(&conn->conn_data_lock);
6636 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6639 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6640 RX_PACKET_TYPE_ABORT, (char *)&error,
6642 rxi_FreePacket(packet);
6646 /* This routine is called to send call abort messages
6647 * that have been delayed to throttle looping clients. */
6649 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6652 struct rx_call *call = arg1;
6655 struct rx_packet *packet;
6657 MUTEX_ENTER(&call->lock);
6658 rxevent_Put(call->delayedAbortEvent);
6659 call->delayedAbortEvent = NULL;
6660 error = htonl(call->error);
6662 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6665 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6666 (char *)&error, sizeof(error), 0);
6667 rxi_FreePacket(packet);
6669 MUTEX_EXIT(&call->lock);
6670 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6673 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6674 * seconds) to ask the client to authenticate itself. The routine
6675 * issues a challenge to the client, which is obtained from the
6676 * security object associated with the connection */
6678 rxi_ChallengeEvent(struct rxevent *event,
6679 void *arg0, void *arg1, int tries)
6681 struct rx_connection *conn = arg0;
6684 rxevent_Put(conn->challengeEvent);
6685 conn->challengeEvent = NULL;
6688 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6689 struct rx_packet *packet;
6690 struct clock when, now;
6693 /* We've failed to authenticate for too long.
6694 * Reset any calls waiting for authentication;
6695 * they are all in RX_STATE_PRECALL.
6699 MUTEX_ENTER(&conn->conn_call_lock);
6700 for (i = 0; i < RX_MAXCALLS; i++) {
6701 struct rx_call *call = conn->call[i];
6703 MUTEX_ENTER(&call->lock);
6704 if (call->state == RX_STATE_PRECALL) {
6705 rxi_CallError(call, RX_CALL_DEAD);
6706 rxi_SendCallAbort(call, NULL, 0, 0);
6708 MUTEX_EXIT(&call->lock);
6711 MUTEX_EXIT(&conn->conn_call_lock);
6715 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6717 /* If there's no packet available, do this later. */
6718 RXS_GetChallenge(conn->securityObject, conn, packet);
6719 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6720 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6721 rxi_FreePacket(packet);
6723 clock_GetTime(&now);
6725 when.sec += RX_CHALLENGE_TIMEOUT;
6726 conn->challengeEvent =
6727 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6732 /* Call this routine to start requesting the client to authenticate
6733 * itself. This will continue until authentication is established,
6734 * the call times out, or an invalid response is returned. The
6735 * security object associated with the connection is asked to create
6736 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6737 * defined earlier. */
6739 rxi_ChallengeOn(struct rx_connection *conn)
6741 if (!conn->challengeEvent) {
6742 RXS_CreateChallenge(conn->securityObject, conn);
6743 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6748 /* rxi_ComputeRoundTripTime is called with peer locked. */
6749 /* peer may be null */
6751 rxi_ComputeRoundTripTime(struct rx_packet *p,
6752 struct rx_ackPacket *ack,
6753 struct rx_call *call,
6754 struct rx_peer *peer,
6757 struct clock thisRtt, *sentp;
6761 /* If the ACK is delayed, then do nothing */
6762 if (ack->reason == RX_ACK_DELAY)
6765 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6766 * their RTT multiple times, so only include the RTT of the last packet
6768 if (p->flags & RX_JUMBO_PACKET)
6771 /* Use the serial number to determine which transmission the ACK is for,
6772 * and set the sent time to match this. If we have no serial number, then
6773 * only use the ACK for RTT calculations if the packet has not been
6777 serial = ntohl(ack->serial);
6779 if (serial == p->header.serial) {
6780 sentp = &p->timeSent;
6781 } else if (serial == p->firstSerial) {
6782 sentp = &p->firstSent;
6783 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6784 sentp = &p->firstSent;
6788 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6789 sentp = &p->firstSent;
6796 if (clock_Lt(&thisRtt, sentp))
6797 return; /* somebody set the clock back, don't count this time. */
6799 clock_Sub(&thisRtt, sentp);
6800 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6801 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6803 if (clock_IsZero(&thisRtt)) {
6805 * The actual round trip time is shorter than the
6806 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6807 * Since we can't tell which at the moment we will assume 1ms.
6809 thisRtt.usec = 1000;
6812 if (rx_stats_active) {
6813 MUTEX_ENTER(&rx_stats_mutex);
6814 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6815 rx_stats.minRtt = thisRtt;
6816 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6817 if (thisRtt.sec > 60) {
6818 MUTEX_EXIT(&rx_stats_mutex);
6819 return; /* somebody set the clock ahead */
6821 rx_stats.maxRtt = thisRtt;
6823 clock_Add(&rx_stats.totalRtt, &thisRtt);
6824 rx_atomic_inc(&rx_stats.nRttSamples);
6825 MUTEX_EXIT(&rx_stats_mutex);
6828 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6830 /* Apply VanJacobson round-trip estimations */
6835 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6836 * srtt is stored as fixed point with 3 bits after the binary
6837 * point (i.e., scaled by 8). The following magic is
6838 * equivalent to the smoothing algorithm in rfc793 with an
6839 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6840 * srtt'*8 = rtt + srtt*7
6841 * srtt'*8 = srtt*8 + rtt - srtt
6842 * srtt' = srtt + rtt/8 - srtt/8
6843 * srtt' = srtt + (rtt - srtt)/8
6846 delta = _8THMSEC(&thisRtt) - call->rtt;
6847 call->rtt += (delta >> 3);
6850 * We accumulate a smoothed rtt variance (actually, a smoothed
6851 * mean difference), then set the retransmit timer to smoothed
6852 * rtt + 4 times the smoothed variance (was 2x in van's original
6853 * paper, but 4x works better for me, and apparently for him as
6855 * rttvar is stored as
6856 * fixed point with 2 bits after the binary point (scaled by
6857 * 4). The following is equivalent to rfc793 smoothing with
6858 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6859 * rttvar'*4 = rttvar*3 + |delta|
6860 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6861 * rttvar' = rttvar + |delta|/4 - rttvar/4
6862 * rttvar' = rttvar + (|delta| - rttvar)/4
6863 * This replaces rfc793's wired-in beta.
6864 * dev*4 = dev*4 + (|actual - expected| - dev)
6870 delta -= (call->rtt_dev << 1);
6871 call->rtt_dev += (delta >> 3);
6873 /* I don't have a stored RTT so I start with this value. Since I'm
6874 * probably just starting a call, and will be pushing more data down
6875 * this, I expect congestion to increase rapidly. So I fudge a
6876 * little, and I set deviance to half the rtt. In practice,
6877 * deviance tends to approach something a little less than
6878 * half the smoothed rtt. */
6879 call->rtt = _8THMSEC(&thisRtt) + 8;
6880 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6882 /* the smoothed RTT time is RTT + 4*MDEV
6884 * We allow a user specified minimum to be set for this, to allow clamping
6885 * at a minimum value in the same way as TCP. In addition, we have to allow
6886 * for the possibility that this packet is answered by a delayed ACK, so we
6887 * add on a fixed 200ms to account for that timer expiring.
6890 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6891 rx_minPeerTimeout) + 200;
6892 clock_Zero(&call->rto);
6893 clock_Addmsec(&call->rto, rtt_timeout);
6895 /* Update the peer, so any new calls start with our values */
6896 peer->rtt_dev = call->rtt_dev;
6897 peer->rtt = call->rtt;
6899 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6900 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6904 /* Find all server connections that have not been active for a long time, and
6907 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6910 struct clock now, when;
6911 clock_GetTime(&now);
6913 /* Find server connection structures that haven't been used for
6914 * greater than rx_idleConnectionTime */
6916 struct rx_connection **conn_ptr, **conn_end;
6917 int i, havecalls = 0;
6918 MUTEX_ENTER(&rx_connHashTable_lock);
6919 for (conn_ptr = &rx_connHashTable[0], conn_end =
6920 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6922 struct rx_connection *conn, *next;
6923 struct rx_call *call;
6927 for (conn = *conn_ptr; conn; conn = next) {
6928 /* XXX -- Shouldn't the connection be locked? */
6931 for (i = 0; i < RX_MAXCALLS; i++) {
6932 call = conn->call[i];
6936 code = MUTEX_TRYENTER(&call->lock);
6939 #ifdef RX_ENABLE_LOCKS
6940 result = rxi_CheckCall(call, 1);
6941 #else /* RX_ENABLE_LOCKS */
6942 result = rxi_CheckCall(call);
6943 #endif /* RX_ENABLE_LOCKS */
6944 MUTEX_EXIT(&call->lock);
6946 /* If CheckCall freed the call, it might
6947 * have destroyed the connection as well,
6948 * which screws up the linked lists.
6954 if (conn->type == RX_SERVER_CONNECTION) {
6955 /* This only actually destroys the connection if
6956 * there are no outstanding calls */
6957 MUTEX_ENTER(&conn->conn_data_lock);
6958 MUTEX_ENTER(&rx_refcnt_mutex);
6959 if (!havecalls && !conn->refCount
6960 && ((conn->lastSendTime + rx_idleConnectionTime) <
6962 conn->refCount++; /* it will be decr in rx_DestroyConn */
6963 MUTEX_EXIT(&rx_refcnt_mutex);
6964 MUTEX_EXIT(&conn->conn_data_lock);
6965 #ifdef RX_ENABLE_LOCKS
6966 rxi_DestroyConnectionNoLock(conn);
6967 #else /* RX_ENABLE_LOCKS */
6968 rxi_DestroyConnection(conn);
6969 #endif /* RX_ENABLE_LOCKS */
6971 #ifdef RX_ENABLE_LOCKS
6973 MUTEX_EXIT(&rx_refcnt_mutex);
6974 MUTEX_EXIT(&conn->conn_data_lock);
6976 #endif /* RX_ENABLE_LOCKS */
6980 #ifdef RX_ENABLE_LOCKS
6981 while (rx_connCleanup_list) {
6982 struct rx_connection *conn;
6983 conn = rx_connCleanup_list;
6984 rx_connCleanup_list = rx_connCleanup_list->next;
6985 MUTEX_EXIT(&rx_connHashTable_lock);
6986 rxi_CleanupConnection(conn);
6987 MUTEX_ENTER(&rx_connHashTable_lock);
6989 MUTEX_EXIT(&rx_connHashTable_lock);
6990 #endif /* RX_ENABLE_LOCKS */
6993 /* Find any peer structures that haven't been used (haven't had an
6994 * associated connection) for greater than rx_idlePeerTime */
6996 struct rx_peer **peer_ptr, **peer_end;
7000 * Why do we need to hold the rx_peerHashTable_lock across
7001 * the incrementing of peer_ptr since the rx_peerHashTable
7002 * array is not changing? We don't.
7004 * By dropping the lock periodically we can permit other
7005 * activities to be performed while a rxi_ReapConnections
7006 * call is in progress. The goal of reap connections
7007 * is to clean up quickly without causing large amounts
7008 * of contention. Therefore, it is important that global
7009 * mutexes not be held for extended periods of time.
7011 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7012 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7014 struct rx_peer *peer, *next, *prev;
7016 MUTEX_ENTER(&rx_peerHashTable_lock);
7017 for (prev = peer = *peer_ptr; peer; peer = next) {
7019 code = MUTEX_TRYENTER(&peer->peer_lock);
7020 if ((code) && (peer->refCount == 0)
7021 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7022 rx_interface_stat_p rpc_stat, nrpc_stat;
7026 * now know that this peer object is one to be
7027 * removed from the hash table. Once it is removed
7028 * it can't be referenced by other threads.
7029 * Lets remove it first and decrement the struct
7030 * nPeerStructs count.
7032 if (peer == *peer_ptr) {
7038 if (rx_stats_active)
7039 rx_atomic_dec(&rx_stats.nPeerStructs);
7042 * Now if we hold references on 'prev' and 'next'
7043 * we can safely drop the rx_peerHashTable_lock
7044 * while we destroy this 'peer' object.
7050 MUTEX_EXIT(&rx_peerHashTable_lock);
7052 MUTEX_EXIT(&peer->peer_lock);
7053 MUTEX_DESTROY(&peer->peer_lock);
7055 (&peer->rpcStats, rpc_stat, nrpc_stat,
7056 rx_interface_stat)) {
7057 unsigned int num_funcs;
7060 queue_Remove(&rpc_stat->queue_header);
7061 queue_Remove(&rpc_stat->all_peers);
7062 num_funcs = rpc_stat->stats[0].func_total;
7064 sizeof(rx_interface_stat_t) +
7065 rpc_stat->stats[0].func_total *
7066 sizeof(rx_function_entry_v1_t);
7068 rxi_Free(rpc_stat, space);
7070 MUTEX_ENTER(&rx_rpc_stats);
7071 rxi_rpc_peer_stat_cnt -= num_funcs;
7072 MUTEX_EXIT(&rx_rpc_stats);
7077 * Regain the rx_peerHashTable_lock and
7078 * decrement the reference count on 'prev'
7081 MUTEX_ENTER(&rx_peerHashTable_lock);
7088 MUTEX_EXIT(&peer->peer_lock);
7093 MUTEX_EXIT(&rx_peerHashTable_lock);
7097 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7098 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7099 * GC, just below. Really, we shouldn't have to keep moving packets from
7100 * one place to another, but instead ought to always know if we can
7101 * afford to hold onto a packet in its particular use. */
7102 MUTEX_ENTER(&rx_freePktQ_lock);
7103 if (rx_waitingForPackets) {
7104 rx_waitingForPackets = 0;
7105 #ifdef RX_ENABLE_LOCKS
7106 CV_BROADCAST(&rx_waitingForPackets_cv);
7108 osi_rxWakeup(&rx_waitingForPackets);
7111 MUTEX_EXIT(&rx_freePktQ_lock);
7114 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7115 rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7119 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7120 * rx.h is sort of strange this is better. This is called with a security
7121 * object before it is discarded. Each connection using a security object has
7122 * its own refcount to the object so it won't actually be freed until the last
7123 * connection is destroyed.
7125 * This is the only rxs module call. A hold could also be written but no one
7129 rxs_Release(struct rx_securityClass *aobj)
7131 return RXS_Close(aobj);
7139 #define TRACE_OPTION_RX_DEBUG 16
7147 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7148 0, KEY_QUERY_VALUE, &parmKey);
7149 if (code != ERROR_SUCCESS)
7152 dummyLen = sizeof(TraceOption);
7153 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7154 (BYTE *) &TraceOption, &dummyLen);
7155 if (code == ERROR_SUCCESS) {
7156 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7158 RegCloseKey (parmKey);
7159 #endif /* AFS_NT40_ENV */
7164 rx_DebugOnOff(int on)
7168 rxdebug_active = on;
7174 rx_StatsOnOff(int on)
7176 rx_stats_active = on;
7180 /* Don't call this debugging routine directly; use dpf */
7182 rxi_DebugPrint(char *format, ...)
7191 va_start(ap, format);
7193 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7196 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7198 OutputDebugString(msg);
7204 va_start(ap, format);
7206 clock_GetTime(&now);
7207 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7208 (unsigned int)now.usec);
7209 vfprintf(rx_Log, format, ap);
7217 * This function is used to process the rx_stats structure that is local
7218 * to a process as well as an rx_stats structure received from a remote
7219 * process (via rxdebug). Therefore, it needs to do minimal version
7223 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7224 afs_int32 freePackets, char version)
7228 if (size != sizeof(struct rx_statistics)) {
7230 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7231 size, sizeof(struct rx_statistics));
7234 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7237 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7238 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7239 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7240 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7241 s->specialPktAllocFailures);
7243 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7244 s->receivePktAllocFailures, s->sendPktAllocFailures,
7245 s->specialPktAllocFailures);
7249 " greedy %u, " "bogusReads %u (last from host %x), "
7250 "noPackets %u, " "noBuffers %u, " "selects %u, "
7251 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7252 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7253 s->selects, s->sendSelects);
7255 fprintf(file, " packets read: ");
7256 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7257 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7259 fprintf(file, "\n");
7262 " other read counters: data %u, " "ack %u, " "dup %u "
7263 "spurious %u " "dally %u\n", s->dataPacketsRead,
7264 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7265 s->ignorePacketDally);
7267 fprintf(file, " packets sent: ");
7268 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7269 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7271 fprintf(file, "\n");
7274 " other send counters: ack %u, " "data %u (not resends), "
7275 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7276 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7277 s->dataPacketsPushed, s->ignoreAckedPacket);
7280 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7281 s->netSendFailures, (int)s->fatalErrors);
7283 if (s->nRttSamples) {
7284 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7285 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7287 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7288 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7292 " %d server connections, " "%d client connections, "
7293 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7294 s->nServerConns, s->nClientConns, s->nPeerStructs,
7295 s->nCallStructs, s->nFreeCallStructs);
7297 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7298 fprintf(file, " %d clock updates\n", clock_nUpdates);
7302 /* for backward compatibility */
7304 rx_PrintStats(FILE * file)
7306 MUTEX_ENTER(&rx_stats_mutex);
7307 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7308 sizeof(rx_stats), rx_nFreePackets,
7310 MUTEX_EXIT(&rx_stats_mutex);
7314 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7316 fprintf(file, "Peer %x.%d. " "Burst size %d, " "burst wait %d.%06d.\n",
7317 ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7318 (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7321 " Rtt %d, " "total sent %d, " "resent %d\n",
7322 peer->rtt, peer->nSent, peer->reSends);
7325 " Packet size %d, " "max in packet skew %d, "
7326 "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7327 (int)peer->outPacketSkew);
7331 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7333 * This mutex protects the following static variables:
7337 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7338 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7340 #define LOCK_RX_DEBUG
7341 #define UNLOCK_RX_DEBUG
7342 #endif /* AFS_PTHREAD_ENV */
7344 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7346 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7347 u_char type, void *inputData, size_t inputLength,
7348 void *outputData, size_t outputLength)
7350 static afs_int32 counter = 100;
7351 time_t waitTime, waitCount;
7352 struct rx_header theader;
7355 struct timeval tv_now, tv_wake, tv_delta;
7356 struct sockaddr_in taddr, faddr;
7370 tp = &tbuffer[sizeof(struct rx_header)];
7371 taddr.sin_family = AF_INET;
7372 taddr.sin_port = remotePort;
7373 taddr.sin_addr.s_addr = remoteAddr;
7374 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7375 taddr.sin_len = sizeof(struct sockaddr_in);
7378 memset(&theader, 0, sizeof(theader));
7379 theader.epoch = htonl(999);
7381 theader.callNumber = htonl(counter);
7384 theader.type = type;
7385 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7386 theader.serviceId = 0;
7388 memcpy(tbuffer, &theader, sizeof(theader));
7389 memcpy(tp, inputData, inputLength);
7391 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7392 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7394 /* see if there's a packet available */
7395 gettimeofday(&tv_wake, NULL);
7396 tv_wake.tv_sec += waitTime;
7399 FD_SET(socket, &imask);
7400 tv_delta.tv_sec = tv_wake.tv_sec;
7401 tv_delta.tv_usec = tv_wake.tv_usec;
7402 gettimeofday(&tv_now, NULL);
7404 if (tv_delta.tv_usec < tv_now.tv_usec) {
7406 tv_delta.tv_usec += 1000000;
7409 tv_delta.tv_usec -= tv_now.tv_usec;
7411 if (tv_delta.tv_sec < tv_now.tv_sec) {
7415 tv_delta.tv_sec -= tv_now.tv_sec;
7418 code = select(0, &imask, 0, 0, &tv_delta);
7419 #else /* AFS_NT40_ENV */
7420 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7421 #endif /* AFS_NT40_ENV */
7422 if (code == 1 && FD_ISSET(socket, &imask)) {
7423 /* now receive a packet */
7424 faddrLen = sizeof(struct sockaddr_in);
7426 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7427 (struct sockaddr *)&faddr, &faddrLen);
7430 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7431 if (counter == ntohl(theader.callNumber))
7439 /* see if we've timed out */
7447 code -= sizeof(struct rx_header);
7448 if (code > outputLength)
7449 code = outputLength;
7450 memcpy(outputData, tp, code);
7453 #endif /* RXDEBUG */
7456 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7457 afs_uint16 remotePort, struct rx_debugStats * stat,
7458 afs_uint32 * supportedValues)
7460 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7462 struct rx_debugIn in;
7464 *supportedValues = 0;
7465 in.type = htonl(RX_DEBUGI_GETSTATS);
7468 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7469 &in, sizeof(in), stat, sizeof(*stat));
7472 * If the call was successful, fixup the version and indicate
7473 * what contents of the stat structure are valid.
7474 * Also do net to host conversion of fields here.
7478 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7479 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7481 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7482 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7484 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7485 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7487 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7488 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7490 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7491 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7493 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7494 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7496 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7497 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7499 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7500 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7502 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7503 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7505 stat->nFreePackets = ntohl(stat->nFreePackets);
7506 stat->packetReclaims = ntohl(stat->packetReclaims);
7507 stat->callsExecuted = ntohl(stat->callsExecuted);
7508 stat->nWaiting = ntohl(stat->nWaiting);
7509 stat->idleThreads = ntohl(stat->idleThreads);
7510 stat->nWaited = ntohl(stat->nWaited);
7511 stat->nPackets = ntohl(stat->nPackets);
7520 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7521 afs_uint16 remotePort, struct rx_statistics * stat,
7522 afs_uint32 * supportedValues)
7524 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7526 struct rx_debugIn in;
7527 afs_int32 *lp = (afs_int32 *) stat;
7531 * supportedValues is currently unused, but added to allow future
7532 * versioning of this function.
7535 *supportedValues = 0;
7536 in.type = htonl(RX_DEBUGI_RXSTATS);
7538 memset(stat, 0, sizeof(*stat));
7540 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7541 &in, sizeof(in), stat, sizeof(*stat));
7546 * Do net to host conversion here
7549 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7560 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7561 afs_uint16 remotePort, size_t version_length,
7564 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7566 return MakeDebugCall(socket, remoteAddr, remotePort,
7567 RX_PACKET_TYPE_VERSION, a, 1, version,
7575 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7576 afs_uint16 remotePort, afs_int32 * nextConnection,
7577 int allConnections, afs_uint32 debugSupportedValues,
7578 struct rx_debugConn * conn,
7579 afs_uint32 * supportedValues)
7581 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7583 struct rx_debugIn in;
7587 * supportedValues is currently unused, but added to allow future
7588 * versioning of this function.
7591 *supportedValues = 0;
7592 if (allConnections) {
7593 in.type = htonl(RX_DEBUGI_GETALLCONN);
7595 in.type = htonl(RX_DEBUGI_GETCONN);
7597 in.index = htonl(*nextConnection);
7598 memset(conn, 0, sizeof(*conn));
7600 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7601 &in, sizeof(in), conn, sizeof(*conn));
7604 *nextConnection += 1;
7607 * Convert old connection format to new structure.
7610 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7611 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7612 #define MOVEvL(a) (conn->a = vL->a)
7614 /* any old or unrecognized version... */
7615 for (i = 0; i < RX_MAXCALLS; i++) {
7616 MOVEvL(callState[i]);
7617 MOVEvL(callMode[i]);
7618 MOVEvL(callFlags[i]);
7619 MOVEvL(callOther[i]);
7621 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7622 MOVEvL(secStats.type);
7623 MOVEvL(secStats.level);
7624 MOVEvL(secStats.flags);
7625 MOVEvL(secStats.expires);
7626 MOVEvL(secStats.packetsReceived);
7627 MOVEvL(secStats.packetsSent);
7628 MOVEvL(secStats.bytesReceived);
7629 MOVEvL(secStats.bytesSent);
7634 * Do net to host conversion here
7636 * I don't convert host or port since we are most likely
7637 * going to want these in NBO.
7639 conn->cid = ntohl(conn->cid);
7640 conn->serial = ntohl(conn->serial);
7641 for (i = 0; i < RX_MAXCALLS; i++) {
7642 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7644 conn->error = ntohl(conn->error);
7645 conn->secStats.flags = ntohl(conn->secStats.flags);
7646 conn->secStats.expires = ntohl(conn->secStats.expires);
7647 conn->secStats.packetsReceived =
7648 ntohl(conn->secStats.packetsReceived);
7649 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7650 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7651 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7652 conn->epoch = ntohl(conn->epoch);
7653 conn->natMTU = ntohl(conn->natMTU);
7662 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7663 afs_uint16 remotePort, afs_int32 * nextPeer,
7664 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7665 afs_uint32 * supportedValues)
7667 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7669 struct rx_debugIn in;
7672 * supportedValues is currently unused, but added to allow future
7673 * versioning of this function.
7676 *supportedValues = 0;
7677 in.type = htonl(RX_DEBUGI_GETPEER);
7678 in.index = htonl(*nextPeer);
7679 memset(peer, 0, sizeof(*peer));
7681 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7682 &in, sizeof(in), peer, sizeof(*peer));
7688 * Do net to host conversion here
7690 * I don't convert host or port since we are most likely
7691 * going to want these in NBO.
7693 peer->ifMTU = ntohs(peer->ifMTU);
7694 peer->idleWhen = ntohl(peer->idleWhen);
7695 peer->refCount = ntohs(peer->refCount);
7696 peer->burstWait.sec = ntohl(peer->burstWait.sec);
7697 peer->burstWait.usec = ntohl(peer->burstWait.usec);
7698 peer->rtt = ntohl(peer->rtt);
7699 peer->rtt_dev = ntohl(peer->rtt_dev);
7700 peer->timeout.sec = 0;
7701 peer->timeout.usec = 0;
7702 peer->nSent = ntohl(peer->nSent);
7703 peer->reSends = ntohl(peer->reSends);
7704 peer->inPacketSkew = ntohl(peer->inPacketSkew);
7705 peer->outPacketSkew = ntohl(peer->outPacketSkew);
7706 peer->natMTU = ntohs(peer->natMTU);
7707 peer->maxMTU = ntohs(peer->maxMTU);
7708 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7709 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7710 peer->MTU = ntohs(peer->MTU);
7711 peer->cwind = ntohs(peer->cwind);
7712 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7713 peer->congestSeq = ntohs(peer->congestSeq);
7714 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7715 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7716 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7717 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7726 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7727 struct rx_debugPeer * peerStats)
7730 afs_int32 error = 1; /* default to "did not succeed" */
7731 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7733 MUTEX_ENTER(&rx_peerHashTable_lock);
7734 for(tp = rx_peerHashTable[hashValue];
7735 tp != NULL; tp = tp->next) {
7736 if (tp->host == peerHost)
7742 MUTEX_EXIT(&rx_peerHashTable_lock);
7746 MUTEX_ENTER(&tp->peer_lock);
7747 peerStats->host = tp->host;
7748 peerStats->port = tp->port;
7749 peerStats->ifMTU = tp->ifMTU;
7750 peerStats->idleWhen = tp->idleWhen;
7751 peerStats->refCount = tp->refCount;
7752 peerStats->burstSize = tp->burstSize;
7753 peerStats->burst = tp->burst;
7754 peerStats->burstWait.sec = tp->burstWait.sec;
7755 peerStats->burstWait.usec = tp->burstWait.usec;
7756 peerStats->rtt = tp->rtt;
7757 peerStats->rtt_dev = tp->rtt_dev;
7758 peerStats->timeout.sec = 0;
7759 peerStats->timeout.usec = 0;
7760 peerStats->nSent = tp->nSent;
7761 peerStats->reSends = tp->reSends;
7762 peerStats->inPacketSkew = tp->inPacketSkew;
7763 peerStats->outPacketSkew = tp->outPacketSkew;
7764 peerStats->natMTU = tp->natMTU;
7765 peerStats->maxMTU = tp->maxMTU;
7766 peerStats->maxDgramPackets = tp->maxDgramPackets;
7767 peerStats->ifDgramPackets = tp->ifDgramPackets;
7768 peerStats->MTU = tp->MTU;
7769 peerStats->cwind = tp->cwind;
7770 peerStats->nDgramPackets = tp->nDgramPackets;
7771 peerStats->congestSeq = tp->congestSeq;
7772 peerStats->bytesSent.high = tp->bytesSent.high;
7773 peerStats->bytesSent.low = tp->bytesSent.low;
7774 peerStats->bytesReceived.high = tp->bytesReceived.high;
7775 peerStats->bytesReceived.low = tp->bytesReceived.low;
7776 MUTEX_EXIT(&tp->peer_lock);
7778 MUTEX_ENTER(&rx_peerHashTable_lock);
7781 MUTEX_EXIT(&rx_peerHashTable_lock);
7789 struct rx_serverQueueEntry *np;
7792 struct rx_call *call;
7793 struct rx_serverQueueEntry *sq;
7797 if (rxinit_status == 1) {
7799 return; /* Already shutdown. */
7803 #ifndef AFS_PTHREAD_ENV
7804 FD_ZERO(&rx_selectMask);
7805 #endif /* AFS_PTHREAD_ENV */
7806 rxi_dataQuota = RX_MAX_QUOTA;
7807 #ifndef AFS_PTHREAD_ENV
7809 #endif /* AFS_PTHREAD_ENV */
7812 #ifndef AFS_PTHREAD_ENV
7813 #ifndef AFS_USE_GETTIMEOFDAY
7815 #endif /* AFS_USE_GETTIMEOFDAY */
7816 #endif /* AFS_PTHREAD_ENV */
7818 while (!queue_IsEmpty(&rx_freeCallQueue)) {
7819 call = queue_First(&rx_freeCallQueue, rx_call);
7821 rxi_Free(call, sizeof(struct rx_call));
7824 while (!queue_IsEmpty(&rx_idleServerQueue)) {
7825 sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7831 struct rx_peer **peer_ptr, **peer_end;
7832 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7833 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7835 struct rx_peer *peer, *next;
7837 MUTEX_ENTER(&rx_peerHashTable_lock);
7838 for (peer = *peer_ptr; peer; peer = next) {
7839 rx_interface_stat_p rpc_stat, nrpc_stat;
7842 MUTEX_ENTER(&rx_rpc_stats);
7843 MUTEX_ENTER(&peer->peer_lock);
7845 (&peer->rpcStats, rpc_stat, nrpc_stat,
7846 rx_interface_stat)) {
7847 unsigned int num_funcs;
7850 queue_Remove(&rpc_stat->queue_header);
7851 queue_Remove(&rpc_stat->all_peers);
7852 num_funcs = rpc_stat->stats[0].func_total;
7854 sizeof(rx_interface_stat_t) +
7855 rpc_stat->stats[0].func_total *
7856 sizeof(rx_function_entry_v1_t);
7858 rxi_Free(rpc_stat, space);
7860 /* rx_rpc_stats must be held */
7861 rxi_rpc_peer_stat_cnt -= num_funcs;
7863 MUTEX_EXIT(&peer->peer_lock);
7864 MUTEX_EXIT(&rx_rpc_stats);
7868 if (rx_stats_active)
7869 rx_atomic_dec(&rx_stats.nPeerStructs);
7871 MUTEX_EXIT(&rx_peerHashTable_lock);
7874 for (i = 0; i < RX_MAX_SERVICES; i++) {
7876 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7878 for (i = 0; i < rx_hashTableSize; i++) {
7879 struct rx_connection *tc, *ntc;
7880 MUTEX_ENTER(&rx_connHashTable_lock);
7881 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7883 for (j = 0; j < RX_MAXCALLS; j++) {
7885 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7888 rxi_Free(tc, sizeof(*tc));
7890 MUTEX_EXIT(&rx_connHashTable_lock);
7893 MUTEX_ENTER(&freeSQEList_lock);
7895 while ((np = rx_FreeSQEList)) {
7896 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7897 MUTEX_DESTROY(&np->lock);
7898 rxi_Free(np, sizeof(*np));
7901 MUTEX_EXIT(&freeSQEList_lock);
7902 MUTEX_DESTROY(&freeSQEList_lock);
7903 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7904 MUTEX_DESTROY(&rx_connHashTable_lock);
7905 MUTEX_DESTROY(&rx_peerHashTable_lock);
7906 MUTEX_DESTROY(&rx_serverPool_lock);
7908 osi_Free(rx_connHashTable,
7909 rx_hashTableSize * sizeof(struct rx_connection *));
7910 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7912 UNPIN(rx_connHashTable,
7913 rx_hashTableSize * sizeof(struct rx_connection *));
7914 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7916 rxi_FreeAllPackets();
7918 MUTEX_ENTER(&rx_quota_mutex);
7919 rxi_dataQuota = RX_MAX_QUOTA;
7920 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7921 MUTEX_EXIT(&rx_quota_mutex);
7926 #ifdef RX_ENABLE_LOCKS
7928 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7930 if (!MUTEX_ISMINE(lockaddr))
7931 osi_Panic("Lock not held: %s", msg);
7933 #endif /* RX_ENABLE_LOCKS */
7938 * Routines to implement connection specific data.
7942 rx_KeyCreate(rx_destructor_t rtn)
7945 MUTEX_ENTER(&rxi_keyCreate_lock);
7946 key = rxi_keyCreate_counter++;
7947 rxi_keyCreate_destructor = (rx_destructor_t *)
7948 realloc((void *)rxi_keyCreate_destructor,
7949 (key + 1) * sizeof(rx_destructor_t));
7950 rxi_keyCreate_destructor[key] = rtn;
7951 MUTEX_EXIT(&rxi_keyCreate_lock);
7956 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7959 MUTEX_ENTER(&conn->conn_data_lock);
7960 if (!conn->specific) {
7961 conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7962 for (i = 0; i < key; i++)
7963 conn->specific[i] = NULL;
7964 conn->nSpecific = key + 1;
7965 conn->specific[key] = ptr;
7966 } else if (key >= conn->nSpecific) {
7967 conn->specific = (void **)
7968 realloc(conn->specific, (key + 1) * sizeof(void *));
7969 for (i = conn->nSpecific; i < key; i++)
7970 conn->specific[i] = NULL;
7971 conn->nSpecific = key + 1;
7972 conn->specific[key] = ptr;
7974 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7975 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7976 conn->specific[key] = ptr;
7978 MUTEX_EXIT(&conn->conn_data_lock);
7982 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7985 MUTEX_ENTER(&svc->svc_data_lock);
7986 if (!svc->specific) {
7987 svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7988 for (i = 0; i < key; i++)
7989 svc->specific[i] = NULL;
7990 svc->nSpecific = key + 1;
7991 svc->specific[key] = ptr;
7992 } else if (key >= svc->nSpecific) {
7993 svc->specific = (void **)
7994 realloc(svc->specific, (key + 1) * sizeof(void *));
7995 for (i = svc->nSpecific; i < key; i++)
7996 svc->specific[i] = NULL;
7997 svc->nSpecific = key + 1;
7998 svc->specific[key] = ptr;
8000 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8001 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8002 svc->specific[key] = ptr;
8004 MUTEX_EXIT(&svc->svc_data_lock);
8008 rx_GetSpecific(struct rx_connection *conn, int key)
8011 MUTEX_ENTER(&conn->conn_data_lock);
8012 if (key >= conn->nSpecific)
8015 ptr = conn->specific[key];
8016 MUTEX_EXIT(&conn->conn_data_lock);
8021 rx_GetServiceSpecific(struct rx_service *svc, int key)
8024 MUTEX_ENTER(&svc->svc_data_lock);
8025 if (key >= svc->nSpecific)
8028 ptr = svc->specific[key];
8029 MUTEX_EXIT(&svc->svc_data_lock);
8034 #endif /* !KERNEL */
8037 * processStats is a queue used to store the statistics for the local
8038 * process. Its contents are similar to the contents of the rpcStats
8039 * queue on a rx_peer structure, but the actual data stored within
8040 * this queue contains totals across the lifetime of the process (assuming
8041 * the stats have not been reset) - unlike the per peer structures
8042 * which can come and go based upon the peer lifetime.
8045 static struct rx_queue processStats = { &processStats, &processStats };
8048 * peerStats is a queue used to store the statistics for all peer structs.
8049 * Its contents are the union of all the peer rpcStats queues.
8052 static struct rx_queue peerStats = { &peerStats, &peerStats };
8055 * rxi_monitor_processStats is used to turn process wide stat collection
8059 static int rxi_monitor_processStats = 0;
8062 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8065 static int rxi_monitor_peerStats = 0;
8068 * rxi_AddRpcStat - given all of the information for a particular rpc
8069 * call, create (if needed) and update the stat totals for the rpc.
8073 * IN stats - the queue of stats that will be updated with the new value
8075 * IN rxInterface - a unique number that identifies the rpc interface
8077 * IN currentFunc - the index of the function being invoked
8079 * IN totalFunc - the total number of functions in this interface
8081 * IN queueTime - the amount of time this function waited for a thread
8083 * IN execTime - the amount of time this function invocation took to execute
8085 * IN bytesSent - the number bytes sent by this invocation
8087 * IN bytesRcvd - the number bytes received by this invocation
8089 * IN isServer - if true, this invocation was made to a server
8091 * IN remoteHost - the ip address of the remote host
8093 * IN remotePort - the port of the remote host
8095 * IN addToPeerList - if != 0, add newly created stat to the global peer list
8097 * INOUT counter - if a new stats structure is allocated, the counter will
8098 * be updated with the new number of allocated stat structures
8106 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8107 afs_uint32 currentFunc, afs_uint32 totalFunc,
8108 struct clock *queueTime, struct clock *execTime,
8109 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8110 afs_uint32 remoteHost, afs_uint32 remotePort,
8111 int addToPeerList, unsigned int *counter)
8114 rx_interface_stat_p rpc_stat, nrpc_stat;
8117 * See if there's already a structure for this interface
8120 for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8121 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8122 && (rpc_stat->stats[0].remote_is_server == isServer))
8127 * Didn't find a match so allocate a new structure and add it to the
8131 if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8132 || (rpc_stat->stats[0].interfaceId != rxInterface)
8133 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8138 sizeof(rx_interface_stat_t) +
8139 totalFunc * sizeof(rx_function_entry_v1_t);
8141 rpc_stat = rxi_Alloc(space);
8142 if (rpc_stat == NULL) {
8146 *counter += totalFunc;
8147 for (i = 0; i < totalFunc; i++) {
8148 rpc_stat->stats[i].remote_peer = remoteHost;
8149 rpc_stat->stats[i].remote_port = remotePort;
8150 rpc_stat->stats[i].remote_is_server = isServer;
8151 rpc_stat->stats[i].interfaceId = rxInterface;
8152 rpc_stat->stats[i].func_total = totalFunc;
8153 rpc_stat->stats[i].func_index = i;
8154 hzero(rpc_stat->stats[i].invocations);
8155 hzero(rpc_stat->stats[i].bytes_sent);
8156 hzero(rpc_stat->stats[i].bytes_rcvd);
8157 rpc_stat->stats[i].queue_time_sum.sec = 0;
8158 rpc_stat->stats[i].queue_time_sum.usec = 0;
8159 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8160 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8161 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8162 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8163 rpc_stat->stats[i].queue_time_max.sec = 0;
8164 rpc_stat->stats[i].queue_time_max.usec = 0;
8165 rpc_stat->stats[i].execution_time_sum.sec = 0;
8166 rpc_stat->stats[i].execution_time_sum.usec = 0;
8167 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8168 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8169 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8170 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8171 rpc_stat->stats[i].execution_time_max.sec = 0;
8172 rpc_stat->stats[i].execution_time_max.usec = 0;
8174 queue_Prepend(stats, rpc_stat);
8175 if (addToPeerList) {
8176 queue_Prepend(&peerStats, &rpc_stat->all_peers);
8181 * Increment the stats for this function
8184 hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8185 hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8186 hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8187 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8188 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8189 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8190 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8192 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8193 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8195 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8196 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8198 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8199 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8201 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8202 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8210 * rx_IncrementTimeAndCount - increment the times and count for a particular
8215 * IN peer - the peer who invoked the rpc
8217 * IN rxInterface - a unique number that identifies the rpc interface
8219 * IN currentFunc - the index of the function being invoked
8221 * IN totalFunc - the total number of functions in this interface
8223 * IN queueTime - the amount of time this function waited for a thread
8225 * IN execTime - the amount of time this function invocation took to execute
8227 * IN bytesSent - the number bytes sent by this invocation
8229 * IN bytesRcvd - the number bytes received by this invocation
8231 * IN isServer - if true, this invocation was made to a server
8239 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8240 afs_uint32 currentFunc, afs_uint32 totalFunc,
8241 struct clock *queueTime, struct clock *execTime,
8242 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8246 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8249 MUTEX_ENTER(&rx_rpc_stats);
8251 if (rxi_monitor_peerStats) {
8252 MUTEX_ENTER(&peer->peer_lock);
8253 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8254 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8255 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8256 MUTEX_EXIT(&peer->peer_lock);
8259 if (rxi_monitor_processStats) {
8260 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8261 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8262 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8265 MUTEX_EXIT(&rx_rpc_stats);
8270 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8274 * IN callerVersion - the rpc stat version of the caller.
8276 * IN count - the number of entries to marshall.
8278 * IN stats - pointer to stats to be marshalled.
8280 * OUT ptr - Where to store the marshalled data.
8287 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8288 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8294 * We only support the first version
8296 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8297 *(ptr++) = stats->remote_peer;
8298 *(ptr++) = stats->remote_port;
8299 *(ptr++) = stats->remote_is_server;
8300 *(ptr++) = stats->interfaceId;
8301 *(ptr++) = stats->func_total;
8302 *(ptr++) = stats->func_index;
8303 *(ptr++) = hgethi(stats->invocations);
8304 *(ptr++) = hgetlo(stats->invocations);
8305 *(ptr++) = hgethi(stats->bytes_sent);
8306 *(ptr++) = hgetlo(stats->bytes_sent);
8307 *(ptr++) = hgethi(stats->bytes_rcvd);
8308 *(ptr++) = hgetlo(stats->bytes_rcvd);
8309 *(ptr++) = stats->queue_time_sum.sec;
8310 *(ptr++) = stats->queue_time_sum.usec;
8311 *(ptr++) = stats->queue_time_sum_sqr.sec;
8312 *(ptr++) = stats->queue_time_sum_sqr.usec;
8313 *(ptr++) = stats->queue_time_min.sec;
8314 *(ptr++) = stats->queue_time_min.usec;
8315 *(ptr++) = stats->queue_time_max.sec;
8316 *(ptr++) = stats->queue_time_max.usec;
8317 *(ptr++) = stats->execution_time_sum.sec;
8318 *(ptr++) = stats->execution_time_sum.usec;
8319 *(ptr++) = stats->execution_time_sum_sqr.sec;
8320 *(ptr++) = stats->execution_time_sum_sqr.usec;
8321 *(ptr++) = stats->execution_time_min.sec;
8322 *(ptr++) = stats->execution_time_min.usec;
8323 *(ptr++) = stats->execution_time_max.sec;
8324 *(ptr++) = stats->execution_time_max.usec;
8330 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8335 * IN callerVersion - the rpc stat version of the caller
8337 * OUT myVersion - the rpc stat version of this function
8339 * OUT clock_sec - local time seconds
8341 * OUT clock_usec - local time microseconds
8343 * OUT allocSize - the number of bytes allocated to contain stats
8345 * OUT statCount - the number stats retrieved from this process.
8347 * OUT stats - the actual stats retrieved from this process.
8351 * Returns void. If successful, stats will != NULL.
8355 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8356 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8357 size_t * allocSize, afs_uint32 * statCount,
8358 afs_uint32 ** stats)
8368 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8371 * Check to see if stats are enabled
8374 MUTEX_ENTER(&rx_rpc_stats);
8375 if (!rxi_monitor_processStats) {
8376 MUTEX_EXIT(&rx_rpc_stats);
8380 clock_GetTime(&now);
8381 *clock_sec = now.sec;
8382 *clock_usec = now.usec;
8385 * Allocate the space based upon the caller version
8387 * If the client is at an older version than we are,
8388 * we return the statistic data in the older data format, but
8389 * we still return our version number so the client knows we
8390 * are maintaining more data than it can retrieve.
8393 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8394 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8395 *statCount = rxi_rpc_process_stat_cnt;
8398 * This can't happen yet, but in the future version changes
8399 * can be handled by adding additional code here
8403 if (space > (size_t) 0) {
8405 ptr = *stats = rxi_Alloc(space);
8408 rx_interface_stat_p rpc_stat, nrpc_stat;
8412 (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8414 * Copy the data based upon the caller version
8416 rx_MarshallProcessRPCStats(callerVersion,
8417 rpc_stat->stats[0].func_total,
8418 rpc_stat->stats, &ptr);
8424 MUTEX_EXIT(&rx_rpc_stats);
8429 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8433 * IN callerVersion - the rpc stat version of the caller
8435 * OUT myVersion - the rpc stat version of this function
8437 * OUT clock_sec - local time seconds
8439 * OUT clock_usec - local time microseconds
8441 * OUT allocSize - the number of bytes allocated to contain stats
8443 * OUT statCount - the number of stats retrieved from the individual
8446 * OUT stats - the actual stats retrieved from the individual peer structures.
8450 * Returns void. If successful, stats will != NULL.
8454 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8455 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8456 size_t * allocSize, afs_uint32 * statCount,
8457 afs_uint32 ** stats)
8467 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8470 * Check to see if stats are enabled
8473 MUTEX_ENTER(&rx_rpc_stats);
8474 if (!rxi_monitor_peerStats) {
8475 MUTEX_EXIT(&rx_rpc_stats);
8479 clock_GetTime(&now);
8480 *clock_sec = now.sec;
8481 *clock_usec = now.usec;
8484 * Allocate the space based upon the caller version
8486 * If the client is at an older version than we are,
8487 * we return the statistic data in the older data format, but
8488 * we still return our version number so the client knows we
8489 * are maintaining more data than it can retrieve.
8492 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8493 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8494 *statCount = rxi_rpc_peer_stat_cnt;
8497 * This can't happen yet, but in the future version changes
8498 * can be handled by adding additional code here
8502 if (space > (size_t) 0) {
8504 ptr = *stats = rxi_Alloc(space);
8507 rx_interface_stat_p rpc_stat, nrpc_stat;
8511 (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8513 * We have to fix the offset of rpc_stat since we are
8514 * keeping this structure on two rx_queues. The rx_queue
8515 * package assumes that the rx_queue member is the first
8516 * member of the structure. That is, rx_queue assumes that
8517 * any one item is only on one queue at a time. We are
8518 * breaking that assumption and so we have to do a little
8519 * math to fix our pointers.
8522 fix_offset = (char *)rpc_stat;
8523 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8524 rpc_stat = (rx_interface_stat_p) fix_offset;
8527 * Copy the data based upon the caller version
8529 rx_MarshallProcessRPCStats(callerVersion,
8530 rpc_stat->stats[0].func_total,
8531 rpc_stat->stats, &ptr);
8537 MUTEX_EXIT(&rx_rpc_stats);
8542 * rx_FreeRPCStats - free memory allocated by
8543 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8547 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8548 * rx_RetrievePeerRPCStats
8550 * IN allocSize - the number of bytes in stats.
8558 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8560 rxi_Free(stats, allocSize);
8564 * rx_queryProcessRPCStats - see if process rpc stat collection is
8565 * currently enabled.
8571 * Returns 0 if stats are not enabled != 0 otherwise
8575 rx_queryProcessRPCStats(void)
8578 MUTEX_ENTER(&rx_rpc_stats);
8579 rc = rxi_monitor_processStats;
8580 MUTEX_EXIT(&rx_rpc_stats);
8585 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8591 * Returns 0 if stats are not enabled != 0 otherwise
8595 rx_queryPeerRPCStats(void)
8598 MUTEX_ENTER(&rx_rpc_stats);
8599 rc = rxi_monitor_peerStats;
8600 MUTEX_EXIT(&rx_rpc_stats);
8605 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8615 rx_enableProcessRPCStats(void)
8617 MUTEX_ENTER(&rx_rpc_stats);
8618 rx_enable_stats = 1;
8619 rxi_monitor_processStats = 1;
8620 MUTEX_EXIT(&rx_rpc_stats);
8624 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8634 rx_enablePeerRPCStats(void)
8636 MUTEX_ENTER(&rx_rpc_stats);
8637 rx_enable_stats = 1;
8638 rxi_monitor_peerStats = 1;
8639 MUTEX_EXIT(&rx_rpc_stats);
8643 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8653 rx_disableProcessRPCStats(void)
8655 rx_interface_stat_p rpc_stat, nrpc_stat;
8658 MUTEX_ENTER(&rx_rpc_stats);
8661 * Turn off process statistics and if peer stats is also off, turn
8665 rxi_monitor_processStats = 0;
8666 if (rxi_monitor_peerStats == 0) {
8667 rx_enable_stats = 0;
8670 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8671 unsigned int num_funcs = 0;
8674 queue_Remove(rpc_stat);
8675 num_funcs = rpc_stat->stats[0].func_total;
8677 sizeof(rx_interface_stat_t) +
8678 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8680 rxi_Free(rpc_stat, space);
8681 rxi_rpc_process_stat_cnt -= num_funcs;
8683 MUTEX_EXIT(&rx_rpc_stats);
8687 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8697 rx_disablePeerRPCStats(void)
8699 struct rx_peer **peer_ptr, **peer_end;
8703 * Turn off peer statistics and if process stats is also off, turn
8707 rxi_monitor_peerStats = 0;
8708 if (rxi_monitor_processStats == 0) {
8709 rx_enable_stats = 0;
8712 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8713 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8715 struct rx_peer *peer, *next, *prev;
8717 MUTEX_ENTER(&rx_peerHashTable_lock);
8718 MUTEX_ENTER(&rx_rpc_stats);
8719 for (prev = peer = *peer_ptr; peer; peer = next) {
8721 code = MUTEX_TRYENTER(&peer->peer_lock);
8723 rx_interface_stat_p rpc_stat, nrpc_stat;
8726 if (prev == *peer_ptr) {
8737 MUTEX_EXIT(&rx_peerHashTable_lock);
8740 (&peer->rpcStats, rpc_stat, nrpc_stat,
8741 rx_interface_stat)) {
8742 unsigned int num_funcs = 0;
8745 queue_Remove(&rpc_stat->queue_header);
8746 queue_Remove(&rpc_stat->all_peers);
8747 num_funcs = rpc_stat->stats[0].func_total;
8749 sizeof(rx_interface_stat_t) +
8750 rpc_stat->stats[0].func_total *
8751 sizeof(rx_function_entry_v1_t);
8753 rxi_Free(rpc_stat, space);
8754 rxi_rpc_peer_stat_cnt -= num_funcs;
8756 MUTEX_EXIT(&peer->peer_lock);
8758 MUTEX_ENTER(&rx_peerHashTable_lock);
8768 MUTEX_EXIT(&rx_rpc_stats);
8769 MUTEX_EXIT(&rx_peerHashTable_lock);
8774 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8779 * IN clearFlag - flag indicating which stats to clear
8787 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8789 rx_interface_stat_p rpc_stat, nrpc_stat;
8791 MUTEX_ENTER(&rx_rpc_stats);
8793 for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8794 unsigned int num_funcs = 0, i;
8795 num_funcs = rpc_stat->stats[0].func_total;
8796 for (i = 0; i < num_funcs; i++) {
8797 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8798 hzero(rpc_stat->stats[i].invocations);
8800 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8801 hzero(rpc_stat->stats[i].bytes_sent);
8803 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8804 hzero(rpc_stat->stats[i].bytes_rcvd);
8806 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8807 rpc_stat->stats[i].queue_time_sum.sec = 0;
8808 rpc_stat->stats[i].queue_time_sum.usec = 0;
8810 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8811 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8812 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8814 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8815 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8816 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8818 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8819 rpc_stat->stats[i].queue_time_max.sec = 0;
8820 rpc_stat->stats[i].queue_time_max.usec = 0;
8822 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8823 rpc_stat->stats[i].execution_time_sum.sec = 0;
8824 rpc_stat->stats[i].execution_time_sum.usec = 0;
8826 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8827 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8828 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8830 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8831 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8832 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8834 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8835 rpc_stat->stats[i].execution_time_max.sec = 0;
8836 rpc_stat->stats[i].execution_time_max.usec = 0;
8841 MUTEX_EXIT(&rx_rpc_stats);
8845 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8850 * IN clearFlag - flag indicating which stats to clear
8858 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8860 rx_interface_stat_p rpc_stat, nrpc_stat;
8862 MUTEX_ENTER(&rx_rpc_stats);
8864 for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8865 unsigned int num_funcs = 0, i;
8868 * We have to fix the offset of rpc_stat since we are
8869 * keeping this structure on two rx_queues. The rx_queue
8870 * package assumes that the rx_queue member is the first
8871 * member of the structure. That is, rx_queue assumes that
8872 * any one item is only on one queue at a time. We are
8873 * breaking that assumption and so we have to do a little
8874 * math to fix our pointers.
8877 fix_offset = (char *)rpc_stat;
8878 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8879 rpc_stat = (rx_interface_stat_p) fix_offset;
8881 num_funcs = rpc_stat->stats[0].func_total;
8882 for (i = 0; i < num_funcs; i++) {
8883 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8884 hzero(rpc_stat->stats[i].invocations);
8886 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8887 hzero(rpc_stat->stats[i].bytes_sent);
8889 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8890 hzero(rpc_stat->stats[i].bytes_rcvd);
8892 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8893 rpc_stat->stats[i].queue_time_sum.sec = 0;
8894 rpc_stat->stats[i].queue_time_sum.usec = 0;
8896 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8897 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8898 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8900 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8901 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8902 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8904 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8905 rpc_stat->stats[i].queue_time_max.sec = 0;
8906 rpc_stat->stats[i].queue_time_max.usec = 0;
8908 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8909 rpc_stat->stats[i].execution_time_sum.sec = 0;
8910 rpc_stat->stats[i].execution_time_sum.usec = 0;
8912 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8913 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8914 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8916 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8917 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8918 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8920 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8921 rpc_stat->stats[i].execution_time_max.sec = 0;
8922 rpc_stat->stats[i].execution_time_max.usec = 0;
8927 MUTEX_EXIT(&rx_rpc_stats);
8931 * rxi_rxstat_userok points to a routine that returns 1 if the caller
8932 * is authorized to enable/disable/clear RX statistics.
8934 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8937 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8939 rxi_rxstat_userok = proc;
8943 rx_RxStatUserOk(struct rx_call *call)
8945 if (!rxi_rxstat_userok)
8947 return rxi_rxstat_userok(call);
8952 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8953 * function in the MSVC runtime DLL (msvcrt.dll).
8955 * Note: the system serializes calls to this function.
8958 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
8959 DWORD reason, /* reason function is being called */
8960 LPVOID reserved) /* reserved for future use */
8963 case DLL_PROCESS_ATTACH:
8964 /* library is being attached to a process */
8968 case DLL_PROCESS_DETACH:
8975 #endif /* AFS_NT40_ENV */
8978 int rx_DumpCalls(FILE *outputFile, char *cookie)
8980 #ifdef RXDEBUG_PACKET
8981 #ifdef KDUMP_RX_LOCK
8982 struct rx_call_rx_lock *c;
8989 #define RXDPRINTF sprintf
8990 #define RXDPRINTOUT output
8992 #define RXDPRINTF fprintf
8993 #define RXDPRINTOUT outputFile
8996 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8998 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9001 for (c = rx_allCallsp; c; c = c->allNextp) {
9002 u_short rqc, tqc, iovqc;
9003 struct rx_packet *p, *np;
9005 MUTEX_ENTER(&c->lock);
9006 queue_Count(&c->rq, p, np, rx_packet, rqc);
9007 queue_Count(&c->tq, p, np, rx_packet, tqc);
9008 queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9010 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, "
9011 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9012 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9013 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9014 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9015 #ifdef RX_ENABLE_LOCKS
9018 #ifdef RX_REFCOUNT_CHECK
9019 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9020 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9023 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,
9024 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9025 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9026 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9027 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9028 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9029 #ifdef RX_ENABLE_LOCKS
9030 , (afs_uint32)c->refCount
9032 #ifdef RX_REFCOUNT_CHECK
9033 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9036 MUTEX_EXIT(&c->lock);
9039 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9042 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9044 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9046 #endif /* RXDEBUG_PACKET */