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>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110 struct rx_call *, struct rx_peer *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115 void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117 void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119 void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123 struct rx_packet *packet,
124 int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128 u_short serviceId, afs_uint32 cid,
129 afs_uint32 epoch, int type, u_int securityIndex,
130 int *unknownService);
131 static struct rx_packet
132 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133 int istack, osi_socket socket,
134 afs_uint32 host, u_short port, int *tnop,
135 struct rx_call **newcallp);
136 static struct rx_packet
137 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
138 int istack, int *a_invalid);
139 static struct rx_packet
140 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141 struct rx_packet *np, int istack);
142 static struct rx_packet
143 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144 struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146 int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static int rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 /* List of free rx_serverQueueEntry structs */
225 struct opr_queue rx_freeServerQueue;
227 #if !defined(offsetof)
228 #include <stddef.h> /* for definition of offsetof() */
231 #ifdef RX_ENABLE_LOCKS
232 afs_kmutex_t rx_atomic_mutex;
233 static afs_kmutex_t freeSQEList_lock;
236 /* Forward prototypes */
237 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
240 putConnection (struct rx_connection *conn) {
241 MUTEX_ENTER(&rx_refcnt_mutex);
243 MUTEX_EXIT(&rx_refcnt_mutex);
246 #ifdef AFS_PTHREAD_ENV
249 * Use procedural initialization of mutexes/condition variables
253 extern afs_kmutex_t rx_quota_mutex;
254 extern afs_kmutex_t rx_pthread_mutex;
255 extern afs_kmutex_t rx_packets_mutex;
256 extern afs_kmutex_t rx_refcnt_mutex;
257 extern afs_kmutex_t des_init_mutex;
258 extern afs_kmutex_t des_random_mutex;
260 extern afs_kmutex_t rx_clock_mutex;
261 extern afs_kmutex_t rxi_connCacheMutex;
262 extern afs_kmutex_t event_handler_mutex;
263 extern afs_kmutex_t listener_mutex;
264 extern afs_kmutex_t rx_if_init_mutex;
265 extern afs_kmutex_t rx_if_mutex;
267 extern afs_kcondvar_t rx_event_handler_cond;
268 extern afs_kcondvar_t rx_listener_cond;
271 static afs_kmutex_t epoch_mutex;
272 static afs_kmutex_t rx_init_mutex;
273 static afs_kmutex_t rx_debug_mutex;
274 static afs_kmutex_t rx_rpc_stats;
277 rxi_InitPthread(void)
279 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
294 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
295 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
298 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
299 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
302 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
303 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
305 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
306 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
307 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
310 #ifdef RX_ENABLE_LOCKS
313 #endif /* RX_LOCKS_DB */
314 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
315 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
317 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
319 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
321 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
323 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
325 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
327 #endif /* RX_ENABLE_LOCKS */
330 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
331 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
333 * The rx_stats_mutex mutex protects the following global variables:
334 * rxi_lowConnRefCount
335 * rxi_lowPeerRefCount
344 * The rx_quota_mutex mutex protects the following global variables:
352 * The rx_freePktQ_lock protects the following global variables:
357 * The rx_packets_mutex mutex protects the following global variables:
365 * The rx_pthread_mutex mutex protects the following global variables:
366 * rxi_fcfs_thread_num
369 #define INIT_PTHREAD_LOCKS
373 /* Variables for handling the minProcs implementation. availProcs gives the
374 * number of threads available in the pool at this moment (not counting dudes
375 * executing right now). totalMin gives the total number of procs required
376 * for handling all minProcs requests. minDeficit is a dynamic variable
377 * tracking the # of procs required to satisfy all of the remaining minProcs
379 * For fine grain locking to work, the quota check and the reservation of
380 * a server thread has to come while rxi_availProcs and rxi_minDeficit
381 * are locked. To this end, the code has been modified under #ifdef
382 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
383 * same time. A new function, ReturnToServerPool() returns the allocation.
385 * A call can be on several queue's (but only one at a time). When
386 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
387 * that no one else is touching the queue. To this end, we store the address
388 * of the queue lock in the call structure (under the call lock) when we
389 * put the call on a queue, and we clear the call_queue_lock when the
390 * call is removed from a queue (once the call lock has been obtained).
391 * This allows rxi_ResetCall to safely synchronize with others wishing
392 * to manipulate the queue.
395 #if defined(RX_ENABLE_LOCKS)
396 static afs_kmutex_t rx_rpc_stats;
399 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
400 ** pretty good that the next packet coming in is from the same connection
401 ** as the last packet, since we're send multiple packets in a transmit window.
403 struct rx_connection *rxLastConn = 0;
405 #ifdef RX_ENABLE_LOCKS
406 /* The locking hierarchy for rx fine grain locking is composed of these
409 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
410 * also protects updates to rx_nextCid
411 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
412 * call->lock - locks call data fields.
413 * These are independent of each other:
414 * rx_freeCallQueue_lock
419 * serverQueueEntry->lock
420 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
422 * peer->lock - locks peer data fields.
423 * conn_data_lock - that more than one thread is not updating a conn data
424 * field at the same time.
435 * Do we need a lock to protect the peer field in the conn structure?
436 * conn->peer was previously a constant for all intents and so has no
437 * lock protecting this field. The multihomed client delta introduced
438 * a RX code change : change the peer field in the connection structure
439 * to that remote interface from which the last packet for this
440 * connection was sent out. This may become an issue if further changes
443 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
444 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
446 /* rxdb_fileID is used to identify the lock location, along with line#. */
447 static int rxdb_fileID = RXDB_FILE_RX;
448 #endif /* RX_LOCKS_DB */
449 #else /* RX_ENABLE_LOCKS */
450 #define SET_CALL_QUEUE_LOCK(C, L)
451 #define CLEAR_CALL_QUEUE_LOCK(C)
452 #endif /* RX_ENABLE_LOCKS */
453 struct rx_serverQueueEntry *rx_waitForPacket = 0;
456 * This mutex serializes calls to our initialization and shutdown routines
457 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
458 * these at any time; all other threads must wait for it to finish running, and
459 * then examine the value of rxi_running afterwards.
461 #ifdef AFS_PTHREAD_ENV
462 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
463 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
465 # define LOCK_RX_INIT
466 # define UNLOCK_RX_INIT
469 /* ------------Exported Interfaces------------- */
471 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
475 return rx_atomic_read(&rxi_running);
478 /* Initialize rx. A port number may be mentioned, in which case this
479 * becomes the default port number for any service installed later.
480 * If 0 is provided for the port number, a random port will be chosen
481 * by the kernel. Whether this will ever overlap anything in
482 * /etc/services is anybody's guess... Returns 0 on success, -1 on
485 rx_InitHost(u_int host, u_int port)
492 char *htable, *ptable;
498 if (rxi_IsRunning()) {
500 return 0; /* already started */
506 if (afs_winsockInit() < 0)
512 * Initialize anything necessary to provide a non-premptive threading
515 rxi_InitializeThreadSupport();
518 /* Allocate and initialize a socket for client and perhaps server
521 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
522 if (rx_socket == OSI_NULLSOCKET) {
525 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
528 #endif /* RX_LOCKS_DB */
529 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
540 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
542 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
544 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
546 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
547 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
550 #if defined(AFS_HPUX110_ENV)
552 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
553 #endif /* AFS_HPUX110_ENV */
554 #endif /* RX_ENABLE_LOCKS && KERNEL */
557 rx_connDeadTime = 12;
558 rx_tranquil = 0; /* reset flag */
559 rxi_ResetStatistics();
560 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
561 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
562 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
563 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
564 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
565 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
567 /* Malloc up a bunch of packets & buffers */
569 opr_queue_Init(&rx_freePacketQueue);
570 rxi_NeedMorePackets = FALSE;
571 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
572 opr_queue_Init(&rx_mallocedPacketQueue);
574 /* enforce a minimum number of allocated packets */
575 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
576 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
578 /* allocate the initial free packet pool */
579 #ifdef RX_ENABLE_TSFPQ
580 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
581 #else /* RX_ENABLE_TSFPQ */
582 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
583 #endif /* RX_ENABLE_TSFPQ */
590 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
591 tv.tv_sec = clock_now.sec;
592 tv.tv_usec = clock_now.usec;
593 srand((unsigned int)tv.tv_usec);
600 #if defined(KERNEL) && !defined(UKERNEL)
601 /* Really, this should never happen in a real kernel */
604 struct sockaddr_in addr;
606 int addrlen = sizeof(addr);
608 socklen_t addrlen = sizeof(addr);
610 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
611 rxi_Finalize_locked();
612 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
615 rx_port = addr.sin_port;
618 rx_stats.minRtt.sec = 9999999;
619 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
621 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
622 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
624 rx_nextCid &= RX_CIDMASK;
625 MUTEX_ENTER(&rx_quota_mutex);
626 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
627 MUTEX_EXIT(&rx_quota_mutex);
628 /* *Slightly* random start time for the cid. This is just to help
629 * out with the hashing function at the peer */
630 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
631 rx_connHashTable = (struct rx_connection **)htable;
632 rx_peerHashTable = (struct rx_peer **)ptable;
634 rx_hardAckDelay.sec = 0;
635 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
637 rxevent_Init(20, rxi_ReScheduleEvents);
639 /* Initialize various global queues */
640 opr_queue_Init(&rx_idleServerQueue);
641 opr_queue_Init(&rx_freeServerQueue);
642 opr_queue_Init(&rx_incomingCallQueue);
643 opr_queue_Init(&rx_freeCallQueue);
645 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
646 /* Initialize our list of usable IP addresses. */
650 /* Start listener process (exact function is dependent on the
651 * implementation environment--kernel or user space) */
656 rx_atomic_set(&rxi_running, 1);
673 return rx_InitHost(htonl(INADDR_ANY), port);
679 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
680 * maintaing the round trip timer.
685 * Start a new RTT timer for a given call and packet.
687 * There must be no resendEvent already listed for this call, otherwise this
688 * will leak events - intended for internal use within the RTO code only
691 * the RX call to start the timer for
692 * @param[in] lastPacket
693 * a flag indicating whether the last packet has been sent or not
695 * @pre call must be locked before calling this function
699 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
701 struct clock now, retryTime;
703 MUTEX_ASSERT(&call->lock);
707 clock_Add(&retryTime, &call->rto);
709 /* If we're sending the last packet, and we're the client, then the server
710 * may wait for an additional 400ms before returning the ACK, wait for it
711 * rather than hitting a timeout */
712 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
713 clock_Addmsec(&retryTime, 400);
715 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
716 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
721 * Cancel an RTT timer for a given call.
725 * the RX call to cancel the timer for
727 * @pre call must be locked before calling this function
732 rxi_rto_cancel(struct rx_call *call)
734 MUTEX_ASSERT(&call->lock);
735 if (rxevent_Cancel(&call->resendEvent))
736 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
740 * Tell the RTO timer that we have sent a packet.
742 * If the timer isn't already running, then start it. If the timer is running,
746 * the RX call that the packet has been sent on
747 * @param[in] lastPacket
748 * A flag which is true if this is the last packet for the call
750 * @pre The call must be locked before calling this function
755 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
757 if (call->resendEvent)
760 rxi_rto_startTimer(call, lastPacket, istack);
764 * Tell the RTO timer that we have received an new ACK message
766 * This function should be called whenever a call receives an ACK that
767 * acknowledges new packets. Whatever happens, we stop the current timer.
768 * If there are unacked packets in the queue which have been sent, then
769 * we restart the timer from now. Otherwise, we leave it stopped.
772 * the RX call that the ACK has been received on
776 rxi_rto_packet_acked(struct rx_call *call, int istack)
778 struct opr_queue *cursor;
780 rxi_rto_cancel(call);
782 if (opr_queue_IsEmpty(&call->tq))
785 for (opr_queue_Scan(&call->tq, cursor)) {
786 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
787 if (p->header.seq > call->tfirst + call->twind)
790 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
791 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
799 * Set an initial round trip timeout for a peer connection
801 * @param[in] secs The timeout to set in seconds
805 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
806 peer->rtt = secs * 8000;
810 * Set a delayed ack event on the specified call for the given time
812 * @param[in] call - the call on which to set the event
813 * @param[in] offset - the delay from now after which the event fires
816 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
818 struct clock now, when;
820 MUTEX_ASSERT(&call->lock);
823 clock_Add(&when, offset);
825 if (clock_Gt(&call->delayedAckTime, &when) &&
826 rxevent_Cancel(&call->delayedAckEvent)) {
827 /* We successfully cancelled an event too far in the future to install
828 * our new one; we can reuse the reference on the call. */
829 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
832 call->delayedAckTime = when;
833 } else if (call->delayedAckEvent == NULL) {
834 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
835 call->delayedAckEvent = rxevent_Post(&when, &now,
838 call->delayedAckTime = when;
843 rxi_CancelDelayedAckEvent(struct rx_call *call)
845 MUTEX_ASSERT(&call->lock);
846 /* Only drop the ref if we cancelled it before it could run. */
847 if (rxevent_Cancel(&call->delayedAckEvent))
848 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
851 /* called with unincremented nRequestsRunning to see if it is OK to start
852 * a new thread in this service. Could be "no" for two reasons: over the
853 * max quota, or would prevent others from reaching their min quota.
855 #ifdef RX_ENABLE_LOCKS
856 /* This verion of QuotaOK reserves quota if it's ok while the
857 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
860 QuotaOK(struct rx_service *aservice)
862 /* check if over max quota */
863 if (aservice->nRequestsRunning >= aservice->maxProcs) {
867 /* under min quota, we're OK */
868 /* otherwise, can use only if there are enough to allow everyone
869 * to go to their min quota after this guy starts.
872 MUTEX_ENTER(&rx_quota_mutex);
873 if ((aservice->nRequestsRunning < aservice->minProcs)
874 || (rxi_availProcs > rxi_minDeficit)) {
875 aservice->nRequestsRunning++;
876 /* just started call in minProcs pool, need fewer to maintain
878 if (aservice->nRequestsRunning <= aservice->minProcs)
881 MUTEX_EXIT(&rx_quota_mutex);
884 MUTEX_EXIT(&rx_quota_mutex);
890 ReturnToServerPool(struct rx_service *aservice)
892 aservice->nRequestsRunning--;
893 MUTEX_ENTER(&rx_quota_mutex);
894 if (aservice->nRequestsRunning < aservice->minProcs)
897 MUTEX_EXIT(&rx_quota_mutex);
900 #else /* RX_ENABLE_LOCKS */
902 QuotaOK(struct rx_service *aservice)
905 /* under min quota, we're OK */
906 if (aservice->nRequestsRunning < aservice->minProcs)
909 /* check if over max quota */
910 if (aservice->nRequestsRunning >= aservice->maxProcs)
913 /* otherwise, can use only if there are enough to allow everyone
914 * to go to their min quota after this guy starts.
916 MUTEX_ENTER(&rx_quota_mutex);
917 if (rxi_availProcs > rxi_minDeficit)
919 MUTEX_EXIT(&rx_quota_mutex);
922 #endif /* RX_ENABLE_LOCKS */
925 /* Called by rx_StartServer to start up lwp's to service calls.
926 NExistingProcs gives the number of procs already existing, and which
927 therefore needn't be created. */
929 rxi_StartServerProcs(int nExistingProcs)
931 struct rx_service *service;
936 /* For each service, reserve N processes, where N is the "minimum"
937 * number of processes that MUST be able to execute a request in parallel,
938 * at any time, for that process. Also compute the maximum difference
939 * between any service's maximum number of processes that can run
940 * (i.e. the maximum number that ever will be run, and a guarantee
941 * that this number will run if other services aren't running), and its
942 * minimum number. The result is the extra number of processes that
943 * we need in order to provide the latter guarantee */
944 for (i = 0; i < RX_MAX_SERVICES; i++) {
946 service = rx_services[i];
947 if (service == (struct rx_service *)0)
949 nProcs += service->minProcs;
950 diff = service->maxProcs - service->minProcs;
954 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
955 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
956 for (i = 0; i < nProcs; i++) {
957 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
963 /* This routine is only required on Windows */
965 rx_StartClientThread(void)
967 #ifdef AFS_PTHREAD_ENV
969 pid = pthread_self();
970 #endif /* AFS_PTHREAD_ENV */
972 #endif /* AFS_NT40_ENV */
974 /* This routine must be called if any services are exported. If the
975 * donateMe flag is set, the calling process is donated to the server
978 rx_StartServer(int donateMe)
980 struct rx_service *service;
986 /* Start server processes, if necessary (exact function is dependent
987 * on the implementation environment--kernel or user space). DonateMe
988 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
989 * case, one less new proc will be created rx_StartServerProcs.
991 rxi_StartServerProcs(donateMe);
993 /* count up the # of threads in minProcs, and add set the min deficit to
994 * be that value, too.
996 for (i = 0; i < RX_MAX_SERVICES; i++) {
997 service = rx_services[i];
998 if (service == (struct rx_service *)0)
1000 MUTEX_ENTER(&rx_quota_mutex);
1001 rxi_totalMin += service->minProcs;
1002 /* below works even if a thread is running, since minDeficit would
1003 * still have been decremented and later re-incremented.
1005 rxi_minDeficit += service->minProcs;
1006 MUTEX_EXIT(&rx_quota_mutex);
1009 /* Turn on reaping of idle server connections */
1010 rxi_ReapConnections(NULL, NULL, NULL, 0);
1015 #ifndef AFS_NT40_ENV
1019 #ifdef AFS_PTHREAD_ENV
1021 pid = afs_pointer_to_int(pthread_self());
1022 #else /* AFS_PTHREAD_ENV */
1024 LWP_CurrentProcess(&pid);
1025 #endif /* AFS_PTHREAD_ENV */
1027 sprintf(name, "srv_%d", ++nProcs);
1028 if (registerProgram)
1029 (*registerProgram) (pid, name);
1031 #endif /* AFS_NT40_ENV */
1032 rx_ServerProc(NULL); /* Never returns */
1034 #ifdef RX_ENABLE_TSFPQ
1035 /* no use leaving packets around in this thread's local queue if
1036 * it isn't getting donated to the server thread pool.
1038 rxi_FlushLocalPacketsTSFPQ();
1039 #endif /* RX_ENABLE_TSFPQ */
1043 /* Create a new client connection to the specified service, using the
1044 * specified security object to implement the security model for this
1046 struct rx_connection *
1047 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1048 struct rx_securityClass *securityObject,
1049 int serviceSecurityIndex)
1052 struct rx_connection *conn;
1058 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1059 "serviceSecurityIndex %d)\n",
1060 ntohl(shost), ntohs(sport), sservice, securityObject,
1061 serviceSecurityIndex));
1063 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1064 * the case of kmem_alloc? */
1065 conn = rxi_AllocConnection();
1066 #ifdef RX_ENABLE_LOCKS
1067 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1068 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1069 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1072 MUTEX_ENTER(&rx_connHashTable_lock);
1073 conn->type = RX_CLIENT_CONNECTION;
1074 conn->epoch = rx_epoch;
1075 conn->cid = rx_nextCid;
1077 conn->peer = rxi_FindPeer(shost, sport, 1);
1078 conn->serviceId = sservice;
1079 conn->securityObject = securityObject;
1080 conn->securityData = (void *) 0;
1081 conn->securityIndex = serviceSecurityIndex;
1082 rx_SetConnDeadTime(conn, rx_connDeadTime);
1083 rx_SetConnSecondsUntilNatPing(conn, 0);
1084 conn->ackRate = RX_FAST_ACK_RATE;
1085 conn->nSpecific = 0;
1086 conn->specific = NULL;
1087 conn->challengeEvent = NULL;
1088 conn->delayedAbortEvent = NULL;
1089 conn->abortCount = 0;
1091 for (i = 0; i < RX_MAXCALLS; i++) {
1092 conn->twind[i] = rx_initSendWindow;
1093 conn->rwind[i] = rx_initReceiveWindow;
1094 conn->lastBusy[i] = 0;
1097 code = RXS_NewConnection(securityObject, conn);
1099 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1101 conn->refCount++; /* no lock required since only this thread knows... */
1102 conn->next = rx_connHashTable[hashindex];
1103 rx_connHashTable[hashindex] = conn;
1104 if (rx_stats_active)
1105 rx_atomic_inc(&rx_stats.nClientConns);
1106 MUTEX_EXIT(&rx_connHashTable_lock);
1109 rxi_ConnectionError(conn, code);
1115 * Ensure a connection's timeout values are valid.
1117 * @param[in] conn The connection to check
1119 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1120 * unless idleDeadTime and/or hardDeadTime are not set
1124 rxi_CheckConnTimeouts(struct rx_connection *conn)
1126 /* a connection's timeouts must have the relationship
1127 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1128 * total loss of network to a peer may cause an idle timeout instead of a
1129 * dead timeout, simply because the idle timeout gets hit first. Also set
1130 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1131 /* this logic is slightly complicated by the fact that
1132 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1134 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1135 if (conn->idleDeadTime) {
1136 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1138 if (conn->hardDeadTime) {
1139 if (conn->idleDeadTime) {
1140 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1142 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1148 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1150 /* The idea is to set the dead time to a value that allows several
1151 * keepalives to be dropped without timing out the connection. */
1152 conn->secondsUntilDead = seconds;
1153 rxi_CheckConnTimeouts(conn);
1154 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1158 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1160 conn->hardDeadTime = seconds;
1161 rxi_CheckConnTimeouts(conn);
1165 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1167 conn->idleDeadTime = seconds;
1168 rxi_CheckConnTimeouts(conn);
1171 int rxi_lowPeerRefCount = 0;
1172 int rxi_lowConnRefCount = 0;
1175 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1176 * NOTE: must not be called with rx_connHashTable_lock held.
1179 rxi_CleanupConnection(struct rx_connection *conn)
1181 /* Notify the service exporter, if requested, that this connection
1182 * is being destroyed */
1183 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1184 (*conn->service->destroyConnProc) (conn);
1186 /* Notify the security module that this connection is being destroyed */
1187 RXS_DestroyConnection(conn->securityObject, conn);
1189 /* If this is the last connection using the rx_peer struct, set its
1190 * idle time to now. rxi_ReapConnections will reap it if it's still
1191 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1193 MUTEX_ENTER(&rx_peerHashTable_lock);
1194 if (conn->peer->refCount < 2) {
1195 conn->peer->idleWhen = clock_Sec();
1196 if (conn->peer->refCount < 1) {
1197 conn->peer->refCount = 1;
1198 if (rx_stats_active) {
1199 MUTEX_ENTER(&rx_stats_mutex);
1200 rxi_lowPeerRefCount++;
1201 MUTEX_EXIT(&rx_stats_mutex);
1205 conn->peer->refCount--;
1206 MUTEX_EXIT(&rx_peerHashTable_lock);
1208 if (rx_stats_active)
1210 if (conn->type == RX_SERVER_CONNECTION)
1211 rx_atomic_dec(&rx_stats.nServerConns);
1213 rx_atomic_dec(&rx_stats.nClientConns);
1216 if (conn->specific) {
1218 for (i = 0; i < conn->nSpecific; i++) {
1219 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1220 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1221 conn->specific[i] = NULL;
1223 free(conn->specific);
1225 conn->specific = NULL;
1226 conn->nSpecific = 0;
1227 #endif /* !KERNEL */
1229 MUTEX_DESTROY(&conn->conn_call_lock);
1230 MUTEX_DESTROY(&conn->conn_data_lock);
1231 CV_DESTROY(&conn->conn_call_cv);
1233 rxi_FreeConnection(conn);
1236 /* Destroy the specified connection */
1238 rxi_DestroyConnection(struct rx_connection *conn)
1240 MUTEX_ENTER(&rx_connHashTable_lock);
1241 rxi_DestroyConnectionNoLock(conn);
1242 /* conn should be at the head of the cleanup list */
1243 if (conn == rx_connCleanup_list) {
1244 rx_connCleanup_list = rx_connCleanup_list->next;
1245 MUTEX_EXIT(&rx_connHashTable_lock);
1246 rxi_CleanupConnection(conn);
1248 #ifdef RX_ENABLE_LOCKS
1250 MUTEX_EXIT(&rx_connHashTable_lock);
1252 #endif /* RX_ENABLE_LOCKS */
1256 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1258 struct rx_connection **conn_ptr;
1266 MUTEX_ENTER(&conn->conn_data_lock);
1267 MUTEX_ENTER(&rx_refcnt_mutex);
1268 if (conn->refCount > 0)
1271 #ifdef RX_REFCOUNT_CHECK
1272 osi_Assert(conn->refCount == 0);
1274 if (rx_stats_active) {
1275 MUTEX_ENTER(&rx_stats_mutex);
1276 rxi_lowConnRefCount++;
1277 MUTEX_EXIT(&rx_stats_mutex);
1281 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1282 /* Busy; wait till the last guy before proceeding */
1283 MUTEX_EXIT(&rx_refcnt_mutex);
1284 MUTEX_EXIT(&conn->conn_data_lock);
1289 /* If the client previously called rx_NewCall, but it is still
1290 * waiting, treat this as a running call, and wait to destroy the
1291 * connection later when the call completes. */
1292 if ((conn->type == RX_CLIENT_CONNECTION)
1293 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1294 conn->flags |= RX_CONN_DESTROY_ME;
1295 MUTEX_EXIT(&rx_refcnt_mutex);
1296 MUTEX_EXIT(&conn->conn_data_lock);
1300 MUTEX_EXIT(&rx_refcnt_mutex);
1301 MUTEX_EXIT(&conn->conn_data_lock);
1303 /* Check for extant references to this connection */
1304 MUTEX_ENTER(&conn->conn_call_lock);
1305 for (i = 0; i < RX_MAXCALLS; i++) {
1306 struct rx_call *call = conn->call[i];
1309 if (conn->type == RX_CLIENT_CONNECTION) {
1310 MUTEX_ENTER(&call->lock);
1311 if (call->delayedAckEvent) {
1312 /* Push the final acknowledgment out now--there
1313 * won't be a subsequent call to acknowledge the
1314 * last reply packets */
1315 rxi_CancelDelayedAckEvent(call);
1316 if (call->state == RX_STATE_PRECALL
1317 || call->state == RX_STATE_ACTIVE) {
1318 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1323 MUTEX_EXIT(&call->lock);
1327 MUTEX_EXIT(&conn->conn_call_lock);
1329 #ifdef RX_ENABLE_LOCKS
1331 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1332 MUTEX_EXIT(&conn->conn_data_lock);
1334 /* Someone is accessing a packet right now. */
1338 #endif /* RX_ENABLE_LOCKS */
1341 /* Don't destroy the connection if there are any call
1342 * structures still in use */
1343 MUTEX_ENTER(&conn->conn_data_lock);
1344 conn->flags |= RX_CONN_DESTROY_ME;
1345 MUTEX_EXIT(&conn->conn_data_lock);
1350 /* Remove from connection hash table before proceeding */
1352 &rx_connHashTable[CONN_HASH
1353 (peer->host, peer->port, conn->cid, conn->epoch,
1355 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1356 if (*conn_ptr == conn) {
1357 *conn_ptr = conn->next;
1361 /* if the conn that we are destroying was the last connection, then we
1362 * clear rxLastConn as well */
1363 if (rxLastConn == conn)
1366 /* Make sure the connection is completely reset before deleting it. */
1368 * Pending events hold a refcount, so we can't get here if they are
1370 osi_Assert(conn->challengeEvent == NULL);
1371 osi_Assert(conn->delayedAbortEvent == NULL);
1372 osi_Assert(conn->natKeepAliveEvent == NULL);
1373 osi_Assert(conn->checkReachEvent == NULL);
1375 /* Add the connection to the list of destroyed connections that
1376 * need to be cleaned up. This is necessary to avoid deadlocks
1377 * in the routines we call to inform others that this connection is
1378 * being destroyed. */
1379 conn->next = rx_connCleanup_list;
1380 rx_connCleanup_list = conn;
1383 /* Externally available version */
1385 rx_DestroyConnection(struct rx_connection *conn)
1390 rxi_DestroyConnection(conn);
1395 rx_GetConnection(struct rx_connection *conn)
1400 MUTEX_ENTER(&rx_refcnt_mutex);
1402 MUTEX_EXIT(&rx_refcnt_mutex);
1406 #ifdef RX_ENABLE_LOCKS
1407 /* Wait for the transmit queue to no longer be busy.
1408 * requires the call->lock to be held */
1410 rxi_WaitforTQBusy(struct rx_call *call) {
1411 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1412 call->flags |= RX_CALL_TQ_WAIT;
1414 MUTEX_ASSERT(&call->lock);
1415 CV_WAIT(&call->cv_tq, &call->lock);
1417 if (call->tqWaiters == 0) {
1418 call->flags &= ~RX_CALL_TQ_WAIT;
1425 rxi_WakeUpTransmitQueue(struct rx_call *call)
1427 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1428 dpf(("call %p has %d waiters and flags %d\n",
1429 call, call->tqWaiters, call->flags));
1430 #ifdef RX_ENABLE_LOCKS
1431 MUTEX_ASSERT(&call->lock);
1432 CV_BROADCAST(&call->cv_tq);
1433 #else /* RX_ENABLE_LOCKS */
1434 osi_rxWakeup(&call->tq);
1435 #endif /* RX_ENABLE_LOCKS */
1439 /* Start a new rx remote procedure call, on the specified connection.
1440 * If wait is set to 1, wait for a free call channel; otherwise return
1441 * 0. Maxtime gives the maximum number of seconds this call may take,
1442 * after rx_NewCall returns. After this time interval, a call to any
1443 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1444 * For fine grain locking, we hold the conn_call_lock in order to
1445 * to ensure that we don't get signalle after we found a call in an active
1446 * state and before we go to sleep.
1449 rx_NewCall(struct rx_connection *conn)
1451 int i, wait, ignoreBusy = 1;
1452 struct rx_call *call;
1453 struct clock queueTime;
1454 afs_uint32 leastBusy = 0;
1458 dpf(("rx_NewCall(conn %p)\n", conn));
1461 clock_GetTime(&queueTime);
1463 * Check if there are others waiting for a new call.
1464 * If so, let them go first to avoid starving them.
1465 * This is a fairly simple scheme, and might not be
1466 * a complete solution for large numbers of waiters.
1468 * makeCallWaiters keeps track of the number of
1469 * threads waiting to make calls and the
1470 * RX_CONN_MAKECALL_WAITING flag bit is used to
1471 * indicate that there are indeed calls waiting.
1472 * The flag is set when the waiter is incremented.
1473 * It is only cleared when makeCallWaiters is 0.
1474 * This prevents us from accidently destroying the
1475 * connection while it is potentially about to be used.
1477 MUTEX_ENTER(&conn->conn_call_lock);
1478 MUTEX_ENTER(&conn->conn_data_lock);
1479 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1480 conn->flags |= RX_CONN_MAKECALL_WAITING;
1481 conn->makeCallWaiters++;
1482 MUTEX_EXIT(&conn->conn_data_lock);
1484 #ifdef RX_ENABLE_LOCKS
1485 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1489 MUTEX_ENTER(&conn->conn_data_lock);
1490 conn->makeCallWaiters--;
1491 if (conn->makeCallWaiters == 0)
1492 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1495 /* We are now the active thread in rx_NewCall */
1496 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1497 MUTEX_EXIT(&conn->conn_data_lock);
1502 for (i = 0; i < RX_MAXCALLS; i++) {
1503 call = conn->call[i];
1505 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1506 /* we're not ignoring busy call slots; only look at the
1507 * call slot that is the "least" busy */
1511 if (call->state == RX_STATE_DALLY) {
1512 MUTEX_ENTER(&call->lock);
1513 if (call->state == RX_STATE_DALLY) {
1514 if (ignoreBusy && conn->lastBusy[i]) {
1515 /* if we're ignoring busy call slots, skip any ones that
1516 * have lastBusy set */
1517 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1518 leastBusy = conn->lastBusy[i];
1520 MUTEX_EXIT(&call->lock);
1525 * We are setting the state to RX_STATE_RESET to
1526 * ensure that no one else will attempt to use this
1527 * call once we drop the conn->conn_call_lock and
1528 * call->lock. We must drop the conn->conn_call_lock
1529 * before calling rxi_ResetCall because the process
1530 * of clearing the transmit queue can block for an
1531 * extended period of time. If we block while holding
1532 * the conn->conn_call_lock, then all rx_EndCall
1533 * processing will block as well. This has a detrimental
1534 * effect on overall system performance.
1536 call->state = RX_STATE_RESET;
1537 (*call->callNumber)++;
1538 MUTEX_EXIT(&conn->conn_call_lock);
1539 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1540 rxi_ResetCall(call, 0);
1541 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1545 * If we failed to be able to safely obtain the
1546 * conn->conn_call_lock we will have to drop the
1547 * call->lock to avoid a deadlock. When the call->lock
1548 * is released the state of the call can change. If it
1549 * is no longer RX_STATE_RESET then some other thread is
1552 MUTEX_EXIT(&call->lock);
1553 MUTEX_ENTER(&conn->conn_call_lock);
1554 MUTEX_ENTER(&call->lock);
1556 if (call->state == RX_STATE_RESET)
1560 * If we get here it means that after dropping
1561 * the conn->conn_call_lock and call->lock that
1562 * the call is no longer ours. If we can't find
1563 * a free call in the remaining slots we should
1564 * not go immediately to RX_CONN_MAKECALL_WAITING
1565 * because by dropping the conn->conn_call_lock
1566 * we have given up synchronization with rx_EndCall.
1567 * Instead, cycle through one more time to see if
1568 * we can find a call that can call our own.
1570 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1573 MUTEX_EXIT(&call->lock);
1576 if (ignoreBusy && conn->lastBusy[i]) {
1577 /* if we're ignoring busy call slots, skip any ones that
1578 * have lastBusy set */
1579 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1580 leastBusy = conn->lastBusy[i];
1585 /* rxi_NewCall returns with mutex locked */
1586 call = rxi_NewCall(conn, i);
1587 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1591 if (i < RX_MAXCALLS) {
1592 conn->lastBusy[i] = 0;
1597 if (leastBusy && ignoreBusy) {
1598 /* we didn't find a useable call slot, but we did see at least one
1599 * 'busy' slot; look again and only use a slot with the 'least
1605 MUTEX_ENTER(&conn->conn_data_lock);
1606 conn->flags |= RX_CONN_MAKECALL_WAITING;
1607 conn->makeCallWaiters++;
1608 MUTEX_EXIT(&conn->conn_data_lock);
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1615 MUTEX_ENTER(&conn->conn_data_lock);
1616 conn->makeCallWaiters--;
1617 if (conn->makeCallWaiters == 0)
1618 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1619 MUTEX_EXIT(&conn->conn_data_lock);
1621 /* Client is initially in send mode */
1622 call->state = RX_STATE_ACTIVE;
1623 call->error = conn->error;
1625 call->app.mode = RX_MODE_ERROR;
1627 call->app.mode = RX_MODE_SENDING;
1629 #ifdef AFS_RXERRQ_ENV
1630 /* remember how many network errors the peer has when we started, so if
1631 * more errors are encountered after the call starts, we know the other endpoint won't be
1632 * responding to us */
1633 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1636 /* remember start time for call in case we have hard dead time limit */
1637 call->queueTime = queueTime;
1638 clock_GetTime(&call->startTime);
1639 call->app.bytesSent = 0;
1640 call->app.bytesRcvd = 0;
1642 /* Turn on busy protocol. */
1643 rxi_KeepAliveOn(call);
1645 /* Attempt MTU discovery */
1646 rxi_GrowMTUOn(call);
1649 * We are no longer the active thread in rx_NewCall
1651 MUTEX_ENTER(&conn->conn_data_lock);
1652 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1653 MUTEX_EXIT(&conn->conn_data_lock);
1656 * Wake up anyone else who might be giving us a chance to
1657 * run (see code above that avoids resource starvation).
1659 #ifdef RX_ENABLE_LOCKS
1660 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1661 osi_Panic("rx_NewCall call about to be used without an empty tq");
1664 CV_BROADCAST(&conn->conn_call_cv);
1668 MUTEX_EXIT(&conn->conn_call_lock);
1669 MUTEX_EXIT(&call->lock);
1672 dpf(("rx_NewCall(call %p)\n", call));
1677 rxi_HasActiveCalls(struct rx_connection *aconn)
1680 struct rx_call *tcall;
1684 for (i = 0; i < RX_MAXCALLS; i++) {
1685 if ((tcall = aconn->call[i])) {
1686 if ((tcall->state == RX_STATE_ACTIVE)
1687 || (tcall->state == RX_STATE_PRECALL)) {
1698 rxi_GetCallNumberVector(struct rx_connection *aconn,
1699 afs_int32 * aint32s)
1702 struct rx_call *tcall;
1706 MUTEX_ENTER(&aconn->conn_call_lock);
1707 for (i = 0; i < RX_MAXCALLS; i++) {
1708 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1709 aint32s[i] = aconn->callNumber[i] + 1;
1711 aint32s[i] = aconn->callNumber[i];
1713 MUTEX_EXIT(&aconn->conn_call_lock);
1719 rxi_SetCallNumberVector(struct rx_connection *aconn,
1720 afs_int32 * aint32s)
1723 struct rx_call *tcall;
1727 MUTEX_ENTER(&aconn->conn_call_lock);
1728 for (i = 0; i < RX_MAXCALLS; i++) {
1729 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1730 aconn->callNumber[i] = aint32s[i] - 1;
1732 aconn->callNumber[i] = aint32s[i];
1734 MUTEX_EXIT(&aconn->conn_call_lock);
1739 /* Advertise a new service. A service is named locally by a UDP port
1740 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1743 char *serviceName; Name for identification purposes (e.g. the
1744 service name might be used for probing for
1747 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1748 char *serviceName, struct rx_securityClass **securityObjects,
1749 int nSecurityObjects,
1750 afs_int32(*serviceProc) (struct rx_call * acall))
1752 osi_socket socket = OSI_NULLSOCKET;
1753 struct rx_service *tservice;
1759 if (serviceId == 0) {
1761 "rx_NewService: service id for service %s is not non-zero.\n",
1768 "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",
1776 tservice = rxi_AllocService();
1779 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1781 for (i = 0; i < RX_MAX_SERVICES; i++) {
1782 struct rx_service *service = rx_services[i];
1784 if (port == service->servicePort && host == service->serviceHost) {
1785 if (service->serviceId == serviceId) {
1786 /* The identical service has already been
1787 * installed; if the caller was intending to
1788 * change the security classes used by this
1789 * service, he/she loses. */
1791 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1792 serviceName, serviceId, service->serviceName);
1794 rxi_FreeService(tservice);
1797 /* Different service, same port: re-use the socket
1798 * which is bound to the same port */
1799 socket = service->socket;
1802 if (socket == OSI_NULLSOCKET) {
1803 /* If we don't already have a socket (from another
1804 * service on same port) get a new one */
1805 socket = rxi_GetHostUDPSocket(host, port);
1806 if (socket == OSI_NULLSOCKET) {
1808 rxi_FreeService(tservice);
1813 service->socket = socket;
1814 service->serviceHost = host;
1815 service->servicePort = port;
1816 service->serviceId = serviceId;
1817 service->serviceName = serviceName;
1818 service->nSecurityObjects = nSecurityObjects;
1819 service->securityObjects = securityObjects;
1820 service->minProcs = 0;
1821 service->maxProcs = 1;
1822 service->idleDeadTime = 60;
1823 service->connDeadTime = rx_connDeadTime;
1824 service->executeRequestProc = serviceProc;
1825 service->checkReach = 0;
1826 service->nSpecific = 0;
1827 service->specific = NULL;
1828 rx_services[i] = service; /* not visible until now */
1834 rxi_FreeService(tservice);
1835 (osi_Msg "rx_NewService: cannot support > %d services\n",
1840 /* Set configuration options for all of a service's security objects */
1843 rx_SetSecurityConfiguration(struct rx_service *service,
1844 rx_securityConfigVariables type,
1849 for (i = 0; i<service->nSecurityObjects; i++) {
1850 if (service->securityObjects[i]) {
1851 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1862 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1863 struct rx_securityClass **securityObjects, int nSecurityObjects,
1864 afs_int32(*serviceProc) (struct rx_call * acall))
1866 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1869 /* Generic request processing loop. This routine should be called
1870 * by the implementation dependent rx_ServerProc. If socketp is
1871 * non-null, it will be set to the file descriptor that this thread
1872 * is now listening on. If socketp is null, this routine will never
1875 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1877 struct rx_call *call;
1879 struct rx_service *tservice = NULL;
1886 call = rx_GetCall(threadID, tservice, socketp);
1887 if (socketp && *socketp != OSI_NULLSOCKET) {
1888 /* We are now a listener thread */
1894 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1898 afs_termState = AFSOP_STOP_AFS;
1899 afs_osi_Wakeup(&afs_termState);
1900 #ifdef RX_ENABLE_LOCKS
1902 #endif /* RX_ENABLE_LOCKS */
1907 /* if server is restarting( typically smooth shutdown) then do not
1908 * allow any new calls.
1911 if (rx_tranquil && (call != NULL)) {
1915 MUTEX_ENTER(&call->lock);
1917 rxi_CallError(call, RX_RESTARTING);
1918 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1920 MUTEX_EXIT(&call->lock);
1925 tservice = call->conn->service;
1927 if (tservice->beforeProc)
1928 (*tservice->beforeProc) (call);
1930 code = tservice->executeRequestProc(call);
1932 if (tservice->afterProc)
1933 (*tservice->afterProc) (call, code);
1935 rx_EndCall(call, code);
1937 if (tservice->postProc)
1938 (*tservice->postProc) (code);
1940 if (rx_stats_active) {
1941 MUTEX_ENTER(&rx_stats_mutex);
1943 MUTEX_EXIT(&rx_stats_mutex);
1950 rx_WakeupServerProcs(void)
1952 struct rx_serverQueueEntry *np;
1953 struct opr_queue *cursor;
1957 MUTEX_ENTER(&rx_serverPool_lock);
1959 #ifdef RX_ENABLE_LOCKS
1960 if (rx_waitForPacket)
1961 CV_BROADCAST(&rx_waitForPacket->cv);
1962 #else /* RX_ENABLE_LOCKS */
1963 if (rx_waitForPacket)
1964 osi_rxWakeup(rx_waitForPacket);
1965 #endif /* RX_ENABLE_LOCKS */
1966 MUTEX_ENTER(&freeSQEList_lock);
1967 for (opr_queue_Scan(&rx_freeServerQueue, cursor)) {
1968 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1969 #ifdef RX_ENABLE_LOCKS
1970 CV_BROADCAST(&np->cv);
1971 #else /* RX_ENABLE_LOCKS */
1973 #endif /* RX_ENABLE_LOCKS */
1975 MUTEX_EXIT(&freeSQEList_lock);
1976 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1977 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1978 #ifdef RX_ENABLE_LOCKS
1979 CV_BROADCAST(&np->cv);
1980 #else /* RX_ENABLE_LOCKS */
1982 #endif /* RX_ENABLE_LOCKS */
1984 MUTEX_EXIT(&rx_serverPool_lock);
1989 * One thing that seems to happen is that all the server threads get
1990 * tied up on some empty or slow call, and then a whole bunch of calls
1991 * arrive at once, using up the packet pool, so now there are more
1992 * empty calls. The most critical resources here are server threads
1993 * and the free packet pool. The "doreclaim" code seems to help in
1994 * general. I think that eventually we arrive in this state: there
1995 * are lots of pending calls which do have all their packets present,
1996 * so they won't be reclaimed, are multi-packet calls, so they won't
1997 * be scheduled until later, and thus are tying up most of the free
1998 * packet pool for a very long time.
2000 * 1. schedule multi-packet calls if all the packets are present.
2001 * Probably CPU-bound operation, useful to return packets to pool.
2002 * Do what if there is a full window, but the last packet isn't here?
2003 * 3. preserve one thread which *only* runs "best" calls, otherwise
2004 * it sleeps and waits for that type of call.
2005 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2006 * the current dataquota business is badly broken. The quota isn't adjusted
2007 * to reflect how many packets are presently queued for a running call.
2008 * So, when we schedule a queued call with a full window of packets queued
2009 * up for it, that *should* free up a window full of packets for other 2d-class
2010 * calls to be able to use from the packet pool. But it doesn't.
2012 * NB. Most of the time, this code doesn't run -- since idle server threads
2013 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2014 * as a new call arrives.
2016 /* Sleep until a call arrives. Returns a pointer to the call, ready
2017 * for an rx_Read. */
2018 #ifdef RX_ENABLE_LOCKS
2020 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2022 struct rx_serverQueueEntry *sq;
2023 struct rx_call *call = (struct rx_call *)0;
2024 struct rx_service *service = NULL;
2026 MUTEX_ENTER(&freeSQEList_lock);
2028 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2029 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2031 opr_queue_Remove(&sq->entry);
2032 MUTEX_EXIT(&freeSQEList_lock);
2033 } else { /* otherwise allocate a new one and return that */
2034 MUTEX_EXIT(&freeSQEList_lock);
2035 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2036 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2037 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2040 MUTEX_ENTER(&rx_serverPool_lock);
2041 if (cur_service != NULL) {
2042 ReturnToServerPool(cur_service);
2045 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2046 struct rx_call *tcall, *choice2 = NULL;
2047 struct opr_queue *cursor;
2049 /* Scan for eligible incoming calls. A call is not eligible
2050 * if the maximum number of calls for its service type are
2051 * already executing */
2052 /* One thread will process calls FCFS (to prevent starvation),
2053 * while the other threads may run ahead looking for calls which
2054 * have all their input data available immediately. This helps
2055 * keep threads from blocking, waiting for data from the client. */
2056 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2057 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2059 service = tcall->conn->service;
2060 if (!QuotaOK(service)) {
2063 MUTEX_ENTER(&rx_pthread_mutex);
2064 if (tno == rxi_fcfs_thread_num
2065 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2066 MUTEX_EXIT(&rx_pthread_mutex);
2067 /* If we're the fcfs thread , then we'll just use
2068 * this call. If we haven't been able to find an optimal
2069 * choice, and we're at the end of the list, then use a
2070 * 2d choice if one has been identified. Otherwise... */
2071 call = (choice2 ? choice2 : tcall);
2072 service = call->conn->service;
2074 MUTEX_EXIT(&rx_pthread_mutex);
2075 if (!opr_queue_IsEmpty(&tcall->rq)) {
2076 struct rx_packet *rp;
2077 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2079 if (rp->header.seq == 1) {
2081 || (rp->header.flags & RX_LAST_PACKET)) {
2083 } else if (rxi_2dchoice && !choice2
2084 && !(tcall->flags & RX_CALL_CLEARED)
2085 && (tcall->rprev > rxi_HardAckRate)) {
2095 ReturnToServerPool(service);
2101 opr_queue_Remove(&call->entry);
2102 MUTEX_EXIT(&rx_serverPool_lock);
2103 MUTEX_ENTER(&call->lock);
2104 CLEAR_CALL_QUEUE_LOCK(call);
2106 if (call->flags & RX_CALL_WAIT_PROC) {
2107 call->flags &= ~RX_CALL_WAIT_PROC;
2108 rx_atomic_dec(&rx_nWaiting);
2111 if (call->state != RX_STATE_PRECALL || call->error) {
2112 MUTEX_EXIT(&call->lock);
2113 MUTEX_ENTER(&rx_serverPool_lock);
2114 ReturnToServerPool(service);
2119 if (opr_queue_IsEmpty(&call->rq)
2120 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2121 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2125 /* If there are no eligible incoming calls, add this process
2126 * to the idle server queue, to wait for one */
2130 *socketp = OSI_NULLSOCKET;
2132 sq->socketp = socketp;
2133 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2134 #ifndef AFS_AIX41_ENV
2135 rx_waitForPacket = sq;
2136 #endif /* AFS_AIX41_ENV */
2138 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2140 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2144 } while (!(call = sq->newcall)
2145 && !(socketp && *socketp != OSI_NULLSOCKET));
2146 if (opr_queue_IsOnQueue(&sq->entry)) {
2147 opr_queue_Remove(&sq->entry);
2149 MUTEX_EXIT(&rx_serverPool_lock);
2151 MUTEX_ENTER(&call->lock);
2157 MUTEX_ENTER(&freeSQEList_lock);
2158 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2159 MUTEX_EXIT(&freeSQEList_lock);
2162 clock_GetTime(&call->startTime);
2163 call->state = RX_STATE_ACTIVE;
2164 call->app.mode = RX_MODE_RECEIVING;
2165 #ifdef RX_KERNEL_TRACE
2166 if (ICL_SETACTIVE(afs_iclSetp)) {
2167 int glockOwner = ISAFS_GLOCK();
2170 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2171 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2178 rxi_calltrace(RX_CALL_START, call);
2179 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2180 call->conn->service->servicePort, call->conn->service->serviceId,
2183 MUTEX_EXIT(&call->lock);
2184 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2186 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2191 #else /* RX_ENABLE_LOCKS */
2193 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2195 struct rx_serverQueueEntry *sq;
2196 struct rx_call *call = (struct rx_call *)0, *choice2;
2197 struct rx_service *service = NULL;
2201 MUTEX_ENTER(&freeSQEList_lock);
2203 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2204 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2206 opr_queue_Remove(&sq->entry);
2207 MUTEX_EXIT(&freeSQEList_lock);
2208 } else { /* otherwise allocate a new one and return that */
2209 MUTEX_EXIT(&freeSQEList_lock);
2210 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2211 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2212 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2214 MUTEX_ENTER(&sq->lock);
2216 if (cur_service != NULL) {
2217 cur_service->nRequestsRunning--;
2218 MUTEX_ENTER(&rx_quota_mutex);
2219 if (cur_service->nRequestsRunning < cur_service->minProcs)
2222 MUTEX_EXIT(&rx_quota_mutex);
2224 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2225 struct rx_call *tcall;
2226 struct opr_queue *cursor;
2227 /* Scan for eligible incoming calls. A call is not eligible
2228 * if the maximum number of calls for its service type are
2229 * already executing */
2230 /* One thread will process calls FCFS (to prevent starvation),
2231 * while the other threads may run ahead looking for calls which
2232 * have all their input data available immediately. This helps
2233 * keep threads from blocking, waiting for data from the client. */
2234 choice2 = (struct rx_call *)0;
2235 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2236 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2237 service = tcall->conn->service;
2238 if (QuotaOK(service)) {
2239 MUTEX_ENTER(&rx_pthread_mutex);
2240 if (tno == rxi_fcfs_thread_num
2241 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2242 MUTEX_EXIT(&rx_pthread_mutex);
2243 /* If we're the fcfs thread, then we'll just use
2244 * this call. If we haven't been able to find an optimal
2245 * choice, and we're at the end of the list, then use a
2246 * 2d choice if one has been identified. Otherwise... */
2247 call = (choice2 ? choice2 : tcall);
2248 service = call->conn->service;
2250 MUTEX_EXIT(&rx_pthread_mutex);
2251 if (!opr_queue_IsEmpty(&tcall->rq)) {
2252 struct rx_packet *rp;
2253 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2255 if (rp->header.seq == 1
2257 || (rp->header.flags & RX_LAST_PACKET))) {
2259 } else if (rxi_2dchoice && !choice2
2260 && !(tcall->flags & RX_CALL_CLEARED)
2261 && (tcall->rprev > rxi_HardAckRate)) {
2274 opr_queue_Remove(&call->entry);
2275 CLEAR_CALL_QUEUE_LOCK(call);
2276 /* we can't schedule a call if there's no data!!! */
2277 /* send an ack if there's no data, if we're missing the
2278 * first packet, or we're missing something between first
2279 * and last -- there's a "hole" in the incoming data. */
2280 if (opr_queue_IsEmpty(&call->rq)
2281 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2282 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2283 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2285 call->flags &= (~RX_CALL_WAIT_PROC);
2286 service->nRequestsRunning++;
2287 /* just started call in minProcs pool, need fewer to maintain
2289 MUTEX_ENTER(&rx_quota_mutex);
2290 if (service->nRequestsRunning <= service->minProcs)
2293 MUTEX_EXIT(&rx_quota_mutex);
2294 rx_atomic_dec(&rx_nWaiting);
2295 /* MUTEX_EXIT(&call->lock); */
2297 /* If there are no eligible incoming calls, add this process
2298 * to the idle server queue, to wait for one */
2301 *socketp = OSI_NULLSOCKET;
2303 sq->socketp = socketp;
2304 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2308 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2310 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2311 return (struct rx_call *)0;
2314 } while (!(call = sq->newcall)
2315 && !(socketp && *socketp != OSI_NULLSOCKET));
2317 MUTEX_EXIT(&sq->lock);
2319 MUTEX_ENTER(&freeSQEList_lock);
2320 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2321 MUTEX_EXIT(&freeSQEList_lock);
2324 clock_GetTime(&call->startTime);
2325 call->state = RX_STATE_ACTIVE;
2326 call->app.mode = RX_MODE_RECEIVING;
2327 #ifdef RX_KERNEL_TRACE
2328 if (ICL_SETACTIVE(afs_iclSetp)) {
2329 int glockOwner = ISAFS_GLOCK();
2332 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2333 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2340 rxi_calltrace(RX_CALL_START, call);
2341 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2342 call->conn->service->servicePort, call->conn->service->serviceId,
2345 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2352 #endif /* RX_ENABLE_LOCKS */
2356 /* Establish a procedure to be called when a packet arrives for a
2357 * call. This routine will be called at most once after each call,
2358 * and will also be called if there is an error condition on the or
2359 * the call is complete. Used by multi rx to build a selection
2360 * function which determines which of several calls is likely to be a
2361 * good one to read from.
2362 * NOTE: the way this is currently implemented it is probably only a
2363 * good idea to (1) use it immediately after a newcall (clients only)
2364 * and (2) only use it once. Other uses currently void your warranty
2367 rx_SetArrivalProc(struct rx_call *call,
2368 void (*proc) (struct rx_call * call,
2371 void * handle, int arg)
2373 call->arrivalProc = proc;
2374 call->arrivalProcHandle = handle;
2375 call->arrivalProcArg = arg;
2378 /* Call is finished (possibly prematurely). Return rc to the peer, if
2379 * appropriate, and return the final error code from the conversation
2383 rx_EndCall(struct rx_call *call, afs_int32 rc)
2385 struct rx_connection *conn = call->conn;
2389 dpf(("rx_EndCall(call %p rc %d error %d abortCode %d)\n",
2390 call, rc, call->error, call->abortCode));
2393 MUTEX_ENTER(&call->lock);
2395 if (rc == 0 && call->error == 0) {
2396 call->abortCode = 0;
2397 call->abortCount = 0;
2400 call->arrivalProc = NULL;
2401 if (rc && call->error == 0) {
2402 rxi_CallError(call, rc);
2403 call->app.mode = RX_MODE_ERROR;
2404 /* Send an abort message to the peer if this error code has
2405 * only just been set. If it was set previously, assume the
2406 * peer has already been sent the error code or will request it
2408 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2410 if (conn->type == RX_SERVER_CONNECTION) {
2411 /* Make sure reply or at least dummy reply is sent */
2412 if (call->app.mode == RX_MODE_RECEIVING) {
2413 MUTEX_EXIT(&call->lock);
2414 rxi_WriteProc(call, 0, 0);
2415 MUTEX_ENTER(&call->lock);
2417 if (call->app.mode == RX_MODE_SENDING) {
2418 rxi_FlushWriteLocked(call);
2420 rxi_calltrace(RX_CALL_END, call);
2421 /* Call goes to hold state until reply packets are acknowledged */
2422 if (call->tfirst + call->nSoftAcked < call->tnext) {
2423 call->state = RX_STATE_HOLD;
2425 call->state = RX_STATE_DALLY;
2426 rxi_ClearTransmitQueue(call, 0);
2427 rxi_rto_cancel(call);
2428 rxi_CancelKeepAliveEvent(call);
2430 } else { /* Client connection */
2432 /* Make sure server receives input packets, in the case where
2433 * no reply arguments are expected */
2435 if ((call->app.mode == RX_MODE_SENDING)
2436 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2437 MUTEX_EXIT(&call->lock);
2438 (void)rxi_ReadProc(call, &dummy, 1);
2439 MUTEX_ENTER(&call->lock);
2442 /* If we had an outstanding delayed ack, be nice to the server
2443 * and force-send it now.
2445 if (call->delayedAckEvent) {
2446 rxi_CancelDelayedAckEvent(call);
2447 rxi_SendDelayedAck(NULL, call, NULL, 0);
2450 /* We need to release the call lock since it's lower than the
2451 * conn_call_lock and we don't want to hold the conn_call_lock
2452 * over the rx_ReadProc call. The conn_call_lock needs to be held
2453 * here for the case where rx_NewCall is perusing the calls on
2454 * the connection structure. We don't want to signal until
2455 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2456 * have checked this call, found it active and by the time it
2457 * goes to sleep, will have missed the signal.
2459 MUTEX_EXIT(&call->lock);
2460 MUTEX_ENTER(&conn->conn_call_lock);
2461 MUTEX_ENTER(&call->lock);
2464 /* While there are some circumstances where a call with an error is
2465 * obviously not on a "busy" channel, be conservative (clearing
2466 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2467 * The call channel is definitely not busy if we just successfully
2468 * completed a call on it. */
2469 conn->lastBusy[call->channel] = 0;
2471 } else if (call->error == RX_CALL_TIMEOUT) {
2472 /* The call is still probably running on the server side, so try to
2473 * avoid this call channel in the future. */
2474 conn->lastBusy[call->channel] = clock_Sec();
2477 MUTEX_ENTER(&conn->conn_data_lock);
2478 conn->flags |= RX_CONN_BUSY;
2479 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2480 MUTEX_EXIT(&conn->conn_data_lock);
2481 #ifdef RX_ENABLE_LOCKS
2482 CV_BROADCAST(&conn->conn_call_cv);
2487 #ifdef RX_ENABLE_LOCKS
2489 MUTEX_EXIT(&conn->conn_data_lock);
2491 #endif /* RX_ENABLE_LOCKS */
2492 call->state = RX_STATE_DALLY;
2494 error = call->error;
2496 /* currentPacket, nLeft, and NFree must be zeroed here, because
2497 * ResetCall cannot: ResetCall may be called at splnet(), in the
2498 * kernel version, and may interrupt the macros rx_Read or
2499 * rx_Write, which run at normal priority for efficiency. */
2500 if (call->app.currentPacket) {
2501 #ifdef RX_TRACK_PACKETS
2502 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2504 rxi_FreePacket(call->app.currentPacket);
2505 call->app.currentPacket = (struct rx_packet *)0;
2508 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2510 /* Free any packets from the last call to ReadvProc/WritevProc */
2511 #ifdef RXDEBUG_PACKET
2513 #endif /* RXDEBUG_PACKET */
2514 rxi_FreePackets(0, &call->app.iovq);
2515 MUTEX_EXIT(&call->lock);
2517 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2518 if (conn->type == RX_CLIENT_CONNECTION) {
2519 MUTEX_ENTER(&conn->conn_data_lock);
2520 conn->flags &= ~RX_CONN_BUSY;
2521 MUTEX_EXIT(&conn->conn_data_lock);
2522 MUTEX_EXIT(&conn->conn_call_lock);
2526 * Map errors to the local host's errno.h format.
2528 error = ntoh_syserr_conv(error);
2530 /* If the caller said the call failed with some error, we had better
2531 * return an error code. */
2532 osi_Assert(!rc || error);
2536 #if !defined(KERNEL)
2538 /* Call this routine when shutting down a server or client (especially
2539 * clients). This will allow Rx to gracefully garbage collect server
2540 * connections, and reduce the number of retries that a server might
2541 * make to a dead client.
2542 * This is not quite right, since some calls may still be ongoing and
2543 * we can't lock them to destroy them. */
2549 if (!rxi_IsRunning()) {
2551 return; /* Already shutdown. */
2553 rxi_Finalize_locked();
2558 rxi_Finalize_locked(void)
2560 struct rx_connection **conn_ptr, **conn_end;
2561 rx_atomic_set(&rxi_running, 0);
2562 rxi_DeleteCachedConnections();
2563 if (rx_connHashTable) {
2564 MUTEX_ENTER(&rx_connHashTable_lock);
2565 for (conn_ptr = &rx_connHashTable[0], conn_end =
2566 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2568 struct rx_connection *conn, *next;
2569 for (conn = *conn_ptr; conn; conn = next) {
2571 if (conn->type == RX_CLIENT_CONNECTION) {
2572 rx_GetConnection(conn);
2573 #ifdef RX_ENABLE_LOCKS
2574 rxi_DestroyConnectionNoLock(conn);
2575 #else /* RX_ENABLE_LOCKS */
2576 rxi_DestroyConnection(conn);
2577 #endif /* RX_ENABLE_LOCKS */
2581 #ifdef RX_ENABLE_LOCKS
2582 while (rx_connCleanup_list) {
2583 struct rx_connection *conn;
2584 conn = rx_connCleanup_list;
2585 rx_connCleanup_list = rx_connCleanup_list->next;
2586 MUTEX_EXIT(&rx_connHashTable_lock);
2587 rxi_CleanupConnection(conn);
2588 MUTEX_ENTER(&rx_connHashTable_lock);
2590 MUTEX_EXIT(&rx_connHashTable_lock);
2591 #endif /* RX_ENABLE_LOCKS */
2596 afs_winsockCleanup();
2601 /* if we wakeup packet waiter too often, can get in loop with two
2602 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2604 rxi_PacketsUnWait(void)
2606 if (!rx_waitingForPackets) {
2610 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2611 return; /* still over quota */
2614 rx_waitingForPackets = 0;
2615 #ifdef RX_ENABLE_LOCKS
2616 CV_BROADCAST(&rx_waitingForPackets_cv);
2618 osi_rxWakeup(&rx_waitingForPackets);
2624 /* ------------------Internal interfaces------------------------- */
2626 /* Return this process's service structure for the
2627 * specified socket and service */
2628 static struct rx_service *
2629 rxi_FindService(osi_socket socket, u_short serviceId)
2631 struct rx_service **sp;
2632 for (sp = &rx_services[0]; *sp; sp++) {
2633 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2639 #ifdef RXDEBUG_PACKET
2640 #ifdef KDUMP_RX_LOCK
2641 static struct rx_call_rx_lock *rx_allCallsp = 0;
2643 static struct rx_call *rx_allCallsp = 0;
2645 #endif /* RXDEBUG_PACKET */
2647 /* Allocate a call structure, for the indicated channel of the
2648 * supplied connection. The mode and state of the call must be set by
2649 * the caller. Returns the call with mutex locked. */
2650 static struct rx_call *
2651 rxi_NewCall(struct rx_connection *conn, int channel)
2653 struct rx_call *call;
2654 #ifdef RX_ENABLE_LOCKS
2655 struct rx_call *cp; /* Call pointer temp */
2656 struct opr_queue *cursor;
2659 dpf(("rxi_NewCall(conn %p, channel %d)\n", conn, channel));
2661 /* Grab an existing call structure, or allocate a new one.
2662 * Existing call structures are assumed to have been left reset by
2664 MUTEX_ENTER(&rx_freeCallQueue_lock);
2666 #ifdef RX_ENABLE_LOCKS
2668 * EXCEPT that the TQ might not yet be cleared out.
2669 * Skip over those with in-use TQs.
2672 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2673 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2674 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2680 #else /* RX_ENABLE_LOCKS */
2681 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2682 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2683 #endif /* RX_ENABLE_LOCKS */
2684 opr_queue_Remove(&call->entry);
2685 if (rx_stats_active)
2686 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2687 MUTEX_EXIT(&rx_freeCallQueue_lock);
2688 MUTEX_ENTER(&call->lock);
2689 CLEAR_CALL_QUEUE_LOCK(call);
2690 #ifdef RX_ENABLE_LOCKS
2691 /* Now, if TQ wasn't cleared earlier, do it now. */
2692 rxi_WaitforTQBusy(call);
2693 if (call->flags & RX_CALL_TQ_CLEARME) {
2694 rxi_ClearTransmitQueue(call, 1);
2695 /*queue_Init(&call->tq);*/
2697 #endif /* RX_ENABLE_LOCKS */
2698 /* Bind the call to its connection structure */
2700 rxi_ResetCall(call, 1);
2703 call = rxi_Alloc(sizeof(struct rx_call));
2704 #ifdef RXDEBUG_PACKET
2705 call->allNextp = rx_allCallsp;
2706 rx_allCallsp = call;
2708 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2709 #else /* RXDEBUG_PACKET */
2710 rx_atomic_inc(&rx_stats.nCallStructs);
2711 #endif /* RXDEBUG_PACKET */
2713 MUTEX_EXIT(&rx_freeCallQueue_lock);
2714 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2715 MUTEX_ENTER(&call->lock);
2716 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2717 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2718 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2720 /* Initialize once-only items */
2721 opr_queue_Init(&call->tq);
2722 opr_queue_Init(&call->rq);
2723 opr_queue_Init(&call->app.iovq);
2724 #ifdef RXDEBUG_PACKET
2725 call->rqc = call->tqc = call->iovqc = 0;
2726 #endif /* RXDEBUG_PACKET */
2727 /* Bind the call to its connection structure (prereq for reset) */
2729 rxi_ResetCall(call, 1);
2731 call->channel = channel;
2732 call->callNumber = &conn->callNumber[channel];
2733 call->rwind = conn->rwind[channel];
2734 call->twind = conn->twind[channel];
2735 /* Note that the next expected call number is retained (in
2736 * conn->callNumber[i]), even if we reallocate the call structure
2738 conn->call[channel] = call;
2739 /* if the channel's never been used (== 0), we should start at 1, otherwise
2740 * the call number is valid from the last time this channel was used */
2741 if (*call->callNumber == 0)
2742 *call->callNumber = 1;
2747 /* A call has been inactive long enough that so we can throw away
2748 * state, including the call structure, which is placed on the call
2751 * call->lock amd rx_refcnt_mutex are held upon entry.
2752 * haveCTLock is set when called from rxi_ReapConnections.
2754 * return 1 if the call is freed, 0 if not.
2757 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2759 int channel = call->channel;
2760 struct rx_connection *conn = call->conn;
2761 u_char state = call->state;
2764 * We are setting the state to RX_STATE_RESET to
2765 * ensure that no one else will attempt to use this
2766 * call once we drop the refcnt lock. We must drop
2767 * the refcnt lock before calling rxi_ResetCall
2768 * because it cannot be held across acquiring the
2769 * freepktQ lock. NewCall does the same.
2771 call->state = RX_STATE_RESET;
2772 MUTEX_EXIT(&rx_refcnt_mutex);
2773 rxi_ResetCall(call, 0);
2775 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2777 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2778 (*call->callNumber)++;
2780 if (call->conn->call[channel] == call)
2781 call->conn->call[channel] = 0;
2782 MUTEX_EXIT(&conn->conn_call_lock);
2785 * We couldn't obtain the conn_call_lock so we can't
2786 * disconnect the call from the connection. Set the
2787 * call state to dally so that the call can be reused.
2789 MUTEX_ENTER(&rx_refcnt_mutex);
2790 call->state = RX_STATE_DALLY;
2794 MUTEX_ENTER(&rx_freeCallQueue_lock);
2795 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2796 #ifdef RX_ENABLE_LOCKS
2797 /* A call may be free even though its transmit queue is still in use.
2798 * Since we search the call list from head to tail, put busy calls at
2799 * the head of the list, and idle calls at the tail.
2801 if (call->flags & RX_CALL_TQ_BUSY)
2802 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2804 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2805 #else /* RX_ENABLE_LOCKS */
2806 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2807 #endif /* RX_ENABLE_LOCKS */
2808 if (rx_stats_active)
2809 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2810 MUTEX_EXIT(&rx_freeCallQueue_lock);
2812 /* Destroy the connection if it was previously slated for
2813 * destruction, i.e. the Rx client code previously called
2814 * rx_DestroyConnection (client connections), or
2815 * rxi_ReapConnections called the same routine (server
2816 * connections). Only do this, however, if there are no
2817 * outstanding calls. Note that for fine grain locking, there appears
2818 * to be a deadlock in that rxi_FreeCall has a call locked and
2819 * DestroyConnectionNoLock locks each call in the conn. But note a
2820 * few lines up where we have removed this call from the conn.
2821 * If someone else destroys a connection, they either have no
2822 * call lock held or are going through this section of code.
2824 MUTEX_ENTER(&conn->conn_data_lock);
2825 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2826 rx_GetConnection(conn);
2827 MUTEX_EXIT(&conn->conn_data_lock);
2828 #ifdef RX_ENABLE_LOCKS
2830 rxi_DestroyConnectionNoLock(conn);
2832 rxi_DestroyConnection(conn);
2833 #else /* RX_ENABLE_LOCKS */
2834 rxi_DestroyConnection(conn);
2835 #endif /* RX_ENABLE_LOCKS */
2837 MUTEX_EXIT(&conn->conn_data_lock);
2839 MUTEX_ENTER(&rx_refcnt_mutex);
2843 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2844 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2847 rxi_Alloc(size_t size)
2851 if (rx_stats_active) {
2852 rx_atomic_add(&rxi_Allocsize, (int) size);
2853 rx_atomic_inc(&rxi_Alloccnt);
2857 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD_ENV)
2858 afs_osi_Alloc_NoSleep(size);
2863 osi_Panic("rxi_Alloc error");
2869 rxi_Free(void *addr, size_t size)
2874 if (rx_stats_active) {
2875 rx_atomic_sub(&rxi_Allocsize, (int) size);
2876 rx_atomic_dec(&rxi_Alloccnt);
2878 osi_Free(addr, size);
2882 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2884 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2885 struct rx_peer *next = NULL;
2889 MUTEX_ENTER(&rx_peerHashTable_lock);
2891 peer_ptr = &rx_peerHashTable[0];
2892 peer_end = &rx_peerHashTable[rx_hashTableSize];
2895 for ( ; peer_ptr < peer_end; peer_ptr++) {
2898 for ( ; peer; peer = next) {
2900 if (host == peer->host)
2905 hashIndex = PEER_HASH(host, port);
2906 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2907 if ((peer->host == host) && (peer->port == port))
2912 MUTEX_ENTER(&rx_peerHashTable_lock);
2917 MUTEX_EXIT(&rx_peerHashTable_lock);
2919 MUTEX_ENTER(&peer->peer_lock);
2920 /* We don't handle dropping below min, so don't */
2921 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2922 peer->ifMTU=MIN(mtu, peer->ifMTU);
2923 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2924 /* if we tweaked this down, need to tune our peer MTU too */
2925 peer->MTU = MIN(peer->MTU, peer->natMTU);
2926 /* if we discovered a sub-1500 mtu, degrade */
2927 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2928 peer->maxDgramPackets = 1;
2929 /* We no longer have valid peer packet information */
2930 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2931 peer->maxPacketSize = 0;
2932 MUTEX_EXIT(&peer->peer_lock);
2934 MUTEX_ENTER(&rx_peerHashTable_lock);
2936 if (host && !port) {
2938 /* pick up where we left off */
2942 MUTEX_EXIT(&rx_peerHashTable_lock);
2945 #ifdef AFS_RXERRQ_ENV
2947 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2949 int hashIndex = PEER_HASH(host, port);
2950 struct rx_peer *peer;
2952 MUTEX_ENTER(&rx_peerHashTable_lock);
2954 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2955 if (peer->host == host && peer->port == port) {
2961 MUTEX_EXIT(&rx_peerHashTable_lock);
2964 rx_atomic_inc(&peer->neterrs);
2965 MUTEX_ENTER(&peer->peer_lock);
2966 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2967 peer->last_err_type = err->ee_type;
2968 peer->last_err_code = err->ee_code;
2969 MUTEX_EXIT(&peer->peer_lock);
2971 MUTEX_ENTER(&rx_peerHashTable_lock);
2973 MUTEX_EXIT(&rx_peerHashTable_lock);
2978 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2980 # ifdef AFS_ADAPT_PMTU
2981 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2982 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2986 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2987 switch (err->ee_code) {
2988 case ICMP_NET_UNREACH:
2989 case ICMP_HOST_UNREACH:
2990 case ICMP_PORT_UNREACH:
2993 rxi_SetPeerDead(err, addr, port);
3000 rxi_TranslateICMP(int type, int code)
3003 case ICMP_DEST_UNREACH:
3005 case ICMP_NET_UNREACH:
3006 return "Destination Net Unreachable";
3007 case ICMP_HOST_UNREACH:
3008 return "Destination Host Unreachable";
3009 case ICMP_PROT_UNREACH:
3010 return "Destination Protocol Unreachable";
3011 case ICMP_PORT_UNREACH:
3012 return "Destination Port Unreachable";
3014 return "Destination Net Prohibited";
3016 return "Destination Host Prohibited";
3022 #endif /* AFS_RXERRQ_ENV */
3025 * Get the last network error for a connection
3027 * A "network error" here means an error retrieved from ICMP, or some other
3028 * mechanism outside of Rx that informs us of errors in network reachability.
3030 * If a peer associated with the given Rx connection has received a network
3031 * error recently, this function allows the caller to know what error
3032 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3033 * can cause calls to that peer to be quickly aborted. So, this function can
3034 * help see why a call was aborted due to network errors.
3036 * If we have received traffic from a peer since the last network error, we
3037 * treat that peer as if we had not received an network error for it.
3039 * @param[in] conn The Rx connection to examine
3040 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3041 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3042 * @param[out] err_type The type of the last error
3043 * @param[out] err_code The code of the last error
3044 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3046 * @return If we have an error
3047 * @retval -1 No error to get; 'out' params are undefined
3048 * @retval 0 We have an error; 'out' params contain the last error
3051 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3052 int *err_code, const char **msg)
3054 #ifdef AFS_RXERRQ_ENV
3055 struct rx_peer *peer = conn->peer;
3056 if (rx_atomic_read(&peer->neterrs)) {
3057 MUTEX_ENTER(&peer->peer_lock);
3058 *err_origin = peer->last_err_origin;
3059 *err_type = peer->last_err_type;
3060 *err_code = peer->last_err_code;
3061 MUTEX_EXIT(&peer->peer_lock);
3064 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3065 *msg = rxi_TranslateICMP(*err_type, *err_code);
3074 /* Find the peer process represented by the supplied (host,port)
3075 * combination. If there is no appropriate active peer structure, a
3076 * new one will be allocated and initialized
3079 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3083 hashIndex = PEER_HASH(host, port);
3084 MUTEX_ENTER(&rx_peerHashTable_lock);
3085 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3086 if ((pp->host == host) && (pp->port == port))
3091 pp = rxi_AllocPeer(); /* This bzero's *pp */
3092 pp->host = host; /* set here or in InitPeerParams is zero */
3094 #ifdef AFS_RXERRQ_ENV
3095 rx_atomic_set(&pp->neterrs, 0);
3097 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3098 opr_queue_Init(&pp->rpcStats);
3099 pp->next = rx_peerHashTable[hashIndex];
3100 rx_peerHashTable[hashIndex] = pp;
3101 rxi_InitPeerParams(pp);
3102 if (rx_stats_active)
3103 rx_atomic_inc(&rx_stats.nPeerStructs);
3109 MUTEX_EXIT(&rx_peerHashTable_lock);
3114 /* Find the connection at (host, port) started at epoch, and with the
3115 * given connection id. Creates the server connection if necessary.
3116 * The type specifies whether a client connection or a server
3117 * connection is desired. In both cases, (host, port) specify the
3118 * peer's (host, pair) pair. Client connections are not made
3119 * automatically by this routine. The parameter socket gives the
3120 * socket descriptor on which the packet was received. This is used,
3121 * in the case of server connections, to check that *new* connections
3122 * come via a valid (port, serviceId). Finally, the securityIndex
3123 * parameter must match the existing index for the connection. If a
3124 * server connection is created, it will be created using the supplied
3125 * index, if the index is valid for this service */
3126 static struct rx_connection *
3127 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3128 u_short port, u_short serviceId, afs_uint32 cid,
3129 afs_uint32 epoch, int type, u_int securityIndex,
3130 int *unknownService)
3132 int hashindex, flag, i;
3134 struct rx_connection *conn;
3135 *unknownService = 0;
3136 hashindex = CONN_HASH(host, port, cid, epoch, type);
3137 MUTEX_ENTER(&rx_connHashTable_lock);
3138 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3139 rx_connHashTable[hashindex],
3142 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3143 && (epoch == conn->epoch)) {
3144 struct rx_peer *pp = conn->peer;
3145 if (securityIndex != conn->securityIndex) {
3146 /* this isn't supposed to happen, but someone could forge a packet
3147 * like this, and there seems to be some CM bug that makes this
3148 * happen from time to time -- in which case, the fileserver
3150 MUTEX_EXIT(&rx_connHashTable_lock);
3151 return (struct rx_connection *)0;
3153 if (pp->host == host && pp->port == port)
3155 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3157 /* So what happens when it's a callback connection? */
3158 if ( /*type == RX_CLIENT_CONNECTION && */
3159 (conn->epoch & 0x80000000))
3163 /* the connection rxLastConn that was used the last time is not the
3164 ** one we are looking for now. Hence, start searching in the hash */
3166 conn = rx_connHashTable[hashindex];
3171 struct rx_service *service;
3172 if (type == RX_CLIENT_CONNECTION) {
3173 MUTEX_EXIT(&rx_connHashTable_lock);
3174 return (struct rx_connection *)0;
3176 service = rxi_FindService(socket, serviceId);
3177 if (!service || (securityIndex >= service->nSecurityObjects)
3178 || (service->securityObjects[securityIndex] == 0)) {
3179 MUTEX_EXIT(&rx_connHashTable_lock);
3180 *unknownService = 1;
3181 return (struct rx_connection *)0;
3183 conn = rxi_AllocConnection(); /* This bzero's the connection */
3184 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3185 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3186 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3187 conn->next = rx_connHashTable[hashindex];
3188 rx_connHashTable[hashindex] = conn;
3189 conn->peer = rxi_FindPeer(host, port, 1);
3190 conn->type = RX_SERVER_CONNECTION;
3191 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3192 conn->epoch = epoch;
3193 conn->cid = cid & RX_CIDMASK;
3194 conn->ackRate = RX_FAST_ACK_RATE;
3195 conn->service = service;
3196 conn->serviceId = serviceId;
3197 conn->securityIndex = securityIndex;
3198 conn->securityObject = service->securityObjects[securityIndex];
3199 conn->nSpecific = 0;
3200 conn->specific = NULL;
3201 rx_SetConnDeadTime(conn, service->connDeadTime);
3202 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3203 for (i = 0; i < RX_MAXCALLS; i++) {
3204 conn->twind[i] = rx_initSendWindow;
3205 conn->rwind[i] = rx_initReceiveWindow;
3207 /* Notify security object of the new connection */
3208 code = RXS_NewConnection(conn->securityObject, conn);
3209 /* XXXX Connection timeout? */
3210 if (service->newConnProc)
3211 (*service->newConnProc) (conn);
3212 if (rx_stats_active)
3213 rx_atomic_inc(&rx_stats.nServerConns);
3216 rx_GetConnection(conn);
3218 rxLastConn = conn; /* store this connection as the last conn used */
3219 MUTEX_EXIT(&rx_connHashTable_lock);
3221 rxi_ConnectionError(conn, code);
3227 * Abort the call if the server is over the busy threshold. This
3228 * can be used without requiring a call structure be initialised,
3229 * or connected to a particular channel
3232 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3233 struct rx_packet *np)
3237 if ((rx_BusyThreshold > 0) &&
3238 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3239 MUTEX_ENTER(&conn->conn_data_lock);
3240 serial = ++conn->serial;
3241 MUTEX_EXIT(&conn->conn_data_lock);
3242 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3243 serial, rx_BusyError, np, 0);
3244 if (rx_stats_active)
3245 rx_atomic_inc(&rx_stats.nBusies);
3252 static_inline struct rx_call *
3253 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3256 struct rx_call *call;
3258 channel = np->header.cid & RX_CHANNELMASK;
3259 MUTEX_ENTER(&conn->conn_call_lock);
3260 call = conn->call[channel];
3261 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3262 conn->lastBusy[channel] = clock_Sec();
3264 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3265 MUTEX_EXIT(&conn->conn_call_lock);
3266 if (rx_stats_active)
3267 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3271 MUTEX_ENTER(&call->lock);
3272 MUTEX_EXIT(&conn->conn_call_lock);
3274 if ((call->state == RX_STATE_DALLY)
3275 && np->header.type == RX_PACKET_TYPE_ACK) {
3276 if (rx_stats_active)
3277 rx_atomic_inc(&rx_stats.ignorePacketDally);
3278 MUTEX_EXIT(&call->lock);
3285 static_inline struct rx_call *
3286 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3287 struct rx_connection *conn)
3290 struct rx_call *call;
3292 channel = np->header.cid & RX_CHANNELMASK;
3293 MUTEX_ENTER(&conn->conn_call_lock);
3294 call = conn->call[channel];
3297 if (np->header.type != RX_PACKET_TYPE_DATA) {
3299 * Clients must send DATA packets at some point to create a new
3300 * call. If the first packet we saw for this call channel is
3301 * something else, then either the DATA packets got lost/delayed,
3302 * or we were restarted and this is an existing call from before we
3303 * were restarted. In the latter case, some clients get confused if
3304 * we respond to such requests, so just drop the packet to make
3305 * things easier for them.
3307 MUTEX_EXIT(&conn->conn_call_lock);
3308 if (rx_stats_active)
3309 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3313 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3314 MUTEX_EXIT(&conn->conn_call_lock);
3318 call = rxi_NewCall(conn, channel); /* returns locked call */
3319 *call->callNumber = np->header.callNumber;
3320 MUTEX_EXIT(&conn->conn_call_lock);
3322 call->state = RX_STATE_PRECALL;
3323 clock_GetTime(&call->queueTime);
3324 call->app.bytesSent = 0;
3325 call->app.bytesRcvd = 0;
3326 rxi_KeepAliveOn(call);
3331 if (np->header.callNumber == conn->callNumber[channel]) {
3332 MUTEX_ENTER(&call->lock);
3333 MUTEX_EXIT(&conn->conn_call_lock);
3337 if (np->header.callNumber < conn->callNumber[channel]) {
3338 MUTEX_EXIT(&conn->conn_call_lock);
3339 if (rx_stats_active)
3340 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3344 MUTEX_ENTER(&call->lock);
3345 MUTEX_EXIT(&conn->conn_call_lock);
3347 /* Wait until the transmit queue is idle before deciding
3348 * whether to reset the current call. Chances are that the
3349 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3352 #ifdef RX_ENABLE_LOCKS
3353 if (call->state == RX_STATE_ACTIVE && !call->error) {
3354 rxi_WaitforTQBusy(call);
3355 /* If we entered error state while waiting,
3356 * must call rxi_CallError to permit rxi_ResetCall
3357 * to processed when the tqWaiter count hits zero.
3360 rxi_CallError(call, call->error);
3361 MUTEX_EXIT(&call->lock);
3365 #endif /* RX_ENABLE_LOCKS */
3366 /* If the new call cannot be taken right now send a busy and set
3367 * the error condition in this call, so that it terminates as
3368 * quickly as possible */
3369 if (call->state == RX_STATE_ACTIVE) {
3370 rxi_CallError(call, RX_CALL_DEAD);
3371 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3373 MUTEX_EXIT(&call->lock);
3377 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3378 MUTEX_EXIT(&call->lock);
3382 rxi_ResetCall(call, 0);
3383 /* The conn_call_lock is not held but no one else should be
3384 * using this call channel while we are processing this incoming
3385 * packet. This assignment should be safe.
3387 *call->callNumber = np->header.callNumber;
3388 call->state = RX_STATE_PRECALL;
3389 clock_GetTime(&call->queueTime);
3390 call->app.bytesSent = 0;
3391 call->app.bytesRcvd = 0;
3392 rxi_KeepAliveOn(call);
3398 /* There are two packet tracing routines available for testing and monitoring
3399 * Rx. One is called just after every packet is received and the other is
3400 * called just before every packet is sent. Received packets, have had their
3401 * headers decoded, and packets to be sent have not yet had their headers
3402 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3403 * containing the network address. Both can be modified. The return value, if
3404 * non-zero, indicates that the packet should be dropped. */
3406 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3407 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3409 /* A packet has been received off the interface. Np is the packet, socket is
3410 * the socket number it was received from (useful in determining which service
3411 * this packet corresponds to), and (host, port) reflect the host,port of the
3412 * sender. This call returns the packet to the caller if it is finished with
3413 * it, rather than de-allocating it, just as a small performance hack */
3416 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3417 afs_uint32 host, u_short port, int *tnop,
3418 struct rx_call **newcallp)
3420 struct rx_call *call;
3421 struct rx_connection *conn;
3423 int unknownService = 0;
3428 struct rx_packet *tnp;
3431 /* We don't print out the packet until now because (1) the time may not be
3432 * accurate enough until now in the lwp implementation (rx_Listener only gets
3433 * the time after the packet is read) and (2) from a protocol point of view,
3434 * this is the first time the packet has been seen */
3435 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3436 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3437 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3438 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3439 np->header.epoch, np->header.cid, np->header.callNumber,
3440 np->header.seq, np->header.flags, np));
3443 /* Account for connectionless packets */
3444 if (rx_stats_active &&
3445 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3446 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3447 struct rx_peer *peer;
3449 /* Try to look up the peer structure, but don't create one */
3450 peer = rxi_FindPeer(host, port, 0);
3452 /* Since this may not be associated with a connection, it may have
3453 * no refCount, meaning we could race with ReapConnections
3456 if (peer && (peer->refCount > 0)) {
3457 #ifdef AFS_RXERRQ_ENV
3458 if (rx_atomic_read(&peer->neterrs)) {
3459 rx_atomic_set(&peer->neterrs, 0);
3462 MUTEX_ENTER(&peer->peer_lock);
3463 peer->bytesReceived += np->length;
3464 MUTEX_EXIT(&peer->peer_lock);
3468 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3469 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3472 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3473 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3476 /* If an input tracer function is defined, call it with the packet and
3477 * network address. Note this function may modify its arguments. */
3478 if (rx_justReceived) {
3479 struct sockaddr_in addr;
3481 addr.sin_family = AF_INET;
3482 addr.sin_port = port;
3483 addr.sin_addr.s_addr = host;
3484 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3485 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3486 addr.sin_len = sizeof(addr);
3488 drop = (*rx_justReceived) (np, &addr);
3489 /* drop packet if return value is non-zero */
3492 port = addr.sin_port; /* in case fcn changed addr */
3493 host = addr.sin_addr.s_addr;
3497 /* If packet was not sent by the client, then *we* must be the client */
3498 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3499 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3501 /* Find the connection (or fabricate one, if we're the server & if
3502 * necessary) associated with this packet */
3504 rxi_FindConnection(socket, host, port, np->header.serviceId,
3505 np->header.cid, np->header.epoch, type,
3506 np->header.securityIndex, &unknownService);
3508 /* To avoid having 2 connections just abort at each other,
3509 don't abort an abort. */
3511 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3512 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3517 #ifdef AFS_RXERRQ_ENV
3518 if (rx_atomic_read(&conn->peer->neterrs)) {
3519 rx_atomic_set(&conn->peer->neterrs, 0);
3523 /* If we're doing statistics, then account for the incoming packet */
3524 if (rx_stats_active) {
3525 MUTEX_ENTER(&conn->peer->peer_lock);
3526 conn->peer->bytesReceived += np->length;
3527 MUTEX_EXIT(&conn->peer->peer_lock);
3530 /* If the connection is in an error state, send an abort packet and ignore
3531 * the incoming packet */
3533 /* Don't respond to an abort packet--we don't want loops! */
3534 MUTEX_ENTER(&conn->conn_data_lock);
3535 if (np->header.type != RX_PACKET_TYPE_ABORT)
3536 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3537 putConnection(conn);
3538 MUTEX_EXIT(&conn->conn_data_lock);
3542 /* Check for connection-only requests (i.e. not call specific). */
3543 if (np->header.callNumber == 0) {
3544 switch (np->header.type) {
3545 case RX_PACKET_TYPE_ABORT: {
3546 /* What if the supplied error is zero? */
3547 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3548 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3549 rxi_ConnectionError(conn, errcode);
3550 putConnection(conn);
3553 case RX_PACKET_TYPE_CHALLENGE:
3554 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3555 putConnection(conn);
3557 case RX_PACKET_TYPE_RESPONSE:
3558 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3559 putConnection(conn);
3561 case RX_PACKET_TYPE_PARAMS:
3562 case RX_PACKET_TYPE_PARAMS + 1:
3563 case RX_PACKET_TYPE_PARAMS + 2:
3564 /* ignore these packet types for now */
3565 putConnection(conn);
3569 /* Should not reach here, unless the peer is broken: send an
3571 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3572 MUTEX_ENTER(&conn->conn_data_lock);
3573 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3574 putConnection(conn);
3575 MUTEX_EXIT(&conn->conn_data_lock);
3580 if (type == RX_SERVER_CONNECTION)
3581 call = rxi_ReceiveServerCall(socket, np, conn);
3583 call = rxi_ReceiveClientCall(np, conn);
3586 putConnection(conn);
3590 MUTEX_ASSERT(&call->lock);
3591 /* Set remote user defined status from packet */
3592 call->remoteStatus = np->header.userStatus;
3594 /* Now do packet type-specific processing */
3595 switch (np->header.type) {
3596 case RX_PACKET_TYPE_DATA:
3597 /* If we're a client, and receiving a response, then all the packets
3598 * we transmitted packets are implicitly acknowledged. */
3599 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3600 rxi_AckAllInTransmitQueue(call);
3602 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3605 case RX_PACKET_TYPE_ACK:
3606 /* Respond immediately to ack packets requesting acknowledgement
3608 if (np->header.flags & RX_REQUEST_ACK) {
3610 (void)rxi_SendCallAbort(call, 0, 1, 0);
3612 (void)rxi_SendAck(call, 0, np->header.serial,
3613 RX_ACK_PING_RESPONSE, 1);
3615 np = rxi_ReceiveAckPacket(call, np, 1, &invalid);
3617 case RX_PACKET_TYPE_ABORT: {
3618 /* An abort packet: reset the call, passing the error up to the user. */
3619 /* What if error is zero? */
3620 /* What if the error is -1? the application will treat it as a timeout. */
3621 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3622 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3623 rxi_CallError(call, errdata);
3624 MUTEX_EXIT(&call->lock);
3625 putConnection(conn);
3626 return np; /* xmitting; drop packet */
3628 case RX_PACKET_TYPE_BUSY:
3629 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3630 * so we don't think the endpoint is completely dead, but otherwise
3631 * just act as if we never saw anything. If all we get are BUSY packets
3632 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3633 * connection is configured with idle/hard timeouts. */
3636 case RX_PACKET_TYPE_ACKALL:
3637 /* All packets acknowledged, so we can drop all packets previously
3638 * readied for sending */
3639 rxi_AckAllInTransmitQueue(call);
3642 /* Should not reach here, unless the peer is broken: send an abort
3644 rxi_CallError(call, RX_PROTOCOL_ERROR);
3645 np = rxi_SendCallAbort(call, np, 1, 0);
3649 if (rx_stats_active)
3650 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3653 * Note when this last legitimate packet was received, for keep-alive
3656 call->lastReceiveTime = clock_Sec();
3658 MUTEX_EXIT(&call->lock);
3659 putConnection(conn);
3663 /* return true if this is an "interesting" connection from the point of view
3664 of someone trying to debug the system */
3666 rxi_IsConnInteresting(struct rx_connection *aconn)
3669 struct rx_call *tcall;
3671 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3674 for (i = 0; i < RX_MAXCALLS; i++) {
3675 tcall = aconn->call[i];
3677 if ((tcall->state == RX_STATE_PRECALL)
3678 || (tcall->state == RX_STATE_ACTIVE))
3680 if ((tcall->app.mode == RX_MODE_SENDING)
3681 || (tcall->app.mode == RX_MODE_RECEIVING))
3689 /* if this is one of the last few packets AND it wouldn't be used by the
3690 receiving call to immediately satisfy a read request, then drop it on
3691 the floor, since accepting it might prevent a lock-holding thread from
3692 making progress in its reading. If a call has been cleared while in
3693 the precall state then ignore all subsequent packets until the call
3694 is assigned to a thread. */
3697 TooLow(struct rx_packet *ap, struct rx_call *acall)
3701 MUTEX_ENTER(&rx_quota_mutex);
3702 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3703 && (acall->state == RX_STATE_PRECALL))
3704 || ((rx_nFreePackets < rxi_dataQuota + 2)
3705 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3706 && (acall->flags & RX_CALL_READER_WAIT)))) {
3709 MUTEX_EXIT(&rx_quota_mutex);
3715 * Clear the attach wait flag on a connection and proceed.
3717 * Any processing waiting for a connection to be attached should be
3718 * unblocked. We clear the flag and do any other needed tasks.
3721 * the conn to unmark waiting for attach
3723 * @pre conn's conn_data_lock must be locked before calling this function
3727 rxi_ConnClearAttachWait(struct rx_connection *conn)
3729 /* Indicate that rxi_CheckReachEvent is no longer running by
3730 * clearing the flag. Must be atomic under conn_data_lock to
3731 * avoid a new call slipping by: rxi_CheckConnReach holds
3732 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3734 conn->flags &= ~RX_CONN_ATTACHWAIT;
3735 if (conn->flags & RX_CONN_NAT_PING) {
3736 conn->flags &= ~RX_CONN_NAT_PING;
3737 rxi_ScheduleNatKeepAliveEvent(conn);
3742 * Event handler function for connection-specific events for checking
3743 * reachability. Also called directly from main code with |event| == NULL
3744 * in order to trigger the initial reachability check.
3746 * When |event| == NULL, must be called with the connection data lock held,
3747 * but returns with the lock unlocked.
3750 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3752 struct rx_connection *conn = arg1;
3753 struct rx_call *acall = arg2;
3754 struct rx_call *call = acall;
3755 struct clock when, now;
3759 MUTEX_ENTER(&conn->conn_data_lock);
3761 MUTEX_ASSERT(&conn->conn_data_lock);
3763 if (event != NULL && event == conn->checkReachEvent)
3764 rxevent_Put(&conn->checkReachEvent);
3765 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3766 MUTEX_EXIT(&conn->conn_data_lock);
3770 MUTEX_ENTER(&conn->conn_call_lock);
3771 MUTEX_ENTER(&conn->conn_data_lock);
3772 for (i = 0; i < RX_MAXCALLS; i++) {
3773 struct rx_call *tc = conn->call[i];
3774 if (tc && tc->state == RX_STATE_PRECALL) {
3780 rxi_ConnClearAttachWait(conn);
3781 MUTEX_EXIT(&conn->conn_data_lock);
3782 MUTEX_EXIT(&conn->conn_call_lock);
3787 MUTEX_ENTER(&call->lock);
3788 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3790 MUTEX_EXIT(&call->lock);
3792 clock_GetTime(&now);
3794 when.sec += RX_CHECKREACH_TIMEOUT;
3795 MUTEX_ENTER(&conn->conn_data_lock);
3796 if (!conn->checkReachEvent) {
3797 rx_GetConnection(conn);
3798 conn->checkReachEvent = rxevent_Post(&when, &now,
3799 rxi_CheckReachEvent, conn,
3802 MUTEX_EXIT(&conn->conn_data_lock);
3805 /* If fired as an event handler, drop our refcount on the connection. */
3807 putConnection(conn);
3811 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3813 struct rx_service *service = conn->service;
3814 struct rx_peer *peer = conn->peer;
3815 afs_uint32 now, lastReach;
3817 if (service->checkReach == 0)
3821 MUTEX_ENTER(&peer->peer_lock);
3822 lastReach = peer->lastReachTime;
3823 MUTEX_EXIT(&peer->peer_lock);
3824 if (now - lastReach < RX_CHECKREACH_TTL)
3827 MUTEX_ENTER(&conn->conn_data_lock);
3828 if (conn->flags & RX_CONN_ATTACHWAIT) {
3829 MUTEX_EXIT(&conn->conn_data_lock);
3832 conn->flags |= RX_CONN_ATTACHWAIT;
3833 if (conn->checkReachEvent == NULL) {
3834 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3835 rxi_CheckReachEvent(NULL, conn, call, 0);
3837 MUTEX_EXIT(&conn->conn_data_lock);
3843 /* try to attach call, if authentication is complete */
3845 TryAttach(struct rx_call *acall, osi_socket socket,
3846 int *tnop, struct rx_call **newcallp,
3847 int reachOverride, int istack)
3849 struct rx_connection *conn = acall->conn;
3851 if (conn->type == RX_SERVER_CONNECTION
3852 && acall->state == RX_STATE_PRECALL) {
3853 /* Don't attach until we have any req'd. authentication. */
3854 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3855 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3856 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3857 /* Note: this does not necessarily succeed; there
3858 * may not any proc available
3862 code = rxi_ChallengeOn(acall->conn);
3865 * Ideally we would rxi_ConnectionError here, but doing that is
3866 * difficult, because some callers may have locked 'call',
3867 * _and_ another call on the same conn. So we cannot
3868 * rxi_ConnectionError, since that needs to lock every call on
3869 * the conn. But we can at least abort the call we have.
3871 rxi_CallError(acall, code);
3872 rxi_SendCallAbort(acall, NULL, istack, 0);
3878 /* A data packet has been received off the interface. This packet is
3879 * appropriate to the call (the call is in the right state, etc.). This
3880 * routine can return a packet to the caller, for re-use */
3882 static struct rx_packet *
3883 rxi_ReceiveDataPacket(struct rx_call *call,
3884 struct rx_packet *np, int istack,
3885 osi_socket socket, afs_uint32 host, u_short port,
3886 int *tnop, struct rx_call **newcallp)
3888 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3893 afs_uint32 serial=0, flags=0;
3895 struct rx_packet *tnp;
3896 if (rx_stats_active)
3897 rx_atomic_inc(&rx_stats.dataPacketsRead);
3900 /* If there are no packet buffers, drop this new packet, unless we can find
3901 * packet buffers from inactive calls */
3903 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3904 MUTEX_ENTER(&rx_freePktQ_lock);
3905 rxi_NeedMorePackets = TRUE;
3906 MUTEX_EXIT(&rx_freePktQ_lock);
3907 if (rx_stats_active)
3908 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3909 rxi_calltrace(RX_TRACE_DROP, call);
3910 dpf(("packet %p dropped on receipt - quota problems\n", np));
3911 /* We used to clear the receive queue here, in an attempt to free
3912 * packets. However this is unsafe if the queue has received a
3913 * soft ACK for the final packet */
3914 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3920 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3921 * packet is one of several packets transmitted as a single
3922 * datagram. Do not send any soft or hard acks until all packets
3923 * in a jumbogram have been processed. Send negative acks right away.
3925 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3926 /* tnp is non-null when there are more packets in the
3927 * current jumbo gram */
3934 seq = np->header.seq;
3935 serial = np->header.serial;
3936 flags = np->header.flags;
3938 /* If the call is in an error state, send an abort message */
3940 return rxi_SendCallAbort(call, np, istack, 0);
3942 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3943 * AFS 3.5 jumbogram. */
3944 if (flags & RX_JUMBO_PACKET) {
3945 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3950 if (np->header.spare != 0) {
3951 MUTEX_ENTER(&call->conn->conn_data_lock);
3952 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3953 MUTEX_EXIT(&call->conn->conn_data_lock);
3956 /* The usual case is that this is the expected next packet */
3957 if (seq == call->rnext) {
3959 /* Check to make sure it is not a duplicate of one already queued */
3960 if (!opr_queue_IsEmpty(&call->rq)
3961 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3962 if (rx_stats_active)
3963 rx_atomic_inc(&rx_stats.dupPacketsRead);
3964 dpf(("packet %p dropped on receipt - duplicate\n", np));
3965 rxi_CancelDelayedAckEvent(call);
3966 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3972 /* It's the next packet. Stick it on the receive queue
3973 * for this call. Set newPackets to make sure we wake
3974 * the reader once all packets have been processed */
3975 #ifdef RX_TRACK_PACKETS
3976 np->flags |= RX_PKTFLAG_RQ;
3978 opr_queue_Prepend(&call->rq, &np->entry);
3979 #ifdef RXDEBUG_PACKET
3981 #endif /* RXDEBUG_PACKET */
3983 np = NULL; /* We can't use this anymore */
3986 /* If an ack is requested then set a flag to make sure we
3987 * send an acknowledgement for this packet */
3988 if (flags & RX_REQUEST_ACK) {
3989 ackNeeded = RX_ACK_REQUESTED;
3992 /* Keep track of whether we have received the last packet */
3993 if (flags & RX_LAST_PACKET) {
3994 call->flags |= RX_CALL_HAVE_LAST;
3998 /* Check whether we have all of the packets for this call */
3999 if (call->flags & RX_CALL_HAVE_LAST) {
4000 afs_uint32 tseq; /* temporary sequence number */
4001 struct opr_queue *cursor;
4003 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
4004 struct rx_packet *tp;
4006 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
4007 if (tseq != tp->header.seq)
4009 if (tp->header.flags & RX_LAST_PACKET) {
4010 call->flags |= RX_CALL_RECEIVE_DONE;
4017 /* Provide asynchronous notification for those who want it
4018 * (e.g. multi rx) */
4019 if (call->arrivalProc) {
4020 (*call->arrivalProc) (call, call->arrivalProcHandle,
4021 call->arrivalProcArg);
4022 call->arrivalProc = NULL;
4025 /* Update last packet received */
4028 /* If there is no server process serving this call, grab
4029 * one, if available. We only need to do this once. If a
4030 * server thread is available, this thread becomes a server
4031 * thread and the server thread becomes a listener thread. */
4033 TryAttach(call, socket, tnop, newcallp, 0, istack);
4036 /* This is not the expected next packet. */
4038 /* Determine whether this is a new or old packet, and if it's
4039 * a new one, whether it fits into the current receive window.
4040 * Also figure out whether the packet was delivered in sequence.
4041 * We use the prev variable to determine whether the new packet
4042 * is the successor of its immediate predecessor in the
4043 * receive queue, and the missing flag to determine whether
4044 * any of this packets predecessors are missing. */
4046 afs_uint32 prev; /* "Previous packet" sequence number */
4047 struct opr_queue *cursor;
4048 int missing; /* Are any predecessors missing? */
4050 /* If the new packet's sequence number has been sent to the
4051 * application already, then this is a duplicate */
4052 if (seq < call->rnext) {
4053 if (rx_stats_active)
4054 rx_atomic_inc(&rx_stats.dupPacketsRead);
4055 rxi_CancelDelayedAckEvent(call);
4056 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4062 /* If the sequence number is greater than what can be
4063 * accomodated by the current window, then send a negative
4064 * acknowledge and drop the packet */
4065 if ((call->rnext + call->rwind) <= seq) {
4066 rxi_CancelDelayedAckEvent(call);
4067 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4074 /* Look for the packet in the queue of old received packets */
4075 prev = call->rnext - 1;
4077 for (opr_queue_Scan(&call->rq, cursor)) {
4078 struct rx_packet *tp
4079 = opr_queue_Entry(cursor, struct rx_packet, entry);
4081 /*Check for duplicate packet */
4082 if (seq == tp->header.seq) {
4083 if (rx_stats_active)
4084 rx_atomic_inc(&rx_stats.dupPacketsRead);
4085 rxi_CancelDelayedAckEvent(call);
4086 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4092 /* If we find a higher sequence packet, break out and
4093 * insert the new packet here. */
4094 if (seq < tp->header.seq)
4096 /* Check for missing packet */
4097 if (tp->header.seq != prev + 1) {
4101 prev = tp->header.seq;
4104 /* Keep track of whether we have received the last packet. */
4105 if (flags & RX_LAST_PACKET) {
4106 call->flags |= RX_CALL_HAVE_LAST;
4109 /* It's within the window: add it to the the receive queue.
4110 * tp is left by the previous loop either pointing at the
4111 * packet before which to insert the new packet, or at the
4112 * queue head if the queue is empty or the packet should be
4114 #ifdef RX_TRACK_PACKETS
4115 np->flags |= RX_PKTFLAG_RQ;
4117 #ifdef RXDEBUG_PACKET
4119 #endif /* RXDEBUG_PACKET */
4120 opr_queue_InsertBefore(cursor, &np->entry);
4124 /* Check whether we have all of the packets for this call */
4125 if ((call->flags & RX_CALL_HAVE_LAST)
4126 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4127 afs_uint32 tseq; /* temporary sequence number */
4130 for (opr_queue_Scan(&call->rq, cursor)) {
4131 struct rx_packet *tp
4132 = opr_queue_Entry(cursor, struct rx_packet, entry);
4133 if (tseq != tp->header.seq)
4135 if (tp->header.flags & RX_LAST_PACKET) {
4136 call->flags |= RX_CALL_RECEIVE_DONE;
4143 /* We need to send an ack of the packet is out of sequence,
4144 * or if an ack was requested by the peer. */
4145 if (seq != prev + 1 || missing) {
4146 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4147 } else if (flags & RX_REQUEST_ACK) {
4148 ackNeeded = RX_ACK_REQUESTED;
4151 /* Acknowledge the last packet for each call */
4152 if (flags & RX_LAST_PACKET) {
4163 * If the receiver is waiting for an iovec, fill the iovec
4164 * using the data from the receive queue */
4165 if (call->flags & RX_CALL_IOVEC_WAIT) {
4166 didHardAck = rxi_FillReadVec(call, serial);
4167 /* the call may have been aborted */
4176 /* Wakeup the reader if any */
4177 if ((call->flags & RX_CALL_READER_WAIT)
4178 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4179 || (call->iovNext >= call->iovMax)
4180 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4181 call->flags &= ~RX_CALL_READER_WAIT;
4182 #ifdef RX_ENABLE_LOCKS
4183 CV_BROADCAST(&call->cv_rq);
4185 osi_rxWakeup(&call->rq);
4191 * Send an ack when requested by the peer, or once every
4192 * rxi_SoftAckRate packets until the last packet has been
4193 * received. Always send a soft ack for the last packet in
4194 * the server's reply. */
4196 rxi_CancelDelayedAckEvent(call);
4197 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4198 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4199 rxi_CancelDelayedAckEvent(call);
4200 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4201 } else if (call->nSoftAcks) {
4202 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4203 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4205 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4206 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4207 rxi_CancelDelayedAckEvent(call);
4214 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4217 struct rx_peer *peer = conn->peer;
4219 MUTEX_ENTER(&peer->peer_lock);
4220 peer->lastReachTime = clock_Sec();
4221 MUTEX_EXIT(&peer->peer_lock);
4223 MUTEX_ENTER(&conn->conn_data_lock);
4224 if (conn->flags & RX_CONN_ATTACHWAIT) {
4227 rxi_ConnClearAttachWait(conn);
4228 MUTEX_EXIT(&conn->conn_data_lock);
4230 for (i = 0; i < RX_MAXCALLS; i++) {
4231 struct rx_call *call = conn->call[i];
4234 MUTEX_ENTER(&call->lock);
4235 /* tnop can be null if newcallp is null */
4236 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4238 MUTEX_EXIT(&call->lock);
4242 MUTEX_EXIT(&conn->conn_data_lock);
4245 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4247 rx_ack_reason(int reason)
4250 case RX_ACK_REQUESTED:
4252 case RX_ACK_DUPLICATE:
4254 case RX_ACK_OUT_OF_SEQUENCE:
4256 case RX_ACK_EXCEEDS_WINDOW:
4258 case RX_ACK_NOSPACE:
4262 case RX_ACK_PING_RESPONSE:
4275 ack_is_valid(struct rx_call *call, afs_uint32 first, afs_uint32 prev)
4277 if (first < call->tfirst) {
4279 * The peer indicated that the window went backwards. That's not
4280 * allowed; the window can only move forwards.
4285 if (first == call->tfirst && prev < call->tprev) {
4287 * The peer said the last DATA packet it received was seq X, but it
4288 * already told us before that it had received data after X. This is
4289 * probably just an out-of-order ACK, and so we can ignore it.
4291 if (prev >= call->tfirst + call->twind) {
4293 * Some peers (OpenAFS libafs before 1.6.23) mistakenly set the
4294 * previousPacket field to a serial number, not a sequence number.
4295 * The sequence number the peer told us about is further than our
4296 * transmit window, so it cannot possibly be correct; it's probably
4297 * actually a serial number. Don't ignore packets based on this;
4298 * the previousPacket information is not accurate.
4306 /* Otherwise, the ack looks valid. */
4310 /* The real smarts of the whole thing. */
4311 static struct rx_packet *
4312 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4313 int istack, int *a_invalid)
4315 struct rx_ackPacket *ap;
4317 struct rx_packet *tp;
4318 struct rx_connection *conn = call->conn;
4319 struct rx_peer *peer = conn->peer;
4320 struct opr_queue *cursor;
4321 struct clock now; /* Current time, for RTT calculations */
4329 int newAckCount = 0;
4330 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4331 int pktsize = 0; /* Set if we need to update the peer mtu */
4332 int conn_data_locked = 0;
4336 if (rx_stats_active)
4337 rx_atomic_inc(&rx_stats.ackPacketsRead);
4338 ap = (struct rx_ackPacket *)rx_DataOf(np);
4339 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4341 return np; /* truncated ack packet */
4343 /* depends on ack packet struct */
4344 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4345 first = ntohl(ap->firstPacket);
4346 prev = ntohl(ap->previousPacket);
4347 serial = ntohl(ap->serial);
4349 if (!ack_is_valid(call, first, prev)) {
4357 if (np->header.flags & RX_SLOW_START_OK) {
4358 call->flags |= RX_CALL_SLOW_START_OK;
4361 if (ap->reason == RX_ACK_PING_RESPONSE)
4362 rxi_UpdatePeerReach(conn, call, istack);
4364 if (conn->lastPacketSizeSeq) {
4365 MUTEX_ENTER(&conn->conn_data_lock);
4366 conn_data_locked = 1;
4367 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4368 pktsize = conn->lastPacketSize;
4369 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4372 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4373 if (!conn_data_locked) {
4374 MUTEX_ENTER(&conn->conn_data_lock);
4375 conn_data_locked = 1;
4377 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4378 /* process mtu ping ack */
4379 pktsize = conn->lastPingSize;
4380 conn->lastPingSizeSer = conn->lastPingSize = 0;
4384 if (conn_data_locked) {
4385 MUTEX_EXIT(&conn->conn_data_lock);
4386 conn_data_locked = 0;
4390 if (rxdebug_active) {
4394 len = _snprintf(msg, sizeof(msg),
4395 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4396 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4397 ntohl(ap->serial), ntohl(ap->previousPacket),
4398 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4399 ap->nAcks, ntohs(ap->bufferSpace) );
4403 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4404 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4408 OutputDebugString(msg);
4410 #else /* AFS_NT40_ENV */
4413 "RACK: reason %x previous %u seq %u serial %u first %u",
4414 ap->reason, ntohl(ap->previousPacket),
4415 (unsigned int)np->header.seq, (unsigned int)serial,
4416 ntohl(ap->firstPacket));
4419 for (offset = 0; offset < nAcks; offset++)
4420 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4425 #endif /* AFS_NT40_ENV */
4428 MUTEX_ENTER(&peer->peer_lock);
4431 * Start somewhere. Can't assume we can send what we can receive,
4432 * but we are clearly receiving.
4434 if (!peer->maxPacketSize)
4435 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4437 if (pktsize > peer->maxPacketSize) {
4438 peer->maxPacketSize = pktsize;
4439 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4440 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4441 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4442 rxi_ScheduleGrowMTUEvent(call, 1);
4447 clock_GetTime(&now);
4449 /* The transmit queue splits into 4 sections.
4451 * The first section is packets which have now been acknowledged
4452 * by a window size change in the ack. These have reached the
4453 * application layer, and may be discarded. These are packets
4454 * with sequence numbers < ap->firstPacket.
4456 * The second section is packets which have sequence numbers in
4457 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4458 * contents of the packet's ack array determines whether these
4459 * packets are acknowledged or not.
4461 * The third section is packets which fall above the range
4462 * addressed in the ack packet. These have not yet been received
4465 * The four section is packets which have not yet been transmitted.
4466 * These packets will have a header.serial of 0.
4469 /* First section - implicitly acknowledged packets that can be
4473 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4474 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4475 struct rx_packet *next;
4477 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4478 call->tfirst = tp->header.seq + 1;
4480 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4482 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4485 #ifdef RX_ENABLE_LOCKS
4486 /* XXX Hack. Because we have to release the global call lock when sending
4487 * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4488 * in rxi_Start sending packets out because packets may move to the
4489 * freePacketQueue as result of being here! So we drop these packets until
4490 * we're safely out of the traversing. Really ugly!
4491 * To make it even uglier, if we're using fine grain locking, we can
4492 * set the ack bits in the packets and have rxi_Start remove the packets
4493 * when it's done transmitting.
4495 if (call->flags & RX_CALL_TQ_BUSY) {
4496 tp->flags |= RX_PKTFLAG_ACKED;
4497 call->flags |= RX_CALL_TQ_SOME_ACKED;
4499 #endif /* RX_ENABLE_LOCKS */
4501 opr_queue_Remove(&tp->entry);
4502 #ifdef RX_TRACK_PACKETS
4503 tp->flags &= ~RX_PKTFLAG_TQ;
4505 #ifdef RXDEBUG_PACKET
4507 #endif /* RXDEBUG_PACKET */
4508 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4513 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4515 /* Second section of the queue - packets for which we are receiving
4518 * Go through the explicit acks/nacks and record the results in
4519 * the waiting packets. These are packets that can't be released
4520 * yet, even with a positive acknowledge. This positive
4521 * acknowledge only means the packet has been received by the
4522 * peer, not that it will be retained long enough to be sent to
4523 * the peer's upper level. In addition, reset the transmit timers
4524 * of any missing packets (those packets that must be missing
4525 * because this packet was out of sequence) */
4527 call->nSoftAcked = 0;
4529 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4530 && tp->header.seq < first + nAcks) {
4531 /* Set the acknowledge flag per packet based on the
4532 * information in the ack packet. An acknowlegded packet can
4533 * be downgraded when the server has discarded a packet it
4534 * soacked previously, or when an ack packet is received
4535 * out of sequence. */
4536 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4537 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4539 tp->flags |= RX_PKTFLAG_ACKED;
4540 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4547 } else /* RX_ACK_TYPE_NACK */ {
4548 tp->flags &= ~RX_PKTFLAG_ACKED;
4552 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4555 /* We don't need to take any action with the 3rd or 4th section in the
4556 * queue - they're not addressed by the contents of this ACK packet.
4559 /* if the ack packet has a receivelen field hanging off it,
4560 * update our state */
4561 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4564 /* If the ack packet has a "recommended" size that is less than
4565 * what I am using now, reduce my size to match */
4566 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4567 (int)sizeof(afs_int32), &tSize);
4568 tSize = (afs_uint32) ntohl(tSize);
4569 if (tSize > RX_MAX_PACKET_SIZE)
4570 tSize = RX_MAX_PACKET_SIZE;
4571 if (tSize < RX_MIN_PACKET_SIZE)
4572 tSize = RX_MIN_PACKET_SIZE;
4573 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4575 /* Get the maximum packet size to send to this peer */
4576 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4578 tSize = (afs_uint32) ntohl(tSize);
4579 if (tSize > RX_MAX_PACKET_SIZE)
4580 tSize = RX_MAX_PACKET_SIZE;
4581 if (tSize < RX_MIN_PACKET_SIZE)
4582 tSize = RX_MIN_PACKET_SIZE;
4583 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4584 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4586 /* sanity check - peer might have restarted with different params.
4587 * If peer says "send less", dammit, send less... Peer should never
4588 * be unable to accept packets of the size that prior AFS versions would
4589 * send without asking. */
4590 if (peer->maxMTU != tSize) {
4591 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4593 peer->maxMTU = tSize;
4594 peer->MTU = MIN(tSize, peer->MTU);
4595 call->MTU = MIN(call->MTU, tSize);
4598 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4601 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4602 (int)sizeof(afs_int32), &tSize);
4603 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4606 if (tSize >= rx_maxSendWindow)
4607 tSize = rx_maxSendWindow;
4608 if (tSize < call->twind) { /* smaller than our send */
4609 call->twind = tSize; /* window, we must send less... */
4610 call->ssthresh = MIN(call->twind, call->ssthresh);
4611 call->conn->twind[call->channel] = call->twind;
4614 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4615 * network MTU confused with the loopback MTU. Calculate the
4616 * maximum MTU here for use in the slow start code below.
4618 /* Did peer restart with older RX version? */
4619 if (peer->maxDgramPackets > 1) {
4620 peer->maxDgramPackets = 1;
4622 } else if (np->length >=
4623 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4626 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4627 sizeof(afs_int32), &tSize);
4628 tSize = (afs_uint32) ntohl(tSize);
4631 if (tSize >= rx_maxSendWindow)
4632 tSize = rx_maxSendWindow;
4634 * As of AFS 3.5 we set the send window to match the receive window.
4636 if (tSize < call->twind) {
4637 call->twind = tSize;
4638 call->conn->twind[call->channel] = call->twind;
4639 call->ssthresh = MIN(call->twind, call->ssthresh);
4640 } else if (tSize > call->twind) {
4641 call->twind = tSize;
4642 call->conn->twind[call->channel] = call->twind;
4646 * As of AFS 3.5, a jumbogram is more than one fixed size
4647 * packet transmitted in a single UDP datagram. If the remote
4648 * MTU is smaller than our local MTU then never send a datagram
4649 * larger than the natural MTU.
4652 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4653 (int)sizeof(afs_int32), &tSize);
4654 maxDgramPackets = (afs_uint32) ntohl(tSize);
4655 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4657 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4658 if (maxDgramPackets > 1) {
4659 peer->maxDgramPackets = maxDgramPackets;
4660 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4662 peer->maxDgramPackets = 1;
4663 call->MTU = peer->natMTU;
4665 } else if (peer->maxDgramPackets > 1) {
4666 /* Restarted with lower version of RX */
4667 peer->maxDgramPackets = 1;
4669 } else if (peer->maxDgramPackets > 1
4670 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4671 /* Restarted with lower version of RX */
4672 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4673 peer->natMTU = OLD_MAX_PACKET_SIZE;
4674 peer->MTU = OLD_MAX_PACKET_SIZE;
4675 peer->maxDgramPackets = 1;
4676 peer->nDgramPackets = 1;
4678 call->MTU = OLD_MAX_PACKET_SIZE;
4681 /* If the window has been extended by this acknowledge packet,
4682 * then wakeup a sender waiting in alloc for window space, or try
4683 * sending packets now, if he's been sitting on packets due to
4684 * lack of window space */
4685 if (call->tnext < (call->tfirst + call->twind)) {
4686 #ifdef RX_ENABLE_LOCKS
4687 CV_SIGNAL(&call->cv_twind);
4689 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4690 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4691 osi_rxWakeup(&call->twind);
4694 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4695 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4701 * Calculate how many datagrams were successfully received after
4702 * the first missing packet and adjust the negative ack counter
4707 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4708 if (call->nNacks < nNacked) {
4709 call->nNacks = nNacked;
4712 call->nAcks += newAckCount;
4716 /* If the packet contained new acknowledgements, rather than just
4717 * being a duplicate of one we have previously seen, then we can restart
4720 if (newAckCount > 0)
4721 rxi_rto_packet_acked(call, istack);
4723 if (call->flags & RX_CALL_FAST_RECOVER) {
4724 if (newAckCount == 0) {
4725 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4727 call->flags &= ~RX_CALL_FAST_RECOVER;
4728 call->cwind = call->nextCwind;
4729 call->nextCwind = 0;
4732 call->nCwindAcks = 0;
4733 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4734 /* Three negative acks in a row trigger congestion recovery */
4735 call->flags |= RX_CALL_FAST_RECOVER;
4736 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4738 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4739 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4740 call->nextCwind = call->ssthresh;
4743 peer->MTU = call->MTU;
4744 peer->cwind = call->nextCwind;
4745 peer->nDgramPackets = call->nDgramPackets;
4747 call->congestSeq = peer->congestSeq;
4749 /* Reset the resend times on the packets that were nacked
4750 * so we will retransmit as soon as the window permits
4754 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4755 struct rx_packet *tp =
4756 opr_queue_Entry(cursor, struct rx_packet, entry);
4758 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4759 tp->flags &= ~RX_PKTFLAG_SENT;
4761 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4766 /* If cwind is smaller than ssthresh, then increase
4767 * the window one packet for each ack we receive (exponential
4769 * If cwind is greater than or equal to ssthresh then increase
4770 * the congestion window by one packet for each cwind acks we
4771 * receive (linear growth). */
4772 if (call->cwind < call->ssthresh) {
4774 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4775 call->nCwindAcks = 0;
4777 call->nCwindAcks += newAckCount;
4778 if (call->nCwindAcks >= call->cwind) {
4779 call->nCwindAcks = 0;
4780 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4784 * If we have received several acknowledgements in a row then
4785 * it is time to increase the size of our datagrams
4787 if ((int)call->nAcks > rx_nDgramThreshold) {
4788 if (peer->maxDgramPackets > 1) {
4789 if (call->nDgramPackets < peer->maxDgramPackets) {
4790 call->nDgramPackets++;
4792 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4793 } else if (call->MTU < peer->maxMTU) {
4794 /* don't upgrade if we can't handle it */
4795 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4796 call->MTU = peer->ifMTU;
4798 call->MTU += peer->natMTU;
4799 call->MTU = MIN(call->MTU, peer->maxMTU);
4806 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4808 /* Servers need to hold the call until all response packets have
4809 * been acknowledged. Soft acks are good enough since clients
4810 * are not allowed to clear their receive queues. */
4811 if (call->state == RX_STATE_HOLD
4812 && call->tfirst + call->nSoftAcked >= call->tnext) {
4813 call->state = RX_STATE_DALLY;
4814 rxi_ClearTransmitQueue(call, 0);
4815 rxi_CancelKeepAliveEvent(call);
4816 } else if (!opr_queue_IsEmpty(&call->tq)) {
4817 rxi_Start(call, istack);
4823 * Schedule a connection abort to be sent after some delay.
4825 * @param[in] conn The connection to send the abort on.
4826 * @param[in] msec The number of milliseconds to wait before sending.
4828 * @pre conn_data_lock must be held
4831 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4833 struct clock when, now;
4835 MUTEX_ASSERT(&conn->conn_data_lock);
4839 if (!conn->delayedAbortEvent) {
4840 clock_GetTime(&now);
4842 clock_Addmsec(&when, msec);
4843 rx_GetConnection(conn);
4844 conn->delayedAbortEvent =
4845 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4849 /* Received a response to a challenge packet */
4850 static struct rx_packet *
4851 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4852 struct rx_packet *np, int istack)
4856 /* Ignore the packet if we're the client */
4857 if (conn->type == RX_CLIENT_CONNECTION)
4860 /* If already authenticated, ignore the packet (it's probably a retry) */
4861 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4864 if (!conn->securityChallengeSent) {
4865 /* We've never sent out a challenge for this connection, so this
4866 * response cannot possibly be correct; ignore it. This can happen
4867 * if we sent a challenge to the client, then we were restarted, and
4868 * then the client sent us a response. If we ignore the response, the
4869 * client will eventually resend a data packet, causing us to send a
4870 * new challenge and the client to send a new response. */
4874 /* Otherwise, have the security object evaluate the response packet */
4875 error = RXS_CheckResponse(conn->securityObject, conn, np);
4877 /* If the response is invalid, reset the connection, sending
4878 * an abort to the peer. Send the abort with a 1 second delay,
4879 * to avoid a peer hammering us by constantly recreating a
4880 * connection with bad credentials. */
4881 rxi_ConnectionError(conn, error);
4882 MUTEX_ENTER(&conn->conn_data_lock);
4883 rxi_SendConnectionAbortLater(conn, 1000);
4884 MUTEX_EXIT(&conn->conn_data_lock);
4887 /* If the response is valid, any calls waiting to attach
4888 * servers can now do so */
4891 for (i = 0; i < RX_MAXCALLS; i++) {
4892 struct rx_call *call = conn->call[i];
4894 MUTEX_ENTER(&call->lock);
4895 if (call->state == RX_STATE_PRECALL)
4896 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4897 /* tnop can be null if newcallp is null */
4898 MUTEX_EXIT(&call->lock);
4902 /* Update the peer reachability information, just in case
4903 * some calls went into attach-wait while we were waiting
4904 * for authentication..
4906 rxi_UpdatePeerReach(conn, NULL, istack);
4911 /* A client has received an authentication challenge: the security
4912 * object is asked to cough up a respectable response packet to send
4913 * back to the server. The server is responsible for retrying the
4914 * challenge if it fails to get a response. */
4916 static struct rx_packet *
4917 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4918 struct rx_packet *np, int istack)
4922 /* Ignore the challenge if we're the server */
4923 if (conn->type == RX_SERVER_CONNECTION)
4926 /* Ignore the challenge if the connection is otherwise idle; someone's
4927 * trying to use us as an oracle. */
4928 if (!rxi_HasActiveCalls(conn))
4931 /* Send the security object the challenge packet. It is expected to fill
4932 * in the response. */
4933 error = RXS_GetResponse(conn->securityObject, conn, np);
4935 /* If the security object is unable to return a valid response, reset the
4936 * connection and send an abort to the peer. Otherwise send the response
4937 * packet to the peer connection. */
4939 rxi_ConnectionError(conn, error);
4940 MUTEX_ENTER(&conn->conn_data_lock);
4941 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4942 MUTEX_EXIT(&conn->conn_data_lock);
4944 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4945 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4951 /* Find an available server process to service the current request in
4952 * the given call structure. If one isn't available, queue up this
4953 * call so it eventually gets one */
4955 rxi_AttachServerProc(struct rx_call *call,
4956 osi_socket socket, int *tnop,
4957 struct rx_call **newcallp)
4959 struct rx_serverQueueEntry *sq;
4960 struct rx_service *service = call->conn->service;
4963 /* May already be attached */
4964 if (call->state == RX_STATE_ACTIVE)
4967 MUTEX_ENTER(&rx_serverPool_lock);
4969 haveQuota = QuotaOK(service);
4970 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4971 /* If there are no processes available to service this call,
4972 * put the call on the incoming call queue (unless it's
4973 * already on the queue).
4975 #ifdef RX_ENABLE_LOCKS
4977 ReturnToServerPool(service);
4978 #endif /* RX_ENABLE_LOCKS */
4980 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4981 call->flags |= RX_CALL_WAIT_PROC;
4982 rx_atomic_inc(&rx_nWaiting);
4983 rx_atomic_inc(&rx_nWaited);
4984 rxi_calltrace(RX_CALL_ARRIVAL, call);
4985 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4986 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4989 sq = opr_queue_Last(&rx_idleServerQueue,
4990 struct rx_serverQueueEntry, entry);
4992 /* If hot threads are enabled, and both newcallp and sq->socketp
4993 * are non-null, then this thread will process the call, and the
4994 * idle server thread will start listening on this threads socket.
4996 opr_queue_Remove(&sq->entry);
4998 if (rx_enable_hot_thread && newcallp && sq->socketp) {
5001 *sq->socketp = socket;
5002 clock_GetTime(&call->startTime);
5003 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
5007 if (call->flags & RX_CALL_WAIT_PROC) {
5008 /* Conservative: I don't think this should happen */
5009 call->flags &= ~RX_CALL_WAIT_PROC;
5010 rx_atomic_dec(&rx_nWaiting);
5011 if (opr_queue_IsOnQueue(&call->entry)) {
5012 opr_queue_Remove(&call->entry);
5014 CLEAR_CALL_QUEUE_LOCK(call);
5016 call->state = RX_STATE_ACTIVE;
5017 call->app.mode = RX_MODE_RECEIVING;
5018 #ifdef RX_KERNEL_TRACE
5020 int glockOwner = ISAFS_GLOCK();
5023 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
5024 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
5030 if (call->flags & RX_CALL_CLEARED) {
5031 /* send an ack now to start the packet flow up again */
5032 call->flags &= ~RX_CALL_CLEARED;
5033 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5035 #ifdef RX_ENABLE_LOCKS
5038 service->nRequestsRunning++;
5039 MUTEX_ENTER(&rx_quota_mutex);
5040 if (service->nRequestsRunning <= service->minProcs)
5043 MUTEX_EXIT(&rx_quota_mutex);
5047 MUTEX_EXIT(&rx_serverPool_lock);
5050 /* Delay the sending of an acknowledge event for a short while, while
5051 * a new call is being prepared (in the case of a client) or a reply
5052 * is being prepared (in the case of a server). Rather than sending
5053 * an ack packet, an ACKALL packet is sent. */
5055 rxi_AckAll(struct rx_call *call)
5057 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
5059 call->flags |= RX_CALL_ACKALL_SENT;
5063 * Event handler for per-call delayed acks.
5064 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5068 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5071 struct rx_call *call = arg1;
5072 #ifdef RX_ENABLE_LOCKS
5074 MUTEX_ENTER(&call->lock);
5075 if (event == call->delayedAckEvent)
5076 rxevent_Put(&call->delayedAckEvent);
5078 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5080 MUTEX_EXIT(&call->lock);
5081 #else /* RX_ENABLE_LOCKS */
5083 rxevent_Put(&call->delayedAckEvent);
5084 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5085 #endif /* RX_ENABLE_LOCKS */
5086 /* Release the call reference for the event that fired. */
5088 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5091 #ifdef RX_ENABLE_LOCKS
5092 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5093 * clearing them out.
5096 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5098 struct opr_queue *cursor;
5101 for (opr_queue_Scan(&call->tq, cursor)) {
5103 = opr_queue_Entry(cursor, struct rx_packet, entry);
5105 p->flags |= RX_PKTFLAG_ACKED;
5110 call->flags |= RX_CALL_TQ_CLEARME;
5111 call->flags |= RX_CALL_TQ_SOME_ACKED;
5114 rxi_rto_cancel(call);
5116 call->tfirst = call->tnext;
5117 call->nSoftAcked = 0;
5119 if (call->flags & RX_CALL_FAST_RECOVER) {
5120 call->flags &= ~RX_CALL_FAST_RECOVER;
5121 call->cwind = call->nextCwind;
5122 call->nextCwind = 0;
5125 CV_SIGNAL(&call->cv_twind);
5127 #endif /* RX_ENABLE_LOCKS */
5130 * Acknowledge the whole transmit queue.
5132 * If we're running without locks, or the transmit queue isn't busy, then
5133 * we can just clear the queue now. Otherwise, we have to mark all of the
5134 * packets as acknowledged, and let rxi_Start clear it later on
5137 rxi_AckAllInTransmitQueue(struct rx_call *call)
5139 #ifdef RX_ENABLE_LOCKS
5140 if (call->flags & RX_CALL_TQ_BUSY) {
5141 rxi_SetAcksInTransmitQueue(call);
5145 rxi_ClearTransmitQueue(call, 0);
5147 /* Clear out the transmit queue for the current call (all packets have
5148 * been received by peer) */
5150 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5152 #ifdef RX_ENABLE_LOCKS
5153 struct opr_queue *cursor;
5154 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5156 for (opr_queue_Scan(&call->tq, cursor)) {
5158 = opr_queue_Entry(cursor, struct rx_packet, entry);
5160 p->flags |= RX_PKTFLAG_ACKED;
5164 call->flags |= RX_CALL_TQ_CLEARME;
5165 call->flags |= RX_CALL_TQ_SOME_ACKED;
5168 #endif /* RX_ENABLE_LOCKS */
5169 #ifdef RXDEBUG_PACKET
5171 #endif /* RXDEBUG_PACKET */
5172 rxi_FreePackets(0, &call->tq);
5173 rxi_WakeUpTransmitQueue(call);
5174 #ifdef RX_ENABLE_LOCKS
5175 call->flags &= ~RX_CALL_TQ_CLEARME;
5179 rxi_rto_cancel(call);
5180 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5181 call->nSoftAcked = 0;
5183 if (call->flags & RX_CALL_FAST_RECOVER) {
5184 call->flags &= ~RX_CALL_FAST_RECOVER;
5185 call->cwind = call->nextCwind;
5187 #ifdef RX_ENABLE_LOCKS
5188 CV_SIGNAL(&call->cv_twind);
5190 osi_rxWakeup(&call->twind);
5195 rxi_ClearReceiveQueue(struct rx_call *call)
5197 if (!opr_queue_IsEmpty(&call->rq)) {
5200 count = rxi_FreePackets(0, &call->rq);
5201 rx_packetReclaims += count;
5202 #ifdef RXDEBUG_PACKET
5204 if ( call->rqc != 0 )
5205 dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5207 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5209 if (call->state == RX_STATE_PRECALL) {
5210 call->flags |= RX_CALL_CLEARED;
5214 /* Send an abort packet for the specified call */
5215 static struct rx_packet *
5216 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5217 int istack, int force)
5220 struct clock when, now;
5225 /* Clients should never delay abort messages */
5226 if (rx_IsClientConn(call->conn))
5230 * An opcode that has been deprecated or has yet to be implemented is not
5231 * a misbehavior of the client. Do not punish the client by introducing
5234 if (call->error == RXGEN_OPCODE) {
5236 } else if (call->abortCode != call->error) {
5237 call->abortCode = call->error;
5238 call->abortCount = 0;
5241 if (force || rxi_callAbortThreshhold == 0
5242 || call->abortCount < rxi_callAbortThreshhold) {
5243 rxi_CancelDelayedAbortEvent(call);
5244 error = htonl(call->error);
5248 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5249 (char *)&error, sizeof(error), istack);
5250 } else if (!call->delayedAbortEvent) {
5251 clock_GetTime(&now);
5253 clock_Addmsec(&when, rxi_callAbortDelay);
5254 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5255 call->delayedAbortEvent =
5256 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5262 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5264 MUTEX_ASSERT(&call->lock);
5265 if (rxevent_Cancel(&call->delayedAbortEvent))
5266 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5269 /* Send an abort packet for the specified connection. Packet is an
5270 * optional pointer to a packet that can be used to send the abort.
5271 * Once the number of abort messages reaches the threshhold, an
5272 * event is scheduled to send the abort. Setting the force flag
5273 * overrides sending delayed abort messages.
5275 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5276 * to send the abort packet.
5279 rxi_SendConnectionAbort(struct rx_connection *conn,
5280 struct rx_packet *packet, int istack, int force)
5287 /* Clients should never delay abort messages */
5288 if (rx_IsClientConn(conn))
5291 if (force || rxi_connAbortThreshhold == 0
5292 || conn->abortCount < rxi_connAbortThreshhold) {
5294 if (rxevent_Cancel(&conn->delayedAbortEvent))
5295 putConnection(conn);
5296 error = htonl(conn->error);
5298 MUTEX_EXIT(&conn->conn_data_lock);
5300 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5301 RX_PACKET_TYPE_ABORT, (char *)&error,
5302 sizeof(error), istack);
5303 MUTEX_ENTER(&conn->conn_data_lock);
5305 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5310 /* Associate an error all of the calls owned by a connection. Called
5311 * with error non-zero. This is only for really fatal things, like
5312 * bad authentication responses. The connection itself is set in
5313 * error at this point, so that future packets received will be
5316 rxi_ConnectionError(struct rx_connection *conn,
5322 dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5324 MUTEX_ENTER(&conn->conn_data_lock);
5325 if (rxevent_Cancel(&conn->challengeEvent))
5326 putConnection(conn);
5327 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5328 putConnection(conn);
5329 if (rxevent_Cancel(&conn->checkReachEvent)) {
5330 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5331 putConnection(conn);
5333 MUTEX_EXIT(&conn->conn_data_lock);
5334 for (i = 0; i < RX_MAXCALLS; i++) {
5335 struct rx_call *call = conn->call[i];
5337 MUTEX_ENTER(&call->lock);
5338 rxi_CallError(call, error);
5339 MUTEX_EXIT(&call->lock);
5342 conn->error = error;
5343 if (rx_stats_active)
5344 rx_atomic_inc(&rx_stats.fatalErrors);
5349 * Interrupt an in-progress call with the specified error and wakeup waiters.
5351 * @param[in] call The call to interrupt
5352 * @param[in] error The error code to send to the peer
5355 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5357 MUTEX_ENTER(&call->lock);
5358 rxi_CallError(call, error);
5359 rxi_SendCallAbort(call, NULL, 0, 1);
5360 MUTEX_EXIT(&call->lock);
5364 rxi_CallError(struct rx_call *call, afs_int32 error)
5366 MUTEX_ASSERT(&call->lock);
5367 dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5369 error = call->error;
5371 #ifdef RX_ENABLE_LOCKS
5372 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5373 rxi_ResetCall(call, 0);
5376 rxi_ResetCall(call, 0);
5378 call->error = error;
5381 /* Reset various fields in a call structure, and wakeup waiting
5382 * processes. Some fields aren't changed: state & mode are not
5383 * touched (these must be set by the caller), and bufptr, nLeft, and
5384 * nFree are not reset, since these fields are manipulated by
5385 * unprotected macros, and may only be reset by non-interrupting code.
5389 rxi_ResetCall(struct rx_call *call, int newcall)
5392 struct rx_peer *peer;
5393 struct rx_packet *packet;
5395 MUTEX_ASSERT(&call->lock);
5396 dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5398 /* Notify anyone who is waiting for asynchronous packet arrival */
5399 if (call->arrivalProc) {
5400 (*call->arrivalProc) (call, call->arrivalProcHandle,
5401 call->arrivalProcArg);
5402 call->arrivalProc = NULL;
5406 rxi_CancelGrowMTUEvent(call);
5408 if (call->delayedAbortEvent) {
5409 rxi_CancelDelayedAbortEvent(call);
5410 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5412 rxi_SendCallAbort(call, packet, 0, 1);
5413 rxi_FreePacket(packet);
5418 * Update the peer with the congestion information in this call
5419 * so other calls on this connection can pick up where this call
5420 * left off. If the congestion sequence numbers don't match then
5421 * another call experienced a retransmission.
5423 peer = call->conn->peer;
5424 MUTEX_ENTER(&peer->peer_lock);
5426 if (call->congestSeq == peer->congestSeq) {
5427 peer->cwind = MAX(peer->cwind, call->cwind);
5428 peer->MTU = MAX(peer->MTU, call->MTU);
5429 peer->nDgramPackets =
5430 MAX(peer->nDgramPackets, call->nDgramPackets);
5433 call->abortCode = 0;
5434 call->abortCount = 0;
5436 if (peer->maxDgramPackets > 1) {
5437 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5439 call->MTU = peer->MTU;
5441 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5442 call->ssthresh = rx_maxSendWindow;
5443 call->nDgramPackets = peer->nDgramPackets;
5444 call->congestSeq = peer->congestSeq;
5445 call->rtt = peer->rtt;
5446 call->rtt_dev = peer->rtt_dev;
5447 clock_Zero(&call->rto);
5448 clock_Addmsec(&call->rto,
5449 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5450 MUTEX_EXIT(&peer->peer_lock);
5452 flags = call->flags;
5453 rxi_WaitforTQBusy(call);
5455 rxi_ClearTransmitQueue(call, 1);
5456 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5457 dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5461 rxi_ClearReceiveQueue(call);
5462 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5466 call->twind = call->conn->twind[call->channel];
5467 call->rwind = call->conn->rwind[call->channel];
5468 call->nSoftAcked = 0;
5469 call->nextCwind = 0;
5472 call->nCwindAcks = 0;
5473 call->nSoftAcks = 0;
5474 call->nHardAcks = 0;
5476 call->tfirst = call->rnext = call->tnext = 1;
5479 call->lastAcked = 0;
5480 call->localStatus = call->remoteStatus = 0;
5482 if (flags & RX_CALL_READER_WAIT) {
5483 #ifdef RX_ENABLE_LOCKS
5484 CV_BROADCAST(&call->cv_rq);
5486 osi_rxWakeup(&call->rq);
5489 if (flags & RX_CALL_WAIT_PACKETS) {
5490 MUTEX_ENTER(&rx_freePktQ_lock);
5491 rxi_PacketsUnWait(); /* XXX */
5492 MUTEX_EXIT(&rx_freePktQ_lock);
5494 #ifdef RX_ENABLE_LOCKS
5495 CV_SIGNAL(&call->cv_twind);
5497 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5498 osi_rxWakeup(&call->twind);
5501 if (flags & RX_CALL_WAIT_PROC) {
5502 rx_atomic_dec(&rx_nWaiting);
5504 #ifdef RX_ENABLE_LOCKS
5505 /* The following ensures that we don't mess with any queue while some
5506 * other thread might also be doing so. The call_queue_lock field is
5507 * is only modified under the call lock. If the call is in the process
5508 * of being removed from a queue, the call is not locked until the
5509 * the queue lock is dropped and only then is the call_queue_lock field
5510 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5511 * Note that any other routine which removes a call from a queue has to
5512 * obtain the queue lock before examing the queue and removing the call.
5514 if (call->call_queue_lock) {
5515 MUTEX_ENTER(call->call_queue_lock);
5516 if (opr_queue_IsOnQueue(&call->entry)) {
5517 opr_queue_Remove(&call->entry);
5519 MUTEX_EXIT(call->call_queue_lock);
5520 CLEAR_CALL_QUEUE_LOCK(call);
5522 #else /* RX_ENABLE_LOCKS */
5523 if (opr_queue_IsOnQueue(&call->entry)) {
5524 opr_queue_Remove(&call->entry);
5526 #endif /* RX_ENABLE_LOCKS */
5528 rxi_CancelKeepAliveEvent(call);
5529 rxi_CancelDelayedAckEvent(call);
5532 /* Send an acknowledge for the indicated packet (seq,serial) of the
5533 * indicated call, for the indicated reason (reason). This
5534 * acknowledge will specifically acknowledge receiving the packet, and
5535 * will also specify which other packets for this call have been
5536 * received. This routine returns the packet that was used to the
5537 * caller. The caller is responsible for freeing it or re-using it.
5538 * This acknowledgement also returns the highest sequence number
5539 * actually read out by the higher level to the sender; the sender
5540 * promises to keep around packets that have not been read by the
5541 * higher level yet (unless, of course, the sender decides to abort
5542 * the call altogether). Any of p, seq, serial, pflags, or reason may
5543 * be set to zero without ill effect. That is, if they are zero, they
5544 * will not convey any information.
5545 * NOW there is a trailer field, after the ack where it will safely be
5546 * ignored by mundanes, which indicates the maximum size packet this
5547 * host can swallow. */
5549 struct rx_packet *optionalPacket; use to send ack (or null)
5550 int seq; Sequence number of the packet we are acking
5551 int serial; Serial number of the packet
5552 int pflags; Flags field from packet header
5553 int reason; Reason an acknowledge was prompted
5556 #define RX_ZEROS 1024
5557 static char rx_zeros[RX_ZEROS];
5560 rxi_SendAck(struct rx_call *call,
5561 struct rx_packet *optionalPacket, int serial, int reason,
5564 struct rx_ackPacket *ap;
5565 struct rx_packet *p;
5566 struct opr_queue *cursor;
5569 afs_uint32 padbytes = 0;
5570 #ifdef RX_ENABLE_TSFPQ
5571 struct rx_ts_info_t * rx_ts_info;
5575 * Open the receive window once a thread starts reading packets
5577 if (call->rnext > 1) {
5578 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5581 /* Don't attempt to grow MTU if this is a critical ping */
5582 if (reason == RX_ACK_MTU) {
5583 /* keep track of per-call attempts, if we're over max, do in small
5584 * otherwise in larger? set a size to increment by, decrease
5587 if (call->conn->peer->maxPacketSize &&
5588 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5590 padbytes = call->conn->peer->maxPacketSize+16;
5592 padbytes = call->conn->peer->maxMTU + 128;
5594 /* do always try a minimum size ping */
5595 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5597 /* subtract the ack payload */
5598 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5599 reason = RX_ACK_PING;
5602 call->nHardAcks = 0;
5603 call->nSoftAcks = 0;
5604 if (call->rnext > call->lastAcked)
5605 call->lastAcked = call->rnext;
5609 rx_computelen(p, p->length); /* reset length, you never know */
5610 } /* where that's been... */
5611 #ifdef RX_ENABLE_TSFPQ
5613 RX_TS_INFO_GET(rx_ts_info);
5614 if ((p = rx_ts_info->local_special_packet)) {
5615 rx_computelen(p, p->length);
5616 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5617 rx_ts_info->local_special_packet = p;
5618 } else { /* We won't send the ack, but don't panic. */
5619 return optionalPacket;
5623 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5624 /* We won't send the ack, but don't panic. */
5625 return optionalPacket;
5630 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5633 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5634 #ifndef RX_ENABLE_TSFPQ
5635 if (!optionalPacket)
5638 return optionalPacket;
5640 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5641 if (rx_Contiguous(p) < templ) {
5642 #ifndef RX_ENABLE_TSFPQ
5643 if (!optionalPacket)
5646 return optionalPacket;
5651 /* MTUXXX failing to send an ack is very serious. We should */
5652 /* try as hard as possible to send even a partial ack; it's */
5653 /* better than nothing. */
5654 ap = (struct rx_ackPacket *)rx_DataOf(p);
5655 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5656 ap->reason = reason;
5658 /* The skew computation used to be bogus, I think it's better now. */
5659 /* We should start paying attention to skew. XXX */
5660 ap->serial = htonl(serial);
5661 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5664 * First packet not yet forwarded to reader. When ACKALL has been
5665 * sent the peer has been told that all received packets will be
5666 * delivered to the reader. The value 'rnext' is used internally
5667 * to refer to the next packet in the receive queue that must be
5668 * delivered to the reader. From the perspective of the peer it
5669 * already has so report the last sequence number plus one if there
5670 * are packets in the receive queue awaiting processing.
5672 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5673 !opr_queue_IsEmpty(&call->rq)) {
5674 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5676 ap->firstPacket = htonl(call->rnext);
5678 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5680 /* No fear of running out of ack packet here because there can only
5681 * be at most one window full of unacknowledged packets. The window
5682 * size must be constrained to be less than the maximum ack size,
5683 * of course. Also, an ack should always fit into a single packet
5684 * -- it should not ever be fragmented. */
5686 for (opr_queue_Scan(&call->rq, cursor)) {
5687 struct rx_packet *rqp
5688 = opr_queue_Entry(cursor, struct rx_packet, entry);
5690 if (!rqp || !call->rq.next
5691 || (rqp->header.seq > (call->rnext + call->rwind))) {
5692 #ifndef RX_ENABLE_TSFPQ
5693 if (!optionalPacket)
5696 rxi_CallError(call, RX_CALL_DEAD);
5697 return optionalPacket;
5700 while (rqp->header.seq > call->rnext + offset)
5701 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5702 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5704 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5705 #ifndef RX_ENABLE_TSFPQ
5706 if (!optionalPacket)
5709 rxi_CallError(call, RX_CALL_DEAD);
5710 return optionalPacket;
5716 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5718 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5721 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5723 /* these are new for AFS 3.3 */
5724 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5725 templ = htonl(templ);
5726 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5727 templ = htonl(call->conn->peer->ifMTU);
5728 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5729 sizeof(afs_int32), &templ);
5731 /* new for AFS 3.4 */
5732 templ = htonl(call->rwind);
5733 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5734 sizeof(afs_int32), &templ);
5736 /* new for AFS 3.5 */
5737 templ = htonl(call->conn->peer->ifDgramPackets);
5738 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5739 sizeof(afs_int32), &templ);
5741 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5743 p->header.serviceId = call->conn->serviceId;
5744 p->header.cid = (call->conn->cid | call->channel);
5745 p->header.callNumber = *call->callNumber;
5747 p->header.securityIndex = call->conn->securityIndex;
5748 p->header.epoch = call->conn->epoch;
5749 p->header.type = RX_PACKET_TYPE_ACK;
5750 p->header.flags = RX_SLOW_START_OK;
5751 if (reason == RX_ACK_PING)
5752 p->header.flags |= RX_REQUEST_ACK;
5754 while (padbytes > 0) {
5755 if (padbytes > RX_ZEROS) {
5756 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5757 p->length += RX_ZEROS;
5758 padbytes -= RX_ZEROS;
5760 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5761 p->length += padbytes;
5766 if (call->conn->type == RX_CLIENT_CONNECTION)
5767 p->header.flags |= RX_CLIENT_INITIATED;
5771 if (rxdebug_active) {
5775 len = _snprintf(msg, sizeof(msg),
5776 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5777 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5778 ntohl(ap->serial), ntohl(ap->previousPacket),
5779 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5780 ap->nAcks, ntohs(ap->bufferSpace) );
5784 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5785 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5789 OutputDebugString(msg);
5791 #else /* AFS_NT40_ENV */
5793 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5794 ap->reason, ntohl(ap->previousPacket),
5795 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5797 for (offset = 0; offset < ap->nAcks; offset++)
5798 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5803 #endif /* AFS_NT40_ENV */
5806 int i, nbytes = p->length;
5808 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5809 if (nbytes <= p->wirevec[i].iov_len) {
5812 savelen = p->wirevec[i].iov_len;
5814 p->wirevec[i].iov_len = nbytes;
5816 rxi_Send(call, p, istack);
5817 p->wirevec[i].iov_len = savelen;
5821 nbytes -= p->wirevec[i].iov_len;
5824 if (rx_stats_active)
5825 rx_atomic_inc(&rx_stats.ackPacketsSent);
5826 #ifndef RX_ENABLE_TSFPQ
5827 if (!optionalPacket)
5830 return optionalPacket; /* Return packet for re-use by caller */
5834 struct rx_packet **list;
5839 /* Send all of the packets in the list in single datagram */
5841 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5842 int istack, int moreFlag)
5848 struct rx_connection *conn = call->conn;
5849 struct rx_peer *peer = conn->peer;
5851 MUTEX_ENTER(&peer->peer_lock);
5852 peer->nSent += xmit->len;
5853 if (xmit->resending)
5854 peer->reSends += xmit->len;
5855 MUTEX_EXIT(&peer->peer_lock);
5857 if (rx_stats_active) {
5858 if (xmit->resending)
5859 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5861 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5864 clock_GetTime(&now);
5866 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5870 /* Set the packet flags and schedule the resend events */
5871 /* Only request an ack for the last packet in the list */
5872 for (i = 0; i < xmit->len; i++) {
5873 struct rx_packet *packet = xmit->list[i];
5875 /* Record the time sent */
5876 packet->timeSent = now;
5877 packet->flags |= RX_PKTFLAG_SENT;
5879 /* Ask for an ack on retransmitted packets, on every other packet
5880 * if the peer doesn't support slow start. Ask for an ack on every
5881 * packet until the congestion window reaches the ack rate. */
5882 if (packet->header.serial) {
5885 packet->firstSent = now;
5886 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5887 || (!(call->flags & RX_CALL_SLOW_START_OK)
5888 && (packet->header.seq & 1)))) {
5893 /* Tag this packet as not being the last in this group,
5894 * for the receiver's benefit */
5895 if (i < xmit->len - 1 || moreFlag) {
5896 packet->header.flags |= RX_MORE_PACKETS;
5901 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5904 /* Since we're about to send a data packet to the peer, it's
5905 * safe to nuke any scheduled end-of-packets ack */
5906 rxi_CancelDelayedAckEvent(call);
5908 MUTEX_EXIT(&call->lock);
5909 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5910 if (xmit->len > 1) {
5911 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5913 rxi_SendPacket(call, conn, xmit->list[0], istack);
5915 MUTEX_ENTER(&call->lock);
5916 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5918 /* Tell the RTO calculation engine that we have sent a packet, and
5919 * if it was the last one */
5920 rxi_rto_packet_sent(call, lastPacket, istack);
5922 /* Update last send time for this call (for keep-alive
5923 * processing), and for the connection (so that we can discover
5924 * idle connections) */
5925 conn->lastSendTime = call->lastSendTime = clock_Sec();
5928 /* When sending packets we need to follow these rules:
5929 * 1. Never send more than maxDgramPackets in a jumbogram.
5930 * 2. Never send a packet with more than two iovecs in a jumbogram.
5931 * 3. Never send a retransmitted packet in a jumbogram.
5932 * 4. Never send more than cwind/4 packets in a jumbogram
5933 * We always keep the last list we should have sent so we
5934 * can set the RX_MORE_PACKETS flags correctly.
5938 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5943 struct xmitlist working;
5944 struct xmitlist last;
5946 struct rx_peer *peer = call->conn->peer;
5947 int morePackets = 0;
5949 memset(&last, 0, sizeof(struct xmitlist));
5950 working.list = &list[0];
5952 working.resending = 0;
5954 recovery = call->flags & RX_CALL_FAST_RECOVER;
5956 for (i = 0; i < len; i++) {
5957 /* Does the current packet force us to flush the current list? */
5959 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5960 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5962 /* This sends the 'last' list and then rolls the current working
5963 * set into the 'last' one, and resets the working set */
5966 rxi_SendList(call, &last, istack, 1);
5967 /* If the call enters an error state stop sending, or if
5968 * we entered congestion recovery mode, stop sending */
5970 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5975 working.resending = 0;
5976 working.list = &list[i];
5978 /* Add the current packet to the list if it hasn't been acked.
5979 * Otherwise adjust the list pointer to skip the current packet. */
5980 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5983 if (list[i]->header.serial)
5984 working.resending = 1;
5986 /* Do we need to flush the list? */
5987 if (working.len >= (int)peer->maxDgramPackets
5988 || working.len >= (int)call->nDgramPackets
5989 || working.len >= (int)call->cwind
5990 || list[i]->header.serial
5991 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5993 rxi_SendList(call, &last, istack, 1);
5994 /* If the call enters an error state stop sending, or if
5995 * we entered congestion recovery mode, stop sending */
5997 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6002 working.resending = 0;
6003 working.list = &list[i + 1];
6006 if (working.len != 0) {
6007 osi_Panic("rxi_SendList error");
6009 working.list = &list[i + 1];
6013 /* Send the whole list when the call is in receive mode, when
6014 * the call is in eof mode, when we are in fast recovery mode,
6015 * and when we have the last packet */
6016 /* XXX - The accesses to app.mode aren't safe, as this may be called by
6017 * the listener or event threads
6019 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
6020 || (call->flags & RX_CALL_FLUSH)
6021 || (call->flags & RX_CALL_FAST_RECOVER)) {
6022 /* Check for the case where the current list contains
6023 * an acked packet. Since we always send retransmissions
6024 * in a separate packet, we only need to check the first
6025 * packet in the list */
6026 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
6030 rxi_SendList(call, &last, istack, morePackets);
6031 /* If the call enters an error state stop sending, or if
6032 * we entered congestion recovery mode, stop sending */
6034 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6038 rxi_SendList(call, &working, istack, 0);
6040 } else if (last.len > 0) {
6041 rxi_SendList(call, &last, istack, 0);
6042 /* Packets which are in 'working' are not sent by this call */
6047 * Check if the peer for the given call is known to be dead
6049 * If the call's peer appears dead (it has encountered fatal network errors
6050 * since the call started) the call is killed with RX_CALL_DEAD if the call
6051 * is active. Otherwise, we do nothing.
6053 * @param[in] call The call to check
6056 * @retval 0 The call is fine, and we haven't done anything to the call
6057 * @retval nonzero The call's peer appears dead, and the call has been
6058 * terminated if it was active
6060 * @pre call->lock must be locked
6063 rxi_CheckPeerDead(struct rx_call *call)
6065 #ifdef AFS_RXERRQ_ENV
6068 if (call->state == RX_STATE_DALLY) {
6072 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6073 if (call->neterr_gen < peererrs) {
6074 /* we have received network errors since this call started; kill
6076 if (call->state == RX_STATE_ACTIVE) {
6077 rxi_CallError(call, RX_CALL_DEAD);
6081 if (call->neterr_gen > peererrs) {
6082 /* someone has reset the number of peer errors; set the call error gen
6083 * so we can detect if more errors are encountered */
6084 call->neterr_gen = peererrs;
6091 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6093 struct rx_call *call = arg0;
6094 struct rx_peer *peer;
6095 struct opr_queue *cursor;
6096 struct clock maxTimeout = { 60, 0 };
6098 MUTEX_ENTER(&call->lock);
6100 peer = call->conn->peer;
6102 /* Make sure that the event pointer is removed from the call
6103 * structure, since there is no longer a per-call retransmission
6105 if (event == call->resendEvent)
6106 rxevent_Put(&call->resendEvent);
6108 rxi_CheckPeerDead(call);
6110 if (opr_queue_IsEmpty(&call->tq)) {
6111 /* Nothing to do. This means that we've been raced, and that an
6112 * ACK has come in between when we were triggered, and when we
6113 * actually got to run. */
6117 /* We're in loss recovery */
6118 call->flags |= RX_CALL_FAST_RECOVER;
6120 /* Mark all of the pending packets in the queue as being lost */
6121 for (opr_queue_Scan(&call->tq, cursor)) {
6122 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6123 if (!(p->flags & RX_PKTFLAG_ACKED))
6124 p->flags &= ~RX_PKTFLAG_SENT;
6127 /* We're resending, so we double the timeout of the call. This will be
6128 * dropped back down by the first successful ACK that we receive.
6130 * We apply a maximum value here of 60 seconds
6132 clock_Add(&call->rto, &call->rto);
6133 if (clock_Gt(&call->rto, &maxTimeout))
6134 call->rto = maxTimeout;
6136 /* Packet loss is most likely due to congestion, so drop our window size
6137 * and start again from the beginning */
6138 if (peer->maxDgramPackets >1) {
6139 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6140 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6142 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6143 call->nDgramPackets = 1;
6145 call->nextCwind = 1;
6148 MUTEX_ENTER(&peer->peer_lock);
6149 peer->MTU = call->MTU;
6150 peer->cwind = call->cwind;
6151 peer->nDgramPackets = 1;
6153 call->congestSeq = peer->congestSeq;
6154 MUTEX_EXIT(&peer->peer_lock);
6156 rxi_Start(call, istack);
6159 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6160 MUTEX_EXIT(&call->lock);
6163 /* This routine is called when new packets are readied for
6164 * transmission and when retransmission may be necessary, or when the
6165 * transmission window or burst count are favourable. This should be
6166 * better optimized for new packets, the usual case, now that we've
6167 * got rid of queues of send packets. XXXXXXXXXXX */
6169 rxi_Start(struct rx_call *call, int istack)
6171 struct opr_queue *cursor;
6172 #ifdef RX_ENABLE_LOCKS
6173 struct opr_queue *store;
6179 #ifdef RX_ENABLE_LOCKS
6180 if (rx_stats_active)
6181 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6186 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6187 /* Send (or resend) any packets that need it, subject to
6188 * window restrictions and congestion burst control
6189 * restrictions. Ask for an ack on the last packet sent in
6190 * this burst. For now, we're relying upon the window being
6191 * considerably bigger than the largest number of packets that
6192 * are typically sent at once by one initial call to
6193 * rxi_Start. This is probably bogus (perhaps we should ask
6194 * for an ack when we're half way through the current
6195 * window?). Also, for non file transfer applications, this
6196 * may end up asking for an ack for every packet. Bogus. XXXX
6199 * But check whether we're here recursively, and let the other guy
6202 #ifdef RX_ENABLE_LOCKS
6203 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6204 call->flags |= RX_CALL_TQ_BUSY;
6206 #endif /* RX_ENABLE_LOCKS */
6208 #ifdef RX_ENABLE_LOCKS
6209 call->flags &= ~RX_CALL_NEED_START;
6210 #endif /* RX_ENABLE_LOCKS */
6212 maxXmitPackets = MIN(call->twind, call->cwind);
6213 for (opr_queue_Scan(&call->tq, cursor)) {
6215 = opr_queue_Entry(cursor, struct rx_packet, entry);
6217 if (p->flags & RX_PKTFLAG_ACKED) {
6218 /* Since we may block, don't trust this */
6219 if (rx_stats_active)
6220 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6221 continue; /* Ignore this packet if it has been acknowledged */
6224 /* Turn off all flags except these ones, which are the same
6225 * on each transmission */
6226 p->header.flags &= RX_PRESET_FLAGS;
6228 if (p->header.seq >=
6229 call->tfirst + MIN((int)call->twind,
6230 (int)(call->nSoftAcked +
6232 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6233 /* Note: if we're waiting for more window space, we can
6234 * still send retransmits; hence we don't return here, but
6235 * break out to schedule a retransmit event */
6236 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6237 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6242 /* Transmit the packet if it needs to be sent. */
6243 if (!(p->flags & RX_PKTFLAG_SENT)) {
6244 if (nXmitPackets == maxXmitPackets) {
6245 rxi_SendXmitList(call, call->xmitList,
6246 nXmitPackets, istack);
6249 dpf(("call %d xmit packet %p\n",
6250 *(call->callNumber), p));
6251 call->xmitList[nXmitPackets++] = p;
6253 } /* end of the queue_Scan */
6255 /* xmitList now hold pointers to all of the packets that are
6256 * ready to send. Now we loop to send the packets */
6257 if (nXmitPackets > 0) {
6258 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6262 #ifdef RX_ENABLE_LOCKS
6264 /* We went into the error state while sending packets. Now is
6265 * the time to reset the call. This will also inform the using
6266 * process that the call is in an error state.
6268 if (rx_stats_active)
6269 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6270 call->flags &= ~RX_CALL_TQ_BUSY;
6271 rxi_WakeUpTransmitQueue(call);
6272 rxi_CallError(call, call->error);
6276 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6278 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6279 /* Some packets have received acks. If they all have, we can clear
6280 * the transmit queue.
6283 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6285 = opr_queue_Entry(cursor, struct rx_packet, entry);
6287 if (p->header.seq < call->tfirst
6288 && (p->flags & RX_PKTFLAG_ACKED)) {
6289 opr_queue_Remove(&p->entry);
6290 #ifdef RX_TRACK_PACKETS
6291 p->flags &= ~RX_PKTFLAG_TQ;
6293 #ifdef RXDEBUG_PACKET
6301 call->flags |= RX_CALL_TQ_CLEARME;
6303 if (call->flags & RX_CALL_TQ_CLEARME)
6304 rxi_ClearTransmitQueue(call, 1);
6305 } while (call->flags & RX_CALL_NEED_START);
6307 * TQ references no longer protected by this flag; they must remain
6308 * protected by the call lock.
6310 call->flags &= ~RX_CALL_TQ_BUSY;
6311 rxi_WakeUpTransmitQueue(call);
6313 call->flags |= RX_CALL_NEED_START;
6315 #endif /* RX_ENABLE_LOCKS */
6317 rxi_rto_cancel(call);
6321 /* Also adjusts the keep alive parameters for the call, to reflect
6322 * that we have just sent a packet (so keep alives aren't sent
6325 rxi_Send(struct rx_call *call, struct rx_packet *p,
6329 struct rx_connection *conn = call->conn;
6331 /* Stamp each packet with the user supplied status */
6332 p->header.userStatus = call->localStatus;
6334 /* Allow the security object controlling this call's security to
6335 * make any last-minute changes to the packet */
6336 code = RXS_SendPacket(conn->securityObject, call, p);
6338 MUTEX_EXIT(&call->lock);
6339 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6340 rxi_ConnectionError(conn, code);
6341 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6342 MUTEX_ENTER(&call->lock);
6346 /* Since we're about to send SOME sort of packet to the peer, it's
6347 * safe to nuke any scheduled end-of-packets ack */
6348 rxi_CancelDelayedAckEvent(call);
6350 /* Actually send the packet, filling in more connection-specific fields */
6351 MUTEX_EXIT(&call->lock);
6352 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6353 rxi_SendPacket(call, conn, p, istack);
6354 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6355 MUTEX_ENTER(&call->lock);
6357 /* Update last send time for this call (for keep-alive
6358 * processing), and for the connection (so that we can discover
6359 * idle connections) */
6360 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6361 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6362 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6364 conn->lastSendTime = call->lastSendTime = clock_Sec();
6368 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6369 * that things are fine. Also called periodically to guarantee that nothing
6370 * falls through the cracks (e.g. (error + dally) connections have keepalive
6371 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6373 * haveCTLock Set if calling from rxi_ReapConnections
6376 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6378 struct rx_connection *conn = call->conn;
6380 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6381 afs_uint32 fudgeFactor;
6384 int idle_timeout = 0;
6385 afs_int32 clock_diff = 0;
6387 if (rxi_CheckPeerDead(call)) {
6393 /* Large swings in the clock can have a significant impact on
6394 * the performance of RX call processing. Forward clock shifts
6395 * will result in premature event triggering or timeouts.
6396 * Backward shifts can result in calls not completing until
6397 * the clock catches up with the original start clock value.
6399 * If a backward clock shift of more than five minutes is noticed,
6400 * just fail the call.
6402 if (now < call->lastSendTime)
6403 clock_diff = call->lastSendTime - now;
6404 if (now < call->startWait)
6405 clock_diff = MAX(clock_diff, call->startWait - now);
6406 if (now < call->lastReceiveTime)
6407 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6408 if (clock_diff > 5 * 60)
6410 if (call->state == RX_STATE_ACTIVE)
6411 rxi_CallError(call, RX_CALL_TIMEOUT);
6415 #ifdef RX_ENABLE_LOCKS
6416 if (call->flags & RX_CALL_TQ_BUSY) {
6417 /* Call is active and will be reset by rxi_Start if it's
6418 * in an error state.
6423 /* RTT + 8*MDEV, rounded up to the next second. */
6424 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6425 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6427 deadTime = conn->secondsUntilDead + fudgeFactor;
6428 /* These are computed to the second (+- 1 second). But that's
6429 * good enough for these values, which should be a significant
6430 * number of seconds. */
6431 if (now > (call->lastReceiveTime + deadTime)) {
6432 if (call->state == RX_STATE_ACTIVE) {
6433 cerror = RX_CALL_DEAD;
6436 #ifdef RX_ENABLE_LOCKS
6437 /* Cancel pending events */
6438 rxi_CancelDelayedAckEvent(call);
6439 rxi_rto_cancel(call);
6440 rxi_CancelKeepAliveEvent(call);
6441 rxi_CancelGrowMTUEvent(call);
6442 MUTEX_ENTER(&rx_refcnt_mutex);
6443 /* if rxi_FreeCall returns 1 it has freed the call */
6444 if (call->refCount == 0 &&
6445 rxi_FreeCall(call, haveCTLock))
6447 MUTEX_EXIT(&rx_refcnt_mutex);
6450 MUTEX_EXIT(&rx_refcnt_mutex);
6452 #else /* RX_ENABLE_LOCKS */
6453 rxi_FreeCall(call, 0);
6455 #endif /* RX_ENABLE_LOCKS */
6457 /* Non-active calls are destroyed if they are not responding
6458 * to pings; active calls are simply flagged in error, so the
6459 * attached process can die reasonably gracefully. */
6462 if (conn->idleDeadTime) {
6463 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6467 /* see if we have a non-activity timeout */
6468 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6469 if (call->state == RX_STATE_ACTIVE) {
6470 cerror = RX_CALL_TIMEOUT;
6476 if (conn->hardDeadTime) {
6477 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6480 /* see if we have a hard timeout */
6482 && (now > (hardDeadTime + call->startTime.sec))) {
6483 if (call->state == RX_STATE_ACTIVE)
6484 rxi_CallError(call, RX_CALL_TIMEOUT);
6489 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6490 call->lastReceiveTime) {
6491 int oldMTU = conn->peer->ifMTU;
6493 /* If we thought we could send more, perhaps things got worse.
6494 * Shrink by 128 bytes and try again. */
6495 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6496 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6497 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6498 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6500 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6502 /* minimum capped in SetPeerMtu */
6503 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6506 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6508 /* needed so ResetCall doesn't clobber us. */
6509 call->MTU = conn->peer->ifMTU;
6511 /* if we never succeeded, let the error pass out as-is */
6512 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6513 cerror = conn->msgsizeRetryErr;
6516 rxi_CallError(call, cerror);
6521 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6522 void *dummy, int dummy2)
6524 struct rx_connection *conn = arg1;
6525 struct rx_header theader;
6526 char tbuffer[1 + sizeof(struct rx_header)];
6527 struct sockaddr_in taddr;
6531 struct iovec tmpiov[2];
6534 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6537 tp = &tbuffer[sizeof(struct rx_header)];
6538 taddr.sin_family = AF_INET;
6539 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6540 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6541 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6542 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6543 taddr.sin_len = sizeof(struct sockaddr_in);
6545 memset(&theader, 0, sizeof(theader));
6546 theader.epoch = htonl(999);
6548 theader.callNumber = 0;
6551 theader.type = RX_PACKET_TYPE_VERSION;
6552 theader.flags = RX_LAST_PACKET;
6553 theader.serviceId = 0;
6555 memcpy(tbuffer, &theader, sizeof(theader));
6556 memcpy(tp, &a, sizeof(a));
6557 tmpiov[0].iov_base = tbuffer;
6558 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6560 rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6562 MUTEX_ENTER(&conn->conn_data_lock);
6563 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6564 if (event == conn->natKeepAliveEvent)
6565 rxevent_Put(&conn->natKeepAliveEvent);
6566 MUTEX_ENTER(&rx_refcnt_mutex);
6567 /* Only reschedule ourselves if the connection would not be destroyed */
6568 if (conn->refCount > 1)
6570 if (conn->refCount <= 0) {
6571 #ifdef RX_REFCOUNT_CHECK
6572 osi_Assert(conn->refCount == 0);
6574 if (rx_stats_active) {
6575 MUTEX_ENTER(&rx_stats_mutex);
6576 rxi_lowConnRefCount++;
6577 MUTEX_EXIT(&rx_stats_mutex);
6580 MUTEX_EXIT(&rx_refcnt_mutex);
6582 rxi_ScheduleNatKeepAliveEvent(conn);
6583 MUTEX_EXIT(&conn->conn_data_lock);
6584 putConnection(conn);
6588 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6590 MUTEX_ASSERT(&conn->conn_data_lock);
6591 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6592 struct clock when, now;
6593 clock_GetTime(&now);
6595 when.sec += conn->secondsUntilNatPing;
6596 rx_GetConnection(conn);
6597 conn->natKeepAliveEvent =
6598 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6603 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6605 MUTEX_ENTER(&conn->conn_data_lock);
6606 conn->secondsUntilNatPing = seconds;
6608 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6609 rxi_ScheduleNatKeepAliveEvent(conn);
6611 conn->flags |= RX_CONN_NAT_PING;
6613 MUTEX_EXIT(&conn->conn_data_lock);
6616 /* When a call is in progress, this routine is called occasionally to
6617 * make sure that some traffic has arrived (or been sent to) the peer.
6618 * If nothing has arrived in a reasonable amount of time, the call is
6619 * declared dead; if nothing has been sent for a while, we send a
6620 * keep-alive packet (if we're actually trying to keep the call alive)
6623 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6626 struct rx_call *call = arg1;
6627 struct rx_connection *conn;
6630 MUTEX_ENTER(&call->lock);
6632 if (event == call->keepAliveEvent)
6633 rxevent_Put(&call->keepAliveEvent);
6637 if (rxi_CheckCall(call, 0)) {
6638 MUTEX_EXIT(&call->lock);
6639 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6643 /* Don't try to keep alive dallying calls */
6644 if (call->state == RX_STATE_DALLY) {
6645 MUTEX_EXIT(&call->lock);
6646 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6651 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6652 /* Don't try to send keepalives if there is unacknowledged data */
6653 /* the rexmit code should be good enough, this little hack
6654 * doesn't quite work XXX */
6655 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6657 rxi_ScheduleKeepAliveEvent(call);
6658 MUTEX_EXIT(&call->lock);
6659 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6662 /* Does what's on the nameplate. */
6664 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6666 struct rx_call *call = arg1;
6667 struct rx_connection *conn;
6669 MUTEX_ENTER(&call->lock);
6671 if (event == call->growMTUEvent)
6672 rxevent_Put(&call->growMTUEvent);
6674 if (rxi_CheckCall(call, 0))
6677 /* Don't bother with dallying calls */
6678 if (call->state == RX_STATE_DALLY)
6684 * keep being scheduled, just don't do anything if we're at peak,
6685 * or we're not set up to be properly handled (idle timeout required)
6687 if ((conn->peer->maxPacketSize != 0) &&
6688 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6690 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6691 rxi_ScheduleGrowMTUEvent(call, 0);
6693 MUTEX_EXIT(&call->lock);
6694 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6698 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6700 MUTEX_ASSERT(&call->lock);
6701 if (!call->keepAliveEvent) {
6702 struct clock when, now;
6703 clock_GetTime(&now);
6705 when.sec += call->conn->secondsUntilPing;
6706 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6707 call->keepAliveEvent =
6708 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6713 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6714 MUTEX_ASSERT(&call->lock);
6715 if (rxevent_Cancel(&call->keepAliveEvent))
6716 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6720 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6722 MUTEX_ASSERT(&call->lock);
6723 if (!call->growMTUEvent) {
6724 struct clock when, now;
6726 clock_GetTime(&now);
6729 if (call->conn->secondsUntilPing)
6730 secs = (6*call->conn->secondsUntilPing)-1;
6732 if (call->conn->secondsUntilDead)
6733 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6737 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6738 call->growMTUEvent =
6739 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6744 rxi_CancelGrowMTUEvent(struct rx_call *call)
6746 MUTEX_ASSERT(&call->lock);
6747 if (rxevent_Cancel(&call->growMTUEvent))
6748 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6752 * Increment the counter for the next connection ID, handling overflow.
6755 update_nextCid(void)
6757 /* Overflow is technically undefined behavior; avoid it. */
6758 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6759 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6761 rx_nextCid += 1 << RX_CIDSHIFT;
6765 rxi_KeepAliveOn(struct rx_call *call)
6767 /* Pretend last packet received was received now--i.e. if another
6768 * packet isn't received within the keep alive time, then the call
6769 * will die; Initialize last send time to the current time--even
6770 * if a packet hasn't been sent yet. This will guarantee that a
6771 * keep-alive is sent within the ping time */
6772 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6773 rxi_ScheduleKeepAliveEvent(call);
6777 rxi_GrowMTUOn(struct rx_call *call)
6779 struct rx_connection *conn = call->conn;
6780 MUTEX_ENTER(&conn->conn_data_lock);
6781 conn->lastPingSizeSer = conn->lastPingSize = 0;
6782 MUTEX_EXIT(&conn->conn_data_lock);
6783 rxi_ScheduleGrowMTUEvent(call, 1);
6786 /* This routine is called to send connection abort messages
6787 * that have been delayed to throttle looping clients. */
6789 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6792 struct rx_connection *conn = arg1;
6795 struct rx_packet *packet;
6797 MUTEX_ENTER(&conn->conn_data_lock);
6798 if (event == conn->delayedAbortEvent)
6799 rxevent_Put(&conn->delayedAbortEvent);
6800 error = htonl(conn->error);
6802 MUTEX_EXIT(&conn->conn_data_lock);
6803 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6806 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6807 RX_PACKET_TYPE_ABORT, (char *)&error,
6809 rxi_FreePacket(packet);
6811 putConnection(conn);
6814 /* This routine is called to send call abort messages
6815 * that have been delayed to throttle looping clients. */
6817 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6820 struct rx_call *call = arg1;
6823 struct rx_packet *packet;
6825 MUTEX_ENTER(&call->lock);
6826 if (event == call->delayedAbortEvent)
6827 rxevent_Put(&call->delayedAbortEvent);
6828 error = htonl(call->error);
6830 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6833 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6834 (char *)&error, sizeof(error), 0);
6835 rxi_FreePacket(packet);
6837 MUTEX_EXIT(&call->lock);
6838 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6842 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6843 * seconds) to ask the client to authenticate itself. The routine
6844 * issues a challenge to the client, which is obtained from the
6845 * security object associated with the connection
6847 * This routine is both an event handler and a function called directly;
6848 * when called directly the passed |event| is NULL and the
6849 * conn->conn->data>lock must must not be held. Also, when called as an
6850 * an event handler, we must putConnection before we exit; but when called
6851 * directly (the first challenge), we must NOT putConnection.
6854 rxi_ChallengeEvent(struct rxevent *event,
6855 void *arg0, void *arg1, int tries)
6857 struct rx_connection *conn = arg0;
6858 int event_raised = 0; /* assume we were called directly */
6860 MUTEX_ENTER(&conn->conn_data_lock);
6861 if (event != NULL && event == conn->challengeEvent) {
6862 event_raised = 1; /* called as an event */
6863 rxevent_Put(&conn->challengeEvent);
6865 MUTEX_EXIT(&conn->conn_data_lock);
6867 /* If there are no active calls it is not worth re-issuing the
6868 * challenge. If the client issues another call on this connection
6869 * the challenge can be requested at that time.
6871 if (!rxi_HasActiveCalls(conn))
6874 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6875 struct rx_packet *packet;
6876 struct clock when, now;
6879 /* We've failed to authenticate for too long.
6880 * Reset any calls waiting for authentication;
6881 * they are all in RX_STATE_PRECALL.
6885 MUTEX_ENTER(&conn->conn_call_lock);
6886 for (i = 0; i < RX_MAXCALLS; i++) {
6887 struct rx_call *call = conn->call[i];
6889 MUTEX_ENTER(&call->lock);
6890 if (call->state == RX_STATE_PRECALL) {
6891 rxi_CallError(call, RX_CALL_DEAD);
6892 rxi_SendCallAbort(call, NULL, 0, 0);
6894 MUTEX_EXIT(&call->lock);
6897 MUTEX_EXIT(&conn->conn_call_lock);
6901 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6904 code = RXS_GetChallenge(conn->securityObject, conn, packet);
6905 if (code && event_raised) {
6907 * We can only rxi_ConnectionError the connection if we are
6908 * running as an event. Otherwise, the caller may have our call
6909 * locked, and so we cannot call rxi_ConnectionError (since it
6910 * tries to lock each call in the conn).
6912 rxi_FreePacket(packet);
6913 rxi_ConnectionError(conn, code);
6917 /* Only send a challenge packet if we were able to allocate a
6918 * packet, and the security layer successfully populated the
6920 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6921 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6922 conn->securityChallengeSent = 1;
6924 rxi_FreePacket(packet);
6926 clock_GetTime(&now);
6928 when.sec += RX_CHALLENGE_TIMEOUT;
6929 MUTEX_ENTER(&conn->conn_data_lock);
6930 /* Only reschedule ourselves if not already pending. */
6931 if (conn->challengeEvent == NULL) {
6932 rx_GetConnection(conn);
6933 conn->challengeEvent =
6934 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6937 MUTEX_EXIT(&conn->conn_data_lock);
6941 putConnection(conn);
6944 /* Call this routine to start requesting the client to authenticate
6945 * itself. This will continue until authentication is established,
6946 * the call times out, or an invalid response is returned. The
6947 * security object associated with the connection is asked to create
6948 * the challenge at this time. */
6950 rxi_ChallengeOn(struct rx_connection *conn)
6953 MUTEX_ENTER(&conn->conn_data_lock);
6954 if (!conn->challengeEvent)
6956 MUTEX_EXIT(&conn->conn_data_lock);
6959 code = RXS_CreateChallenge(conn->securityObject, conn);
6963 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6969 /* rxi_ComputeRoundTripTime is called with peer locked. */
6970 /* peer may be null */
6972 rxi_ComputeRoundTripTime(struct rx_packet *p,
6973 struct rx_ackPacket *ack,
6974 struct rx_call *call,
6975 struct rx_peer *peer,
6978 struct clock thisRtt, *sentp;
6982 /* If the ACK is delayed, then do nothing */
6983 if (ack->reason == RX_ACK_DELAY)
6986 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6987 * their RTT multiple times, so only include the RTT of the last packet
6989 if (p->flags & RX_JUMBO_PACKET)
6992 /* Use the serial number to determine which transmission the ACK is for,
6993 * and set the sent time to match this. If we have no serial number, then
6994 * only use the ACK for RTT calculations if the packet has not been
6998 serial = ntohl(ack->serial);
7000 if (serial == p->header.serial) {
7001 sentp = &p->timeSent;
7002 } else if (serial == p->firstSerial) {
7003 sentp = &p->firstSent;
7004 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
7005 sentp = &p->firstSent;
7009 if (clock_Eq(&p->timeSent, &p->firstSent)) {
7010 sentp = &p->firstSent;
7017 if (clock_Lt(&thisRtt, sentp))
7018 return; /* somebody set the clock back, don't count this time. */
7020 clock_Sub(&thisRtt, sentp);
7021 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
7022 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
7024 if (clock_IsZero(&thisRtt)) {
7026 * The actual round trip time is shorter than the
7027 * clock_GetTime resolution. It is most likely 1ms or 100ns.
7028 * Since we can't tell which at the moment we will assume 1ms.
7030 thisRtt.usec = 1000;
7033 if (rx_stats_active) {
7034 MUTEX_ENTER(&rx_stats_mutex);
7035 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
7036 rx_stats.minRtt = thisRtt;
7037 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
7038 if (thisRtt.sec > 60) {
7039 MUTEX_EXIT(&rx_stats_mutex);
7040 return; /* somebody set the clock ahead */
7042 rx_stats.maxRtt = thisRtt;
7044 clock_Add(&rx_stats.totalRtt, &thisRtt);
7045 rx_atomic_inc(&rx_stats.nRttSamples);
7046 MUTEX_EXIT(&rx_stats_mutex);
7049 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
7051 /* Apply VanJacobson round-trip estimations */
7056 * srtt (call->rtt) is in units of one-eighth-milliseconds.
7057 * srtt is stored as fixed point with 3 bits after the binary
7058 * point (i.e., scaled by 8). The following magic is
7059 * equivalent to the smoothing algorithm in rfc793 with an
7060 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7061 * srtt'*8 = rtt + srtt*7
7062 * srtt'*8 = srtt*8 + rtt - srtt
7063 * srtt' = srtt + rtt/8 - srtt/8
7064 * srtt' = srtt + (rtt - srtt)/8
7067 delta = _8THMSEC(&thisRtt) - call->rtt;
7068 call->rtt += (delta >> 3);
7071 * We accumulate a smoothed rtt variance (actually, a smoothed
7072 * mean difference), then set the retransmit timer to smoothed
7073 * rtt + 4 times the smoothed variance (was 2x in van's original
7074 * paper, but 4x works better for me, and apparently for him as
7076 * rttvar is stored as
7077 * fixed point with 2 bits after the binary point (scaled by
7078 * 4). The following is equivalent to rfc793 smoothing with
7079 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7080 * rttvar'*4 = rttvar*3 + |delta|
7081 * rttvar'*4 = rttvar*4 + |delta| - rttvar
7082 * rttvar' = rttvar + |delta|/4 - rttvar/4
7083 * rttvar' = rttvar + (|delta| - rttvar)/4
7084 * This replaces rfc793's wired-in beta.
7085 * dev*4 = dev*4 + (|actual - expected| - dev)
7091 delta -= (call->rtt_dev << 1);
7092 call->rtt_dev += (delta >> 3);
7094 /* I don't have a stored RTT so I start with this value. Since I'm
7095 * probably just starting a call, and will be pushing more data down
7096 * this, I expect congestion to increase rapidly. So I fudge a
7097 * little, and I set deviance to half the rtt. In practice,
7098 * deviance tends to approach something a little less than
7099 * half the smoothed rtt. */
7100 call->rtt = _8THMSEC(&thisRtt) + 8;
7101 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7103 /* the smoothed RTT time is RTT + 4*MDEV
7105 * We allow a user specified minimum to be set for this, to allow clamping
7106 * at a minimum value in the same way as TCP. In addition, we have to allow
7107 * for the possibility that this packet is answered by a delayed ACK, so we
7108 * add on a fixed 200ms to account for that timer expiring.
7111 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7112 rx_minPeerTimeout) + 200;
7113 clock_Zero(&call->rto);
7114 clock_Addmsec(&call->rto, rtt_timeout);
7116 /* Update the peer, so any new calls start with our values */
7117 peer->rtt_dev = call->rtt_dev;
7118 peer->rtt = call->rtt;
7120 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7121 "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7122 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7123 call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7127 /* Find all server connections that have not been active for a long time, and
7130 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7133 struct clock now, when;
7134 struct rxevent *event;
7135 clock_GetTime(&now);
7137 /* Find server connection structures that haven't been used for
7138 * greater than rx_idleConnectionTime */
7140 struct rx_connection **conn_ptr, **conn_end;
7141 int i, havecalls = 0;
7142 MUTEX_ENTER(&rx_connHashTable_lock);
7143 for (conn_ptr = &rx_connHashTable[0], conn_end =
7144 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7146 struct rx_connection *conn, *next;
7147 struct rx_call *call;
7151 for (conn = *conn_ptr; conn; conn = next) {
7152 /* XXX -- Shouldn't the connection be locked? */
7155 for (i = 0; i < RX_MAXCALLS; i++) {
7156 call = conn->call[i];
7160 code = MUTEX_TRYENTER(&call->lock);
7163 result = rxi_CheckCall(call, 1);
7164 MUTEX_EXIT(&call->lock);
7166 /* If CheckCall freed the call, it might
7167 * have destroyed the connection as well,
7168 * which screws up the linked lists.
7174 if (conn->type == RX_SERVER_CONNECTION) {
7175 /* This only actually destroys the connection if
7176 * there are no outstanding calls */
7177 MUTEX_ENTER(&conn->conn_data_lock);
7178 MUTEX_ENTER(&rx_refcnt_mutex);
7179 if (!havecalls && !conn->refCount
7180 && ((conn->lastSendTime + rx_idleConnectionTime) <
7182 conn->refCount++; /* it will be decr in rx_DestroyConn */
7183 MUTEX_EXIT(&rx_refcnt_mutex);
7184 MUTEX_EXIT(&conn->conn_data_lock);
7185 #ifdef RX_ENABLE_LOCKS
7186 rxi_DestroyConnectionNoLock(conn);
7187 #else /* RX_ENABLE_LOCKS */
7188 rxi_DestroyConnection(conn);
7189 #endif /* RX_ENABLE_LOCKS */
7191 #ifdef RX_ENABLE_LOCKS
7193 MUTEX_EXIT(&rx_refcnt_mutex);
7194 MUTEX_EXIT(&conn->conn_data_lock);
7196 #endif /* RX_ENABLE_LOCKS */
7200 #ifdef RX_ENABLE_LOCKS
7201 while (rx_connCleanup_list) {
7202 struct rx_connection *conn;
7203 conn = rx_connCleanup_list;
7204 rx_connCleanup_list = rx_connCleanup_list->next;
7205 MUTEX_EXIT(&rx_connHashTable_lock);
7206 rxi_CleanupConnection(conn);
7207 MUTEX_ENTER(&rx_connHashTable_lock);
7209 MUTEX_EXIT(&rx_connHashTable_lock);
7210 #endif /* RX_ENABLE_LOCKS */
7213 /* Find any peer structures that haven't been used (haven't had an
7214 * associated connection) for greater than rx_idlePeerTime */
7216 struct rx_peer **peer_ptr, **peer_end;
7220 * Why do we need to hold the rx_peerHashTable_lock across
7221 * the incrementing of peer_ptr since the rx_peerHashTable
7222 * array is not changing? We don't.
7224 * By dropping the lock periodically we can permit other
7225 * activities to be performed while a rxi_ReapConnections
7226 * call is in progress. The goal of reap connections
7227 * is to clean up quickly without causing large amounts
7228 * of contention. Therefore, it is important that global
7229 * mutexes not be held for extended periods of time.
7231 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7232 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7234 struct rx_peer *peer, *next, *prev;
7236 MUTEX_ENTER(&rx_peerHashTable_lock);
7237 for (prev = peer = *peer_ptr; peer; peer = next) {
7239 code = MUTEX_TRYENTER(&peer->peer_lock);
7240 if ((code) && (peer->refCount == 0)
7241 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7242 struct opr_queue *cursor, *store;
7246 * now know that this peer object is one to be
7247 * removed from the hash table. Once it is removed
7248 * it can't be referenced by other threads.
7249 * Lets remove it first and decrement the struct
7250 * nPeerStructs count.
7252 if (peer == *peer_ptr) {
7258 if (rx_stats_active)
7259 rx_atomic_dec(&rx_stats.nPeerStructs);
7262 * Now if we hold references on 'prev' and 'next'
7263 * we can safely drop the rx_peerHashTable_lock
7264 * while we destroy this 'peer' object.
7270 MUTEX_EXIT(&rx_peerHashTable_lock);
7272 MUTEX_EXIT(&peer->peer_lock);
7273 MUTEX_DESTROY(&peer->peer_lock);
7275 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7276 unsigned int num_funcs;
7277 struct rx_interface_stat *rpc_stat
7278 = opr_queue_Entry(cursor, struct rx_interface_stat,
7283 opr_queue_Remove(&rpc_stat->entry);
7284 opr_queue_Remove(&rpc_stat->entryPeers);
7286 num_funcs = rpc_stat->stats[0].func_total;
7288 sizeof(rx_interface_stat_t) +
7289 rpc_stat->stats[0].func_total *
7290 sizeof(rx_function_entry_v1_t);
7292 rxi_Free(rpc_stat, space);
7294 MUTEX_ENTER(&rx_rpc_stats);
7295 rxi_rpc_peer_stat_cnt -= num_funcs;
7296 MUTEX_EXIT(&rx_rpc_stats);
7301 * Regain the rx_peerHashTable_lock and
7302 * decrement the reference count on 'prev'
7305 MUTEX_ENTER(&rx_peerHashTable_lock);
7312 MUTEX_EXIT(&peer->peer_lock);
7317 MUTEX_EXIT(&rx_peerHashTable_lock);
7321 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7322 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7323 * GC, just below. Really, we shouldn't have to keep moving packets from
7324 * one place to another, but instead ought to always know if we can
7325 * afford to hold onto a packet in its particular use. */
7326 MUTEX_ENTER(&rx_freePktQ_lock);
7327 if (rx_waitingForPackets) {
7328 rx_waitingForPackets = 0;
7329 #ifdef RX_ENABLE_LOCKS
7330 CV_BROADCAST(&rx_waitingForPackets_cv);
7332 osi_rxWakeup(&rx_waitingForPackets);
7335 MUTEX_EXIT(&rx_freePktQ_lock);
7338 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7339 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7340 rxevent_Put(&event);
7344 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7345 * rx.h is sort of strange this is better. This is called with a security
7346 * object before it is discarded. Each connection using a security object has
7347 * its own refcount to the object so it won't actually be freed until the last
7348 * connection is destroyed.
7350 * This is the only rxs module call. A hold could also be written but no one
7354 rxs_Release(struct rx_securityClass *aobj)
7356 return RXS_Close(aobj);
7364 #define TRACE_OPTION_RX_DEBUG 16
7372 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7373 0, KEY_QUERY_VALUE, &parmKey);
7374 if (code != ERROR_SUCCESS)
7377 dummyLen = sizeof(TraceOption);
7378 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7379 (BYTE *) &TraceOption, &dummyLen);
7380 if (code == ERROR_SUCCESS) {
7381 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7383 RegCloseKey (parmKey);
7384 #endif /* AFS_NT40_ENV */
7389 rx_DebugOnOff(int on)
7393 rxdebug_active = on;
7399 rx_StatsOnOff(int on)
7401 rx_stats_active = on;
7405 /* Don't call this debugging routine directly; use dpf */
7407 rxi_DebugPrint(char *format, ...)
7416 va_start(ap, format);
7418 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7421 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7423 OutputDebugString(msg);
7429 va_start(ap, format);
7431 clock_GetTime(&now);
7432 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7433 (unsigned int)now.usec);
7434 vfprintf(rx_Log, format, ap);
7442 * This function is used to process the rx_stats structure that is local
7443 * to a process as well as an rx_stats structure received from a remote
7444 * process (via rxdebug). Therefore, it needs to do minimal version
7448 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7449 afs_int32 freePackets, char version)
7453 if (size != sizeof(struct rx_statistics)) {
7455 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7456 size, sizeof(struct rx_statistics));
7459 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7462 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7463 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7464 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7465 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7466 s->specialPktAllocFailures);
7468 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7469 s->receivePktAllocFailures, s->sendPktAllocFailures,
7470 s->specialPktAllocFailures);
7474 " greedy %u, " "bogusReads %u (last from host %x), "
7475 "noPackets %u, " "noBuffers %u, " "selects %u, "
7476 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7477 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7478 s->selects, s->sendSelects);
7480 fprintf(file, " packets read: ");
7481 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7482 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7484 fprintf(file, "\n");
7487 " other read counters: data %u, " "ack %u, " "dup %u "
7488 "spurious %u " "dally %u\n", s->dataPacketsRead,
7489 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7490 s->ignorePacketDally);
7492 fprintf(file, " packets sent: ");
7493 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7494 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7496 fprintf(file, "\n");
7499 " other send counters: ack %u, " "data %u (not resends), "
7500 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7501 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7502 s->dataPacketsPushed, s->ignoreAckedPacket);
7505 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7506 s->netSendFailures, (int)s->fatalErrors);
7508 if (s->nRttSamples) {
7509 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7510 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7512 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7513 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7517 " %d server connections, " "%d client connections, "
7518 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7519 s->nServerConns, s->nClientConns, s->nPeerStructs,
7520 s->nCallStructs, s->nFreeCallStructs);
7522 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7523 fprintf(file, " %d clock updates\n", clock_nUpdates);
7527 /* for backward compatibility */
7529 rx_PrintStats(FILE * file)
7531 MUTEX_ENTER(&rx_stats_mutex);
7532 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7533 sizeof(rx_stats), rx_nFreePackets,
7535 MUTEX_EXIT(&rx_stats_mutex);
7539 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7541 fprintf(file, "Peer %x.%d.\n",
7542 ntohl(peer->host), (int)ntohs(peer->port));
7545 " Rtt %d, " "total sent %d, " "resent %d\n",
7546 peer->rtt, peer->nSent, peer->reSends);
7548 fprintf(file, " Packet size %d\n", peer->ifMTU);
7552 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7554 * This mutex protects the following static variables:
7558 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7559 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7561 #define LOCK_RX_DEBUG
7562 #define UNLOCK_RX_DEBUG
7563 #endif /* AFS_PTHREAD_ENV */
7565 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7567 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7568 u_char type, void *inputData, size_t inputLength,
7569 void *outputData, size_t outputLength)
7571 static afs_int32 counter = 100;
7572 time_t waitTime, waitCount;
7573 struct rx_header theader;
7576 struct timeval tv_now, tv_wake, tv_delta;
7577 struct sockaddr_in taddr, faddr;
7591 tp = &tbuffer[sizeof(struct rx_header)];
7592 taddr.sin_family = AF_INET;
7593 taddr.sin_port = remotePort;
7594 taddr.sin_addr.s_addr = remoteAddr;
7595 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7596 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7597 taddr.sin_len = sizeof(struct sockaddr_in);
7600 memset(&theader, 0, sizeof(theader));
7601 theader.epoch = htonl(999);
7603 theader.callNumber = htonl(counter);
7606 theader.type = type;
7607 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7608 theader.serviceId = 0;
7610 memcpy(tbuffer, &theader, sizeof(theader));
7611 memcpy(tp, inputData, inputLength);
7613 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7614 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7616 /* see if there's a packet available */
7617 gettimeofday(&tv_wake, NULL);
7618 tv_wake.tv_sec += waitTime;
7621 FD_SET(socket, &imask);
7622 tv_delta.tv_sec = tv_wake.tv_sec;
7623 tv_delta.tv_usec = tv_wake.tv_usec;
7624 gettimeofday(&tv_now, NULL);
7626 if (tv_delta.tv_usec < tv_now.tv_usec) {
7628 tv_delta.tv_usec += 1000000;
7631 tv_delta.tv_usec -= tv_now.tv_usec;
7633 if (tv_delta.tv_sec < tv_now.tv_sec) {
7637 tv_delta.tv_sec -= tv_now.tv_sec;
7640 code = select(0, &imask, 0, 0, &tv_delta);
7641 #else /* AFS_NT40_ENV */
7642 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7643 #endif /* AFS_NT40_ENV */
7644 if (code == 1 && FD_ISSET(socket, &imask)) {
7645 /* now receive a packet */
7646 faddrLen = sizeof(struct sockaddr_in);
7648 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7649 (struct sockaddr *)&faddr, &faddrLen);
7652 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7653 if (counter == ntohl(theader.callNumber))
7661 /* see if we've timed out */
7669 code -= sizeof(struct rx_header);
7670 if (code > outputLength)
7671 code = outputLength;
7672 memcpy(outputData, tp, code);
7675 #endif /* RXDEBUG */
7678 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7679 afs_uint16 remotePort, struct rx_debugStats * stat,
7680 afs_uint32 * supportedValues)
7682 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7684 struct rx_debugIn in;
7686 *supportedValues = 0;
7687 in.type = htonl(RX_DEBUGI_GETSTATS);
7690 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7691 &in, sizeof(in), stat, sizeof(*stat));
7694 * If the call was successful, fixup the version and indicate
7695 * what contents of the stat structure are valid.
7696 * Also do net to host conversion of fields here.
7700 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7701 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7703 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7704 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7706 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7707 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7709 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7710 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7712 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7713 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7715 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7716 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7718 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7719 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7721 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7722 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7724 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7725 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7727 stat->nFreePackets = ntohl(stat->nFreePackets);
7728 stat->packetReclaims = ntohl(stat->packetReclaims);
7729 stat->callsExecuted = ntohl(stat->callsExecuted);
7730 stat->nWaiting = ntohl(stat->nWaiting);
7731 stat->idleThreads = ntohl(stat->idleThreads);
7732 stat->nWaited = ntohl(stat->nWaited);
7733 stat->nPackets = ntohl(stat->nPackets);
7742 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7743 afs_uint16 remotePort, struct rx_statistics * stat,
7744 afs_uint32 * supportedValues)
7746 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7748 struct rx_debugIn in;
7749 afs_int32 *lp = (afs_int32 *) stat;
7753 * supportedValues is currently unused, but added to allow future
7754 * versioning of this function.
7757 *supportedValues = 0;
7758 in.type = htonl(RX_DEBUGI_RXSTATS);
7760 memset(stat, 0, sizeof(*stat));
7762 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7763 &in, sizeof(in), stat, sizeof(*stat));
7768 * Do net to host conversion here
7771 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7782 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7783 afs_uint16 remotePort, size_t version_length,
7786 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7788 return MakeDebugCall(socket, remoteAddr, remotePort,
7789 RX_PACKET_TYPE_VERSION, a, 1, version,
7797 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7798 afs_uint16 remotePort, afs_int32 * nextConnection,
7799 int allConnections, afs_uint32 debugSupportedValues,
7800 struct rx_debugConn * conn,
7801 afs_uint32 * supportedValues)
7803 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7805 struct rx_debugIn in;
7809 * supportedValues is currently unused, but added to allow future
7810 * versioning of this function.
7813 *supportedValues = 0;
7814 if (allConnections) {
7815 in.type = htonl(RX_DEBUGI_GETALLCONN);
7817 in.type = htonl(RX_DEBUGI_GETCONN);
7819 in.index = htonl(*nextConnection);
7820 memset(conn, 0, sizeof(*conn));
7822 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7823 &in, sizeof(in), conn, sizeof(*conn));
7826 *nextConnection += 1;
7829 * Convert old connection format to new structure.
7832 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7833 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7834 #define MOVEvL(a) (conn->a = vL->a)
7836 /* any old or unrecognized version... */
7837 for (i = 0; i < RX_MAXCALLS; i++) {
7838 MOVEvL(callState[i]);
7839 MOVEvL(callMode[i]);
7840 MOVEvL(callFlags[i]);
7841 MOVEvL(callOther[i]);
7843 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7844 MOVEvL(secStats.type);
7845 MOVEvL(secStats.level);
7846 MOVEvL(secStats.flags);
7847 MOVEvL(secStats.expires);
7848 MOVEvL(secStats.packetsReceived);
7849 MOVEvL(secStats.packetsSent);
7850 MOVEvL(secStats.bytesReceived);
7851 MOVEvL(secStats.bytesSent);
7856 * Do net to host conversion here
7858 * I don't convert host or port since we are most likely
7859 * going to want these in NBO.
7861 conn->cid = ntohl(conn->cid);
7862 conn->serial = ntohl(conn->serial);
7863 for (i = 0; i < RX_MAXCALLS; i++) {
7864 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7866 conn->error = ntohl(conn->error);
7867 conn->secStats.flags = ntohl(conn->secStats.flags);
7868 conn->secStats.expires = ntohl(conn->secStats.expires);
7869 conn->secStats.packetsReceived =
7870 ntohl(conn->secStats.packetsReceived);
7871 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7872 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7873 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7874 conn->epoch = ntohl(conn->epoch);
7875 conn->natMTU = ntohl(conn->natMTU);
7884 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7885 afs_uint16 remotePort, afs_int32 * nextPeer,
7886 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7887 afs_uint32 * supportedValues)
7889 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7891 struct rx_debugIn in;
7894 * supportedValues is currently unused, but added to allow future
7895 * versioning of this function.
7898 *supportedValues = 0;
7899 in.type = htonl(RX_DEBUGI_GETPEER);
7900 in.index = htonl(*nextPeer);
7901 memset(peer, 0, sizeof(*peer));
7903 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7904 &in, sizeof(in), peer, sizeof(*peer));
7910 * Do net to host conversion here
7912 * I don't convert host or port since we are most likely
7913 * going to want these in NBO.
7915 peer->ifMTU = ntohs(peer->ifMTU);
7916 peer->idleWhen = ntohl(peer->idleWhen);
7917 peer->refCount = ntohs(peer->refCount);
7918 peer->rtt = ntohl(peer->rtt);
7919 peer->rtt_dev = ntohl(peer->rtt_dev);
7920 peer->timeout.sec = 0;
7921 peer->timeout.usec = 0;
7922 peer->nSent = ntohl(peer->nSent);
7923 peer->reSends = ntohl(peer->reSends);
7924 peer->natMTU = ntohs(peer->natMTU);
7925 peer->maxMTU = ntohs(peer->maxMTU);
7926 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7927 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7928 peer->MTU = ntohs(peer->MTU);
7929 peer->cwind = ntohs(peer->cwind);
7930 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7931 peer->congestSeq = ntohs(peer->congestSeq);
7932 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7933 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7934 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7935 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7944 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7945 struct rx_debugPeer * peerStats)
7948 afs_int32 error = 1; /* default to "did not succeed" */
7949 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7951 MUTEX_ENTER(&rx_peerHashTable_lock);
7952 for(tp = rx_peerHashTable[hashValue];
7953 tp != NULL; tp = tp->next) {
7954 if (tp->host == peerHost)
7960 MUTEX_EXIT(&rx_peerHashTable_lock);
7964 MUTEX_ENTER(&tp->peer_lock);
7965 peerStats->host = tp->host;
7966 peerStats->port = tp->port;
7967 peerStats->ifMTU = tp->ifMTU;
7968 peerStats->idleWhen = tp->idleWhen;
7969 peerStats->refCount = tp->refCount;
7970 peerStats->burstSize = 0;
7971 peerStats->burst = 0;
7972 peerStats->burstWait.sec = 0;
7973 peerStats->burstWait.usec = 0;
7974 peerStats->rtt = tp->rtt;
7975 peerStats->rtt_dev = tp->rtt_dev;
7976 peerStats->timeout.sec = 0;
7977 peerStats->timeout.usec = 0;
7978 peerStats->nSent = tp->nSent;
7979 peerStats->reSends = tp->reSends;
7980 peerStats->natMTU = tp->natMTU;
7981 peerStats->maxMTU = tp->maxMTU;
7982 peerStats->maxDgramPackets = tp->maxDgramPackets;
7983 peerStats->ifDgramPackets = tp->ifDgramPackets;
7984 peerStats->MTU = tp->MTU;
7985 peerStats->cwind = tp->cwind;
7986 peerStats->nDgramPackets = tp->nDgramPackets;
7987 peerStats->congestSeq = tp->congestSeq;
7988 peerStats->bytesSent.high = tp->bytesSent >> 32;
7989 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7990 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7991 peerStats->bytesReceived.low
7992 = tp->bytesReceived & MAX_AFS_UINT32;
7993 MUTEX_EXIT(&tp->peer_lock);
7995 MUTEX_ENTER(&rx_peerHashTable_lock);
7998 MUTEX_EXIT(&rx_peerHashTable_lock);
8006 struct rx_serverQueueEntry *np;
8009 struct rx_call *call;
8010 struct rx_serverQueueEntry *sq;
8014 if (!rxi_IsRunning()) {
8016 return; /* Already shutdown. */
8018 rx_atomic_set(&rxi_running, 0);
8021 #ifndef AFS_PTHREAD_ENV
8022 FD_ZERO(&rx_selectMask);
8023 #endif /* AFS_PTHREAD_ENV */
8024 rxi_dataQuota = RX_MAX_QUOTA;
8025 #ifndef AFS_PTHREAD_ENV
8027 #endif /* AFS_PTHREAD_ENV */
8030 #ifndef AFS_PTHREAD_ENV
8031 #ifndef AFS_USE_GETTIMEOFDAY
8033 #endif /* AFS_USE_GETTIMEOFDAY */
8034 #endif /* AFS_PTHREAD_ENV */
8036 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
8037 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
8038 opr_queue_Remove(&call->entry);
8039 rxi_Free(call, sizeof(struct rx_call));
8042 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
8043 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
8045 opr_queue_Remove(&sq->entry);
8050 struct rx_peer **peer_ptr, **peer_end;
8051 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8052 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8054 struct rx_peer *peer, *next;
8056 MUTEX_ENTER(&rx_peerHashTable_lock);
8057 for (peer = *peer_ptr; peer; peer = next) {
8058 struct opr_queue *cursor, *store;
8061 MUTEX_ENTER(&rx_rpc_stats);
8062 MUTEX_ENTER(&peer->peer_lock);
8063 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8064 unsigned int num_funcs;
8065 struct rx_interface_stat *rpc_stat
8066 = opr_queue_Entry(cursor, struct rx_interface_stat,
8070 opr_queue_Remove(&rpc_stat->entry);
8071 opr_queue_Remove(&rpc_stat->entryPeers);
8072 num_funcs = rpc_stat->stats[0].func_total;
8074 sizeof(rx_interface_stat_t) +
8075 rpc_stat->stats[0].func_total *
8076 sizeof(rx_function_entry_v1_t);
8078 rxi_Free(rpc_stat, space);
8080 /* rx_rpc_stats must be held */
8081 rxi_rpc_peer_stat_cnt -= num_funcs;
8083 MUTEX_EXIT(&peer->peer_lock);
8084 MUTEX_EXIT(&rx_rpc_stats);
8088 if (rx_stats_active)
8089 rx_atomic_dec(&rx_stats.nPeerStructs);
8091 MUTEX_EXIT(&rx_peerHashTable_lock);
8094 for (i = 0; i < RX_MAX_SERVICES; i++) {
8096 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8098 for (i = 0; i < rx_hashTableSize; i++) {
8099 struct rx_connection *tc, *ntc;
8100 MUTEX_ENTER(&rx_connHashTable_lock);
8101 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8103 for (j = 0; j < RX_MAXCALLS; j++) {
8105 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8108 rxi_Free(tc, sizeof(*tc));
8110 MUTEX_EXIT(&rx_connHashTable_lock);
8113 MUTEX_ENTER(&freeSQEList_lock);
8115 while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8116 np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8118 opr_queue_Remove(&np->entry);
8119 MUTEX_DESTROY(&np->lock);
8120 rxi_Free(np, sizeof(*np));
8123 MUTEX_EXIT(&freeSQEList_lock);
8124 MUTEX_DESTROY(&freeSQEList_lock);
8125 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8126 MUTEX_DESTROY(&rx_connHashTable_lock);
8127 MUTEX_DESTROY(&rx_peerHashTable_lock);
8128 MUTEX_DESTROY(&rx_serverPool_lock);
8130 osi_Free(rx_connHashTable,
8131 rx_hashTableSize * sizeof(struct rx_connection *));
8132 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8134 UNPIN(rx_connHashTable,
8135 rx_hashTableSize * sizeof(struct rx_connection *));
8136 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8138 MUTEX_ENTER(&rx_quota_mutex);
8139 rxi_dataQuota = RX_MAX_QUOTA;
8140 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8141 MUTEX_EXIT(&rx_quota_mutex);
8148 * Routines to implement connection specific data.
8152 rx_KeyCreate(rx_destructor_t rtn)
8155 MUTEX_ENTER(&rxi_keyCreate_lock);
8156 key = rxi_keyCreate_counter++;
8157 rxi_keyCreate_destructor = (rx_destructor_t *)
8158 realloc((void *)rxi_keyCreate_destructor,
8159 (key + 1) * sizeof(rx_destructor_t));
8160 rxi_keyCreate_destructor[key] = rtn;
8161 MUTEX_EXIT(&rxi_keyCreate_lock);
8166 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8169 MUTEX_ENTER(&conn->conn_data_lock);
8170 if (!conn->specific) {
8171 conn->specific = malloc((key + 1) * sizeof(void *));
8172 for (i = 0; i < key; i++)
8173 conn->specific[i] = NULL;
8174 conn->nSpecific = key + 1;
8175 conn->specific[key] = ptr;
8176 } else if (key >= conn->nSpecific) {
8177 conn->specific = (void **)
8178 realloc(conn->specific, (key + 1) * sizeof(void *));
8179 for (i = conn->nSpecific; i < key; i++)
8180 conn->specific[i] = NULL;
8181 conn->nSpecific = key + 1;
8182 conn->specific[key] = ptr;
8184 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8185 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8186 conn->specific[key] = ptr;
8188 MUTEX_EXIT(&conn->conn_data_lock);
8192 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8195 MUTEX_ENTER(&svc->svc_data_lock);
8196 if (!svc->specific) {
8197 svc->specific = malloc((key + 1) * sizeof(void *));
8198 for (i = 0; i < key; i++)
8199 svc->specific[i] = NULL;
8200 svc->nSpecific = key + 1;
8201 svc->specific[key] = ptr;
8202 } else if (key >= svc->nSpecific) {
8203 svc->specific = (void **)
8204 realloc(svc->specific, (key + 1) * sizeof(void *));
8205 for (i = svc->nSpecific; i < key; i++)
8206 svc->specific[i] = NULL;
8207 svc->nSpecific = key + 1;
8208 svc->specific[key] = ptr;
8210 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8211 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8212 svc->specific[key] = ptr;
8214 MUTEX_EXIT(&svc->svc_data_lock);
8218 rx_GetSpecific(struct rx_connection *conn, int key)
8221 MUTEX_ENTER(&conn->conn_data_lock);
8222 if (key >= conn->nSpecific)
8225 ptr = conn->specific[key];
8226 MUTEX_EXIT(&conn->conn_data_lock);
8231 rx_GetServiceSpecific(struct rx_service *svc, int key)
8234 MUTEX_ENTER(&svc->svc_data_lock);
8235 if (key >= svc->nSpecific)
8238 ptr = svc->specific[key];
8239 MUTEX_EXIT(&svc->svc_data_lock);
8244 #endif /* !KERNEL */
8247 * processStats is a queue used to store the statistics for the local
8248 * process. Its contents are similar to the contents of the rpcStats
8249 * queue on a rx_peer structure, but the actual data stored within
8250 * this queue contains totals across the lifetime of the process (assuming
8251 * the stats have not been reset) - unlike the per peer structures
8252 * which can come and go based upon the peer lifetime.
8255 static struct opr_queue processStats = { &processStats, &processStats };
8258 * peerStats is a queue used to store the statistics for all peer structs.
8259 * Its contents are the union of all the peer rpcStats queues.
8262 static struct opr_queue peerStats = { &peerStats, &peerStats };
8265 * rxi_monitor_processStats is used to turn process wide stat collection
8269 static int rxi_monitor_processStats = 0;
8272 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8275 static int rxi_monitor_peerStats = 0;
8279 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8281 rpc_stat->invocations = 0;
8282 rpc_stat->bytes_sent = 0;
8283 rpc_stat->bytes_rcvd = 0;
8284 rpc_stat->queue_time_sum.sec = 0;
8285 rpc_stat->queue_time_sum.usec = 0;
8286 rpc_stat->queue_time_sum_sqr.sec = 0;
8287 rpc_stat->queue_time_sum_sqr.usec = 0;
8288 rpc_stat->queue_time_min.sec = 9999999;
8289 rpc_stat->queue_time_min.usec = 9999999;
8290 rpc_stat->queue_time_max.sec = 0;
8291 rpc_stat->queue_time_max.usec = 0;
8292 rpc_stat->execution_time_sum.sec = 0;
8293 rpc_stat->execution_time_sum.usec = 0;
8294 rpc_stat->execution_time_sum_sqr.sec = 0;
8295 rpc_stat->execution_time_sum_sqr.usec = 0;
8296 rpc_stat->execution_time_min.sec = 9999999;
8297 rpc_stat->execution_time_min.usec = 9999999;
8298 rpc_stat->execution_time_max.sec = 0;
8299 rpc_stat->execution_time_max.usec = 0;
8303 * Given all of the information for a particular rpc
8304 * call, find or create (if requested) the stat structure for the rpc.
8307 * the queue of stats that will be updated with the new value
8309 * @param rxInterface
8310 * a unique number that identifies the rpc interface
8313 * the total number of functions in this interface. this is only
8314 * required if create is true
8317 * if true, this invocation was made to a server
8320 * the ip address of the remote host. this is only required if create
8321 * and addToPeerList are true
8324 * the port of the remote host. this is only required if create
8325 * and addToPeerList are true
8327 * @param addToPeerList
8328 * if != 0, add newly created stat to the global peer list
8331 * if a new stats structure is allocated, the counter will
8332 * be updated with the new number of allocated stat structures.
8333 * only required if create is true
8336 * if no stats structure exists, allocate one
8340 static rx_interface_stat_p
8341 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8342 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8343 afs_uint32 remotePort, int addToPeerList,
8344 unsigned int *counter, int create)
8346 rx_interface_stat_p rpc_stat = NULL;
8347 struct opr_queue *cursor;
8350 * See if there's already a structure for this interface
8353 for (opr_queue_Scan(stats, cursor)) {
8354 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8356 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8357 && (rpc_stat->stats[0].remote_is_server == isServer))
8361 /* if they didn't ask us to create, we're done */
8363 if (opr_queue_IsEnd(stats, cursor))
8369 /* can't proceed without these */
8370 if (!totalFunc || !counter)
8374 * Didn't find a match so allocate a new structure and add it to the
8378 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8379 || (rpc_stat->stats[0].interfaceId != rxInterface)
8380 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8385 sizeof(rx_interface_stat_t) +
8386 totalFunc * sizeof(rx_function_entry_v1_t);
8388 rpc_stat = rxi_Alloc(space);
8389 if (rpc_stat == NULL)
8392 *counter += totalFunc;
8393 for (i = 0; i < totalFunc; i++) {
8394 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8395 rpc_stat->stats[i].remote_peer = remoteHost;
8396 rpc_stat->stats[i].remote_port = remotePort;
8397 rpc_stat->stats[i].remote_is_server = isServer;
8398 rpc_stat->stats[i].interfaceId = rxInterface;
8399 rpc_stat->stats[i].func_total = totalFunc;
8400 rpc_stat->stats[i].func_index = i;
8402 opr_queue_Prepend(stats, &rpc_stat->entry);
8403 if (addToPeerList) {
8404 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8411 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8413 rx_interface_stat_p rpc_stat;
8416 if (rxInterface == -1)
8419 MUTEX_ENTER(&rx_rpc_stats);
8420 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8423 totalFunc = rpc_stat->stats[0].func_total;
8424 for (i = 0; i < totalFunc; i++)
8425 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8427 MUTEX_EXIT(&rx_rpc_stats);
8432 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8434 rx_interface_stat_p rpc_stat;
8436 struct rx_peer * peer;
8438 if (rxInterface == -1)
8441 peer = rxi_FindPeer(peerHost, peerPort, 0);
8445 MUTEX_ENTER(&rx_rpc_stats);
8446 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8449 totalFunc = rpc_stat->stats[0].func_total;
8450 for (i = 0; i < totalFunc; i++)
8451 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8453 MUTEX_EXIT(&rx_rpc_stats);
8458 rx_CopyProcessRPCStats(afs_uint64 op)
8460 rx_interface_stat_p rpc_stat;
8461 rx_function_entry_v1_p rpcop_stat =
8462 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8463 int currentFunc = (op & MAX_AFS_UINT32);
8464 afs_int32 rxInterface = (op >> 32);
8466 if (!rxi_monitor_processStats)
8469 if (rxInterface == -1)
8472 if (rpcop_stat == NULL)
8475 MUTEX_ENTER(&rx_rpc_stats);
8476 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8479 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8480 sizeof(rx_function_entry_v1_t));
8481 MUTEX_EXIT(&rx_rpc_stats);
8483 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8490 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8492 rx_interface_stat_p rpc_stat;
8493 rx_function_entry_v1_p rpcop_stat =
8494 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8495 int currentFunc = (op & MAX_AFS_UINT32);
8496 afs_int32 rxInterface = (op >> 32);
8497 struct rx_peer *peer;
8499 if (!rxi_monitor_peerStats)
8502 if (rxInterface == -1)
8505 if (rpcop_stat == NULL)
8508 peer = rxi_FindPeer(peerHost, peerPort, 0);
8512 MUTEX_ENTER(&rx_rpc_stats);
8513 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8516 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8517 sizeof(rx_function_entry_v1_t));
8518 MUTEX_EXIT(&rx_rpc_stats);
8520 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8527 rx_ReleaseRPCStats(void *stats)
8530 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8534 * Given all of the information for a particular rpc
8535 * call, create (if needed) and update the stat totals for the rpc.
8538 * the queue of stats that will be updated with the new value
8540 * @param rxInterface
8541 * a unique number that identifies the rpc interface
8543 * @param currentFunc
8544 * the index of the function being invoked
8547 * the total number of functions in this interface
8550 * the amount of time this function waited for a thread
8553 * the amount of time this function invocation took to execute
8556 * the number bytes sent by this invocation
8559 * the number bytes received by this invocation
8562 * if true, this invocation was made to a server
8565 * the ip address of the remote host
8568 * the port of the remote host
8570 * @param addToPeerList
8571 * if != 0, add newly created stat to the global peer list
8574 * if a new stats structure is allocated, the counter will
8575 * be updated with the new number of allocated stat structures
8580 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8581 afs_uint32 currentFunc, afs_uint32 totalFunc,
8582 struct clock *queueTime, struct clock *execTime,
8583 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8584 afs_uint32 remoteHost, afs_uint32 remotePort,
8585 int addToPeerList, unsigned int *counter)
8588 rx_interface_stat_p rpc_stat;
8590 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8591 remoteHost, remotePort, addToPeerList, counter,
8599 * Increment the stats for this function
8602 rpc_stat->stats[currentFunc].invocations++;
8603 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8604 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8605 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8606 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8607 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8608 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8610 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8611 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8613 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8614 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8616 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8617 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8619 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8620 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8628 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8629 afs_uint32 currentFunc, afs_uint32 totalFunc,
8630 struct clock *queueTime, struct clock *execTime,
8631 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8635 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8638 MUTEX_ENTER(&rx_rpc_stats);
8640 if (rxi_monitor_peerStats) {
8641 MUTEX_ENTER(&peer->peer_lock);
8642 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8643 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8644 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8645 MUTEX_EXIT(&peer->peer_lock);
8648 if (rxi_monitor_processStats) {
8649 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8650 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8651 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8654 MUTEX_EXIT(&rx_rpc_stats);
8658 * Increment the times and count for a particular rpc function.
8660 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8661 * call rx_RecordCallStatistics instead, so the public version of this
8662 * function is left purely for legacy callers.
8665 * The peer who invoked the rpc
8667 * @param rxInterface
8668 * A unique number that identifies the rpc interface
8670 * @param currentFunc
8671 * The index of the function being invoked
8674 * The total number of functions in this interface
8677 * The amount of time this function waited for a thread
8680 * The amount of time this function invocation took to execute
8683 * The number bytes sent by this invocation
8686 * The number bytes received by this invocation
8689 * If true, this invocation was made to a server
8693 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8694 afs_uint32 currentFunc, afs_uint32 totalFunc,
8695 struct clock *queueTime, struct clock *execTime,
8696 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8702 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8703 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8705 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8706 queueTime, execTime, sent64, rcvd64,
8713 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8717 * IN callerVersion - the rpc stat version of the caller.
8719 * IN count - the number of entries to marshall.
8721 * IN stats - pointer to stats to be marshalled.
8723 * OUT ptr - Where to store the marshalled data.
8730 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8731 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8737 * We only support the first version
8739 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8740 *(ptr++) = stats->remote_peer;
8741 *(ptr++) = stats->remote_port;
8742 *(ptr++) = stats->remote_is_server;
8743 *(ptr++) = stats->interfaceId;
8744 *(ptr++) = stats->func_total;
8745 *(ptr++) = stats->func_index;
8746 *(ptr++) = stats->invocations >> 32;
8747 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8748 *(ptr++) = stats->bytes_sent >> 32;
8749 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8750 *(ptr++) = stats->bytes_rcvd >> 32;
8751 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8752 *(ptr++) = stats->queue_time_sum.sec;
8753 *(ptr++) = stats->queue_time_sum.usec;
8754 *(ptr++) = stats->queue_time_sum_sqr.sec;
8755 *(ptr++) = stats->queue_time_sum_sqr.usec;
8756 *(ptr++) = stats->queue_time_min.sec;
8757 *(ptr++) = stats->queue_time_min.usec;
8758 *(ptr++) = stats->queue_time_max.sec;
8759 *(ptr++) = stats->queue_time_max.usec;
8760 *(ptr++) = stats->execution_time_sum.sec;
8761 *(ptr++) = stats->execution_time_sum.usec;
8762 *(ptr++) = stats->execution_time_sum_sqr.sec;
8763 *(ptr++) = stats->execution_time_sum_sqr.usec;
8764 *(ptr++) = stats->execution_time_min.sec;
8765 *(ptr++) = stats->execution_time_min.usec;
8766 *(ptr++) = stats->execution_time_max.sec;
8767 *(ptr++) = stats->execution_time_max.usec;
8773 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8778 * IN callerVersion - the rpc stat version of the caller
8780 * OUT myVersion - the rpc stat version of this function
8782 * OUT clock_sec - local time seconds
8784 * OUT clock_usec - local time microseconds
8786 * OUT allocSize - the number of bytes allocated to contain stats
8788 * OUT statCount - the number stats retrieved from this process.
8790 * OUT stats - the actual stats retrieved from this process.
8794 * Returns void. If successful, stats will != NULL.
8798 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8799 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8800 size_t * allocSize, afs_uint32 * statCount,
8801 afs_uint32 ** stats)
8811 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8814 * Check to see if stats are enabled
8817 MUTEX_ENTER(&rx_rpc_stats);
8818 if (!rxi_monitor_processStats) {
8819 MUTEX_EXIT(&rx_rpc_stats);
8823 clock_GetTime(&now);
8824 *clock_sec = now.sec;
8825 *clock_usec = now.usec;
8828 * Allocate the space based upon the caller version
8830 * If the client is at an older version than we are,
8831 * we return the statistic data in the older data format, but
8832 * we still return our version number so the client knows we
8833 * are maintaining more data than it can retrieve.
8836 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8837 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8838 *statCount = rxi_rpc_process_stat_cnt;
8841 * This can't happen yet, but in the future version changes
8842 * can be handled by adding additional code here
8846 if (space > (size_t) 0) {
8848 ptr = *stats = rxi_Alloc(space);
8851 struct opr_queue *cursor;
8853 for (opr_queue_Scan(&processStats, cursor)) {
8854 struct rx_interface_stat *rpc_stat =
8855 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8857 * Copy the data based upon the caller version
8859 rx_MarshallProcessRPCStats(callerVersion,
8860 rpc_stat->stats[0].func_total,
8861 rpc_stat->stats, &ptr);
8867 MUTEX_EXIT(&rx_rpc_stats);
8872 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8876 * IN callerVersion - the rpc stat version of the caller
8878 * OUT myVersion - the rpc stat version of this function
8880 * OUT clock_sec - local time seconds
8882 * OUT clock_usec - local time microseconds
8884 * OUT allocSize - the number of bytes allocated to contain stats
8886 * OUT statCount - the number of stats retrieved from the individual
8889 * OUT stats - the actual stats retrieved from the individual peer structures.
8893 * Returns void. If successful, stats will != NULL.
8897 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8898 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8899 size_t * allocSize, afs_uint32 * statCount,
8900 afs_uint32 ** stats)
8910 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8913 * Check to see if stats are enabled
8916 MUTEX_ENTER(&rx_rpc_stats);
8917 if (!rxi_monitor_peerStats) {
8918 MUTEX_EXIT(&rx_rpc_stats);
8922 clock_GetTime(&now);
8923 *clock_sec = now.sec;
8924 *clock_usec = now.usec;
8927 * Allocate the space based upon the caller version
8929 * If the client is at an older version than we are,
8930 * we return the statistic data in the older data format, but
8931 * we still return our version number so the client knows we
8932 * are maintaining more data than it can retrieve.
8935 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8936 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8937 *statCount = rxi_rpc_peer_stat_cnt;
8940 * This can't happen yet, but in the future version changes
8941 * can be handled by adding additional code here
8945 if (space > (size_t) 0) {
8947 ptr = *stats = rxi_Alloc(space);
8950 struct opr_queue *cursor;
8952 for (opr_queue_Scan(&peerStats, cursor)) {
8953 struct rx_interface_stat *rpc_stat
8954 = opr_queue_Entry(cursor, struct rx_interface_stat,
8958 * Copy the data based upon the caller version
8960 rx_MarshallProcessRPCStats(callerVersion,
8961 rpc_stat->stats[0].func_total,
8962 rpc_stat->stats, &ptr);
8968 MUTEX_EXIT(&rx_rpc_stats);
8973 * rx_FreeRPCStats - free memory allocated by
8974 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8978 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8979 * rx_RetrievePeerRPCStats
8981 * IN allocSize - the number of bytes in stats.
8989 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8991 rxi_Free(stats, allocSize);
8995 * rx_queryProcessRPCStats - see if process rpc stat collection is
8996 * currently enabled.
9002 * Returns 0 if stats are not enabled != 0 otherwise
9006 rx_queryProcessRPCStats(void)
9009 MUTEX_ENTER(&rx_rpc_stats);
9010 rc = rxi_monitor_processStats;
9011 MUTEX_EXIT(&rx_rpc_stats);
9016 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
9022 * Returns 0 if stats are not enabled != 0 otherwise
9026 rx_queryPeerRPCStats(void)
9029 MUTEX_ENTER(&rx_rpc_stats);
9030 rc = rxi_monitor_peerStats;
9031 MUTEX_EXIT(&rx_rpc_stats);
9036 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
9046 rx_enableProcessRPCStats(void)
9048 MUTEX_ENTER(&rx_rpc_stats);
9049 rx_enable_stats = 1;
9050 rxi_monitor_processStats = 1;
9051 MUTEX_EXIT(&rx_rpc_stats);
9055 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9065 rx_enablePeerRPCStats(void)
9067 MUTEX_ENTER(&rx_rpc_stats);
9068 rx_enable_stats = 1;
9069 rxi_monitor_peerStats = 1;
9070 MUTEX_EXIT(&rx_rpc_stats);
9074 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9084 rx_disableProcessRPCStats(void)
9086 struct opr_queue *cursor, *store;
9089 MUTEX_ENTER(&rx_rpc_stats);
9092 * Turn off process statistics and if peer stats is also off, turn
9096 rxi_monitor_processStats = 0;
9097 if (rxi_monitor_peerStats == 0) {
9098 rx_enable_stats = 0;
9101 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9102 unsigned int num_funcs = 0;
9103 struct rx_interface_stat *rpc_stat
9104 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9106 opr_queue_Remove(&rpc_stat->entry);
9108 num_funcs = rpc_stat->stats[0].func_total;
9110 sizeof(rx_interface_stat_t) +
9111 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9113 rxi_Free(rpc_stat, space);
9114 rxi_rpc_process_stat_cnt -= num_funcs;
9116 MUTEX_EXIT(&rx_rpc_stats);
9120 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9130 rx_disablePeerRPCStats(void)
9132 struct rx_peer **peer_ptr, **peer_end;
9136 * Turn off peer statistics and if process stats is also off, turn
9140 rxi_monitor_peerStats = 0;
9141 if (rxi_monitor_processStats == 0) {
9142 rx_enable_stats = 0;
9145 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9146 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9148 struct rx_peer *peer, *next, *prev;
9150 MUTEX_ENTER(&rx_peerHashTable_lock);
9151 MUTEX_ENTER(&rx_rpc_stats);
9152 for (prev = peer = *peer_ptr; peer; peer = next) {
9154 code = MUTEX_TRYENTER(&peer->peer_lock);
9157 struct opr_queue *cursor, *store;
9159 if (prev == *peer_ptr) {
9170 MUTEX_EXIT(&rx_peerHashTable_lock);
9172 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9173 unsigned int num_funcs = 0;
9174 struct rx_interface_stat *rpc_stat
9175 = opr_queue_Entry(cursor, struct rx_interface_stat,
9178 opr_queue_Remove(&rpc_stat->entry);
9179 opr_queue_Remove(&rpc_stat->entryPeers);
9180 num_funcs = rpc_stat->stats[0].func_total;
9182 sizeof(rx_interface_stat_t) +
9183 rpc_stat->stats[0].func_total *
9184 sizeof(rx_function_entry_v1_t);
9186 rxi_Free(rpc_stat, space);
9187 rxi_rpc_peer_stat_cnt -= num_funcs;
9189 MUTEX_EXIT(&peer->peer_lock);
9191 MUTEX_ENTER(&rx_peerHashTable_lock);
9201 MUTEX_EXIT(&rx_rpc_stats);
9202 MUTEX_EXIT(&rx_peerHashTable_lock);
9207 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9212 * IN clearFlag - flag indicating which stats to clear
9220 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9222 struct opr_queue *cursor;
9224 MUTEX_ENTER(&rx_rpc_stats);
9226 for (opr_queue_Scan(&processStats, cursor)) {
9227 unsigned int num_funcs = 0, i;
9228 struct rx_interface_stat *rpc_stat
9229 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9231 num_funcs = rpc_stat->stats[0].func_total;
9232 for (i = 0; i < num_funcs; i++) {
9233 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9234 rpc_stat->stats[i].invocations = 0;
9236 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9237 rpc_stat->stats[i].bytes_sent = 0;
9239 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9240 rpc_stat->stats[i].bytes_rcvd = 0;
9242 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9243 rpc_stat->stats[i].queue_time_sum.sec = 0;
9244 rpc_stat->stats[i].queue_time_sum.usec = 0;
9246 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9247 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9248 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9250 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9251 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9252 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9254 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9255 rpc_stat->stats[i].queue_time_max.sec = 0;
9256 rpc_stat->stats[i].queue_time_max.usec = 0;
9258 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9259 rpc_stat->stats[i].execution_time_sum.sec = 0;
9260 rpc_stat->stats[i].execution_time_sum.usec = 0;
9262 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9263 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9264 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9266 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9267 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9268 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9270 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9271 rpc_stat->stats[i].execution_time_max.sec = 0;
9272 rpc_stat->stats[i].execution_time_max.usec = 0;
9277 MUTEX_EXIT(&rx_rpc_stats);
9281 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9286 * IN clearFlag - flag indicating which stats to clear
9294 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9296 struct opr_queue *cursor;
9298 MUTEX_ENTER(&rx_rpc_stats);
9300 for (opr_queue_Scan(&peerStats, cursor)) {
9301 unsigned int num_funcs, i;
9302 struct rx_interface_stat *rpc_stat
9303 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9305 num_funcs = rpc_stat->stats[0].func_total;
9306 for (i = 0; i < num_funcs; i++) {
9307 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9308 rpc_stat->stats[i].invocations = 0;
9310 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9311 rpc_stat->stats[i].bytes_sent = 0;
9313 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9314 rpc_stat->stats[i].bytes_rcvd = 0;
9316 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9317 rpc_stat->stats[i].queue_time_sum.sec = 0;
9318 rpc_stat->stats[i].queue_time_sum.usec = 0;
9320 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9321 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9322 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9324 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9325 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9326 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9328 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9329 rpc_stat->stats[i].queue_time_max.sec = 0;
9330 rpc_stat->stats[i].queue_time_max.usec = 0;
9332 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9333 rpc_stat->stats[i].execution_time_sum.sec = 0;
9334 rpc_stat->stats[i].execution_time_sum.usec = 0;
9336 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9337 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9338 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9340 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9341 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9342 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9344 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9345 rpc_stat->stats[i].execution_time_max.sec = 0;
9346 rpc_stat->stats[i].execution_time_max.usec = 0;
9351 MUTEX_EXIT(&rx_rpc_stats);
9355 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9356 * is authorized to enable/disable/clear RX statistics.
9358 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9361 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9363 rxi_rxstat_userok = proc;
9367 rx_RxStatUserOk(struct rx_call *call)
9369 if (!rxi_rxstat_userok)
9371 return rxi_rxstat_userok(call);
9376 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9377 * function in the MSVC runtime DLL (msvcrt.dll).
9379 * Note: the system serializes calls to this function.
9382 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9383 DWORD reason, /* reason function is being called */
9384 LPVOID reserved) /* reserved for future use */
9387 case DLL_PROCESS_ATTACH:
9388 /* library is being attached to a process */
9392 case DLL_PROCESS_DETACH:
9399 #endif /* AFS_NT40_ENV */
9402 int rx_DumpCalls(FILE *outputFile, char *cookie)
9404 #ifdef RXDEBUG_PACKET
9405 #ifdef KDUMP_RX_LOCK
9406 struct rx_call_rx_lock *c;
9413 #define RXDPRINTF sprintf
9414 #define RXDPRINTOUT output
9416 #define RXDPRINTF fprintf
9417 #define RXDPRINTOUT outputFile
9420 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9422 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9425 for (c = rx_allCallsp; c; c = c->allNextp) {
9426 u_short rqc, tqc, iovqc;
9428 MUTEX_ENTER(&c->lock);
9429 rqc = opr_queue_Count(&c->rq);
9430 tqc = opr_queue_Count(&c->tq);
9431 iovqc = opr_queue_Count(&c->app.iovq);
9433 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, "
9434 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9435 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9436 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9437 "lastSendTime=%u, lastRecvTime=%u"
9438 #ifdef RX_ENABLE_LOCKS
9441 #ifdef RX_REFCOUNT_CHECK
9442 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9443 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9446 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->app.mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
9447 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9448 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9449 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9450 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9451 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9452 #ifdef RX_ENABLE_LOCKS
9453 , (afs_uint32)c->refCount
9455 #ifdef RX_REFCOUNT_CHECK
9456 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9459 MUTEX_EXIT(&c->lock);
9462 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9465 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9467 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9469 #endif /* RXDEBUG_PACKET */
9474 #ifdef AFS_RXERRQ_ENV
9476 rxi_HandleSocketErrors(osi_socket sock)
9478 size_t cmsgbuf_len = 256;
9481 int errno_save = errno;
9484 cmsgbuf = rxi_Alloc(cmsgbuf_len);
9485 if (cmsgbuf == NULL) {
9489 while (osi_HandleSocketError(sock, cmsgbuf, cmsgbuf_len))
9492 rxi_Free(cmsgbuf, cmsgbuf_len);
9502 NetSend_retry(osi_socket sock, void *addr, struct iovec *dvec, int nvecs,
9503 int length, int istack)
9508 * If an ICMP error comes in for any peer, sendmsg() can return -1 with an
9509 * errno of EHOSTUNREACH, ENETUNREACH, etc. There may be no problem with
9510 * sending this packet (an error is returned just to indicate we need to
9511 * read in pending errors), but the packet wasn't actually sent.
9513 * It's difficult to determine in general whether sendmsg() is returning an
9514 * error due to a received ICMP error, or we're getting an actual error for
9515 * this specific sendmsg() call, since there may be other threads running
9516 * sendmsg/recvmsg/rxi_HandleSocketErrors at the same time. So, just retry
9517 * the sendmsg a few times; make sure not to retry forever, in case we are
9518 * getting an actual error from this sendmsg() call.
9520 * Also note that if we accidentally drop a packet here that we didn't need
9521 * to, it's not the end of the world. Packets get dropped, and we should be
9524 for (safety = 0; safety < RXI_SENDMSG_RETRY; safety++) {
9525 code = osi_NetSend(sock, addr, dvec, nvecs, length, istack);
9529 rxi_HandleSocketErrors(sock);
9537 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9538 int nvecs, int length, int istack)
9540 if (rxi_IsRunning()) {
9541 #ifdef AFS_RXERRQ_ENV
9542 return NetSend_retry(socket, addr, dvec, nvecs, length, istack);
9544 return osi_NetSend(socket, addr, dvec, nvecs, length, istack);
9548 return WSAESHUTDOWN;