Import Upstream version 1.8.5
[hcoop/debian/openafs.git] / src / rx / rx.c
1 /*
2 * Copyright 2000, International Business Machines Corporation and others.
3 * All Rights Reserved.
4 *
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
8 */
9
10 /* RX: Extended Remote Procedure Call */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15 #ifdef KERNEL
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
18 # ifndef UKERNEL
19 # include "h/types.h"
20 # include "h/time.h"
21 # include "h/stat.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
24 # endif
25 # include "netinet/in.h"
26 # ifdef AFS_SUN5_ENV
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
29 # include "inet/ip.h"
30 # include "inet/ip_ire.h"
31 # endif
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
36 # endif
37 # if defined(AFS_AIX_ENV)
38 # include "h/systm.h"
39 # endif
40 # ifdef RXDEBUG
41 # undef RXDEBUG /* turn off debugging */
42 # endif /* RXDEBUG */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
45 # endif
46 # else /* !UKERNEL */
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;
57 # ifdef AFS_AIX41_ENV
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
62 #else /* KERNEL */
63 # include <roken.h>
64
65 # ifdef AFS_NT40_ENV
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
68 # endif
69
70 # include <afs/opr.h>
71
72 # include "rx_user.h"
73 #endif /* KERNEL */
74
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
77
78 #include "rx.h"
79 #include "rx_clock.h"
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
82 #include "rx_trace.h"
83 #include "rx_internal.h"
84 #include "rx_stats.h"
85 #include "rx_event.h"
86
87 #include "rx_peer.h"
88 #include "rx_conn.h"
89 #include "rx_call.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
92
93 #include <afs/rxgen_consts.h>
94
95 #ifndef KERNEL
96 #ifdef AFS_PTHREAD_ENV
97 #ifndef AFS_NT40_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
100 #endif
101 #else
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
104 #endif
105 #endif
106
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 *,
111 struct clock *);
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
113 int istack);
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);
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 void 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);
162
163 #ifndef KERNEL
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
167 #endif
168
169 #ifdef RX_ENABLE_LOCKS
170 struct rx_tq_debug {
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
173 } rx_tq_debug;
174 #endif /* RX_ENABLE_LOCKS */
175
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
179 * about to respond.
180 *
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
183 */
184 struct clock rx_lastAckDelay = {0, 400000};
185
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
189 *
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
192 */
193 struct clock rx_softAckDelay = {0, 100000};
194
195 /*
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.
200 */
201
202 static unsigned int rxi_rpc_peer_stat_cnt;
203
204 /*
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.
209 */
210
211 static unsigned int rxi_rpc_process_stat_cnt;
212
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
215
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
219
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
223
224 #if !defined(offsetof)
225 #include <stddef.h> /* for definition of offsetof() */
226 #endif
227
228 #ifdef RX_ENABLE_LOCKS
229 afs_kmutex_t rx_atomic_mutex;
230 #endif
231
232 /* Forward prototypes */
233 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
234
235 static_inline void
236 putConnection (struct rx_connection *conn) {
237 MUTEX_ENTER(&rx_refcnt_mutex);
238 conn->refCount--;
239 MUTEX_EXIT(&rx_refcnt_mutex);
240 }
241
242 #ifdef AFS_PTHREAD_ENV
243
244 /*
245 * Use procedural initialization of mutexes/condition variables
246 * to ease NT porting
247 */
248
249 extern afs_kmutex_t rx_quota_mutex;
250 extern afs_kmutex_t rx_pthread_mutex;
251 extern afs_kmutex_t rx_packets_mutex;
252 extern afs_kmutex_t rx_refcnt_mutex;
253 extern afs_kmutex_t des_init_mutex;
254 extern afs_kmutex_t des_random_mutex;
255 #ifndef KERNEL
256 extern afs_kmutex_t rx_clock_mutex;
257 extern afs_kmutex_t rxi_connCacheMutex;
258 extern afs_kmutex_t event_handler_mutex;
259 extern afs_kmutex_t listener_mutex;
260 extern afs_kmutex_t rx_if_init_mutex;
261 extern afs_kmutex_t rx_if_mutex;
262
263 extern afs_kcondvar_t rx_event_handler_cond;
264 extern afs_kcondvar_t rx_listener_cond;
265 #endif /* !KERNEL */
266
267 static afs_kmutex_t epoch_mutex;
268 static afs_kmutex_t rx_init_mutex;
269 static afs_kmutex_t rx_debug_mutex;
270 static afs_kmutex_t rx_rpc_stats;
271
272 static void
273 rxi_InitPthread(void)
274 {
275 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
278 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
279 #ifndef KERNEL
280 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
283 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
286 #endif
287 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
290 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
292
293 #ifndef KERNEL
294 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
295 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
296 #endif
297
298 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
299 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
300
301 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
302 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
303 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
304 0);
305
306 #ifdef RX_ENABLE_LOCKS
307 #ifdef RX_LOCKS_DB
308 rxdb_init();
309 #endif /* RX_LOCKS_DB */
310 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
311 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
312 0);
313 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
314 0);
315 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
316 0);
317 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
318 0);
319 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
320 #ifndef KERNEL
321 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
322 #endif
323 #endif /* RX_ENABLE_LOCKS */
324 }
325
326 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
327 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
328 /*
329 * The rx_stats_mutex mutex protects the following global variables:
330 * rxi_lowConnRefCount
331 * rxi_lowPeerRefCount
332 * rxi_nCalls
333 * rxi_Alloccnt
334 * rxi_Allocsize
335 * rx_tq_debug
336 * rx_stats
337 */
338
339 /*
340 * The rx_quota_mutex mutex protects the following global variables:
341 * rxi_dataQuota
342 * rxi_minDeficit
343 * rxi_availProcs
344 * rxi_totalMin
345 */
346
347 /*
348 * The rx_freePktQ_lock protects the following global variables:
349 * rx_nFreePackets
350 */
351
352 /*
353 * The rx_packets_mutex mutex protects the following global variables:
354 * rx_nPackets
355 * rx_TSFPQLocalMax
356 * rx_TSFPQGlobSize
357 * rx_TSFPQMaxProcs
358 */
359
360 /*
361 * The rx_pthread_mutex mutex protects the following global variables:
362 * rxi_fcfs_thread_num
363 */
364 #else
365 #define INIT_PTHREAD_LOCKS
366 #endif
367
368
369 /* Variables for handling the minProcs implementation. availProcs gives the
370 * number of threads available in the pool at this moment (not counting dudes
371 * executing right now). totalMin gives the total number of procs required
372 * for handling all minProcs requests. minDeficit is a dynamic variable
373 * tracking the # of procs required to satisfy all of the remaining minProcs
374 * demands.
375 * For fine grain locking to work, the quota check and the reservation of
376 * a server thread has to come while rxi_availProcs and rxi_minDeficit
377 * are locked. To this end, the code has been modified under #ifdef
378 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
379 * same time. A new function, ReturnToServerPool() returns the allocation.
380 *
381 * A call can be on several queue's (but only one at a time). When
382 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
383 * that no one else is touching the queue. To this end, we store the address
384 * of the queue lock in the call structure (under the call lock) when we
385 * put the call on a queue, and we clear the call_queue_lock when the
386 * call is removed from a queue (once the call lock has been obtained).
387 * This allows rxi_ResetCall to safely synchronize with others wishing
388 * to manipulate the queue.
389 */
390
391 #if defined(RX_ENABLE_LOCKS)
392 static afs_kmutex_t rx_rpc_stats;
393 #endif
394
395 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
396 ** pretty good that the next packet coming in is from the same connection
397 ** as the last packet, since we're send multiple packets in a transmit window.
398 */
399 struct rx_connection *rxLastConn = 0;
400
401 #ifdef RX_ENABLE_LOCKS
402 /* The locking hierarchy for rx fine grain locking is composed of these
403 * tiers:
404 *
405 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
406 * also protects updates to rx_nextCid
407 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
408 * call->lock - locks call data fields.
409 * These are independent of each other:
410 * rx_freeCallQueue_lock
411 * rxi_keyCreate_lock
412 * rx_serverPool_lock
413 * freeSQEList_lock
414 *
415 * serverQueueEntry->lock
416 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
417 * rx_rpc_stats
418 * peer->lock - locks peer data fields.
419 * conn_data_lock - that more than one thread is not updating a conn data
420 * field at the same time.
421 * rx_freePktQ_lock
422 *
423 * lowest level:
424 * multi_handle->lock
425 * rxevent_lock
426 * rx_packets_mutex
427 * rx_stats_mutex
428 * rx_refcnt_mutex
429 * rx_atomic_mutex
430 *
431 * Do we need a lock to protect the peer field in the conn structure?
432 * conn->peer was previously a constant for all intents and so has no
433 * lock protecting this field. The multihomed client delta introduced
434 * a RX code change : change the peer field in the connection structure
435 * to that remote interface from which the last packet for this
436 * connection was sent out. This may become an issue if further changes
437 * are made.
438 */
439 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
440 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
441 #ifdef RX_LOCKS_DB
442 /* rxdb_fileID is used to identify the lock location, along with line#. */
443 static int rxdb_fileID = RXDB_FILE_RX;
444 #endif /* RX_LOCKS_DB */
445 #else /* RX_ENABLE_LOCKS */
446 #define SET_CALL_QUEUE_LOCK(C, L)
447 #define CLEAR_CALL_QUEUE_LOCK(C)
448 #endif /* RX_ENABLE_LOCKS */
449 struct rx_serverQueueEntry *rx_waitForPacket = 0;
450
451 /*
452 * This mutex serializes calls to our initialization and shutdown routines
453 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
454 * these at any time; all other threads must wait for it to finish running, and
455 * then examine the value of rxi_running afterwards.
456 */
457 #ifdef AFS_PTHREAD_ENV
458 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
459 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
460 #else
461 # define LOCK_RX_INIT
462 # define UNLOCK_RX_INIT
463 #endif
464
465 /* ------------Exported Interfaces------------- */
466
467 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
468 int
469 rxi_IsRunning(void)
470 {
471 return rx_atomic_read(&rxi_running);
472 }
473
474 /* Initialize rx. A port number may be mentioned, in which case this
475 * becomes the default port number for any service installed later.
476 * If 0 is provided for the port number, a random port will be chosen
477 * by the kernel. Whether this will ever overlap anything in
478 * /etc/services is anybody's guess... Returns 0 on success, -1 on
479 * error. */
480 int
481 rx_InitHost(u_int host, u_int port)
482 {
483 #ifdef KERNEL
484 osi_timeval_t tv;
485 #else /* KERNEL */
486 struct timeval tv;
487 #endif /* KERNEL */
488 char *htable, *ptable;
489
490 SPLVAR;
491
492 INIT_PTHREAD_LOCKS;
493 LOCK_RX_INIT;
494 if (rxi_IsRunning()) {
495 UNLOCK_RX_INIT;
496 return 0; /* already started */
497 }
498 #ifdef RXDEBUG
499 rxi_DebugInit();
500 #endif
501 #ifdef AFS_NT40_ENV
502 if (afs_winsockInit() < 0)
503 goto error;
504 #endif
505
506 #ifndef KERNEL
507 /*
508 * Initialize anything necessary to provide a non-premptive threading
509 * environment.
510 */
511 rxi_InitializeThreadSupport();
512 #endif
513
514 /* Allocate and initialize a socket for client and perhaps server
515 * connections. */
516
517 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
518 if (rx_socket == OSI_NULLSOCKET) {
519 goto addrinuse;
520 }
521 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
522 #ifdef RX_LOCKS_DB
523 rxdb_init();
524 #endif /* RX_LOCKS_DB */
525 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
526 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
527 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
528 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
529 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
535 0);
536 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
537 0);
538 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
539 0);
540 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
541 0);
542 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
543 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
544 0);
545
546 #if defined(AFS_HPUX110_ENV)
547 if (!uniprocessor)
548 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
549 #endif /* AFS_HPUX110_ENV */
550 #endif /* RX_ENABLE_LOCKS && KERNEL */
551
552 rxi_nCalls = 0;
553 rx_connDeadTime = 12;
554 rx_tranquil = 0; /* reset flag */
555 rxi_ResetStatistics();
556 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
557 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
558 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
559 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
560 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
561 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
562
563 /* Malloc up a bunch of packets & buffers */
564 rx_nFreePackets = 0;
565 opr_queue_Init(&rx_freePacketQueue);
566 rxi_NeedMorePackets = FALSE;
567 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
568 opr_queue_Init(&rx_mallocedPacketQueue);
569
570 /* enforce a minimum number of allocated packets */
571 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
572 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
573
574 /* allocate the initial free packet pool */
575 #ifdef RX_ENABLE_TSFPQ
576 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
577 #else /* RX_ENABLE_TSFPQ */
578 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
579 #endif /* RX_ENABLE_TSFPQ */
580 rx_CheckPackets();
581
582 NETPRI;
583
584 clock_Init();
585
586 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
587 tv.tv_sec = clock_now.sec;
588 tv.tv_usec = clock_now.usec;
589 srand((unsigned int)tv.tv_usec);
590 #else
591 osi_GetTime(&tv);
592 #endif
593 if (port) {
594 rx_port = port;
595 } else {
596 #if defined(KERNEL) && !defined(UKERNEL)
597 /* Really, this should never happen in a real kernel */
598 rx_port = 0;
599 #else
600 struct sockaddr_in addr;
601 #ifdef AFS_NT40_ENV
602 int addrlen = sizeof(addr);
603 #else
604 socklen_t addrlen = sizeof(addr);
605 #endif
606 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
607 rxi_Finalize_locked();
608 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
609 goto error;
610 }
611 rx_port = addr.sin_port;
612 #endif
613 }
614 rx_stats.minRtt.sec = 9999999;
615 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
616 goto error;
617 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
618 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
619 goto error;
620 rx_nextCid &= RX_CIDMASK;
621 MUTEX_ENTER(&rx_quota_mutex);
622 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
623 MUTEX_EXIT(&rx_quota_mutex);
624 /* *Slightly* random start time for the cid. This is just to help
625 * out with the hashing function at the peer */
626 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
627 rx_connHashTable = (struct rx_connection **)htable;
628 rx_peerHashTable = (struct rx_peer **)ptable;
629
630 rx_hardAckDelay.sec = 0;
631 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
632
633 rxevent_Init(20, rxi_ReScheduleEvents);
634
635 /* Initialize various global queues */
636 opr_queue_Init(&rx_idleServerQueue);
637 opr_queue_Init(&rx_incomingCallQueue);
638 opr_queue_Init(&rx_freeCallQueue);
639
640 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
641 /* Initialize our list of usable IP addresses. */
642 rx_GetIFInfo();
643 #endif
644
645 /* Start listener process (exact function is dependent on the
646 * implementation environment--kernel or user space) */
647 rxi_StartListener();
648
649 USERPRI;
650
651 rx_atomic_set(&rxi_running, 1);
652 UNLOCK_RX_INIT;
653
654 return 0;
655
656 addrinuse:
657 UNLOCK_RX_INIT;
658 return RX_ADDRINUSE;
659
660 error:
661 UNLOCK_RX_INIT;
662 return -1;
663 }
664
665 int
666 rx_Init(u_int port)
667 {
668 return rx_InitHost(htonl(INADDR_ANY), port);
669 }
670
671 /* RTT Timer
672 * ---------
673 *
674 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
675 * maintaing the round trip timer.
676 *
677 */
678
679 /*!
680 * Start a new RTT timer for a given call and packet.
681 *
682 * There must be no resendEvent already listed for this call, otherwise this
683 * will leak events - intended for internal use within the RTO code only
684 *
685 * @param[in] call
686 * the RX call to start the timer for
687 * @param[in] lastPacket
688 * a flag indicating whether the last packet has been sent or not
689 *
690 * @pre call must be locked before calling this function
691 *
692 */
693 static_inline void
694 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
695 {
696 struct clock now, retryTime;
697
698 MUTEX_ASSERT(&call->lock);
699 clock_GetTime(&now);
700 retryTime = now;
701
702 clock_Add(&retryTime, &call->rto);
703
704 /* If we're sending the last packet, and we're the client, then the server
705 * may wait for an additional 400ms before returning the ACK, wait for it
706 * rather than hitting a timeout */
707 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
708 clock_Addmsec(&retryTime, 400);
709
710 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
711 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
712 call, NULL, istack);
713 }
714
715 /*!
716 * Cancel an RTT timer for a given call.
717 *
718 *
719 * @param[in] call
720 * the RX call to cancel the timer for
721 *
722 * @pre call must be locked before calling this function
723 *
724 */
725
726 static_inline void
727 rxi_rto_cancel(struct rx_call *call)
728 {
729 MUTEX_ASSERT(&call->lock);
730 if (rxevent_Cancel(&call->resendEvent))
731 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
732 }
733
734 /*!
735 * Tell the RTO timer that we have sent a packet.
736 *
737 * If the timer isn't already running, then start it. If the timer is running,
738 * then do nothing.
739 *
740 * @param[in] call
741 * the RX call that the packet has been sent on
742 * @param[in] lastPacket
743 * A flag which is true if this is the last packet for the call
744 *
745 * @pre The call must be locked before calling this function
746 *
747 */
748
749 static_inline void
750 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
751 {
752 if (call->resendEvent)
753 return;
754
755 rxi_rto_startTimer(call, lastPacket, istack);
756 }
757
758 /*!
759 * Tell the RTO timer that we have received an new ACK message
760 *
761 * This function should be called whenever a call receives an ACK that
762 * acknowledges new packets. Whatever happens, we stop the current timer.
763 * If there are unacked packets in the queue which have been sent, then
764 * we restart the timer from now. Otherwise, we leave it stopped.
765 *
766 * @param[in] call
767 * the RX call that the ACK has been received on
768 */
769
770 static_inline void
771 rxi_rto_packet_acked(struct rx_call *call, int istack)
772 {
773 struct opr_queue *cursor;
774
775 rxi_rto_cancel(call);
776
777 if (opr_queue_IsEmpty(&call->tq))
778 return;
779
780 for (opr_queue_Scan(&call->tq, cursor)) {
781 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
782 if (p->header.seq > call->tfirst + call->twind)
783 return;
784
785 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
786 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
787 return;
788 }
789 }
790 }
791
792
793 /**
794 * Set an initial round trip timeout for a peer connection
795 *
796 * @param[in] secs The timeout to set in seconds
797 */
798
799 void
800 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
801 peer->rtt = secs * 8000;
802 }
803
804 /**
805 * Set a delayed ack event on the specified call for the given time
806 *
807 * @param[in] call - the call on which to set the event
808 * @param[in] offset - the delay from now after which the event fires
809 */
810 void
811 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
812 {
813 struct clock now, when;
814
815 MUTEX_ASSERT(&call->lock);
816 clock_GetTime(&now);
817 when = now;
818 clock_Add(&when, offset);
819
820 if (clock_Gt(&call->delayedAckTime, &when) &&
821 rxevent_Cancel(&call->delayedAckEvent)) {
822 /* We successfully cancelled an event too far in the future to install
823 * our new one; we can reuse the reference on the call. */
824 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
825 call, NULL, 0);
826
827 call->delayedAckTime = when;
828 } else if (call->delayedAckEvent == NULL) {
829 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
830 call->delayedAckEvent = rxevent_Post(&when, &now,
831 rxi_SendDelayedAck,
832 call, NULL, 0);
833 call->delayedAckTime = when;
834 }
835 }
836
837 void
838 rxi_CancelDelayedAckEvent(struct rx_call *call)
839 {
840 MUTEX_ASSERT(&call->lock);
841 /* Only drop the ref if we cancelled it before it could run. */
842 if (rxevent_Cancel(&call->delayedAckEvent))
843 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
844 }
845
846 /* called with unincremented nRequestsRunning to see if it is OK to start
847 * a new thread in this service. Could be "no" for two reasons: over the
848 * max quota, or would prevent others from reaching their min quota.
849 */
850 #ifdef RX_ENABLE_LOCKS
851 /* This verion of QuotaOK reserves quota if it's ok while the
852 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
853 */
854 static int
855 QuotaOK(struct rx_service *aservice)
856 {
857 /* check if over max quota */
858 if (aservice->nRequestsRunning >= aservice->maxProcs) {
859 return 0;
860 }
861
862 /* under min quota, we're OK */
863 /* otherwise, can use only if there are enough to allow everyone
864 * to go to their min quota after this guy starts.
865 */
866
867 MUTEX_ENTER(&rx_quota_mutex);
868 if ((aservice->nRequestsRunning < aservice->minProcs)
869 || (rxi_availProcs > rxi_minDeficit)) {
870 aservice->nRequestsRunning++;
871 /* just started call in minProcs pool, need fewer to maintain
872 * guarantee */
873 if (aservice->nRequestsRunning <= aservice->minProcs)
874 rxi_minDeficit--;
875 rxi_availProcs--;
876 MUTEX_EXIT(&rx_quota_mutex);
877 return 1;
878 }
879 MUTEX_EXIT(&rx_quota_mutex);
880
881 return 0;
882 }
883
884 static void
885 ReturnToServerPool(struct rx_service *aservice)
886 {
887 aservice->nRequestsRunning--;
888 MUTEX_ENTER(&rx_quota_mutex);
889 if (aservice->nRequestsRunning < aservice->minProcs)
890 rxi_minDeficit++;
891 rxi_availProcs++;
892 MUTEX_EXIT(&rx_quota_mutex);
893 }
894
895 #else /* RX_ENABLE_LOCKS */
896 static int
897 QuotaOK(struct rx_service *aservice)
898 {
899 int rc = 0;
900 /* under min quota, we're OK */
901 if (aservice->nRequestsRunning < aservice->minProcs)
902 return 1;
903
904 /* check if over max quota */
905 if (aservice->nRequestsRunning >= aservice->maxProcs)
906 return 0;
907
908 /* otherwise, can use only if there are enough to allow everyone
909 * to go to their min quota after this guy starts.
910 */
911 MUTEX_ENTER(&rx_quota_mutex);
912 if (rxi_availProcs > rxi_minDeficit)
913 rc = 1;
914 MUTEX_EXIT(&rx_quota_mutex);
915 return rc;
916 }
917 #endif /* RX_ENABLE_LOCKS */
918
919 #ifndef KERNEL
920 /* Called by rx_StartServer to start up lwp's to service calls.
921 NExistingProcs gives the number of procs already existing, and which
922 therefore needn't be created. */
923 static void
924 rxi_StartServerProcs(int nExistingProcs)
925 {
926 struct rx_service *service;
927 int i;
928 int maxdiff = 0;
929 int nProcs = 0;
930
931 /* For each service, reserve N processes, where N is the "minimum"
932 * number of processes that MUST be able to execute a request in parallel,
933 * at any time, for that process. Also compute the maximum difference
934 * between any service's maximum number of processes that can run
935 * (i.e. the maximum number that ever will be run, and a guarantee
936 * that this number will run if other services aren't running), and its
937 * minimum number. The result is the extra number of processes that
938 * we need in order to provide the latter guarantee */
939 for (i = 0; i < RX_MAX_SERVICES; i++) {
940 int diff;
941 service = rx_services[i];
942 if (service == (struct rx_service *)0)
943 break;
944 nProcs += service->minProcs;
945 diff = service->maxProcs - service->minProcs;
946 if (diff > maxdiff)
947 maxdiff = diff;
948 }
949 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
950 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
951 for (i = 0; i < nProcs; i++) {
952 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
953 }
954 }
955 #endif /* KERNEL */
956
957 #ifdef AFS_NT40_ENV
958 /* This routine is only required on Windows */
959 void
960 rx_StartClientThread(void)
961 {
962 #ifdef AFS_PTHREAD_ENV
963 pthread_t pid;
964 pid = pthread_self();
965 #endif /* AFS_PTHREAD_ENV */
966 }
967 #endif /* AFS_NT40_ENV */
968
969 /* This routine must be called if any services are exported. If the
970 * donateMe flag is set, the calling process is donated to the server
971 * process pool */
972 void
973 rx_StartServer(int donateMe)
974 {
975 struct rx_service *service;
976 int i;
977 SPLVAR;
978 clock_NewTime();
979
980 NETPRI;
981 /* Start server processes, if necessary (exact function is dependent
982 * on the implementation environment--kernel or user space). DonateMe
983 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
984 * case, one less new proc will be created rx_StartServerProcs.
985 */
986 rxi_StartServerProcs(donateMe);
987
988 /* count up the # of threads in minProcs, and add set the min deficit to
989 * be that value, too.
990 */
991 for (i = 0; i < RX_MAX_SERVICES; i++) {
992 service = rx_services[i];
993 if (service == (struct rx_service *)0)
994 break;
995 MUTEX_ENTER(&rx_quota_mutex);
996 rxi_totalMin += service->minProcs;
997 /* below works even if a thread is running, since minDeficit would
998 * still have been decremented and later re-incremented.
999 */
1000 rxi_minDeficit += service->minProcs;
1001 MUTEX_EXIT(&rx_quota_mutex);
1002 }
1003
1004 /* Turn on reaping of idle server connections */
1005 rxi_ReapConnections(NULL, NULL, NULL, 0);
1006
1007 USERPRI;
1008
1009 if (donateMe) {
1010 #ifndef AFS_NT40_ENV
1011 #ifndef KERNEL
1012 char name[32];
1013 static int nProcs;
1014 #ifdef AFS_PTHREAD_ENV
1015 pid_t pid;
1016 pid = afs_pointer_to_int(pthread_self());
1017 #else /* AFS_PTHREAD_ENV */
1018 PROCESS pid;
1019 LWP_CurrentProcess(&pid);
1020 #endif /* AFS_PTHREAD_ENV */
1021
1022 sprintf(name, "srv_%d", ++nProcs);
1023 if (registerProgram)
1024 (*registerProgram) (pid, name);
1025 #endif /* KERNEL */
1026 #endif /* AFS_NT40_ENV */
1027 rx_ServerProc(NULL); /* Never returns */
1028 }
1029 #ifdef RX_ENABLE_TSFPQ
1030 /* no use leaving packets around in this thread's local queue if
1031 * it isn't getting donated to the server thread pool.
1032 */
1033 rxi_FlushLocalPacketsTSFPQ();
1034 #endif /* RX_ENABLE_TSFPQ */
1035 return;
1036 }
1037
1038 /* Create a new client connection to the specified service, using the
1039 * specified security object to implement the security model for this
1040 * connection. */
1041 struct rx_connection *
1042 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1043 struct rx_securityClass *securityObject,
1044 int serviceSecurityIndex)
1045 {
1046 int hashindex, i;
1047 struct rx_connection *conn;
1048
1049 SPLVAR;
1050
1051 clock_NewTime();
1052 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1053 "serviceSecurityIndex %d)\n",
1054 ntohl(shost), ntohs(sport), sservice, securityObject,
1055 serviceSecurityIndex));
1056
1057 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1058 * the case of kmem_alloc? */
1059 conn = rxi_AllocConnection();
1060 #ifdef RX_ENABLE_LOCKS
1061 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1062 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1063 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1064 #endif
1065 NETPRI;
1066 MUTEX_ENTER(&rx_connHashTable_lock);
1067 conn->type = RX_CLIENT_CONNECTION;
1068 conn->epoch = rx_epoch;
1069 conn->cid = rx_nextCid;
1070 update_nextCid();
1071 conn->peer = rxi_FindPeer(shost, sport, 1);
1072 conn->serviceId = sservice;
1073 conn->securityObject = securityObject;
1074 conn->securityData = (void *) 0;
1075 conn->securityIndex = serviceSecurityIndex;
1076 rx_SetConnDeadTime(conn, rx_connDeadTime);
1077 rx_SetConnSecondsUntilNatPing(conn, 0);
1078 conn->ackRate = RX_FAST_ACK_RATE;
1079 conn->nSpecific = 0;
1080 conn->specific = NULL;
1081 conn->challengeEvent = NULL;
1082 conn->delayedAbortEvent = NULL;
1083 conn->abortCount = 0;
1084 conn->error = 0;
1085 for (i = 0; i < RX_MAXCALLS; i++) {
1086 conn->twind[i] = rx_initSendWindow;
1087 conn->rwind[i] = rx_initReceiveWindow;
1088 conn->lastBusy[i] = 0;
1089 }
1090
1091 RXS_NewConnection(securityObject, conn);
1092 hashindex =
1093 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1094
1095 conn->refCount++; /* no lock required since only this thread knows... */
1096 conn->next = rx_connHashTable[hashindex];
1097 rx_connHashTable[hashindex] = conn;
1098 if (rx_stats_active)
1099 rx_atomic_inc(&rx_stats.nClientConns);
1100 MUTEX_EXIT(&rx_connHashTable_lock);
1101 USERPRI;
1102 return conn;
1103 }
1104
1105 /**
1106 * Ensure a connection's timeout values are valid.
1107 *
1108 * @param[in] conn The connection to check
1109 *
1110 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1111 * unless idleDeadTime and/or hardDeadTime are not set
1112 * @internal
1113 */
1114 static void
1115 rxi_CheckConnTimeouts(struct rx_connection *conn)
1116 {
1117 /* a connection's timeouts must have the relationship
1118 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1119 * total loss of network to a peer may cause an idle timeout instead of a
1120 * dead timeout, simply because the idle timeout gets hit first. Also set
1121 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1122 /* this logic is slightly complicated by the fact that
1123 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1124 */
1125 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1126 if (conn->idleDeadTime) {
1127 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1128 }
1129 if (conn->hardDeadTime) {
1130 if (conn->idleDeadTime) {
1131 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1132 } else {
1133 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1134 }
1135 }
1136 }
1137
1138 void
1139 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1140 {
1141 /* The idea is to set the dead time to a value that allows several
1142 * keepalives to be dropped without timing out the connection. */
1143 conn->secondsUntilDead = seconds;
1144 rxi_CheckConnTimeouts(conn);
1145 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1146 }
1147
1148 void
1149 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1150 {
1151 conn->hardDeadTime = seconds;
1152 rxi_CheckConnTimeouts(conn);
1153 }
1154
1155 void
1156 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1157 {
1158 conn->idleDeadTime = seconds;
1159 rxi_CheckConnTimeouts(conn);
1160 }
1161
1162 int rxi_lowPeerRefCount = 0;
1163 int rxi_lowConnRefCount = 0;
1164
1165 /*
1166 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1167 * NOTE: must not be called with rx_connHashTable_lock held.
1168 */
1169 static void
1170 rxi_CleanupConnection(struct rx_connection *conn)
1171 {
1172 /* Notify the service exporter, if requested, that this connection
1173 * is being destroyed */
1174 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1175 (*conn->service->destroyConnProc) (conn);
1176
1177 /* Notify the security module that this connection is being destroyed */
1178 RXS_DestroyConnection(conn->securityObject, conn);
1179
1180 /* If this is the last connection using the rx_peer struct, set its
1181 * idle time to now. rxi_ReapConnections will reap it if it's still
1182 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1183 */
1184 MUTEX_ENTER(&rx_peerHashTable_lock);
1185 if (conn->peer->refCount < 2) {
1186 conn->peer->idleWhen = clock_Sec();
1187 if (conn->peer->refCount < 1) {
1188 conn->peer->refCount = 1;
1189 if (rx_stats_active) {
1190 MUTEX_ENTER(&rx_stats_mutex);
1191 rxi_lowPeerRefCount++;
1192 MUTEX_EXIT(&rx_stats_mutex);
1193 }
1194 }
1195 }
1196 conn->peer->refCount--;
1197 MUTEX_EXIT(&rx_peerHashTable_lock);
1198
1199 if (rx_stats_active)
1200 {
1201 if (conn->type == RX_SERVER_CONNECTION)
1202 rx_atomic_dec(&rx_stats.nServerConns);
1203 else
1204 rx_atomic_dec(&rx_stats.nClientConns);
1205 }
1206 #ifndef KERNEL
1207 if (conn->specific) {
1208 int i;
1209 for (i = 0; i < conn->nSpecific; i++) {
1210 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1211 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1212 conn->specific[i] = NULL;
1213 }
1214 free(conn->specific);
1215 }
1216 conn->specific = NULL;
1217 conn->nSpecific = 0;
1218 #endif /* !KERNEL */
1219
1220 MUTEX_DESTROY(&conn->conn_call_lock);
1221 MUTEX_DESTROY(&conn->conn_data_lock);
1222 CV_DESTROY(&conn->conn_call_cv);
1223
1224 rxi_FreeConnection(conn);
1225 }
1226
1227 /* Destroy the specified connection */
1228 void
1229 rxi_DestroyConnection(struct rx_connection *conn)
1230 {
1231 MUTEX_ENTER(&rx_connHashTable_lock);
1232 rxi_DestroyConnectionNoLock(conn);
1233 /* conn should be at the head of the cleanup list */
1234 if (conn == rx_connCleanup_list) {
1235 rx_connCleanup_list = rx_connCleanup_list->next;
1236 MUTEX_EXIT(&rx_connHashTable_lock);
1237 rxi_CleanupConnection(conn);
1238 }
1239 #ifdef RX_ENABLE_LOCKS
1240 else {
1241 MUTEX_EXIT(&rx_connHashTable_lock);
1242 }
1243 #endif /* RX_ENABLE_LOCKS */
1244 }
1245
1246 static void
1247 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1248 {
1249 struct rx_connection **conn_ptr;
1250 int havecalls = 0;
1251 int i;
1252 SPLVAR;
1253
1254 clock_NewTime();
1255
1256 NETPRI;
1257 MUTEX_ENTER(&conn->conn_data_lock);
1258 MUTEX_ENTER(&rx_refcnt_mutex);
1259 if (conn->refCount > 0)
1260 conn->refCount--;
1261 else {
1262 #ifdef RX_REFCOUNT_CHECK
1263 osi_Assert(conn->refCount == 0);
1264 #endif
1265 if (rx_stats_active) {
1266 MUTEX_ENTER(&rx_stats_mutex);
1267 rxi_lowConnRefCount++;
1268 MUTEX_EXIT(&rx_stats_mutex);
1269 }
1270 }
1271
1272 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1273 /* Busy; wait till the last guy before proceeding */
1274 MUTEX_EXIT(&rx_refcnt_mutex);
1275 MUTEX_EXIT(&conn->conn_data_lock);
1276 USERPRI;
1277 return;
1278 }
1279
1280 /* If the client previously called rx_NewCall, but it is still
1281 * waiting, treat this as a running call, and wait to destroy the
1282 * connection later when the call completes. */
1283 if ((conn->type == RX_CLIENT_CONNECTION)
1284 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1285 conn->flags |= RX_CONN_DESTROY_ME;
1286 MUTEX_EXIT(&rx_refcnt_mutex);
1287 MUTEX_EXIT(&conn->conn_data_lock);
1288 USERPRI;
1289 return;
1290 }
1291 MUTEX_EXIT(&rx_refcnt_mutex);
1292 MUTEX_EXIT(&conn->conn_data_lock);
1293
1294 /* Check for extant references to this connection */
1295 MUTEX_ENTER(&conn->conn_call_lock);
1296 for (i = 0; i < RX_MAXCALLS; i++) {
1297 struct rx_call *call = conn->call[i];
1298 if (call) {
1299 havecalls = 1;
1300 if (conn->type == RX_CLIENT_CONNECTION) {
1301 MUTEX_ENTER(&call->lock);
1302 if (call->delayedAckEvent) {
1303 /* Push the final acknowledgment out now--there
1304 * won't be a subsequent call to acknowledge the
1305 * last reply packets */
1306 rxi_CancelDelayedAckEvent(call);
1307 if (call->state == RX_STATE_PRECALL
1308 || call->state == RX_STATE_ACTIVE) {
1309 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1310 } else {
1311 rxi_AckAll(call);
1312 }
1313 }
1314 MUTEX_EXIT(&call->lock);
1315 }
1316 }
1317 }
1318 MUTEX_EXIT(&conn->conn_call_lock);
1319
1320 #ifdef RX_ENABLE_LOCKS
1321 if (!havecalls) {
1322 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1323 MUTEX_EXIT(&conn->conn_data_lock);
1324 } else {
1325 /* Someone is accessing a packet right now. */
1326 havecalls = 1;
1327 }
1328 }
1329 #endif /* RX_ENABLE_LOCKS */
1330
1331 if (havecalls) {
1332 /* Don't destroy the connection if there are any call
1333 * structures still in use */
1334 MUTEX_ENTER(&conn->conn_data_lock);
1335 conn->flags |= RX_CONN_DESTROY_ME;
1336 MUTEX_EXIT(&conn->conn_data_lock);
1337 USERPRI;
1338 return;
1339 }
1340
1341 /* Remove from connection hash table before proceeding */
1342 conn_ptr =
1343 &rx_connHashTable[CONN_HASH
1344 (peer->host, peer->port, conn->cid, conn->epoch,
1345 conn->type)];
1346 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1347 if (*conn_ptr == conn) {
1348 *conn_ptr = conn->next;
1349 break;
1350 }
1351 }
1352 /* if the conn that we are destroying was the last connection, then we
1353 * clear rxLastConn as well */
1354 if (rxLastConn == conn)
1355 rxLastConn = 0;
1356
1357 /* Make sure the connection is completely reset before deleting it. */
1358 /*
1359 * Pending events hold a refcount, so we can't get here if they are
1360 * non-NULL. */
1361 osi_Assert(conn->challengeEvent == NULL);
1362 osi_Assert(conn->delayedAbortEvent == NULL);
1363 osi_Assert(conn->natKeepAliveEvent == NULL);
1364 osi_Assert(conn->checkReachEvent == NULL);
1365
1366 /* Add the connection to the list of destroyed connections that
1367 * need to be cleaned up. This is necessary to avoid deadlocks
1368 * in the routines we call to inform others that this connection is
1369 * being destroyed. */
1370 conn->next = rx_connCleanup_list;
1371 rx_connCleanup_list = conn;
1372 }
1373
1374 /* Externally available version */
1375 void
1376 rx_DestroyConnection(struct rx_connection *conn)
1377 {
1378 SPLVAR;
1379
1380 NETPRI;
1381 rxi_DestroyConnection(conn);
1382 USERPRI;
1383 }
1384
1385 void
1386 rx_GetConnection(struct rx_connection *conn)
1387 {
1388 SPLVAR;
1389
1390 NETPRI;
1391 MUTEX_ENTER(&rx_refcnt_mutex);
1392 conn->refCount++;
1393 MUTEX_EXIT(&rx_refcnt_mutex);
1394 USERPRI;
1395 }
1396
1397 #ifdef RX_ENABLE_LOCKS
1398 /* Wait for the transmit queue to no longer be busy.
1399 * requires the call->lock to be held */
1400 void
1401 rxi_WaitforTQBusy(struct rx_call *call) {
1402 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1403 call->flags |= RX_CALL_TQ_WAIT;
1404 call->tqWaiters++;
1405 MUTEX_ASSERT(&call->lock);
1406 CV_WAIT(&call->cv_tq, &call->lock);
1407 call->tqWaiters--;
1408 if (call->tqWaiters == 0) {
1409 call->flags &= ~RX_CALL_TQ_WAIT;
1410 }
1411 }
1412 }
1413 #endif
1414
1415 static void
1416 rxi_WakeUpTransmitQueue(struct rx_call *call)
1417 {
1418 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1419 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1420 call, call->tqWaiters, call->flags));
1421 #ifdef RX_ENABLE_LOCKS
1422 MUTEX_ASSERT(&call->lock);
1423 CV_BROADCAST(&call->cv_tq);
1424 #else /* RX_ENABLE_LOCKS */
1425 osi_rxWakeup(&call->tq);
1426 #endif /* RX_ENABLE_LOCKS */
1427 }
1428 }
1429
1430 /* Start a new rx remote procedure call, on the specified connection.
1431 * If wait is set to 1, wait for a free call channel; otherwise return
1432 * 0. Maxtime gives the maximum number of seconds this call may take,
1433 * after rx_NewCall returns. After this time interval, a call to any
1434 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1435 * For fine grain locking, we hold the conn_call_lock in order to
1436 * to ensure that we don't get signalle after we found a call in an active
1437 * state and before we go to sleep.
1438 */
1439 struct rx_call *
1440 rx_NewCall(struct rx_connection *conn)
1441 {
1442 int i, wait, ignoreBusy = 1;
1443 struct rx_call *call;
1444 struct clock queueTime;
1445 afs_uint32 leastBusy = 0;
1446 SPLVAR;
1447
1448 clock_NewTime();
1449 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1450
1451 NETPRI;
1452 clock_GetTime(&queueTime);
1453 /*
1454 * Check if there are others waiting for a new call.
1455 * If so, let them go first to avoid starving them.
1456 * This is a fairly simple scheme, and might not be
1457 * a complete solution for large numbers of waiters.
1458 *
1459 * makeCallWaiters keeps track of the number of
1460 * threads waiting to make calls and the
1461 * RX_CONN_MAKECALL_WAITING flag bit is used to
1462 * indicate that there are indeed calls waiting.
1463 * The flag is set when the waiter is incremented.
1464 * It is only cleared when makeCallWaiters is 0.
1465 * This prevents us from accidently destroying the
1466 * connection while it is potentially about to be used.
1467 */
1468 MUTEX_ENTER(&conn->conn_call_lock);
1469 MUTEX_ENTER(&conn->conn_data_lock);
1470 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1471 conn->flags |= RX_CONN_MAKECALL_WAITING;
1472 conn->makeCallWaiters++;
1473 MUTEX_EXIT(&conn->conn_data_lock);
1474
1475 #ifdef RX_ENABLE_LOCKS
1476 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1477 #else
1478 osi_rxSleep(conn);
1479 #endif
1480 MUTEX_ENTER(&conn->conn_data_lock);
1481 conn->makeCallWaiters--;
1482 if (conn->makeCallWaiters == 0)
1483 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1484 }
1485
1486 /* We are now the active thread in rx_NewCall */
1487 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1488 MUTEX_EXIT(&conn->conn_data_lock);
1489
1490 for (;;) {
1491 wait = 1;
1492
1493 for (i = 0; i < RX_MAXCALLS; i++) {
1494 call = conn->call[i];
1495 if (call) {
1496 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1497 /* we're not ignoring busy call slots; only look at the
1498 * call slot that is the "least" busy */
1499 continue;
1500 }
1501
1502 if (call->state == RX_STATE_DALLY) {
1503 MUTEX_ENTER(&call->lock);
1504 if (call->state == RX_STATE_DALLY) {
1505 if (ignoreBusy && conn->lastBusy[i]) {
1506 /* if we're ignoring busy call slots, skip any ones that
1507 * have lastBusy set */
1508 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1509 leastBusy = conn->lastBusy[i];
1510 }
1511 MUTEX_EXIT(&call->lock);
1512 continue;
1513 }
1514
1515 /*
1516 * We are setting the state to RX_STATE_RESET to
1517 * ensure that no one else will attempt to use this
1518 * call once we drop the conn->conn_call_lock and
1519 * call->lock. We must drop the conn->conn_call_lock
1520 * before calling rxi_ResetCall because the process
1521 * of clearing the transmit queue can block for an
1522 * extended period of time. If we block while holding
1523 * the conn->conn_call_lock, then all rx_EndCall
1524 * processing will block as well. This has a detrimental
1525 * effect on overall system performance.
1526 */
1527 call->state = RX_STATE_RESET;
1528 (*call->callNumber)++;
1529 MUTEX_EXIT(&conn->conn_call_lock);
1530 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1531 rxi_ResetCall(call, 0);
1532 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1533 break;
1534
1535 /*
1536 * If we failed to be able to safely obtain the
1537 * conn->conn_call_lock we will have to drop the
1538 * call->lock to avoid a deadlock. When the call->lock
1539 * is released the state of the call can change. If it
1540 * is no longer RX_STATE_RESET then some other thread is
1541 * using the call.
1542 */
1543 MUTEX_EXIT(&call->lock);
1544 MUTEX_ENTER(&conn->conn_call_lock);
1545 MUTEX_ENTER(&call->lock);
1546
1547 if (call->state == RX_STATE_RESET)
1548 break;
1549
1550 /*
1551 * If we get here it means that after dropping
1552 * the conn->conn_call_lock and call->lock that
1553 * the call is no longer ours. If we can't find
1554 * a free call in the remaining slots we should
1555 * not go immediately to RX_CONN_MAKECALL_WAITING
1556 * because by dropping the conn->conn_call_lock
1557 * we have given up synchronization with rx_EndCall.
1558 * Instead, cycle through one more time to see if
1559 * we can find a call that can call our own.
1560 */
1561 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1562 wait = 0;
1563 }
1564 MUTEX_EXIT(&call->lock);
1565 }
1566 } else {
1567 if (ignoreBusy && conn->lastBusy[i]) {
1568 /* if we're ignoring busy call slots, skip any ones that
1569 * have lastBusy set */
1570 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1571 leastBusy = conn->lastBusy[i];
1572 }
1573 continue;
1574 }
1575
1576 /* rxi_NewCall returns with mutex locked */
1577 call = rxi_NewCall(conn, i);
1578 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1579 break;
1580 }
1581 }
1582 if (i < RX_MAXCALLS) {
1583 conn->lastBusy[i] = 0;
1584 break;
1585 }
1586 if (!wait)
1587 continue;
1588 if (leastBusy && ignoreBusy) {
1589 /* we didn't find a useable call slot, but we did see at least one
1590 * 'busy' slot; look again and only use a slot with the 'least
1591 * busy time */
1592 ignoreBusy = 0;
1593 continue;
1594 }
1595
1596 MUTEX_ENTER(&conn->conn_data_lock);
1597 conn->flags |= RX_CONN_MAKECALL_WAITING;
1598 conn->makeCallWaiters++;
1599 MUTEX_EXIT(&conn->conn_data_lock);
1600
1601 #ifdef RX_ENABLE_LOCKS
1602 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1603 #else
1604 osi_rxSleep(conn);
1605 #endif
1606 MUTEX_ENTER(&conn->conn_data_lock);
1607 conn->makeCallWaiters--;
1608 if (conn->makeCallWaiters == 0)
1609 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1610 MUTEX_EXIT(&conn->conn_data_lock);
1611 }
1612 /* Client is initially in send mode */
1613 call->state = RX_STATE_ACTIVE;
1614 call->error = conn->error;
1615 if (call->error)
1616 call->app.mode = RX_MODE_ERROR;
1617 else
1618 call->app.mode = RX_MODE_SENDING;
1619
1620 #ifdef AFS_RXERRQ_ENV
1621 /* remember how many network errors the peer has when we started, so if
1622 * more errors are encountered after the call starts, we know the other endpoint won't be
1623 * responding to us */
1624 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1625 #endif
1626
1627 /* remember start time for call in case we have hard dead time limit */
1628 call->queueTime = queueTime;
1629 clock_GetTime(&call->startTime);
1630 call->app.bytesSent = 0;
1631 call->app.bytesRcvd = 0;
1632
1633 /* Turn on busy protocol. */
1634 rxi_KeepAliveOn(call);
1635
1636 /* Attempt MTU discovery */
1637 rxi_GrowMTUOn(call);
1638
1639 /*
1640 * We are no longer the active thread in rx_NewCall
1641 */
1642 MUTEX_ENTER(&conn->conn_data_lock);
1643 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1644 MUTEX_EXIT(&conn->conn_data_lock);
1645
1646 /*
1647 * Wake up anyone else who might be giving us a chance to
1648 * run (see code above that avoids resource starvation).
1649 */
1650 #ifdef RX_ENABLE_LOCKS
1651 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1652 osi_Panic("rx_NewCall call about to be used without an empty tq");
1653 }
1654
1655 CV_BROADCAST(&conn->conn_call_cv);
1656 #else
1657 osi_rxWakeup(conn);
1658 #endif
1659 MUTEX_EXIT(&conn->conn_call_lock);
1660 MUTEX_EXIT(&call->lock);
1661 USERPRI;
1662
1663 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1664 return call;
1665 }
1666
1667 static int
1668 rxi_HasActiveCalls(struct rx_connection *aconn)
1669 {
1670 int i;
1671 struct rx_call *tcall;
1672 SPLVAR;
1673
1674 NETPRI;
1675 for (i = 0; i < RX_MAXCALLS; i++) {
1676 if ((tcall = aconn->call[i])) {
1677 if ((tcall->state == RX_STATE_ACTIVE)
1678 || (tcall->state == RX_STATE_PRECALL)) {
1679 USERPRI;
1680 return 1;
1681 }
1682 }
1683 }
1684 USERPRI;
1685 return 0;
1686 }
1687
1688 int
1689 rxi_GetCallNumberVector(struct rx_connection *aconn,
1690 afs_int32 * aint32s)
1691 {
1692 int i;
1693 struct rx_call *tcall;
1694 SPLVAR;
1695
1696 NETPRI;
1697 MUTEX_ENTER(&aconn->conn_call_lock);
1698 for (i = 0; i < RX_MAXCALLS; i++) {
1699 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1700 aint32s[i] = aconn->callNumber[i] + 1;
1701 else
1702 aint32s[i] = aconn->callNumber[i];
1703 }
1704 MUTEX_EXIT(&aconn->conn_call_lock);
1705 USERPRI;
1706 return 0;
1707 }
1708
1709 int
1710 rxi_SetCallNumberVector(struct rx_connection *aconn,
1711 afs_int32 * aint32s)
1712 {
1713 int i;
1714 struct rx_call *tcall;
1715 SPLVAR;
1716
1717 NETPRI;
1718 MUTEX_ENTER(&aconn->conn_call_lock);
1719 for (i = 0; i < RX_MAXCALLS; i++) {
1720 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1721 aconn->callNumber[i] = aint32s[i] - 1;
1722 else
1723 aconn->callNumber[i] = aint32s[i];
1724 }
1725 MUTEX_EXIT(&aconn->conn_call_lock);
1726 USERPRI;
1727 return 0;
1728 }
1729
1730 /* Advertise a new service. A service is named locally by a UDP port
1731 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1732 * on a failure.
1733 *
1734 char *serviceName; Name for identification purposes (e.g. the
1735 service name might be used for probing for
1736 statistics) */
1737 struct rx_service *
1738 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1739 char *serviceName, struct rx_securityClass **securityObjects,
1740 int nSecurityObjects,
1741 afs_int32(*serviceProc) (struct rx_call * acall))
1742 {
1743 osi_socket socket = OSI_NULLSOCKET;
1744 struct rx_service *tservice;
1745 int i;
1746 SPLVAR;
1747
1748 clock_NewTime();
1749
1750 if (serviceId == 0) {
1751 (osi_Msg
1752 "rx_NewService: service id for service %s is not non-zero.\n",
1753 serviceName);
1754 return 0;
1755 }
1756 if (port == 0) {
1757 if (rx_port == 0) {
1758 (osi_Msg
1759 "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",
1760 serviceName);
1761 return 0;
1762 }
1763 port = rx_port;
1764 socket = rx_socket;
1765 }
1766
1767 tservice = rxi_AllocService();
1768 NETPRI;
1769
1770 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1771
1772 for (i = 0; i < RX_MAX_SERVICES; i++) {
1773 struct rx_service *service = rx_services[i];
1774 if (service) {
1775 if (port == service->servicePort && host == service->serviceHost) {
1776 if (service->serviceId == serviceId) {
1777 /* The identical service has already been
1778 * installed; if the caller was intending to
1779 * change the security classes used by this
1780 * service, he/she loses. */
1781 (osi_Msg
1782 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1783 serviceName, serviceId, service->serviceName);
1784 USERPRI;
1785 rxi_FreeService(tservice);
1786 return service;
1787 }
1788 /* Different service, same port: re-use the socket
1789 * which is bound to the same port */
1790 socket = service->socket;
1791 }
1792 } else {
1793 if (socket == OSI_NULLSOCKET) {
1794 /* If we don't already have a socket (from another
1795 * service on same port) get a new one */
1796 socket = rxi_GetHostUDPSocket(host, port);
1797 if (socket == OSI_NULLSOCKET) {
1798 USERPRI;
1799 rxi_FreeService(tservice);
1800 return 0;
1801 }
1802 }
1803 service = tservice;
1804 service->socket = socket;
1805 service->serviceHost = host;
1806 service->servicePort = port;
1807 service->serviceId = serviceId;
1808 service->serviceName = serviceName;
1809 service->nSecurityObjects = nSecurityObjects;
1810 service->securityObjects = securityObjects;
1811 service->minProcs = 0;
1812 service->maxProcs = 1;
1813 service->idleDeadTime = 60;
1814 service->connDeadTime = rx_connDeadTime;
1815 service->executeRequestProc = serviceProc;
1816 service->checkReach = 0;
1817 service->nSpecific = 0;
1818 service->specific = NULL;
1819 rx_services[i] = service; /* not visible until now */
1820 USERPRI;
1821 return service;
1822 }
1823 }
1824 USERPRI;
1825 rxi_FreeService(tservice);
1826 (osi_Msg "rx_NewService: cannot support > %d services\n",
1827 RX_MAX_SERVICES);
1828 return 0;
1829 }
1830
1831 /* Set configuration options for all of a service's security objects */
1832
1833 afs_int32
1834 rx_SetSecurityConfiguration(struct rx_service *service,
1835 rx_securityConfigVariables type,
1836 void *value)
1837 {
1838 int i;
1839 for (i = 0; i<service->nSecurityObjects; i++) {
1840 if (service->securityObjects[i]) {
1841 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1842 value, NULL);
1843 }
1844 }
1845 return 0;
1846 }
1847
1848 struct rx_service *
1849 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1850 struct rx_securityClass **securityObjects, int nSecurityObjects,
1851 afs_int32(*serviceProc) (struct rx_call * acall))
1852 {
1853 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1854 }
1855
1856 /* Generic request processing loop. This routine should be called
1857 * by the implementation dependent rx_ServerProc. If socketp is
1858 * non-null, it will be set to the file descriptor that this thread
1859 * is now listening on. If socketp is null, this routine will never
1860 * returns. */
1861 void
1862 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1863 {
1864 struct rx_call *call;
1865 afs_int32 code;
1866 struct rx_service *tservice = NULL;
1867
1868 for (;;) {
1869 if (newcall) {
1870 call = newcall;
1871 newcall = NULL;
1872 } else {
1873 call = rx_GetCall(threadID, tservice, socketp);
1874 if (socketp && *socketp != OSI_NULLSOCKET) {
1875 /* We are now a listener thread */
1876 return;
1877 }
1878 }
1879
1880 #ifdef KERNEL
1881 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1882 #ifdef RX_ENABLE_LOCKS
1883 AFS_GLOCK();
1884 #endif /* RX_ENABLE_LOCKS */
1885 afs_termState = AFSOP_STOP_AFS;
1886 afs_osi_Wakeup(&afs_termState);
1887 #ifdef RX_ENABLE_LOCKS
1888 AFS_GUNLOCK();
1889 #endif /* RX_ENABLE_LOCKS */
1890 return;
1891 }
1892 #endif
1893
1894 /* if server is restarting( typically smooth shutdown) then do not
1895 * allow any new calls.
1896 */
1897
1898 if (rx_tranquil && (call != NULL)) {
1899 SPLVAR;
1900
1901 NETPRI;
1902 MUTEX_ENTER(&call->lock);
1903
1904 rxi_CallError(call, RX_RESTARTING);
1905 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1906
1907 MUTEX_EXIT(&call->lock);
1908 USERPRI;
1909 continue;
1910 }
1911
1912 tservice = call->conn->service;
1913
1914 if (tservice->beforeProc)
1915 (*tservice->beforeProc) (call);
1916
1917 code = tservice->executeRequestProc(call);
1918
1919 if (tservice->afterProc)
1920 (*tservice->afterProc) (call, code);
1921
1922 rx_EndCall(call, code);
1923
1924 if (tservice->postProc)
1925 (*tservice->postProc) (code);
1926
1927 if (rx_stats_active) {
1928 MUTEX_ENTER(&rx_stats_mutex);
1929 rxi_nCalls++;
1930 MUTEX_EXIT(&rx_stats_mutex);
1931 }
1932 }
1933 }
1934
1935
1936 void
1937 rx_WakeupServerProcs(void)
1938 {
1939 struct rx_serverQueueEntry *np, *tqp;
1940 struct opr_queue *cursor;
1941 SPLVAR;
1942
1943 NETPRI;
1944 MUTEX_ENTER(&rx_serverPool_lock);
1945
1946 #ifdef RX_ENABLE_LOCKS
1947 if (rx_waitForPacket)
1948 CV_BROADCAST(&rx_waitForPacket->cv);
1949 #else /* RX_ENABLE_LOCKS */
1950 if (rx_waitForPacket)
1951 osi_rxWakeup(rx_waitForPacket);
1952 #endif /* RX_ENABLE_LOCKS */
1953 MUTEX_ENTER(&freeSQEList_lock);
1954 for (np = rx_FreeSQEList; np; np = tqp) {
1955 tqp = *(struct rx_serverQueueEntry **)np;
1956 #ifdef RX_ENABLE_LOCKS
1957 CV_BROADCAST(&np->cv);
1958 #else /* RX_ENABLE_LOCKS */
1959 osi_rxWakeup(np);
1960 #endif /* RX_ENABLE_LOCKS */
1961 }
1962 MUTEX_EXIT(&freeSQEList_lock);
1963 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1964 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1965 #ifdef RX_ENABLE_LOCKS
1966 CV_BROADCAST(&np->cv);
1967 #else /* RX_ENABLE_LOCKS */
1968 osi_rxWakeup(np);
1969 #endif /* RX_ENABLE_LOCKS */
1970 }
1971 MUTEX_EXIT(&rx_serverPool_lock);
1972 USERPRI;
1973 }
1974
1975 /* meltdown:
1976 * One thing that seems to happen is that all the server threads get
1977 * tied up on some empty or slow call, and then a whole bunch of calls
1978 * arrive at once, using up the packet pool, so now there are more
1979 * empty calls. The most critical resources here are server threads
1980 * and the free packet pool. The "doreclaim" code seems to help in
1981 * general. I think that eventually we arrive in this state: there
1982 * are lots of pending calls which do have all their packets present,
1983 * so they won't be reclaimed, are multi-packet calls, so they won't
1984 * be scheduled until later, and thus are tying up most of the free
1985 * packet pool for a very long time.
1986 * future options:
1987 * 1. schedule multi-packet calls if all the packets are present.
1988 * Probably CPU-bound operation, useful to return packets to pool.
1989 * Do what if there is a full window, but the last packet isn't here?
1990 * 3. preserve one thread which *only* runs "best" calls, otherwise
1991 * it sleeps and waits for that type of call.
1992 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1993 * the current dataquota business is badly broken. The quota isn't adjusted
1994 * to reflect how many packets are presently queued for a running call.
1995 * So, when we schedule a queued call with a full window of packets queued
1996 * up for it, that *should* free up a window full of packets for other 2d-class
1997 * calls to be able to use from the packet pool. But it doesn't.
1998 *
1999 * NB. Most of the time, this code doesn't run -- since idle server threads
2000 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2001 * as a new call arrives.
2002 */
2003 /* Sleep until a call arrives. Returns a pointer to the call, ready
2004 * for an rx_Read. */
2005 #ifdef RX_ENABLE_LOCKS
2006 struct rx_call *
2007 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2008 {
2009 struct rx_serverQueueEntry *sq;
2010 struct rx_call *call = (struct rx_call *)0;
2011 struct rx_service *service = NULL;
2012
2013 MUTEX_ENTER(&freeSQEList_lock);
2014
2015 if ((sq = rx_FreeSQEList)) {
2016 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2017 MUTEX_EXIT(&freeSQEList_lock);
2018 } else { /* otherwise allocate a new one and return that */
2019 MUTEX_EXIT(&freeSQEList_lock);
2020 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2021 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2022 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2023 }
2024
2025 MUTEX_ENTER(&rx_serverPool_lock);
2026 if (cur_service != NULL) {
2027 ReturnToServerPool(cur_service);
2028 }
2029 while (1) {
2030 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2031 struct rx_call *tcall, *choice2 = NULL;
2032 struct opr_queue *cursor;
2033
2034 /* Scan for eligible incoming calls. A call is not eligible
2035 * if the maximum number of calls for its service type are
2036 * already executing */
2037 /* One thread will process calls FCFS (to prevent starvation),
2038 * while the other threads may run ahead looking for calls which
2039 * have all their input data available immediately. This helps
2040 * keep threads from blocking, waiting for data from the client. */
2041 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2042 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2043
2044 service = tcall->conn->service;
2045 if (!QuotaOK(service)) {
2046 continue;
2047 }
2048 MUTEX_ENTER(&rx_pthread_mutex);
2049 if (tno == rxi_fcfs_thread_num
2050 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2051 MUTEX_EXIT(&rx_pthread_mutex);
2052 /* If we're the fcfs thread , then we'll just use
2053 * this call. If we haven't been able to find an optimal
2054 * choice, and we're at the end of the list, then use a
2055 * 2d choice if one has been identified. Otherwise... */
2056 call = (choice2 ? choice2 : tcall);
2057 service = call->conn->service;
2058 } else {
2059 MUTEX_EXIT(&rx_pthread_mutex);
2060 if (!opr_queue_IsEmpty(&tcall->rq)) {
2061 struct rx_packet *rp;
2062 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2063 entry);
2064 if (rp->header.seq == 1) {
2065 if (!meltdown_1pkt
2066 || (rp->header.flags & RX_LAST_PACKET)) {
2067 call = tcall;
2068 } else if (rxi_2dchoice && !choice2
2069 && !(tcall->flags & RX_CALL_CLEARED)
2070 && (tcall->rprev > rxi_HardAckRate)) {
2071 choice2 = tcall;
2072 } else
2073 rxi_md2cnt++;
2074 }
2075 }
2076 }
2077 if (call) {
2078 break;
2079 } else {
2080 ReturnToServerPool(service);
2081 }
2082 }
2083 }
2084
2085 if (call) {
2086 opr_queue_Remove(&call->entry);
2087 MUTEX_EXIT(&rx_serverPool_lock);
2088 MUTEX_ENTER(&call->lock);
2089
2090 if (call->flags & RX_CALL_WAIT_PROC) {
2091 call->flags &= ~RX_CALL_WAIT_PROC;
2092 rx_atomic_dec(&rx_nWaiting);
2093 }
2094
2095 if (call->state != RX_STATE_PRECALL || call->error) {
2096 MUTEX_EXIT(&call->lock);
2097 MUTEX_ENTER(&rx_serverPool_lock);
2098 ReturnToServerPool(service);
2099 call = NULL;
2100 continue;
2101 }
2102
2103 if (opr_queue_IsEmpty(&call->rq)
2104 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2105 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2106
2107 CLEAR_CALL_QUEUE_LOCK(call);
2108 break;
2109 } else {
2110 /* If there are no eligible incoming calls, add this process
2111 * to the idle server queue, to wait for one */
2112 sq->newcall = 0;
2113 sq->tno = tno;
2114 if (socketp) {
2115 *socketp = OSI_NULLSOCKET;
2116 }
2117 sq->socketp = socketp;
2118 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2119 #ifndef AFS_AIX41_ENV
2120 rx_waitForPacket = sq;
2121 #endif /* AFS_AIX41_ENV */
2122 do {
2123 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2124 #ifdef KERNEL
2125 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2126 MUTEX_EXIT(&rx_serverPool_lock);
2127 return (struct rx_call *)0;
2128 }
2129 #endif
2130 } while (!(call = sq->newcall)
2131 && !(socketp && *socketp != OSI_NULLSOCKET));
2132 MUTEX_EXIT(&rx_serverPool_lock);
2133 if (call) {
2134 MUTEX_ENTER(&call->lock);
2135 }
2136 break;
2137 }
2138 }
2139
2140 MUTEX_ENTER(&freeSQEList_lock);
2141 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2142 rx_FreeSQEList = sq;
2143 MUTEX_EXIT(&freeSQEList_lock);
2144
2145 if (call) {
2146 clock_GetTime(&call->startTime);
2147 call->state = RX_STATE_ACTIVE;
2148 call->app.mode = RX_MODE_RECEIVING;
2149 #ifdef RX_KERNEL_TRACE
2150 if (ICL_SETACTIVE(afs_iclSetp)) {
2151 int glockOwner = ISAFS_GLOCK();
2152 if (!glockOwner)
2153 AFS_GLOCK();
2154 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2155 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2156 call);
2157 if (!glockOwner)
2158 AFS_GUNLOCK();
2159 }
2160 #endif
2161
2162 rxi_calltrace(RX_CALL_START, call);
2163 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2164 call->conn->service->servicePort, call->conn->service->serviceId,
2165 call));
2166
2167 MUTEX_EXIT(&call->lock);
2168 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2169 } else {
2170 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2171 }
2172
2173 return call;
2174 }
2175 #else /* RX_ENABLE_LOCKS */
2176 struct rx_call *
2177 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2178 {
2179 struct rx_serverQueueEntry *sq;
2180 struct rx_call *call = (struct rx_call *)0, *choice2;
2181 struct rx_service *service = NULL;
2182 SPLVAR;
2183
2184 NETPRI;
2185 MUTEX_ENTER(&freeSQEList_lock);
2186
2187 if ((sq = rx_FreeSQEList)) {
2188 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2189 MUTEX_EXIT(&freeSQEList_lock);
2190 } else { /* otherwise allocate a new one and return that */
2191 MUTEX_EXIT(&freeSQEList_lock);
2192 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2193 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2194 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2195 }
2196 MUTEX_ENTER(&sq->lock);
2197
2198 if (cur_service != NULL) {
2199 cur_service->nRequestsRunning--;
2200 MUTEX_ENTER(&rx_quota_mutex);
2201 if (cur_service->nRequestsRunning < cur_service->minProcs)
2202 rxi_minDeficit++;
2203 rxi_availProcs++;
2204 MUTEX_EXIT(&rx_quota_mutex);
2205 }
2206 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2207 struct rx_call *tcall;
2208 struct opr_queue *cursor;
2209 /* Scan for eligible incoming calls. A call is not eligible
2210 * if the maximum number of calls for its service type are
2211 * already executing */
2212 /* One thread will process calls FCFS (to prevent starvation),
2213 * while the other threads may run ahead looking for calls which
2214 * have all their input data available immediately. This helps
2215 * keep threads from blocking, waiting for data from the client. */
2216 choice2 = (struct rx_call *)0;
2217 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2218 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2219 service = tcall->conn->service;
2220 if (QuotaOK(service)) {
2221 MUTEX_ENTER(&rx_pthread_mutex);
2222 /* XXX - If tcall->entry.next is NULL, then we're no longer
2223 * on a queue at all. This shouldn't happen. */
2224 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2225 MUTEX_EXIT(&rx_pthread_mutex);
2226 /* If we're the fcfs thread, then we'll just use
2227 * this call. If we haven't been able to find an optimal
2228 * choice, and we're at the end of the list, then use a
2229 * 2d choice if one has been identified. Otherwise... */
2230 call = (choice2 ? choice2 : tcall);
2231 service = call->conn->service;
2232 } else {
2233 MUTEX_EXIT(&rx_pthread_mutex);
2234 if (!opr_queue_IsEmpty(&tcall->rq)) {
2235 struct rx_packet *rp;
2236 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2237 entry);
2238 if (rp->header.seq == 1
2239 && (!meltdown_1pkt
2240 || (rp->header.flags & RX_LAST_PACKET))) {
2241 call = tcall;
2242 } else if (rxi_2dchoice && !choice2
2243 && !(tcall->flags & RX_CALL_CLEARED)
2244 && (tcall->rprev > rxi_HardAckRate)) {
2245 choice2 = tcall;
2246 } else
2247 rxi_md2cnt++;
2248 }
2249 }
2250 }
2251 if (call)
2252 break;
2253 }
2254 }
2255
2256 if (call) {
2257 opr_queue_Remove(&call->entry);
2258 /* we can't schedule a call if there's no data!!! */
2259 /* send an ack if there's no data, if we're missing the
2260 * first packet, or we're missing something between first
2261 * and last -- there's a "hole" in the incoming data. */
2262 if (opr_queue_IsEmpty(&call->rq)
2263 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2264 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2265 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2266
2267 call->flags &= (~RX_CALL_WAIT_PROC);
2268 service->nRequestsRunning++;
2269 /* just started call in minProcs pool, need fewer to maintain
2270 * guarantee */
2271 MUTEX_ENTER(&rx_quota_mutex);
2272 if (service->nRequestsRunning <= service->minProcs)
2273 rxi_minDeficit--;
2274 rxi_availProcs--;
2275 MUTEX_EXIT(&rx_quota_mutex);
2276 rx_atomic_dec(&rx_nWaiting);
2277 /* MUTEX_EXIT(&call->lock); */
2278 } else {
2279 /* If there are no eligible incoming calls, add this process
2280 * to the idle server queue, to wait for one */
2281 sq->newcall = 0;
2282 if (socketp) {
2283 *socketp = OSI_NULLSOCKET;
2284 }
2285 sq->socketp = socketp;
2286 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2287 do {
2288 osi_rxSleep(sq);
2289 #ifdef KERNEL
2290 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2291 USERPRI;
2292 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2293 return (struct rx_call *)0;
2294 }
2295 #endif
2296 } while (!(call = sq->newcall)
2297 && !(socketp && *socketp != OSI_NULLSOCKET));
2298 }
2299 MUTEX_EXIT(&sq->lock);
2300
2301 MUTEX_ENTER(&freeSQEList_lock);
2302 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2303 rx_FreeSQEList = sq;
2304 MUTEX_EXIT(&freeSQEList_lock);
2305
2306 if (call) {
2307 clock_GetTime(&call->startTime);
2308 call->state = RX_STATE_ACTIVE;
2309 call->app.mode = RX_MODE_RECEIVING;
2310 #ifdef RX_KERNEL_TRACE
2311 if (ICL_SETACTIVE(afs_iclSetp)) {
2312 int glockOwner = ISAFS_GLOCK();
2313 if (!glockOwner)
2314 AFS_GLOCK();
2315 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2316 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2317 call);
2318 if (!glockOwner)
2319 AFS_GUNLOCK();
2320 }
2321 #endif
2322
2323 rxi_calltrace(RX_CALL_START, call);
2324 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2325 call->conn->service->servicePort, call->conn->service->serviceId,
2326 call));
2327 } else {
2328 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2329 }
2330
2331 USERPRI;
2332
2333 return call;
2334 }
2335 #endif /* RX_ENABLE_LOCKS */
2336
2337
2338
2339 /* Establish a procedure to be called when a packet arrives for a
2340 * call. This routine will be called at most once after each call,
2341 * and will also be called if there is an error condition on the or
2342 * the call is complete. Used by multi rx to build a selection
2343 * function which determines which of several calls is likely to be a
2344 * good one to read from.
2345 * NOTE: the way this is currently implemented it is probably only a
2346 * good idea to (1) use it immediately after a newcall (clients only)
2347 * and (2) only use it once. Other uses currently void your warranty
2348 */
2349 void
2350 rx_SetArrivalProc(struct rx_call *call,
2351 void (*proc) (struct rx_call * call,
2352 void * mh,
2353 int index),
2354 void * handle, int arg)
2355 {
2356 call->arrivalProc = proc;
2357 call->arrivalProcHandle = handle;
2358 call->arrivalProcArg = arg;
2359 }
2360
2361 /* Call is finished (possibly prematurely). Return rc to the peer, if
2362 * appropriate, and return the final error code from the conversation
2363 * to the caller */
2364
2365 afs_int32
2366 rx_EndCall(struct rx_call *call, afs_int32 rc)
2367 {
2368 struct rx_connection *conn = call->conn;
2369 afs_int32 error;
2370 SPLVAR;
2371
2372 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2373 call, rc, call->error, call->abortCode));
2374
2375 NETPRI;
2376 MUTEX_ENTER(&call->lock);
2377
2378 if (rc == 0 && call->error == 0) {
2379 call->abortCode = 0;
2380 call->abortCount = 0;
2381 }
2382
2383 call->arrivalProc = (void (*)())0;
2384 if (rc && call->error == 0) {
2385 rxi_CallError(call, rc);
2386 call->app.mode = RX_MODE_ERROR;
2387 /* Send an abort message to the peer if this error code has
2388 * only just been set. If it was set previously, assume the
2389 * peer has already been sent the error code or will request it
2390 */
2391 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2392 }
2393 if (conn->type == RX_SERVER_CONNECTION) {
2394 /* Make sure reply or at least dummy reply is sent */
2395 if (call->app.mode == RX_MODE_RECEIVING) {
2396 MUTEX_EXIT(&call->lock);
2397 rxi_WriteProc(call, 0, 0);
2398 MUTEX_ENTER(&call->lock);
2399 }
2400 if (call->app.mode == RX_MODE_SENDING) {
2401 rxi_FlushWriteLocked(call);
2402 }
2403 rxi_calltrace(RX_CALL_END, call);
2404 /* Call goes to hold state until reply packets are acknowledged */
2405 if (call->tfirst + call->nSoftAcked < call->tnext) {
2406 call->state = RX_STATE_HOLD;
2407 } else {
2408 call->state = RX_STATE_DALLY;
2409 rxi_ClearTransmitQueue(call, 0);
2410 rxi_rto_cancel(call);
2411 rxi_CancelKeepAliveEvent(call);
2412 }
2413 } else { /* Client connection */
2414 char dummy;
2415 /* Make sure server receives input packets, in the case where
2416 * no reply arguments are expected */
2417
2418 if ((call->app.mode == RX_MODE_SENDING)
2419 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2420 MUTEX_EXIT(&call->lock);
2421 (void)rxi_ReadProc(call, &dummy, 1);
2422 MUTEX_ENTER(&call->lock);
2423 }
2424
2425 /* If we had an outstanding delayed ack, be nice to the server
2426 * and force-send it now.
2427 */
2428 if (call->delayedAckEvent) {
2429 rxi_CancelDelayedAckEvent(call);
2430 rxi_SendDelayedAck(NULL, call, NULL, 0);
2431 }
2432
2433 /* We need to release the call lock since it's lower than the
2434 * conn_call_lock and we don't want to hold the conn_call_lock
2435 * over the rx_ReadProc call. The conn_call_lock needs to be held
2436 * here for the case where rx_NewCall is perusing the calls on
2437 * the connection structure. We don't want to signal until
2438 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2439 * have checked this call, found it active and by the time it
2440 * goes to sleep, will have missed the signal.
2441 */
2442 MUTEX_EXIT(&call->lock);
2443 MUTEX_ENTER(&conn->conn_call_lock);
2444 MUTEX_ENTER(&call->lock);
2445
2446 if (!call->error) {
2447 /* While there are some circumstances where a call with an error is
2448 * obviously not on a "busy" channel, be conservative (clearing
2449 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2450 * The call channel is definitely not busy if we just successfully
2451 * completed a call on it. */
2452 conn->lastBusy[call->channel] = 0;
2453
2454 } else if (call->error == RX_CALL_TIMEOUT) {
2455 /* The call is still probably running on the server side, so try to
2456 * avoid this call channel in the future. */
2457 conn->lastBusy[call->channel] = clock_Sec();
2458 }
2459
2460 MUTEX_ENTER(&conn->conn_data_lock);
2461 conn->flags |= RX_CONN_BUSY;
2462 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2463 MUTEX_EXIT(&conn->conn_data_lock);
2464 #ifdef RX_ENABLE_LOCKS
2465 CV_BROADCAST(&conn->conn_call_cv);
2466 #else
2467 osi_rxWakeup(conn);
2468 #endif
2469 }
2470 #ifdef RX_ENABLE_LOCKS
2471 else {
2472 MUTEX_EXIT(&conn->conn_data_lock);
2473 }
2474 #endif /* RX_ENABLE_LOCKS */
2475 call->state = RX_STATE_DALLY;
2476 }
2477 error = call->error;
2478
2479 /* currentPacket, nLeft, and NFree must be zeroed here, because
2480 * ResetCall cannot: ResetCall may be called at splnet(), in the
2481 * kernel version, and may interrupt the macros rx_Read or
2482 * rx_Write, which run at normal priority for efficiency. */
2483 if (call->app.currentPacket) {
2484 #ifdef RX_TRACK_PACKETS
2485 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2486 #endif
2487 rxi_FreePacket(call->app.currentPacket);
2488 call->app.currentPacket = (struct rx_packet *)0;
2489 }
2490
2491 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2492
2493 /* Free any packets from the last call to ReadvProc/WritevProc */
2494 #ifdef RXDEBUG_PACKET
2495 call->iovqc -=
2496 #endif /* RXDEBUG_PACKET */
2497 rxi_FreePackets(0, &call->app.iovq);
2498 MUTEX_EXIT(&call->lock);
2499
2500 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2501 if (conn->type == RX_CLIENT_CONNECTION) {
2502 MUTEX_ENTER(&conn->conn_data_lock);
2503 conn->flags &= ~RX_CONN_BUSY;
2504 MUTEX_EXIT(&conn->conn_data_lock);
2505 MUTEX_EXIT(&conn->conn_call_lock);
2506 }
2507 USERPRI;
2508 /*
2509 * Map errors to the local host's errno.h format.
2510 */
2511 error = ntoh_syserr_conv(error);
2512
2513 /* If the caller said the call failed with some error, we had better
2514 * return an error code. */
2515 osi_Assert(!rc || error);
2516 return error;
2517 }
2518
2519 #if !defined(KERNEL)
2520
2521 /* Call this routine when shutting down a server or client (especially
2522 * clients). This will allow Rx to gracefully garbage collect server
2523 * connections, and reduce the number of retries that a server might
2524 * make to a dead client.
2525 * This is not quite right, since some calls may still be ongoing and
2526 * we can't lock them to destroy them. */
2527 void
2528 rx_Finalize(void)
2529 {
2530 INIT_PTHREAD_LOCKS;
2531 LOCK_RX_INIT;
2532 if (!rxi_IsRunning()) {
2533 UNLOCK_RX_INIT;
2534 return; /* Already shutdown. */
2535 }
2536 rxi_Finalize_locked();
2537 UNLOCK_RX_INIT;
2538 }
2539
2540 static void
2541 rxi_Finalize_locked(void)
2542 {
2543 struct rx_connection **conn_ptr, **conn_end;
2544 rx_atomic_set(&rxi_running, 0);
2545 rxi_DeleteCachedConnections();
2546 if (rx_connHashTable) {
2547 MUTEX_ENTER(&rx_connHashTable_lock);
2548 for (conn_ptr = &rx_connHashTable[0], conn_end =
2549 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2550 conn_ptr++) {
2551 struct rx_connection *conn, *next;
2552 for (conn = *conn_ptr; conn; conn = next) {
2553 next = conn->next;
2554 if (conn->type == RX_CLIENT_CONNECTION) {
2555 rx_GetConnection(conn);
2556 #ifdef RX_ENABLE_LOCKS
2557 rxi_DestroyConnectionNoLock(conn);
2558 #else /* RX_ENABLE_LOCKS */
2559 rxi_DestroyConnection(conn);
2560 #endif /* RX_ENABLE_LOCKS */
2561 }
2562 }
2563 }
2564 #ifdef RX_ENABLE_LOCKS
2565 while (rx_connCleanup_list) {
2566 struct rx_connection *conn;
2567 conn = rx_connCleanup_list;
2568 rx_connCleanup_list = rx_connCleanup_list->next;
2569 MUTEX_EXIT(&rx_connHashTable_lock);
2570 rxi_CleanupConnection(conn);
2571 MUTEX_ENTER(&rx_connHashTable_lock);
2572 }
2573 MUTEX_EXIT(&rx_connHashTable_lock);
2574 #endif /* RX_ENABLE_LOCKS */
2575 }
2576 rxi_flushtrace();
2577
2578 #ifdef AFS_NT40_ENV
2579 afs_winsockCleanup();
2580 #endif
2581 }
2582 #endif
2583
2584 /* if we wakeup packet waiter too often, can get in loop with two
2585 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2586 void
2587 rxi_PacketsUnWait(void)
2588 {
2589 if (!rx_waitingForPackets) {
2590 return;
2591 }
2592 #ifdef KERNEL
2593 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2594 return; /* still over quota */
2595 }
2596 #endif /* KERNEL */
2597 rx_waitingForPackets = 0;
2598 #ifdef RX_ENABLE_LOCKS
2599 CV_BROADCAST(&rx_waitingForPackets_cv);
2600 #else
2601 osi_rxWakeup(&rx_waitingForPackets);
2602 #endif
2603 return;
2604 }
2605
2606
2607 /* ------------------Internal interfaces------------------------- */
2608
2609 /* Return this process's service structure for the
2610 * specified socket and service */
2611 static struct rx_service *
2612 rxi_FindService(osi_socket socket, u_short serviceId)
2613 {
2614 struct rx_service **sp;
2615 for (sp = &rx_services[0]; *sp; sp++) {
2616 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2617 return *sp;
2618 }
2619 return 0;
2620 }
2621
2622 #ifdef RXDEBUG_PACKET
2623 #ifdef KDUMP_RX_LOCK
2624 static struct rx_call_rx_lock *rx_allCallsp = 0;
2625 #else
2626 static struct rx_call *rx_allCallsp = 0;
2627 #endif
2628 #endif /* RXDEBUG_PACKET */
2629
2630 /* Allocate a call structure, for the indicated channel of the
2631 * supplied connection. The mode and state of the call must be set by
2632 * the caller. Returns the call with mutex locked. */
2633 static struct rx_call *
2634 rxi_NewCall(struct rx_connection *conn, int channel)
2635 {
2636 struct rx_call *call;
2637 #ifdef RX_ENABLE_LOCKS
2638 struct rx_call *cp; /* Call pointer temp */
2639 struct opr_queue *cursor;
2640 #endif
2641
2642 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2643
2644 /* Grab an existing call structure, or allocate a new one.
2645 * Existing call structures are assumed to have been left reset by
2646 * rxi_FreeCall */
2647 MUTEX_ENTER(&rx_freeCallQueue_lock);
2648
2649 #ifdef RX_ENABLE_LOCKS
2650 /*
2651 * EXCEPT that the TQ might not yet be cleared out.
2652 * Skip over those with in-use TQs.
2653 */
2654 call = NULL;
2655 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2656 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2657 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2658 call = cp;
2659 break;
2660 }
2661 }
2662 if (call) {
2663 #else /* RX_ENABLE_LOCKS */
2664 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2665 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2666 #endif /* RX_ENABLE_LOCKS */
2667 opr_queue_Remove(&call->entry);
2668 if (rx_stats_active)
2669 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2670 MUTEX_EXIT(&rx_freeCallQueue_lock);
2671 MUTEX_ENTER(&call->lock);
2672 CLEAR_CALL_QUEUE_LOCK(call);
2673 #ifdef RX_ENABLE_LOCKS
2674 /* Now, if TQ wasn't cleared earlier, do it now. */
2675 rxi_WaitforTQBusy(call);
2676 if (call->flags & RX_CALL_TQ_CLEARME) {
2677 rxi_ClearTransmitQueue(call, 1);
2678 /*queue_Init(&call->tq);*/
2679 }
2680 #endif /* RX_ENABLE_LOCKS */
2681 /* Bind the call to its connection structure */
2682 call->conn = conn;
2683 rxi_ResetCall(call, 1);
2684 } else {
2685
2686 call = rxi_Alloc(sizeof(struct rx_call));
2687 #ifdef RXDEBUG_PACKET
2688 call->allNextp = rx_allCallsp;
2689 rx_allCallsp = call;
2690 call->call_id =
2691 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2692 #else /* RXDEBUG_PACKET */
2693 rx_atomic_inc(&rx_stats.nCallStructs);
2694 #endif /* RXDEBUG_PACKET */
2695
2696 MUTEX_EXIT(&rx_freeCallQueue_lock);
2697 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2698 MUTEX_ENTER(&call->lock);
2699 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2700 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2701 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2702
2703 /* Initialize once-only items */
2704 opr_queue_Init(&call->tq);
2705 opr_queue_Init(&call->rq);
2706 opr_queue_Init(&call->app.iovq);
2707 #ifdef RXDEBUG_PACKET
2708 call->rqc = call->tqc = call->iovqc = 0;
2709 #endif /* RXDEBUG_PACKET */
2710 /* Bind the call to its connection structure (prereq for reset) */
2711 call->conn = conn;
2712 rxi_ResetCall(call, 1);
2713 }
2714 call->channel = channel;
2715 call->callNumber = &conn->callNumber[channel];
2716 call->rwind = conn->rwind[channel];
2717 call->twind = conn->twind[channel];
2718 /* Note that the next expected call number is retained (in
2719 * conn->callNumber[i]), even if we reallocate the call structure
2720 */
2721 conn->call[channel] = call;
2722 /* if the channel's never been used (== 0), we should start at 1, otherwise
2723 * the call number is valid from the last time this channel was used */
2724 if (*call->callNumber == 0)
2725 *call->callNumber = 1;
2726
2727 return call;
2728 }
2729
2730 /* A call has been inactive long enough that so we can throw away
2731 * state, including the call structure, which is placed on the call
2732 * free list.
2733 *
2734 * call->lock amd rx_refcnt_mutex are held upon entry.
2735 * haveCTLock is set when called from rxi_ReapConnections.
2736 *
2737 * return 1 if the call is freed, 0 if not.
2738 */
2739 static int
2740 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2741 {
2742 int channel = call->channel;
2743 struct rx_connection *conn = call->conn;
2744 u_char state = call->state;
2745
2746 /*
2747 * We are setting the state to RX_STATE_RESET to
2748 * ensure that no one else will attempt to use this
2749 * call once we drop the refcnt lock. We must drop
2750 * the refcnt lock before calling rxi_ResetCall
2751 * because it cannot be held across acquiring the
2752 * freepktQ lock. NewCall does the same.
2753 */
2754 call->state = RX_STATE_RESET;
2755 MUTEX_EXIT(&rx_refcnt_mutex);
2756 rxi_ResetCall(call, 0);
2757
2758 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2759 {
2760 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2761 (*call->callNumber)++;
2762
2763 if (call->conn->call[channel] == call)
2764 call->conn->call[channel] = 0;
2765 MUTEX_EXIT(&conn->conn_call_lock);
2766 } else {
2767 /*
2768 * We couldn't obtain the conn_call_lock so we can't
2769 * disconnect the call from the connection. Set the
2770 * call state to dally so that the call can be reused.
2771 */
2772 MUTEX_ENTER(&rx_refcnt_mutex);
2773 call->state = RX_STATE_DALLY;
2774 return 0;
2775 }
2776
2777 MUTEX_ENTER(&rx_freeCallQueue_lock);
2778 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2779 #ifdef RX_ENABLE_LOCKS
2780 /* A call may be free even though its transmit queue is still in use.
2781 * Since we search the call list from head to tail, put busy calls at
2782 * the head of the list, and idle calls at the tail.
2783 */
2784 if (call->flags & RX_CALL_TQ_BUSY)
2785 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2786 else
2787 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2788 #else /* RX_ENABLE_LOCKS */
2789 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2790 #endif /* RX_ENABLE_LOCKS */
2791 if (rx_stats_active)
2792 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2793 MUTEX_EXIT(&rx_freeCallQueue_lock);
2794
2795 /* Destroy the connection if it was previously slated for
2796 * destruction, i.e. the Rx client code previously called
2797 * rx_DestroyConnection (client connections), or
2798 * rxi_ReapConnections called the same routine (server
2799 * connections). Only do this, however, if there are no
2800 * outstanding calls. Note that for fine grain locking, there appears
2801 * to be a deadlock in that rxi_FreeCall has a call locked and
2802 * DestroyConnectionNoLock locks each call in the conn. But note a
2803 * few lines up where we have removed this call from the conn.
2804 * If someone else destroys a connection, they either have no
2805 * call lock held or are going through this section of code.
2806 */
2807 MUTEX_ENTER(&conn->conn_data_lock);
2808 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2809 rx_GetConnection(conn);
2810 MUTEX_EXIT(&conn->conn_data_lock);
2811 #ifdef RX_ENABLE_LOCKS
2812 if (haveCTLock)
2813 rxi_DestroyConnectionNoLock(conn);
2814 else
2815 rxi_DestroyConnection(conn);
2816 #else /* RX_ENABLE_LOCKS */
2817 rxi_DestroyConnection(conn);
2818 #endif /* RX_ENABLE_LOCKS */
2819 } else {
2820 MUTEX_EXIT(&conn->conn_data_lock);
2821 }
2822 MUTEX_ENTER(&rx_refcnt_mutex);
2823 return 1;
2824 }
2825
2826 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2827 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2828
2829 void *
2830 rxi_Alloc(size_t size)
2831 {
2832 char *p;
2833
2834 if (rx_stats_active) {
2835 rx_atomic_add(&rxi_Allocsize, (int) size);
2836 rx_atomic_inc(&rxi_Alloccnt);
2837 }
2838
2839 p = (char *)
2840 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2841 afs_osi_Alloc_NoSleep(size);
2842 #else
2843 osi_Alloc(size);
2844 #endif
2845 if (!p)
2846 osi_Panic("rxi_Alloc error");
2847 memset(p, 0, size);
2848 return p;
2849 }
2850
2851 void
2852 rxi_Free(void *addr, size_t size)
2853 {
2854 if (rx_stats_active) {
2855 rx_atomic_sub(&rxi_Allocsize, (int) size);
2856 rx_atomic_dec(&rxi_Alloccnt);
2857 }
2858 osi_Free(addr, size);
2859 }
2860
2861 void
2862 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2863 {
2864 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2865 struct rx_peer *next = NULL;
2866 int hashIndex;
2867
2868 if (!peer) {
2869 MUTEX_ENTER(&rx_peerHashTable_lock);
2870 if (port == 0) {
2871 peer_ptr = &rx_peerHashTable[0];
2872 peer_end = &rx_peerHashTable[rx_hashTableSize];
2873 next = NULL;
2874 resume:
2875 for ( ; peer_ptr < peer_end; peer_ptr++) {
2876 if (!peer)
2877 peer = *peer_ptr;
2878 for ( ; peer; peer = next) {
2879 next = peer->next;
2880 if (host == peer->host)
2881 break;
2882 }
2883 }
2884 } else {
2885 hashIndex = PEER_HASH(host, port);
2886 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2887 if ((peer->host == host) && (peer->port == port))
2888 break;
2889 }
2890 }
2891 } else {
2892 MUTEX_ENTER(&rx_peerHashTable_lock);
2893 }
2894
2895 if (peer) {
2896 peer->refCount++;
2897 MUTEX_EXIT(&rx_peerHashTable_lock);
2898
2899 MUTEX_ENTER(&peer->peer_lock);
2900 /* We don't handle dropping below min, so don't */
2901 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2902 peer->ifMTU=MIN(mtu, peer->ifMTU);
2903 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2904 /* if we tweaked this down, need to tune our peer MTU too */
2905 peer->MTU = MIN(peer->MTU, peer->natMTU);
2906 /* if we discovered a sub-1500 mtu, degrade */
2907 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2908 peer->maxDgramPackets = 1;
2909 /* We no longer have valid peer packet information */
2910 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2911 peer->maxPacketSize = 0;
2912 MUTEX_EXIT(&peer->peer_lock);
2913
2914 MUTEX_ENTER(&rx_peerHashTable_lock);
2915 peer->refCount--;
2916 if (host && !port) {
2917 peer = next;
2918 /* pick up where we left off */
2919 goto resume;
2920 }
2921 }
2922 MUTEX_EXIT(&rx_peerHashTable_lock);
2923 }
2924
2925 #ifdef AFS_RXERRQ_ENV
2926 static void
2927 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2928 {
2929 int hashIndex = PEER_HASH(host, port);
2930 struct rx_peer *peer;
2931
2932 MUTEX_ENTER(&rx_peerHashTable_lock);
2933
2934 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2935 if (peer->host == host && peer->port == port) {
2936 peer->refCount++;
2937 break;
2938 }
2939 }
2940
2941 MUTEX_EXIT(&rx_peerHashTable_lock);
2942
2943 if (peer) {
2944 rx_atomic_inc(&peer->neterrs);
2945 MUTEX_ENTER(&peer->peer_lock);
2946 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2947 peer->last_err_type = err->ee_type;
2948 peer->last_err_code = err->ee_code;
2949 MUTEX_EXIT(&peer->peer_lock);
2950
2951 MUTEX_ENTER(&rx_peerHashTable_lock);
2952 peer->refCount--;
2953 MUTEX_EXIT(&rx_peerHashTable_lock);
2954 }
2955 }
2956
2957 void
2958 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2959 {
2960 # ifdef AFS_ADAPT_PMTU
2961 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2962 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2963 return;
2964 }
2965 # endif
2966 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2967 switch (err->ee_code) {
2968 case ICMP_NET_UNREACH:
2969 case ICMP_HOST_UNREACH:
2970 case ICMP_PORT_UNREACH:
2971 case ICMP_NET_ANO:
2972 case ICMP_HOST_ANO:
2973 rxi_SetPeerDead(err, addr, port);
2974 break;
2975 }
2976 }
2977 }
2978
2979 static const char *
2980 rxi_TranslateICMP(int type, int code)
2981 {
2982 switch (type) {
2983 case ICMP_DEST_UNREACH:
2984 switch (code) {
2985 case ICMP_NET_UNREACH:
2986 return "Destination Net Unreachable";
2987 case ICMP_HOST_UNREACH:
2988 return "Destination Host Unreachable";
2989 case ICMP_PROT_UNREACH:
2990 return "Destination Protocol Unreachable";
2991 case ICMP_PORT_UNREACH:
2992 return "Destination Port Unreachable";
2993 case ICMP_NET_ANO:
2994 return "Destination Net Prohibited";
2995 case ICMP_HOST_ANO:
2996 return "Destination Host Prohibited";
2997 }
2998 break;
2999 }
3000 return NULL;
3001 }
3002 #endif /* AFS_RXERRQ_ENV */
3003
3004 /**
3005 * Get the last network error for a connection
3006 *
3007 * A "network error" here means an error retrieved from ICMP, or some other
3008 * mechanism outside of Rx that informs us of errors in network reachability.
3009 *
3010 * If a peer associated with the given Rx connection has received a network
3011 * error recently, this function allows the caller to know what error
3012 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3013 * can cause calls to that peer to be quickly aborted. So, this function can
3014 * help see why a call was aborted due to network errors.
3015 *
3016 * If we have received traffic from a peer since the last network error, we
3017 * treat that peer as if we had not received an network error for it.
3018 *
3019 * @param[in] conn The Rx connection to examine
3020 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3021 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3022 * @param[out] err_type The type of the last error
3023 * @param[out] err_code The code of the last error
3024 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3025 *
3026 * @return If we have an error
3027 * @retval -1 No error to get; 'out' params are undefined
3028 * @retval 0 We have an error; 'out' params contain the last error
3029 */
3030 int
3031 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3032 int *err_code, const char **msg)
3033 {
3034 #ifdef AFS_RXERRQ_ENV
3035 struct rx_peer *peer = conn->peer;
3036 if (rx_atomic_read(&peer->neterrs)) {
3037 MUTEX_ENTER(&peer->peer_lock);
3038 *err_origin = peer->last_err_origin;
3039 *err_type = peer->last_err_type;
3040 *err_code = peer->last_err_code;
3041 MUTEX_EXIT(&peer->peer_lock);
3042
3043 *msg = NULL;
3044 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3045 *msg = rxi_TranslateICMP(*err_type, *err_code);
3046 }
3047
3048 return 0;
3049 }
3050 #endif
3051 return -1;
3052 }
3053
3054 /* Find the peer process represented by the supplied (host,port)
3055 * combination. If there is no appropriate active peer structure, a
3056 * new one will be allocated and initialized
3057 */
3058 struct rx_peer *
3059 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3060 {
3061 struct rx_peer *pp;
3062 int hashIndex;
3063 hashIndex = PEER_HASH(host, port);
3064 MUTEX_ENTER(&rx_peerHashTable_lock);
3065 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3066 if ((pp->host == host) && (pp->port == port))
3067 break;
3068 }
3069 if (!pp) {
3070 if (create) {
3071 pp = rxi_AllocPeer(); /* This bzero's *pp */
3072 pp->host = host; /* set here or in InitPeerParams is zero */
3073 pp->port = port;
3074 #ifdef AFS_RXERRQ_ENV
3075 rx_atomic_set(&pp->neterrs, 0);
3076 #endif
3077 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3078 opr_queue_Init(&pp->rpcStats);
3079 pp->next = rx_peerHashTable[hashIndex];
3080 rx_peerHashTable[hashIndex] = pp;
3081 rxi_InitPeerParams(pp);
3082 if (rx_stats_active)
3083 rx_atomic_inc(&rx_stats.nPeerStructs);
3084 }
3085 }
3086 if (pp && create) {
3087 pp->refCount++;
3088 }
3089 MUTEX_EXIT(&rx_peerHashTable_lock);
3090 return pp;
3091 }
3092
3093
3094 /* Find the connection at (host, port) started at epoch, and with the
3095 * given connection id. Creates the server connection if necessary.
3096 * The type specifies whether a client connection or a server
3097 * connection is desired. In both cases, (host, port) specify the
3098 * peer's (host, pair) pair. Client connections are not made
3099 * automatically by this routine. The parameter socket gives the
3100 * socket descriptor on which the packet was received. This is used,
3101 * in the case of server connections, to check that *new* connections
3102 * come via a valid (port, serviceId). Finally, the securityIndex
3103 * parameter must match the existing index for the connection. If a
3104 * server connection is created, it will be created using the supplied
3105 * index, if the index is valid for this service */
3106 static struct rx_connection *
3107 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3108 u_short port, u_short serviceId, afs_uint32 cid,
3109 afs_uint32 epoch, int type, u_int securityIndex,
3110 int *unknownService)
3111 {
3112 int hashindex, flag, i;
3113 struct rx_connection *conn;
3114 *unknownService = 0;
3115 hashindex = CONN_HASH(host, port, cid, epoch, type);
3116 MUTEX_ENTER(&rx_connHashTable_lock);
3117 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3118 rx_connHashTable[hashindex],
3119 flag = 1);
3120 for (; conn;) {
3121 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3122 && (epoch == conn->epoch)) {
3123 struct rx_peer *pp = conn->peer;
3124 if (securityIndex != conn->securityIndex) {
3125 /* this isn't supposed to happen, but someone could forge a packet
3126 * like this, and there seems to be some CM bug that makes this
3127 * happen from time to time -- in which case, the fileserver
3128 * asserts. */
3129 MUTEX_EXIT(&rx_connHashTable_lock);
3130 return (struct rx_connection *)0;
3131 }
3132 if (pp->host == host && pp->port == port)
3133 break;
3134 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3135 break;
3136 /* So what happens when it's a callback connection? */
3137 if ( /*type == RX_CLIENT_CONNECTION && */
3138 (conn->epoch & 0x80000000))
3139 break;
3140 }
3141 if (!flag) {
3142 /* the connection rxLastConn that was used the last time is not the
3143 ** one we are looking for now. Hence, start searching in the hash */
3144 flag = 1;
3145 conn = rx_connHashTable[hashindex];
3146 } else
3147 conn = conn->next;
3148 }
3149 if (!conn) {
3150 struct rx_service *service;
3151 if (type == RX_CLIENT_CONNECTION) {
3152 MUTEX_EXIT(&rx_connHashTable_lock);
3153 return (struct rx_connection *)0;
3154 }
3155 service = rxi_FindService(socket, serviceId);
3156 if (!service || (securityIndex >= service->nSecurityObjects)
3157 || (service->securityObjects[securityIndex] == 0)) {
3158 MUTEX_EXIT(&rx_connHashTable_lock);
3159 *unknownService = 1;
3160 return (struct rx_connection *)0;
3161 }
3162 conn = rxi_AllocConnection(); /* This bzero's the connection */
3163 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3164 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3165 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3166 conn->next = rx_connHashTable[hashindex];
3167 rx_connHashTable[hashindex] = conn;
3168 conn->peer = rxi_FindPeer(host, port, 1);
3169 conn->type = RX_SERVER_CONNECTION;
3170 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3171 conn->epoch = epoch;
3172 conn->cid = cid & RX_CIDMASK;
3173 conn->ackRate = RX_FAST_ACK_RATE;
3174 conn->service = service;
3175 conn->serviceId = serviceId;
3176 conn->securityIndex = securityIndex;
3177 conn->securityObject = service->securityObjects[securityIndex];
3178 conn->nSpecific = 0;
3179 conn->specific = NULL;
3180 rx_SetConnDeadTime(conn, service->connDeadTime);
3181 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3182 for (i = 0; i < RX_MAXCALLS; i++) {
3183 conn->twind[i] = rx_initSendWindow;
3184 conn->rwind[i] = rx_initReceiveWindow;
3185 }
3186 /* Notify security object of the new connection */
3187 RXS_NewConnection(conn->securityObject, conn);
3188 /* XXXX Connection timeout? */
3189 if (service->newConnProc)
3190 (*service->newConnProc) (conn);
3191 if (rx_stats_active)
3192 rx_atomic_inc(&rx_stats.nServerConns);
3193 }
3194
3195 rx_GetConnection(conn);
3196
3197 rxLastConn = conn; /* store this connection as the last conn used */
3198 MUTEX_EXIT(&rx_connHashTable_lock);
3199 return conn;
3200 }
3201
3202 /*!
3203 * Abort the call if the server is over the busy threshold. This
3204 * can be used without requiring a call structure be initialised,
3205 * or connected to a particular channel
3206 */
3207 static_inline int
3208 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3209 struct rx_packet *np)
3210 {
3211 afs_uint32 serial;
3212
3213 if ((rx_BusyThreshold > 0) &&
3214 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3215 MUTEX_ENTER(&conn->conn_data_lock);
3216 serial = ++conn->serial;
3217 MUTEX_EXIT(&conn->conn_data_lock);
3218 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3219 serial, rx_BusyError, np, 0);
3220 if (rx_stats_active)
3221 rx_atomic_inc(&rx_stats.nBusies);
3222 return 1;
3223 }
3224
3225 return 0;
3226 }
3227
3228 static_inline struct rx_call *
3229 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3230 {
3231 int channel;
3232 struct rx_call *call;
3233
3234 channel = np->header.cid & RX_CHANNELMASK;
3235 MUTEX_ENTER(&conn->conn_call_lock);
3236 call = conn->call[channel];
3237 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3238 conn->lastBusy[channel] = clock_Sec();
3239 }
3240 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3241 MUTEX_EXIT(&conn->conn_call_lock);
3242 if (rx_stats_active)
3243 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3244 return NULL;
3245 }
3246
3247 MUTEX_ENTER(&call->lock);
3248 MUTEX_EXIT(&conn->conn_call_lock);
3249
3250 if ((call->state == RX_STATE_DALLY)
3251 && np->header.type == RX_PACKET_TYPE_ACK) {
3252 if (rx_stats_active)
3253 rx_atomic_inc(&rx_stats.ignorePacketDally);
3254 MUTEX_EXIT(&call->lock);
3255 return NULL;
3256 }
3257
3258 return call;
3259 }
3260
3261 static_inline struct rx_call *
3262 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3263 struct rx_connection *conn)
3264 {
3265 int channel;
3266 struct rx_call *call;
3267
3268 channel = np->header.cid & RX_CHANNELMASK;
3269 MUTEX_ENTER(&conn->conn_call_lock);
3270 call = conn->call[channel];
3271
3272 if (!call) {
3273 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3274 MUTEX_EXIT(&conn->conn_call_lock);
3275 return NULL;
3276 }
3277
3278 call = rxi_NewCall(conn, channel); /* returns locked call */
3279 *call->callNumber = np->header.callNumber;
3280 MUTEX_EXIT(&conn->conn_call_lock);
3281
3282 call->state = RX_STATE_PRECALL;
3283 clock_GetTime(&call->queueTime);
3284 call->app.bytesSent = 0;
3285 call->app.bytesRcvd = 0;
3286 rxi_KeepAliveOn(call);
3287
3288 return call;
3289 }
3290
3291 if (np->header.callNumber == conn->callNumber[channel]) {
3292 MUTEX_ENTER(&call->lock);
3293 MUTEX_EXIT(&conn->conn_call_lock);
3294 return call;
3295 }
3296
3297 if (np->header.callNumber < conn->callNumber[channel]) {
3298 MUTEX_EXIT(&conn->conn_call_lock);
3299 if (rx_stats_active)
3300 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3301 return NULL;
3302 }
3303
3304 MUTEX_ENTER(&call->lock);
3305 MUTEX_EXIT(&conn->conn_call_lock);
3306
3307 /* Wait until the transmit queue is idle before deciding
3308 * whether to reset the current call. Chances are that the
3309 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3310 * flag is cleared.
3311 */
3312 #ifdef RX_ENABLE_LOCKS
3313 if (call->state == RX_STATE_ACTIVE && !call->error) {
3314 rxi_WaitforTQBusy(call);
3315 /* If we entered error state while waiting,
3316 * must call rxi_CallError to permit rxi_ResetCall
3317 * to processed when the tqWaiter count hits zero.
3318 */
3319 if (call->error) {
3320 rxi_CallError(call, call->error);
3321 MUTEX_EXIT(&call->lock);
3322 return NULL;
3323 }
3324 }
3325 #endif /* RX_ENABLE_LOCKS */
3326 /* If the new call cannot be taken right now send a busy and set
3327 * the error condition in this call, so that it terminates as
3328 * quickly as possible */
3329 if (call->state == RX_STATE_ACTIVE) {
3330 rxi_CallError(call, RX_CALL_DEAD);
3331 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3332 NULL, 0, 1);
3333 MUTEX_EXIT(&call->lock);
3334 return NULL;
3335 }
3336
3337 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3338 MUTEX_EXIT(&call->lock);
3339 return NULL;
3340 }
3341
3342 rxi_ResetCall(call, 0);
3343 /* The conn_call_lock is not held but no one else should be
3344 * using this call channel while we are processing this incoming
3345 * packet. This assignment should be safe.
3346 */
3347 *call->callNumber = np->header.callNumber;
3348 call->state = RX_STATE_PRECALL;
3349 clock_GetTime(&call->queueTime);
3350 call->app.bytesSent = 0;
3351 call->app.bytesRcvd = 0;
3352 rxi_KeepAliveOn(call);
3353
3354 return call;
3355 }
3356
3357
3358 /* There are two packet tracing routines available for testing and monitoring
3359 * Rx. One is called just after every packet is received and the other is
3360 * called just before every packet is sent. Received packets, have had their
3361 * headers decoded, and packets to be sent have not yet had their headers
3362 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3363 * containing the network address. Both can be modified. The return value, if
3364 * non-zero, indicates that the packet should be dropped. */
3365
3366 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3367 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3368
3369 /* A packet has been received off the interface. Np is the packet, socket is
3370 * the socket number it was received from (useful in determining which service
3371 * this packet corresponds to), and (host, port) reflect the host,port of the
3372 * sender. This call returns the packet to the caller if it is finished with
3373 * it, rather than de-allocating it, just as a small performance hack */
3374
3375 struct rx_packet *
3376 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3377 afs_uint32 host, u_short port, int *tnop,
3378 struct rx_call **newcallp)
3379 {
3380 struct rx_call *call;
3381 struct rx_connection *conn;
3382 int type;
3383 int unknownService = 0;
3384 #ifdef RXDEBUG
3385 char *packetType;
3386 #endif
3387 struct rx_packet *tnp;
3388
3389 #ifdef RXDEBUG
3390 /* We don't print out the packet until now because (1) the time may not be
3391 * accurate enough until now in the lwp implementation (rx_Listener only gets
3392 * the time after the packet is read) and (2) from a protocol point of view,
3393 * this is the first time the packet has been seen */
3394 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3395 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3396 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3397 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3398 np->header.epoch, np->header.cid, np->header.callNumber,
3399 np->header.seq, np->header.flags, np));
3400 #endif
3401
3402 /* Account for connectionless packets */
3403 if (rx_stats_active &&
3404 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3405 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3406 struct rx_peer *peer;
3407
3408 /* Try to look up the peer structure, but don't create one */
3409 peer = rxi_FindPeer(host, port, 0);
3410
3411 /* Since this may not be associated with a connection, it may have
3412 * no refCount, meaning we could race with ReapConnections
3413 */
3414
3415 if (peer && (peer->refCount > 0)) {
3416 #ifdef AFS_RXERRQ_ENV
3417 if (rx_atomic_read(&peer->neterrs)) {
3418 rx_atomic_set(&peer->neterrs, 0);
3419 }
3420 #endif
3421 MUTEX_ENTER(&peer->peer_lock);
3422 peer->bytesReceived += np->length;
3423 MUTEX_EXIT(&peer->peer_lock);
3424 }
3425 }
3426
3427 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3428 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3429 }
3430
3431 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3432 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3433 }
3434 #ifdef RXDEBUG
3435 /* If an input tracer function is defined, call it with the packet and
3436 * network address. Note this function may modify its arguments. */
3437 if (rx_justReceived) {
3438 struct sockaddr_in addr;
3439 int drop;
3440 addr.sin_family = AF_INET;
3441 addr.sin_port = port;
3442 addr.sin_addr.s_addr = host;
3443 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3444 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3445 addr.sin_len = sizeof(addr);
3446 #endif /* AFS_OSF_ENV */
3447 drop = (*rx_justReceived) (np, &addr);
3448 /* drop packet if return value is non-zero */
3449 if (drop)
3450 return np;
3451 port = addr.sin_port; /* in case fcn changed addr */
3452 host = addr.sin_addr.s_addr;
3453 }
3454 #endif
3455
3456 /* If packet was not sent by the client, then *we* must be the client */
3457 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3458 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3459
3460 /* Find the connection (or fabricate one, if we're the server & if
3461 * necessary) associated with this packet */
3462 conn =
3463 rxi_FindConnection(socket, host, port, np->header.serviceId,
3464 np->header.cid, np->header.epoch, type,
3465 np->header.securityIndex, &unknownService);
3466
3467 /* To avoid having 2 connections just abort at each other,
3468 don't abort an abort. */
3469 if (!conn) {
3470 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3471 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3472 np, 0);
3473 return np;
3474 }
3475
3476 #ifdef AFS_RXERRQ_ENV
3477 if (rx_atomic_read(&conn->peer->neterrs)) {
3478 rx_atomic_set(&conn->peer->neterrs, 0);
3479 }
3480 #endif
3481
3482 /* If we're doing statistics, then account for the incoming packet */
3483 if (rx_stats_active) {
3484 MUTEX_ENTER(&conn->peer->peer_lock);
3485 conn->peer->bytesReceived += np->length;
3486 MUTEX_EXIT(&conn->peer->peer_lock);
3487 }
3488
3489 /* If the connection is in an error state, send an abort packet and ignore
3490 * the incoming packet */
3491 if (conn->error) {
3492 /* Don't respond to an abort packet--we don't want loops! */
3493 MUTEX_ENTER(&conn->conn_data_lock);
3494 if (np->header.type != RX_PACKET_TYPE_ABORT)
3495 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3496 putConnection(conn);
3497 MUTEX_EXIT(&conn->conn_data_lock);
3498 return np;
3499 }
3500
3501 /* Check for connection-only requests (i.e. not call specific). */
3502 if (np->header.callNumber == 0) {
3503 switch (np->header.type) {
3504 case RX_PACKET_TYPE_ABORT: {
3505 /* What if the supplied error is zero? */
3506 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3507 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3508 rxi_ConnectionError(conn, errcode);
3509 putConnection(conn);
3510 return np;
3511 }
3512 case RX_PACKET_TYPE_CHALLENGE:
3513 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3514 putConnection(conn);
3515 return tnp;
3516 case RX_PACKET_TYPE_RESPONSE:
3517 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3518 putConnection(conn);
3519 return tnp;
3520 case RX_PACKET_TYPE_PARAMS:
3521 case RX_PACKET_TYPE_PARAMS + 1:
3522 case RX_PACKET_TYPE_PARAMS + 2:
3523 /* ignore these packet types for now */
3524 putConnection(conn);
3525 return np;
3526
3527 default:
3528 /* Should not reach here, unless the peer is broken: send an
3529 * abort packet */
3530 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3531 MUTEX_ENTER(&conn->conn_data_lock);
3532 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3533 putConnection(conn);
3534 MUTEX_EXIT(&conn->conn_data_lock);
3535 return tnp;
3536 }
3537 }
3538
3539 if (type == RX_SERVER_CONNECTION)
3540 call = rxi_ReceiveServerCall(socket, np, conn);
3541 else
3542 call = rxi_ReceiveClientCall(np, conn);
3543
3544 if (call == NULL) {
3545 putConnection(conn);
3546 return np;
3547 }
3548
3549 MUTEX_ASSERT(&call->lock);
3550 /* Set remote user defined status from packet */
3551 call->remoteStatus = np->header.userStatus;
3552
3553 /* Now do packet type-specific processing */
3554 switch (np->header.type) {
3555 case RX_PACKET_TYPE_DATA:
3556 /* If we're a client, and receiving a response, then all the packets
3557 * we transmitted packets are implicitly acknowledged. */
3558 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3559 rxi_AckAllInTransmitQueue(call);
3560
3561 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3562 newcallp);
3563 break;
3564 case RX_PACKET_TYPE_ACK:
3565 /* Respond immediately to ack packets requesting acknowledgement
3566 * (ping packets) */
3567 if (np->header.flags & RX_REQUEST_ACK) {
3568 if (call->error)
3569 (void)rxi_SendCallAbort(call, 0, 1, 0);
3570 else
3571 (void)rxi_SendAck(call, 0, np->header.serial,
3572 RX_ACK_PING_RESPONSE, 1);
3573 }
3574 np = rxi_ReceiveAckPacket(call, np, 1);
3575 break;
3576 case RX_PACKET_TYPE_ABORT: {
3577 /* An abort packet: reset the call, passing the error up to the user. */
3578 /* What if error is zero? */
3579 /* What if the error is -1? the application will treat it as a timeout. */
3580 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3581 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3582 rxi_CallError(call, errdata);
3583 MUTEX_EXIT(&call->lock);
3584 putConnection(conn);
3585 return np; /* xmitting; drop packet */
3586 }
3587 case RX_PACKET_TYPE_BUSY:
3588 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3589 * so we don't think the endpoint is completely dead, but otherwise
3590 * just act as if we never saw anything. If all we get are BUSY packets
3591 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3592 * connection is configured with idle/hard timeouts. */
3593 break;
3594
3595 case RX_PACKET_TYPE_ACKALL:
3596 /* All packets acknowledged, so we can drop all packets previously
3597 * readied for sending */
3598 rxi_AckAllInTransmitQueue(call);
3599 break;
3600 default:
3601 /* Should not reach here, unless the peer is broken: send an abort
3602 * packet */
3603 rxi_CallError(call, RX_PROTOCOL_ERROR);
3604 np = rxi_SendCallAbort(call, np, 1, 0);
3605 break;
3606 };
3607 /* Note when this last legitimate packet was received, for keep-alive
3608 * processing. Note, we delay getting the time until now in the hope that
3609 * the packet will be delivered to the user before any get time is required
3610 * (if not, then the time won't actually be re-evaluated here). */
3611 call->lastReceiveTime = clock_Sec();
3612 MUTEX_EXIT(&call->lock);
3613 putConnection(conn);
3614 return np;
3615 }
3616
3617 /* return true if this is an "interesting" connection from the point of view
3618 of someone trying to debug the system */
3619 int
3620 rxi_IsConnInteresting(struct rx_connection *aconn)
3621 {
3622 int i;
3623 struct rx_call *tcall;
3624
3625 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3626 return 1;
3627
3628 for (i = 0; i < RX_MAXCALLS; i++) {
3629 tcall = aconn->call[i];
3630 if (tcall) {
3631 if ((tcall->state == RX_STATE_PRECALL)
3632 || (tcall->state == RX_STATE_ACTIVE))
3633 return 1;
3634 if ((tcall->app.mode == RX_MODE_SENDING)
3635 || (tcall->app.mode == RX_MODE_RECEIVING))
3636 return 1;
3637 }
3638 }
3639 return 0;
3640 }
3641
3642 #ifdef KERNEL
3643 /* if this is one of the last few packets AND it wouldn't be used by the
3644 receiving call to immediately satisfy a read request, then drop it on
3645 the floor, since accepting it might prevent a lock-holding thread from
3646 making progress in its reading. If a call has been cleared while in
3647 the precall state then ignore all subsequent packets until the call
3648 is assigned to a thread. */
3649
3650 static int
3651 TooLow(struct rx_packet *ap, struct rx_call *acall)
3652 {
3653 int rc = 0;
3654
3655 MUTEX_ENTER(&rx_quota_mutex);
3656 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3657 && (acall->state == RX_STATE_PRECALL))
3658 || ((rx_nFreePackets < rxi_dataQuota + 2)
3659 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3660 && (acall->flags & RX_CALL_READER_WAIT)))) {
3661 rc = 1;
3662 }
3663 MUTEX_EXIT(&rx_quota_mutex);
3664 return rc;
3665 }
3666 #endif /* KERNEL */
3667
3668 /*!
3669 * Clear the attach wait flag on a connection and proceed.
3670 *
3671 * Any processing waiting for a connection to be attached should be
3672 * unblocked. We clear the flag and do any other needed tasks.
3673 *
3674 * @param[in] conn
3675 * the conn to unmark waiting for attach
3676 *
3677 * @pre conn's conn_data_lock must be locked before calling this function
3678 *
3679 */
3680 static void
3681 rxi_ConnClearAttachWait(struct rx_connection *conn)
3682 {
3683 /* Indicate that rxi_CheckReachEvent is no longer running by
3684 * clearing the flag. Must be atomic under conn_data_lock to
3685 * avoid a new call slipping by: rxi_CheckConnReach holds
3686 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3687 */
3688 conn->flags &= ~RX_CONN_ATTACHWAIT;
3689 if (conn->flags & RX_CONN_NAT_PING) {
3690 conn->flags &= ~RX_CONN_NAT_PING;
3691 rxi_ScheduleNatKeepAliveEvent(conn);
3692 }
3693 }
3694
3695 /*
3696 * Event handler function for connection-specific events for checking
3697 * reachability. Also called directly from main code with |event| == NULL
3698 * in order to trigger the initial reachability check.
3699 *
3700 * When |event| == NULL, must be called with the connection data lock held,
3701 * but returns with the lock unlocked.
3702 */
3703 static void
3704 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3705 {
3706 struct rx_connection *conn = arg1;
3707 struct rx_call *acall = arg2;
3708 struct rx_call *call = acall;
3709 struct clock when, now;
3710 int i, waiting;
3711
3712 if (event != NULL)
3713 MUTEX_ENTER(&conn->conn_data_lock);
3714 else
3715 MUTEX_ASSERT(&conn->conn_data_lock);
3716
3717 if (event != NULL && event == conn->checkReachEvent)
3718 rxevent_Put(&conn->checkReachEvent);
3719 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3720 MUTEX_EXIT(&conn->conn_data_lock);
3721
3722 if (waiting) {
3723 if (!call) {
3724 MUTEX_ENTER(&conn->conn_call_lock);
3725 MUTEX_ENTER(&conn->conn_data_lock);
3726 for (i = 0; i < RX_MAXCALLS; i++) {
3727 struct rx_call *tc = conn->call[i];
3728 if (tc && tc->state == RX_STATE_PRECALL) {
3729 call = tc;
3730 break;
3731 }
3732 }
3733 if (!call)
3734 rxi_ConnClearAttachWait(conn);
3735 MUTEX_EXIT(&conn->conn_data_lock);
3736 MUTEX_EXIT(&conn->conn_call_lock);
3737 }
3738
3739 if (call) {
3740 if (call != acall)
3741 MUTEX_ENTER(&call->lock);
3742 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3743 if (call != acall)
3744 MUTEX_EXIT(&call->lock);
3745
3746 clock_GetTime(&now);
3747 when = now;
3748 when.sec += RX_CHECKREACH_TIMEOUT;
3749 MUTEX_ENTER(&conn->conn_data_lock);
3750 if (!conn->checkReachEvent) {
3751 rx_GetConnection(conn);
3752 conn->checkReachEvent = rxevent_Post(&when, &now,
3753 rxi_CheckReachEvent, conn,
3754 NULL, 0);
3755 }
3756 MUTEX_EXIT(&conn->conn_data_lock);
3757 }
3758 }
3759 /* If fired as an event handler, drop our refcount on the connection. */
3760 if (event != NULL)
3761 putConnection(conn);
3762 }
3763
3764 static int
3765 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3766 {
3767 struct rx_service *service = conn->service;
3768 struct rx_peer *peer = conn->peer;
3769 afs_uint32 now, lastReach;
3770
3771 if (service->checkReach == 0)
3772 return 0;
3773
3774 now = clock_Sec();
3775 MUTEX_ENTER(&peer->peer_lock);
3776 lastReach = peer->lastReachTime;
3777 MUTEX_EXIT(&peer->peer_lock);
3778 if (now - lastReach < RX_CHECKREACH_TTL)
3779 return 0;
3780
3781 MUTEX_ENTER(&conn->conn_data_lock);
3782 if (conn->flags & RX_CONN_ATTACHWAIT) {
3783 MUTEX_EXIT(&conn->conn_data_lock);
3784 return 1;
3785 }
3786 conn->flags |= RX_CONN_ATTACHWAIT;
3787 if (conn->checkReachEvent == NULL) {
3788 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3789 rxi_CheckReachEvent(NULL, conn, call, 0);
3790 } else {
3791 MUTEX_EXIT(&conn->conn_data_lock);
3792 }
3793
3794 return 1;
3795 }
3796
3797 /* try to attach call, if authentication is complete */
3798 static void
3799 TryAttach(struct rx_call *acall, osi_socket socket,
3800 int *tnop, struct rx_call **newcallp,
3801 int reachOverride)
3802 {
3803 struct rx_connection *conn = acall->conn;
3804
3805 if (conn->type == RX_SERVER_CONNECTION
3806 && acall->state == RX_STATE_PRECALL) {
3807 /* Don't attach until we have any req'd. authentication. */
3808 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3809 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3810 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3811 /* Note: this does not necessarily succeed; there
3812 * may not any proc available
3813 */
3814 } else {
3815 rxi_ChallengeOn(acall->conn);
3816 }
3817 }
3818 }
3819
3820 /* A data packet has been received off the interface. This packet is
3821 * appropriate to the call (the call is in the right state, etc.). This
3822 * routine can return a packet to the caller, for re-use */
3823
3824 static struct rx_packet *
3825 rxi_ReceiveDataPacket(struct rx_call *call,
3826 struct rx_packet *np, int istack,
3827 osi_socket socket, afs_uint32 host, u_short port,
3828 int *tnop, struct rx_call **newcallp)
3829 {
3830 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3831 int newPackets = 0;
3832 int didHardAck = 0;
3833 int haveLast = 0;
3834 afs_uint32 seq;
3835 afs_uint32 serial=0, flags=0;
3836 int isFirst;
3837 struct rx_packet *tnp;
3838 if (rx_stats_active)
3839 rx_atomic_inc(&rx_stats.dataPacketsRead);
3840
3841 #ifdef KERNEL
3842 /* If there are no packet buffers, drop this new packet, unless we can find
3843 * packet buffers from inactive calls */
3844 if (!call->error
3845 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3846 MUTEX_ENTER(&rx_freePktQ_lock);
3847 rxi_NeedMorePackets = TRUE;
3848 MUTEX_EXIT(&rx_freePktQ_lock);
3849 if (rx_stats_active)
3850 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3851 rxi_calltrace(RX_TRACE_DROP, call);
3852 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3853 /* We used to clear the receive queue here, in an attempt to free
3854 * packets. However this is unsafe if the queue has received a
3855 * soft ACK for the final packet */
3856 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3857 return np;
3858 }
3859 #endif /* KERNEL */
3860
3861 /*
3862 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3863 * packet is one of several packets transmitted as a single
3864 * datagram. Do not send any soft or hard acks until all packets
3865 * in a jumbogram have been processed. Send negative acks right away.
3866 */
3867 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3868 /* tnp is non-null when there are more packets in the
3869 * current jumbo gram */
3870 if (tnp) {
3871 if (np)
3872 rxi_FreePacket(np);
3873 np = tnp;
3874 }
3875
3876 seq = np->header.seq;
3877 serial = np->header.serial;
3878 flags = np->header.flags;
3879
3880 /* If the call is in an error state, send an abort message */
3881 if (call->error)
3882 return rxi_SendCallAbort(call, np, istack, 0);
3883
3884 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3885 * AFS 3.5 jumbogram. */
3886 if (flags & RX_JUMBO_PACKET) {
3887 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3888 } else {
3889 tnp = NULL;
3890 }
3891
3892 if (np->header.spare != 0) {
3893 MUTEX_ENTER(&call->conn->conn_data_lock);
3894 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3895 MUTEX_EXIT(&call->conn->conn_data_lock);
3896 }
3897
3898 /* The usual case is that this is the expected next packet */
3899 if (seq == call->rnext) {
3900
3901 /* Check to make sure it is not a duplicate of one already queued */
3902 if (!opr_queue_IsEmpty(&call->rq)
3903 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3904 if (rx_stats_active)
3905 rx_atomic_inc(&rx_stats.dupPacketsRead);
3906 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3907 rxi_CancelDelayedAckEvent(call);
3908 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3909 ackNeeded = 0;
3910 call->rprev = seq;
3911 continue;
3912 }
3913
3914 /* It's the next packet. Stick it on the receive queue
3915 * for this call. Set newPackets to make sure we wake
3916 * the reader once all packets have been processed */
3917 #ifdef RX_TRACK_PACKETS
3918 np->flags |= RX_PKTFLAG_RQ;
3919 #endif
3920 opr_queue_Prepend(&call->rq, &np->entry);
3921 #ifdef RXDEBUG_PACKET
3922 call->rqc++;
3923 #endif /* RXDEBUG_PACKET */
3924 call->nSoftAcks++;
3925 np = NULL; /* We can't use this anymore */
3926 newPackets = 1;
3927
3928 /* If an ack is requested then set a flag to make sure we
3929 * send an acknowledgement for this packet */
3930 if (flags & RX_REQUEST_ACK) {
3931 ackNeeded = RX_ACK_REQUESTED;
3932 }
3933
3934 /* Keep track of whether we have received the last packet */
3935 if (flags & RX_LAST_PACKET) {
3936 call->flags |= RX_CALL_HAVE_LAST;
3937 haveLast = 1;
3938 }
3939
3940 /* Check whether we have all of the packets for this call */
3941 if (call->flags & RX_CALL_HAVE_LAST) {
3942 afs_uint32 tseq; /* temporary sequence number */
3943 struct opr_queue *cursor;
3944
3945 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3946 struct rx_packet *tp;
3947
3948 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3949 if (tseq != tp->header.seq)
3950 break;
3951 if (tp->header.flags & RX_LAST_PACKET) {
3952 call->flags |= RX_CALL_RECEIVE_DONE;
3953 break;
3954 }
3955 tseq++;
3956 }
3957 }
3958
3959 /* Provide asynchronous notification for those who want it
3960 * (e.g. multi rx) */
3961 if (call->arrivalProc) {
3962 (*call->arrivalProc) (call, call->arrivalProcHandle,
3963 call->arrivalProcArg);
3964 call->arrivalProc = (void (*)())0;
3965 }
3966
3967 /* Update last packet received */
3968 call->rprev = seq;
3969
3970 /* If there is no server process serving this call, grab
3971 * one, if available. We only need to do this once. If a
3972 * server thread is available, this thread becomes a server
3973 * thread and the server thread becomes a listener thread. */
3974 if (isFirst) {
3975 TryAttach(call, socket, tnop, newcallp, 0);
3976 }
3977 }
3978 /* This is not the expected next packet. */
3979 else {
3980 /* Determine whether this is a new or old packet, and if it's
3981 * a new one, whether it fits into the current receive window.
3982 * Also figure out whether the packet was delivered in sequence.
3983 * We use the prev variable to determine whether the new packet
3984 * is the successor of its immediate predecessor in the
3985 * receive queue, and the missing flag to determine whether
3986 * any of this packets predecessors are missing. */
3987
3988 afs_uint32 prev; /* "Previous packet" sequence number */
3989 struct opr_queue *cursor;
3990 int missing; /* Are any predecessors missing? */
3991
3992 /* If the new packet's sequence number has been sent to the
3993 * application already, then this is a duplicate */
3994 if (seq < call->rnext) {
3995 if (rx_stats_active)
3996 rx_atomic_inc(&rx_stats.dupPacketsRead);
3997 rxi_CancelDelayedAckEvent(call);
3998 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3999 ackNeeded = 0;
4000 call->rprev = seq;
4001 continue;
4002 }
4003
4004 /* If the sequence number is greater than what can be
4005 * accomodated by the current window, then send a negative
4006 * acknowledge and drop the packet */
4007 if ((call->rnext + call->rwind) <= seq) {
4008 rxi_CancelDelayedAckEvent(call);
4009 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4010 istack);
4011 ackNeeded = 0;
4012 call->rprev = seq;
4013 continue;
4014 }
4015
4016 /* Look for the packet in the queue of old received packets */
4017 prev = call->rnext - 1;
4018 missing = 0;
4019 for (opr_queue_Scan(&call->rq, cursor)) {
4020 struct rx_packet *tp
4021 = opr_queue_Entry(cursor, struct rx_packet, entry);
4022
4023 /*Check for duplicate packet */
4024 if (seq == tp->header.seq) {
4025 if (rx_stats_active)
4026 rx_atomic_inc(&rx_stats.dupPacketsRead);
4027 rxi_CancelDelayedAckEvent(call);
4028 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4029 istack);
4030 ackNeeded = 0;
4031 call->rprev = seq;
4032 goto nextloop;
4033 }
4034 /* If we find a higher sequence packet, break out and
4035 * insert the new packet here. */
4036 if (seq < tp->header.seq)
4037 break;
4038 /* Check for missing packet */
4039 if (tp->header.seq != prev + 1) {
4040 missing = 1;
4041 }
4042
4043 prev = tp->header.seq;
4044 }
4045
4046 /* Keep track of whether we have received the last packet. */
4047 if (flags & RX_LAST_PACKET) {
4048 call->flags |= RX_CALL_HAVE_LAST;
4049 }
4050
4051 /* It's within the window: add it to the the receive queue.
4052 * tp is left by the previous loop either pointing at the
4053 * packet before which to insert the new packet, or at the
4054 * queue head if the queue is empty or the packet should be
4055 * appended. */
4056 #ifdef RX_TRACK_PACKETS
4057 np->flags |= RX_PKTFLAG_RQ;
4058 #endif
4059 #ifdef RXDEBUG_PACKET
4060 call->rqc++;
4061 #endif /* RXDEBUG_PACKET */
4062 opr_queue_InsertBefore(cursor, &np->entry);
4063 call->nSoftAcks++;
4064 np = NULL;
4065
4066 /* Check whether we have all of the packets for this call */
4067 if ((call->flags & RX_CALL_HAVE_LAST)
4068 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4069 afs_uint32 tseq; /* temporary sequence number */
4070
4071 tseq = call->rnext;
4072 for (opr_queue_Scan(&call->rq, cursor)) {
4073 struct rx_packet *tp
4074 = opr_queue_Entry(cursor, struct rx_packet, entry);
4075 if (tseq != tp->header.seq)
4076 break;
4077 if (tp->header.flags & RX_LAST_PACKET) {
4078 call->flags |= RX_CALL_RECEIVE_DONE;
4079 break;
4080 }
4081 tseq++;
4082 }
4083 }
4084
4085 /* We need to send an ack of the packet is out of sequence,
4086 * or if an ack was requested by the peer. */
4087 if (seq != prev + 1 || missing) {
4088 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4089 } else if (flags & RX_REQUEST_ACK) {
4090 ackNeeded = RX_ACK_REQUESTED;
4091 }
4092
4093 /* Acknowledge the last packet for each call */
4094 if (flags & RX_LAST_PACKET) {
4095 haveLast = 1;
4096 }
4097
4098 call->rprev = seq;
4099 }
4100 nextloop:;
4101 }
4102
4103 if (newPackets) {
4104 /*
4105 * If the receiver is waiting for an iovec, fill the iovec
4106 * using the data from the receive queue */
4107 if (call->flags & RX_CALL_IOVEC_WAIT) {
4108 didHardAck = rxi_FillReadVec(call, serial);
4109 /* the call may have been aborted */
4110 if (call->error) {
4111 return NULL;
4112 }
4113 if (didHardAck) {
4114 ackNeeded = 0;
4115 }
4116 }
4117
4118 /* Wakeup the reader if any */
4119 if ((call->flags & RX_CALL_READER_WAIT)
4120 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4121 || (call->iovNext >= call->iovMax)
4122 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4123 call->flags &= ~RX_CALL_READER_WAIT;
4124 #ifdef RX_ENABLE_LOCKS
4125 CV_BROADCAST(&call->cv_rq);
4126 #else
4127 osi_rxWakeup(&call->rq);
4128 #endif
4129 }
4130 }
4131
4132 /*
4133 * Send an ack when requested by the peer, or once every
4134 * rxi_SoftAckRate packets until the last packet has been
4135 * received. Always send a soft ack for the last packet in
4136 * the server's reply. */
4137 if (ackNeeded) {
4138 rxi_CancelDelayedAckEvent(call);
4139 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4140 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4141 rxi_CancelDelayedAckEvent(call);
4142 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4143 } else if (call->nSoftAcks) {
4144 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4145 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4146 else
4147 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4148 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4149 rxi_CancelDelayedAckEvent(call);
4150 }
4151
4152 return np;
4153 }
4154
4155 static void
4156 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4157 {
4158 struct rx_peer *peer = conn->peer;
4159
4160 MUTEX_ENTER(&peer->peer_lock);
4161 peer->lastReachTime = clock_Sec();
4162 MUTEX_EXIT(&peer->peer_lock);
4163
4164 MUTEX_ENTER(&conn->conn_data_lock);
4165 if (conn->flags & RX_CONN_ATTACHWAIT) {
4166 int i;
4167
4168 rxi_ConnClearAttachWait(conn);
4169 MUTEX_EXIT(&conn->conn_data_lock);
4170
4171 for (i = 0; i < RX_MAXCALLS; i++) {
4172 struct rx_call *call = conn->call[i];
4173 if (call) {
4174 if (call != acall)
4175 MUTEX_ENTER(&call->lock);
4176 /* tnop can be null if newcallp is null */
4177 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4178 if (call != acall)
4179 MUTEX_EXIT(&call->lock);
4180 }
4181 }
4182 } else
4183 MUTEX_EXIT(&conn->conn_data_lock);
4184 }
4185
4186 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4187 static const char *
4188 rx_ack_reason(int reason)
4189 {
4190 switch (reason) {
4191 case RX_ACK_REQUESTED:
4192 return "requested";
4193 case RX_ACK_DUPLICATE:
4194 return "duplicate";
4195 case RX_ACK_OUT_OF_SEQUENCE:
4196 return "sequence";
4197 case RX_ACK_EXCEEDS_WINDOW:
4198 return "window";
4199 case RX_ACK_NOSPACE:
4200 return "nospace";
4201 case RX_ACK_PING:
4202 return "ping";
4203 case RX_ACK_PING_RESPONSE:
4204 return "response";
4205 case RX_ACK_DELAY:
4206 return "delay";
4207 case RX_ACK_IDLE:
4208 return "idle";
4209 default:
4210 return "unknown!!";
4211 }
4212 }
4213 #endif
4214
4215
4216 /* The real smarts of the whole thing. */
4217 static struct rx_packet *
4218 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4219 int istack)
4220 {
4221 struct rx_ackPacket *ap;
4222 int nAcks;
4223 struct rx_packet *tp;
4224 struct rx_connection *conn = call->conn;
4225 struct rx_peer *peer = conn->peer;
4226 struct opr_queue *cursor;
4227 struct clock now; /* Current time, for RTT calculations */
4228 afs_uint32 first;
4229 afs_uint32 prev;
4230 afs_uint32 serial;
4231 int nbytes;
4232 int missing;
4233 int acked;
4234 int nNacked = 0;
4235 int newAckCount = 0;
4236 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4237 int pktsize = 0; /* Set if we need to update the peer mtu */
4238 int conn_data_locked = 0;
4239
4240 if (rx_stats_active)
4241 rx_atomic_inc(&rx_stats.ackPacketsRead);
4242 ap = (struct rx_ackPacket *)rx_DataOf(np);
4243 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4244 if (nbytes < 0)
4245 return np; /* truncated ack packet */
4246
4247 /* depends on ack packet struct */
4248 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4249 first = ntohl(ap->firstPacket);
4250 prev = ntohl(ap->previousPacket);
4251 serial = ntohl(ap->serial);
4252
4253 /*
4254 * Ignore ack packets received out of order while protecting
4255 * against peers that set the previousPacket field to a packet
4256 * serial number instead of a sequence number.
4257 */
4258 if (first < call->tfirst ||
4259 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4260 + call->twind)) {
4261 return np;
4262 }
4263
4264 call->tprev = prev;
4265
4266 if (np->header.flags & RX_SLOW_START_OK) {
4267 call->flags |= RX_CALL_SLOW_START_OK;
4268 }
4269
4270 if (ap->reason == RX_ACK_PING_RESPONSE)
4271 rxi_UpdatePeerReach(conn, call);
4272
4273 if (conn->lastPacketSizeSeq) {
4274 MUTEX_ENTER(&conn->conn_data_lock);
4275 conn_data_locked = 1;
4276 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4277 pktsize = conn->lastPacketSize;
4278 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4279 }
4280 }
4281 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4282 if (!conn_data_locked) {
4283 MUTEX_ENTER(&conn->conn_data_lock);
4284 conn_data_locked = 1;
4285 }
4286 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4287 /* process mtu ping ack */
4288 pktsize = conn->lastPingSize;
4289 conn->lastPingSizeSer = conn->lastPingSize = 0;
4290 }
4291 }
4292
4293 if (conn_data_locked) {
4294 MUTEX_EXIT(&conn->conn_data_lock);
4295 conn_data_locked = 0;
4296 }
4297 #ifdef RXDEBUG
4298 #ifdef AFS_NT40_ENV
4299 if (rxdebug_active) {
4300 char msg[512];
4301 size_t len;
4302
4303 len = _snprintf(msg, sizeof(msg),
4304 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4305 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4306 ntohl(ap->serial), ntohl(ap->previousPacket),
4307 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4308 ap->nAcks, ntohs(ap->bufferSpace) );
4309 if (nAcks) {
4310 int offset;
4311
4312 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4313 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4314 }
4315 msg[len++]='\n';
4316 msg[len] = '\0';
4317 OutputDebugString(msg);
4318 }
4319 #else /* AFS_NT40_ENV */
4320 if (rx_Log) {
4321 fprintf(rx_Log,
4322 "RACK: reason %x previous %u seq %u serial %u first %u",
4323 ap->reason, ntohl(ap->previousPacket),
4324 (unsigned int)np->header.seq, (unsigned int)serial,
4325 ntohl(ap->firstPacket));
4326 if (nAcks) {
4327 int offset;
4328 for (offset = 0; offset < nAcks; offset++)
4329 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4330 rx_Log);
4331 }
4332 putc('\n', rx_Log);
4333 }
4334 #endif /* AFS_NT40_ENV */
4335 #endif
4336
4337 MUTEX_ENTER(&peer->peer_lock);
4338 if (pktsize) {
4339 /*
4340 * Start somewhere. Can't assume we can send what we can receive,
4341 * but we are clearly receiving.
4342 */
4343 if (!peer->maxPacketSize)
4344 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4345
4346 if (pktsize > peer->maxPacketSize) {
4347 peer->maxPacketSize = pktsize;
4348 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4349 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4350 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4351 rxi_ScheduleGrowMTUEvent(call, 1);
4352 }
4353 }
4354 }
4355
4356 clock_GetTime(&now);
4357
4358 /* The transmit queue splits into 4 sections.
4359 *
4360 * The first section is packets which have now been acknowledged
4361 * by a window size change in the ack. These have reached the
4362 * application layer, and may be discarded. These are packets
4363 * with sequence numbers < ap->firstPacket.
4364 *
4365 * The second section is packets which have sequence numbers in
4366 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4367 * contents of the packet's ack array determines whether these
4368 * packets are acknowledged or not.
4369 *
4370 * The third section is packets which fall above the range
4371 * addressed in the ack packet. These have not yet been received
4372 * by the peer.
4373 *
4374 * The four section is packets which have not yet been transmitted.
4375 * These packets will have a header.serial of 0.
4376 */
4377
4378 /* First section - implicitly acknowledged packets that can be
4379 * disposed of
4380 */
4381
4382 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4383 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4384 struct rx_packet *next;
4385
4386 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4387 call->tfirst = tp->header.seq + 1;
4388
4389 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4390 newAckCount++;
4391 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4392 }
4393
4394 #ifdef RX_ENABLE_LOCKS
4395 /* XXX Hack. Because we have to release the global call lock when sending
4396 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4397 * in rxi_Start sending packets out because packets may move to the
4398 * freePacketQueue as result of being here! So we drop these packets until
4399 * we're safely out of the traversing. Really ugly!
4400 * To make it even uglier, if we're using fine grain locking, we can
4401 * set the ack bits in the packets and have rxi_Start remove the packets
4402 * when it's done transmitting.
4403 */
4404 if (call->flags & RX_CALL_TQ_BUSY) {
4405 tp->flags |= RX_PKTFLAG_ACKED;
4406 call->flags |= RX_CALL_TQ_SOME_ACKED;
4407 } else
4408 #endif /* RX_ENABLE_LOCKS */
4409 {
4410 opr_queue_Remove(&tp->entry);
4411 #ifdef RX_TRACK_PACKETS
4412 tp->flags &= ~RX_PKTFLAG_TQ;
4413 #endif
4414 #ifdef RXDEBUG_PACKET
4415 call->tqc--;
4416 #endif /* RXDEBUG_PACKET */
4417 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4418 }
4419 tp = next;
4420 }
4421
4422 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4423
4424 /* Second section of the queue - packets for which we are receiving
4425 * soft ACKs
4426 *
4427 * Go through the explicit acks/nacks and record the results in
4428 * the waiting packets. These are packets that can't be released
4429 * yet, even with a positive acknowledge. This positive
4430 * acknowledge only means the packet has been received by the
4431 * peer, not that it will be retained long enough to be sent to
4432 * the peer's upper level. In addition, reset the transmit timers
4433 * of any missing packets (those packets that must be missing
4434 * because this packet was out of sequence) */
4435
4436 call->nSoftAcked = 0;
4437 missing = 0;
4438 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4439 && tp->header.seq < first + nAcks) {
4440 /* Set the acknowledge flag per packet based on the
4441 * information in the ack packet. An acknowlegded packet can
4442 * be downgraded when the server has discarded a packet it
4443 * soacked previously, or when an ack packet is received
4444 * out of sequence. */
4445 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4446 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4447 newAckCount++;
4448 tp->flags |= RX_PKTFLAG_ACKED;
4449 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4450 }
4451 if (missing) {
4452 nNacked++;
4453 } else {
4454 call->nSoftAcked++;
4455 }
4456 } else /* RX_ACK_TYPE_NACK */ {
4457 tp->flags &= ~RX_PKTFLAG_ACKED;
4458 missing = 1;
4459 }
4460
4461 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4462 }
4463
4464 /* We don't need to take any action with the 3rd or 4th section in the
4465 * queue - they're not addressed by the contents of this ACK packet.
4466 */
4467
4468 /* if the ack packet has a receivelen field hanging off it,
4469 * update our state */
4470 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4471 afs_uint32 tSize;
4472
4473 /* If the ack packet has a "recommended" size that is less than
4474 * what I am using now, reduce my size to match */
4475 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4476 (int)sizeof(afs_int32), &tSize);
4477 tSize = (afs_uint32) ntohl(tSize);
4478 if (tSize > RX_MAX_PACKET_SIZE)
4479 tSize = RX_MAX_PACKET_SIZE;
4480 if (tSize < RX_MIN_PACKET_SIZE)
4481 tSize = RX_MIN_PACKET_SIZE;
4482 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4483
4484 /* Get the maximum packet size to send to this peer */
4485 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4486 &tSize);
4487 tSize = (afs_uint32) ntohl(tSize);
4488 if (tSize > RX_MAX_PACKET_SIZE)
4489 tSize = RX_MAX_PACKET_SIZE;
4490 if (tSize < RX_MIN_PACKET_SIZE)
4491 tSize = RX_MIN_PACKET_SIZE;
4492 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4493 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4494
4495 /* sanity check - peer might have restarted with different params.
4496 * If peer says "send less", dammit, send less... Peer should never
4497 * be unable to accept packets of the size that prior AFS versions would
4498 * send without asking. */
4499 if (peer->maxMTU != tSize) {
4500 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4501 peer->congestSeq++;
4502 peer->maxMTU = tSize;
4503 peer->MTU = MIN(tSize, peer->MTU);
4504 call->MTU = MIN(call->MTU, tSize);
4505 }
4506
4507 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4508 /* AFS 3.4a */
4509 rx_packetread(np,
4510 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4511 (int)sizeof(afs_int32), &tSize);
4512 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4513 if (tSize == 0)
4514 tSize = 1;
4515 if (tSize >= rx_maxSendWindow)
4516 tSize = rx_maxSendWindow;
4517 if (tSize < call->twind) { /* smaller than our send */
4518 call->twind = tSize; /* window, we must send less... */
4519 call->ssthresh = MIN(call->twind, call->ssthresh);
4520 call->conn->twind[call->channel] = call->twind;
4521 }
4522
4523 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4524 * network MTU confused with the loopback MTU. Calculate the
4525 * maximum MTU here for use in the slow start code below.
4526 */
4527 /* Did peer restart with older RX version? */
4528 if (peer->maxDgramPackets > 1) {
4529 peer->maxDgramPackets = 1;
4530 }
4531 } else if (np->length >=
4532 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4533 /* AFS 3.5 */
4534 rx_packetread(np,
4535 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4536 sizeof(afs_int32), &tSize);
4537 tSize = (afs_uint32) ntohl(tSize);
4538 if (tSize == 0)
4539 tSize = 1;
4540 if (tSize >= rx_maxSendWindow)
4541 tSize = rx_maxSendWindow;
4542 /*
4543 * As of AFS 3.5 we set the send window to match the receive window.
4544 */
4545 if (tSize < call->twind) {
4546 call->twind = tSize;
4547 call->conn->twind[call->channel] = call->twind;
4548 call->ssthresh = MIN(call->twind, call->ssthresh);
4549 } else if (tSize > call->twind) {
4550 call->twind = tSize;
4551 call->conn->twind[call->channel] = call->twind;
4552 }
4553
4554 /*
4555 * As of AFS 3.5, a jumbogram is more than one fixed size
4556 * packet transmitted in a single UDP datagram. If the remote
4557 * MTU is smaller than our local MTU then never send a datagram
4558 * larger than the natural MTU.
4559 */
4560 rx_packetread(np,
4561 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4562 (int)sizeof(afs_int32), &tSize);
4563 maxDgramPackets = (afs_uint32) ntohl(tSize);
4564 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4565 maxDgramPackets =
4566 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4567 if (maxDgramPackets > 1) {
4568 peer->maxDgramPackets = maxDgramPackets;
4569 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4570 } else {
4571 peer->maxDgramPackets = 1;
4572 call->MTU = peer->natMTU;
4573 }
4574 } else if (peer->maxDgramPackets > 1) {
4575 /* Restarted with lower version of RX */
4576 peer->maxDgramPackets = 1;
4577 }
4578 } else if (peer->maxDgramPackets > 1
4579 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4580 /* Restarted with lower version of RX */
4581 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4582 peer->natMTU = OLD_MAX_PACKET_SIZE;
4583 peer->MTU = OLD_MAX_PACKET_SIZE;
4584 peer->maxDgramPackets = 1;
4585 peer->nDgramPackets = 1;
4586 peer->congestSeq++;
4587 call->MTU = OLD_MAX_PACKET_SIZE;
4588 }
4589
4590 /* If the window has been extended by this acknowledge packet,
4591 * then wakeup a sender waiting in alloc for window space, or try
4592 * sending packets now, if he's been sitting on packets due to
4593 * lack of window space */
4594 if (call->tnext < (call->tfirst + call->twind)) {
4595 #ifdef RX_ENABLE_LOCKS
4596 CV_SIGNAL(&call->cv_twind);
4597 #else
4598 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4599 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4600 osi_rxWakeup(&call->twind);
4601 }
4602 #endif
4603 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4604 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4605 }
4606 }
4607
4608 if (nNacked) {
4609 /*
4610 * Calculate how many datagrams were successfully received after
4611 * the first missing packet and adjust the negative ack counter
4612 * accordingly.
4613 */
4614 call->nAcks = 0;
4615 call->nNacks++;
4616 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4617 if (call->nNacks < nNacked) {
4618 call->nNacks = nNacked;
4619 }
4620 } else {
4621 call->nAcks += newAckCount;
4622 call->nNacks = 0;
4623 }
4624
4625 /* If the packet contained new acknowledgements, rather than just
4626 * being a duplicate of one we have previously seen, then we can restart
4627 * the RTT timer
4628 */
4629 if (newAckCount > 0)
4630 rxi_rto_packet_acked(call, istack);
4631
4632 if (call->flags & RX_CALL_FAST_RECOVER) {
4633 if (newAckCount == 0) {
4634 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4635 } else {
4636 call->flags &= ~RX_CALL_FAST_RECOVER;
4637 call->cwind = call->nextCwind;
4638 call->nextCwind = 0;
4639 call->nAcks = 0;
4640 }
4641 call->nCwindAcks = 0;
4642 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4643 /* Three negative acks in a row trigger congestion recovery */
4644 call->flags |= RX_CALL_FAST_RECOVER;
4645 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4646 call->cwind =
4647 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4648 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4649 call->nextCwind = call->ssthresh;
4650 call->nAcks = 0;
4651 call->nNacks = 0;
4652 peer->MTU = call->MTU;
4653 peer->cwind = call->nextCwind;
4654 peer->nDgramPackets = call->nDgramPackets;
4655 peer->congestSeq++;
4656 call->congestSeq = peer->congestSeq;
4657
4658 /* Reset the resend times on the packets that were nacked
4659 * so we will retransmit as soon as the window permits
4660 */
4661
4662 acked = 0;
4663 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4664 struct rx_packet *tp =
4665 opr_queue_Entry(cursor, struct rx_packet, entry);
4666 if (acked) {
4667 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4668 tp->flags &= ~RX_PKTFLAG_SENT;
4669 }
4670 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4671 acked = 1;
4672 }
4673 }
4674 } else {
4675 /* If cwind is smaller than ssthresh, then increase
4676 * the window one packet for each ack we receive (exponential
4677 * growth).
4678 * If cwind is greater than or equal to ssthresh then increase
4679 * the congestion window by one packet for each cwind acks we
4680 * receive (linear growth). */
4681 if (call->cwind < call->ssthresh) {
4682 call->cwind =
4683 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4684 call->nCwindAcks = 0;
4685 } else {
4686 call->nCwindAcks += newAckCount;
4687 if (call->nCwindAcks >= call->cwind) {
4688 call->nCwindAcks = 0;
4689 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4690 }
4691 }
4692 /*
4693 * If we have received several acknowledgements in a row then
4694 * it is time to increase the size of our datagrams
4695 */
4696 if ((int)call->nAcks > rx_nDgramThreshold) {
4697 if (peer->maxDgramPackets > 1) {
4698 if (call->nDgramPackets < peer->maxDgramPackets) {
4699 call->nDgramPackets++;
4700 }
4701 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4702 } else if (call->MTU < peer->maxMTU) {
4703 /* don't upgrade if we can't handle it */
4704 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4705 call->MTU = peer->ifMTU;
4706 else {
4707 call->MTU += peer->natMTU;
4708 call->MTU = MIN(call->MTU, peer->maxMTU);
4709 }
4710 }
4711 call->nAcks = 0;
4712 }
4713 }
4714
4715 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4716
4717 /* Servers need to hold the call until all response packets have
4718 * been acknowledged. Soft acks are good enough since clients
4719 * are not allowed to clear their receive queues. */
4720 if (call->state == RX_STATE_HOLD
4721 && call->tfirst + call->nSoftAcked >= call->tnext) {
4722 call->state = RX_STATE_DALLY;
4723 rxi_ClearTransmitQueue(call, 0);
4724 rxi_CancelKeepAliveEvent(call);
4725 } else if (!opr_queue_IsEmpty(&call->tq)) {
4726 rxi_Start(call, istack);
4727 }
4728 return np;
4729 }
4730
4731 /**
4732 * Schedule a connection abort to be sent after some delay.
4733 *
4734 * @param[in] conn The connection to send the abort on.
4735 * @param[in] msec The number of milliseconds to wait before sending.
4736 *
4737 * @pre conn_data_lock must be held
4738 */
4739 static void
4740 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4741 {
4742 struct clock when, now;
4743
4744 MUTEX_ASSERT(&conn->conn_data_lock);
4745 if (!conn->error) {
4746 return;
4747 }
4748 if (!conn->delayedAbortEvent) {
4749 clock_GetTime(&now);
4750 when = now;
4751 clock_Addmsec(&when, msec);
4752 rx_GetConnection(conn);
4753 conn->delayedAbortEvent =
4754 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4755 }
4756 }
4757
4758 /* Received a response to a challenge packet */
4759 static struct rx_packet *
4760 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4761 struct rx_packet *np, int istack)
4762 {
4763 int error;
4764
4765 /* Ignore the packet if we're the client */
4766 if (conn->type == RX_CLIENT_CONNECTION)
4767 return np;
4768
4769 /* If already authenticated, ignore the packet (it's probably a retry) */
4770 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4771 return np;
4772
4773 if (!conn->securityChallengeSent) {
4774 /* We've never sent out a challenge for this connection, so this
4775 * response cannot possibly be correct; ignore it. This can happen
4776 * if we sent a challenge to the client, then we were restarted, and
4777 * then the client sent us a response. If we ignore the response, the
4778 * client will eventually resend a data packet, causing us to send a
4779 * new challenge and the client to send a new response. */
4780 return np;
4781 }
4782
4783 /* Otherwise, have the security object evaluate the response packet */
4784 error = RXS_CheckResponse(conn->securityObject, conn, np);
4785 if (error) {
4786 /* If the response is invalid, reset the connection, sending
4787 * an abort to the peer. Send the abort with a 1 second delay,
4788 * to avoid a peer hammering us by constantly recreating a
4789 * connection with bad credentials. */
4790 rxi_ConnectionError(conn, error);
4791 MUTEX_ENTER(&conn->conn_data_lock);
4792 rxi_SendConnectionAbortLater(conn, 1000);
4793 MUTEX_EXIT(&conn->conn_data_lock);
4794 return np;
4795 } else {
4796 /* If the response is valid, any calls waiting to attach
4797 * servers can now do so */
4798 int i;
4799
4800 for (i = 0; i < RX_MAXCALLS; i++) {
4801 struct rx_call *call = conn->call[i];
4802 if (call) {
4803 MUTEX_ENTER(&call->lock);
4804 if (call->state == RX_STATE_PRECALL)
4805 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4806 /* tnop can be null if newcallp is null */
4807 MUTEX_EXIT(&call->lock);
4808 }
4809 }
4810
4811 /* Update the peer reachability information, just in case
4812 * some calls went into attach-wait while we were waiting
4813 * for authentication..
4814 */
4815 rxi_UpdatePeerReach(conn, NULL);
4816 }
4817 return np;
4818 }
4819
4820 /* A client has received an authentication challenge: the security
4821 * object is asked to cough up a respectable response packet to send
4822 * back to the server. The server is responsible for retrying the
4823 * challenge if it fails to get a response. */
4824
4825 static struct rx_packet *
4826 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4827 struct rx_packet *np, int istack)
4828 {
4829 int error;
4830
4831 /* Ignore the challenge if we're the server */
4832 if (conn->type == RX_SERVER_CONNECTION)
4833 return np;
4834
4835 /* Ignore the challenge if the connection is otherwise idle; someone's
4836 * trying to use us as an oracle. */
4837 if (!rxi_HasActiveCalls(conn))
4838 return np;
4839
4840 /* Send the security object the challenge packet. It is expected to fill
4841 * in the response. */
4842 error = RXS_GetResponse(conn->securityObject, conn, np);
4843
4844 /* If the security object is unable to return a valid response, reset the
4845 * connection and send an abort to the peer. Otherwise send the response
4846 * packet to the peer connection. */
4847 if (error) {
4848 rxi_ConnectionError(conn, error);
4849 MUTEX_ENTER(&conn->conn_data_lock);
4850 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4851 MUTEX_EXIT(&conn->conn_data_lock);
4852 } else {
4853 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4854 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4855 }
4856 return np;
4857 }
4858
4859
4860 /* Find an available server process to service the current request in
4861 * the given call structure. If one isn't available, queue up this
4862 * call so it eventually gets one */
4863 static void
4864 rxi_AttachServerProc(struct rx_call *call,
4865 osi_socket socket, int *tnop,
4866 struct rx_call **newcallp)
4867 {
4868 struct rx_serverQueueEntry *sq;
4869 struct rx_service *service = call->conn->service;
4870 int haveQuota = 0;
4871
4872 /* May already be attached */
4873 if (call->state == RX_STATE_ACTIVE)
4874 return;
4875
4876 MUTEX_ENTER(&rx_serverPool_lock);
4877
4878 haveQuota = QuotaOK(service);
4879 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4880 /* If there are no processes available to service this call,
4881 * put the call on the incoming call queue (unless it's
4882 * already on the queue).
4883 */
4884 #ifdef RX_ENABLE_LOCKS
4885 if (haveQuota)
4886 ReturnToServerPool(service);
4887 #endif /* RX_ENABLE_LOCKS */
4888
4889 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4890 call->flags |= RX_CALL_WAIT_PROC;
4891 rx_atomic_inc(&rx_nWaiting);
4892 rx_atomic_inc(&rx_nWaited);
4893 rxi_calltrace(RX_CALL_ARRIVAL, call);
4894 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4895 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4896 }
4897 } else {
4898 sq = opr_queue_Last(&rx_idleServerQueue,
4899 struct rx_serverQueueEntry, entry);
4900
4901 /* If hot threads are enabled, and both newcallp and sq->socketp
4902 * are non-null, then this thread will process the call, and the
4903 * idle server thread will start listening on this threads socket.
4904 */
4905 opr_queue_Remove(&sq->entry);
4906
4907 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4908 *newcallp = call;
4909 *tnop = sq->tno;
4910 *sq->socketp = socket;
4911 clock_GetTime(&call->startTime);
4912 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4913 } else {
4914 sq->newcall = call;
4915 }
4916 if (call->flags & RX_CALL_WAIT_PROC) {
4917 /* Conservative: I don't think this should happen */
4918 call->flags &= ~RX_CALL_WAIT_PROC;
4919 rx_atomic_dec(&rx_nWaiting);
4920 if (opr_queue_IsOnQueue(&call->entry)) {
4921 opr_queue_Remove(&call->entry);
4922 }
4923 }
4924 call->state = RX_STATE_ACTIVE;
4925 call->app.mode = RX_MODE_RECEIVING;
4926 #ifdef RX_KERNEL_TRACE
4927 {
4928 int glockOwner = ISAFS_GLOCK();
4929 if (!glockOwner)
4930 AFS_GLOCK();
4931 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4932 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4933 call);
4934 if (!glockOwner)
4935 AFS_GUNLOCK();
4936 }
4937 #endif
4938 if (call->flags & RX_CALL_CLEARED) {
4939 /* send an ack now to start the packet flow up again */
4940 call->flags &= ~RX_CALL_CLEARED;
4941 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4942 }
4943 #ifdef RX_ENABLE_LOCKS
4944 CV_SIGNAL(&sq->cv);
4945 #else
4946 service->nRequestsRunning++;
4947 MUTEX_ENTER(&rx_quota_mutex);
4948 if (service->nRequestsRunning <= service->minProcs)
4949 rxi_minDeficit--;
4950 rxi_availProcs--;
4951 MUTEX_EXIT(&rx_quota_mutex);
4952 osi_rxWakeup(sq);
4953 #endif
4954 }
4955 MUTEX_EXIT(&rx_serverPool_lock);
4956 }
4957
4958 /* Delay the sending of an acknowledge event for a short while, while
4959 * a new call is being prepared (in the case of a client) or a reply
4960 * is being prepared (in the case of a server). Rather than sending
4961 * an ack packet, an ACKALL packet is sent. */
4962 static void
4963 rxi_AckAll(struct rx_call *call)
4964 {
4965 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4966 NULL, 0, 0);
4967 call->flags |= RX_CALL_ACKALL_SENT;
4968 }
4969
4970 /*
4971 * Event handler for per-call delayed acks.
4972 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
4973 * immediately.
4974 */
4975 static void
4976 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4977 int unused2)
4978 {
4979 struct rx_call *call = arg1;
4980 #ifdef RX_ENABLE_LOCKS
4981 if (event) {
4982 MUTEX_ENTER(&call->lock);
4983 if (event == call->delayedAckEvent)
4984 rxevent_Put(&call->delayedAckEvent);
4985 }
4986 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4987 if (event)
4988 MUTEX_EXIT(&call->lock);
4989 #else /* RX_ENABLE_LOCKS */
4990 if (event)
4991 rxevent_Put(&call->delayedAckEvent);
4992 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4993 #endif /* RX_ENABLE_LOCKS */
4994 /* Release the call reference for the event that fired. */
4995 if (event)
4996 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4997 }
4998
4999 #ifdef RX_ENABLE_LOCKS
5000 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5001 * clearing them out.
5002 */
5003 static void
5004 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5005 {
5006 struct opr_queue *cursor;
5007 int someAcked = 0;
5008
5009 for (opr_queue_Scan(&call->tq, cursor)) {
5010 struct rx_packet *p
5011 = opr_queue_Entry(cursor, struct rx_packet, entry);
5012
5013 p->flags |= RX_PKTFLAG_ACKED;
5014 someAcked = 1;
5015 }
5016
5017 if (someAcked) {
5018 call->flags |= RX_CALL_TQ_CLEARME;
5019 call->flags |= RX_CALL_TQ_SOME_ACKED;
5020 }
5021
5022 rxi_rto_cancel(call);
5023
5024 call->tfirst = call->tnext;
5025 call->nSoftAcked = 0;
5026
5027 if (call->flags & RX_CALL_FAST_RECOVER) {
5028 call->flags &= ~RX_CALL_FAST_RECOVER;
5029 call->cwind = call->nextCwind;
5030 call->nextCwind = 0;
5031 }
5032
5033 CV_SIGNAL(&call->cv_twind);
5034 }
5035 #endif /* RX_ENABLE_LOCKS */
5036
5037 /*!
5038 * Acknowledge the whole transmit queue.
5039 *
5040 * If we're running without locks, or the transmit queue isn't busy, then
5041 * we can just clear the queue now. Otherwise, we have to mark all of the
5042 * packets as acknowledged, and let rxi_Start clear it later on
5043 */
5044 static void
5045 rxi_AckAllInTransmitQueue(struct rx_call *call)
5046 {
5047 #ifdef RX_ENABLE_LOCKS
5048 if (call->flags & RX_CALL_TQ_BUSY) {
5049 rxi_SetAcksInTransmitQueue(call);
5050 return;
5051 }
5052 #endif
5053 rxi_ClearTransmitQueue(call, 0);
5054 }
5055 /* Clear out the transmit queue for the current call (all packets have
5056 * been received by peer) */
5057 static void
5058 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5059 {
5060 #ifdef RX_ENABLE_LOCKS
5061 struct opr_queue *cursor;
5062 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5063 int someAcked = 0;
5064 for (opr_queue_Scan(&call->tq, cursor)) {
5065 struct rx_packet *p
5066 = opr_queue_Entry(cursor, struct rx_packet, entry);
5067
5068 p->flags |= RX_PKTFLAG_ACKED;
5069 someAcked = 1;
5070 }
5071 if (someAcked) {
5072 call->flags |= RX_CALL_TQ_CLEARME;
5073 call->flags |= RX_CALL_TQ_SOME_ACKED;
5074 }
5075 } else {
5076 #endif /* RX_ENABLE_LOCKS */
5077 #ifdef RXDEBUG_PACKET
5078 call->tqc -=
5079 #endif /* RXDEBUG_PACKET */
5080 rxi_FreePackets(0, &call->tq);
5081 rxi_WakeUpTransmitQueue(call);
5082 #ifdef RX_ENABLE_LOCKS
5083 call->flags &= ~RX_CALL_TQ_CLEARME;
5084 }
5085 #endif
5086
5087 rxi_rto_cancel(call);
5088 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5089 call->nSoftAcked = 0;
5090
5091 if (call->flags & RX_CALL_FAST_RECOVER) {
5092 call->flags &= ~RX_CALL_FAST_RECOVER;
5093 call->cwind = call->nextCwind;
5094 }
5095 #ifdef RX_ENABLE_LOCKS
5096 CV_SIGNAL(&call->cv_twind);
5097 #else
5098 osi_rxWakeup(&call->twind);
5099 #endif
5100 }
5101
5102 static void
5103 rxi_ClearReceiveQueue(struct rx_call *call)
5104 {
5105 if (!opr_queue_IsEmpty(&call->rq)) {
5106 u_short count;
5107
5108 count = rxi_FreePackets(0, &call->rq);
5109 rx_packetReclaims += count;
5110 #ifdef RXDEBUG_PACKET
5111 call->rqc -= count;
5112 if ( call->rqc != 0 )
5113 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5114 #endif
5115 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5116 }
5117 if (call->state == RX_STATE_PRECALL) {
5118 call->flags |= RX_CALL_CLEARED;
5119 }
5120 }
5121
5122 /* Send an abort packet for the specified call */
5123 static struct rx_packet *
5124 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5125 int istack, int force)
5126 {
5127 afs_int32 error;
5128 struct clock when, now;
5129
5130 if (!call->error)
5131 return packet;
5132
5133 /* Clients should never delay abort messages */
5134 if (rx_IsClientConn(call->conn))
5135 force = 1;
5136
5137 /*
5138 * An opcode that has been deprecated or has yet to be implemented is not
5139 * a misbehavior of the client. Do not punish the client by introducing
5140 * delays.
5141 */
5142 if (call->error == RXGEN_OPCODE) {
5143 force = 1;
5144 } else if (call->abortCode != call->error) {
5145 call->abortCode = call->error;
5146 call->abortCount = 0;
5147 }
5148
5149 if (force || rxi_callAbortThreshhold == 0
5150 || call->abortCount < rxi_callAbortThreshhold) {
5151 rxi_CancelDelayedAbortEvent(call);
5152 error = htonl(call->error);
5153 if (!force)
5154 call->abortCount++;
5155 packet =
5156 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5157 (char *)&error, sizeof(error), istack);
5158 } else if (!call->delayedAbortEvent) {
5159 clock_GetTime(&now);
5160 when = now;
5161 clock_Addmsec(&when, rxi_callAbortDelay);
5162 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5163 call->delayedAbortEvent =
5164 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5165 }
5166 return packet;
5167 }
5168
5169 static void
5170 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5171 {
5172 MUTEX_ASSERT(&call->lock);
5173 if (rxevent_Cancel(&call->delayedAbortEvent))
5174 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5175 }
5176
5177 /* Send an abort packet for the specified connection. Packet is an
5178 * optional pointer to a packet that can be used to send the abort.
5179 * Once the number of abort messages reaches the threshhold, an
5180 * event is scheduled to send the abort. Setting the force flag
5181 * overrides sending delayed abort messages.
5182 *
5183 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5184 * to send the abort packet.
5185 */
5186 struct rx_packet *
5187 rxi_SendConnectionAbort(struct rx_connection *conn,
5188 struct rx_packet *packet, int istack, int force)
5189 {
5190 afs_int32 error;
5191
5192 if (!conn->error)
5193 return packet;
5194
5195 /* Clients should never delay abort messages */
5196 if (rx_IsClientConn(conn))
5197 force = 1;
5198
5199 if (force || rxi_connAbortThreshhold == 0
5200 || conn->abortCount < rxi_connAbortThreshhold) {
5201
5202 if (rxevent_Cancel(&conn->delayedAbortEvent))
5203 putConnection(conn);
5204 error = htonl(conn->error);
5205 conn->abortCount++;
5206 MUTEX_EXIT(&conn->conn_data_lock);
5207 packet =
5208 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5209 RX_PACKET_TYPE_ABORT, (char *)&error,
5210 sizeof(error), istack);
5211 MUTEX_ENTER(&conn->conn_data_lock);
5212 } else {
5213 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5214 }
5215 return packet;
5216 }
5217
5218 /* Associate an error all of the calls owned by a connection. Called
5219 * with error non-zero. This is only for really fatal things, like
5220 * bad authentication responses. The connection itself is set in
5221 * error at this point, so that future packets received will be
5222 * rejected. */
5223 void
5224 rxi_ConnectionError(struct rx_connection *conn,
5225 afs_int32 error)
5226 {
5227 if (error) {
5228 int i;
5229
5230 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5231
5232 MUTEX_ENTER(&conn->conn_data_lock);
5233 if (rxevent_Cancel(&conn->challengeEvent))
5234 putConnection(conn);
5235 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5236 putConnection(conn);
5237 if (rxevent_Cancel(&conn->checkReachEvent)) {
5238 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5239 putConnection(conn);
5240 }
5241 MUTEX_EXIT(&conn->conn_data_lock);
5242 for (i = 0; i < RX_MAXCALLS; i++) {
5243 struct rx_call *call = conn->call[i];
5244 if (call) {
5245 MUTEX_ENTER(&call->lock);
5246 rxi_CallError(call, error);
5247 MUTEX_EXIT(&call->lock);
5248 }
5249 }
5250 conn->error = error;
5251 if (rx_stats_active)
5252 rx_atomic_inc(&rx_stats.fatalErrors);
5253 }
5254 }
5255
5256 /**
5257 * Interrupt an in-progress call with the specified error and wakeup waiters.
5258 *
5259 * @param[in] call The call to interrupt
5260 * @param[in] error The error code to send to the peer
5261 */
5262 void
5263 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5264 {
5265 MUTEX_ENTER(&call->lock);
5266 rxi_CallError(call, error);
5267 rxi_SendCallAbort(call, NULL, 0, 1);
5268 MUTEX_EXIT(&call->lock);
5269 }
5270
5271 void
5272 rxi_CallError(struct rx_call *call, afs_int32 error)
5273 {
5274 MUTEX_ASSERT(&call->lock);
5275 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5276 if (call->error)
5277 error = call->error;
5278
5279 #ifdef RX_ENABLE_LOCKS
5280 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5281 rxi_ResetCall(call, 0);
5282 }
5283 #else
5284 rxi_ResetCall(call, 0);
5285 #endif
5286 call->error = error;
5287 }
5288
5289 /* Reset various fields in a call structure, and wakeup waiting
5290 * processes. Some fields aren't changed: state & mode are not
5291 * touched (these must be set by the caller), and bufptr, nLeft, and
5292 * nFree are not reset, since these fields are manipulated by
5293 * unprotected macros, and may only be reset by non-interrupting code.
5294 */
5295
5296 static void
5297 rxi_ResetCall(struct rx_call *call, int newcall)
5298 {
5299 int flags;
5300 struct rx_peer *peer;
5301 struct rx_packet *packet;
5302
5303 MUTEX_ASSERT(&call->lock);
5304 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5305
5306 /* Notify anyone who is waiting for asynchronous packet arrival */
5307 if (call->arrivalProc) {
5308 (*call->arrivalProc) (call, call->arrivalProcHandle,
5309 call->arrivalProcArg);
5310 call->arrivalProc = (void (*)())0;
5311 }
5312
5313
5314 rxi_CancelGrowMTUEvent(call);
5315
5316 if (call->delayedAbortEvent) {
5317 rxi_CancelDelayedAbortEvent(call);
5318 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5319 if (packet) {
5320 rxi_SendCallAbort(call, packet, 0, 1);
5321 rxi_FreePacket(packet);
5322 }
5323 }
5324
5325 /*
5326 * Update the peer with the congestion information in this call
5327 * so other calls on this connection can pick up where this call
5328 * left off. If the congestion sequence numbers don't match then
5329 * another call experienced a retransmission.
5330 */
5331 peer = call->conn->peer;
5332 MUTEX_ENTER(&peer->peer_lock);
5333 if (!newcall) {
5334 if (call->congestSeq == peer->congestSeq) {
5335 peer->cwind = MAX(peer->cwind, call->cwind);
5336 peer->MTU = MAX(peer->MTU, call->MTU);
5337 peer->nDgramPackets =
5338 MAX(peer->nDgramPackets, call->nDgramPackets);
5339 }
5340 } else {
5341 call->abortCode = 0;
5342 call->abortCount = 0;
5343 }
5344 if (peer->maxDgramPackets > 1) {
5345 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5346 } else {
5347 call->MTU = peer->MTU;
5348 }
5349 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5350 call->ssthresh = rx_maxSendWindow;
5351 call->nDgramPackets = peer->nDgramPackets;
5352 call->congestSeq = peer->congestSeq;
5353 call->rtt = peer->rtt;
5354 call->rtt_dev = peer->rtt_dev;
5355 clock_Zero(&call->rto);
5356 clock_Addmsec(&call->rto,
5357 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5358 MUTEX_EXIT(&peer->peer_lock);
5359
5360 flags = call->flags;
5361 rxi_WaitforTQBusy(call);
5362
5363 rxi_ClearTransmitQueue(call, 1);
5364 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5365 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5366 }
5367 call->flags = 0;
5368
5369 rxi_ClearReceiveQueue(call);
5370 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5371
5372
5373 call->error = 0;
5374 call->twind = call->conn->twind[call->channel];
5375 call->rwind = call->conn->rwind[call->channel];
5376 call->nSoftAcked = 0;
5377 call->nextCwind = 0;
5378 call->nAcks = 0;
5379 call->nNacks = 0;
5380 call->nCwindAcks = 0;
5381 call->nSoftAcks = 0;
5382 call->nHardAcks = 0;
5383
5384 call->tfirst = call->rnext = call->tnext = 1;
5385 call->tprev = 0;
5386 call->rprev = 0;
5387 call->lastAcked = 0;
5388 call->localStatus = call->remoteStatus = 0;
5389
5390 if (flags & RX_CALL_READER_WAIT) {
5391 #ifdef RX_ENABLE_LOCKS
5392 CV_BROADCAST(&call->cv_rq);
5393 #else
5394 osi_rxWakeup(&call->rq);
5395 #endif
5396 }
5397 if (flags & RX_CALL_WAIT_PACKETS) {
5398 MUTEX_ENTER(&rx_freePktQ_lock);
5399 rxi_PacketsUnWait(); /* XXX */
5400 MUTEX_EXIT(&rx_freePktQ_lock);
5401 }
5402 #ifdef RX_ENABLE_LOCKS
5403 CV_SIGNAL(&call->cv_twind);
5404 #else
5405 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5406 osi_rxWakeup(&call->twind);
5407 #endif
5408
5409 if (flags & RX_CALL_WAIT_PROC) {
5410 rx_atomic_dec(&rx_nWaiting);
5411 }
5412 #ifdef RX_ENABLE_LOCKS
5413 /* The following ensures that we don't mess with any queue while some
5414 * other thread might also be doing so. The call_queue_lock field is
5415 * is only modified under the call lock. If the call is in the process
5416 * of being removed from a queue, the call is not locked until the
5417 * the queue lock is dropped and only then is the call_queue_lock field
5418 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5419 * Note that any other routine which removes a call from a queue has to
5420 * obtain the queue lock before examing the queue and removing the call.
5421 */
5422 if (call->call_queue_lock) {
5423 MUTEX_ENTER(call->call_queue_lock);
5424 if (opr_queue_IsOnQueue(&call->entry)) {
5425 opr_queue_Remove(&call->entry);
5426 }
5427 MUTEX_EXIT(call->call_queue_lock);
5428 CLEAR_CALL_QUEUE_LOCK(call);
5429 }
5430 #else /* RX_ENABLE_LOCKS */
5431 if (opr_queue_IsOnQueue(&call->entry)) {
5432 opr_queue_Remove(&call->entry);
5433 }
5434 #endif /* RX_ENABLE_LOCKS */
5435
5436 rxi_CancelKeepAliveEvent(call);
5437 rxi_CancelDelayedAckEvent(call);
5438 }
5439
5440 /* Send an acknowledge for the indicated packet (seq,serial) of the
5441 * indicated call, for the indicated reason (reason). This
5442 * acknowledge will specifically acknowledge receiving the packet, and
5443 * will also specify which other packets for this call have been
5444 * received. This routine returns the packet that was used to the
5445 * caller. The caller is responsible for freeing it or re-using it.
5446 * This acknowledgement also returns the highest sequence number
5447 * actually read out by the higher level to the sender; the sender
5448 * promises to keep around packets that have not been read by the
5449 * higher level yet (unless, of course, the sender decides to abort
5450 * the call altogether). Any of p, seq, serial, pflags, or reason may
5451 * be set to zero without ill effect. That is, if they are zero, they
5452 * will not convey any information.
5453 * NOW there is a trailer field, after the ack where it will safely be
5454 * ignored by mundanes, which indicates the maximum size packet this
5455 * host can swallow. */
5456 /*
5457 struct rx_packet *optionalPacket; use to send ack (or null)
5458 int seq; Sequence number of the packet we are acking
5459 int serial; Serial number of the packet
5460 int pflags; Flags field from packet header
5461 int reason; Reason an acknowledge was prompted
5462 */
5463
5464 #define RX_ZEROS 1024
5465 static char rx_zeros[RX_ZEROS];
5466
5467 struct rx_packet *
5468 rxi_SendAck(struct rx_call *call,
5469 struct rx_packet *optionalPacket, int serial, int reason,
5470 int istack)
5471 {
5472 struct rx_ackPacket *ap;
5473 struct rx_packet *p;
5474 struct opr_queue *cursor;
5475 u_char offset = 0;
5476 afs_int32 templ;
5477 afs_uint32 padbytes = 0;
5478 #ifdef RX_ENABLE_TSFPQ
5479 struct rx_ts_info_t * rx_ts_info;
5480 #endif
5481
5482 /*
5483 * Open the receive window once a thread starts reading packets
5484 */
5485 if (call->rnext > 1) {
5486 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5487 }
5488
5489 /* Don't attempt to grow MTU if this is a critical ping */
5490 if (reason == RX_ACK_MTU) {
5491 /* keep track of per-call attempts, if we're over max, do in small
5492 * otherwise in larger? set a size to increment by, decrease
5493 * on failure, here?
5494 */
5495 if (call->conn->peer->maxPacketSize &&
5496 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5497 - RX_HEADER_SIZE))
5498 padbytes = call->conn->peer->maxPacketSize+16;
5499 else
5500 padbytes = call->conn->peer->maxMTU + 128;
5501
5502 /* do always try a minimum size ping */
5503 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5504
5505 /* subtract the ack payload */
5506 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5507 reason = RX_ACK_PING;
5508 }
5509
5510 call->nHardAcks = 0;
5511 call->nSoftAcks = 0;
5512 if (call->rnext > call->lastAcked)
5513 call->lastAcked = call->rnext;
5514 p = optionalPacket;
5515
5516 if (p) {
5517 rx_computelen(p, p->length); /* reset length, you never know */
5518 } /* where that's been... */
5519 #ifdef RX_ENABLE_TSFPQ
5520 else {
5521 RX_TS_INFO_GET(rx_ts_info);
5522 if ((p = rx_ts_info->local_special_packet)) {
5523 rx_computelen(p, p->length);
5524 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5525 rx_ts_info->local_special_packet = p;
5526 } else { /* We won't send the ack, but don't panic. */
5527 return optionalPacket;
5528 }
5529 }
5530 #else
5531 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5532 /* We won't send the ack, but don't panic. */
5533 return optionalPacket;
5534 }
5535 #endif
5536
5537 templ = padbytes +
5538 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5539 rx_GetDataSize(p);
5540 if (templ > 0) {
5541 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5542 #ifndef RX_ENABLE_TSFPQ
5543 if (!optionalPacket)
5544 rxi_FreePacket(p);
5545 #endif
5546 return optionalPacket;
5547 }
5548 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5549 if (rx_Contiguous(p) < templ) {
5550 #ifndef RX_ENABLE_TSFPQ
5551 if (!optionalPacket)
5552 rxi_FreePacket(p);
5553 #endif
5554 return optionalPacket;
5555 }
5556 }
5557
5558
5559 /* MTUXXX failing to send an ack is very serious. We should */
5560 /* try as hard as possible to send even a partial ack; it's */
5561 /* better than nothing. */
5562 ap = (struct rx_ackPacket *)rx_DataOf(p);
5563 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5564 ap->reason = reason;
5565
5566 /* The skew computation used to be bogus, I think it's better now. */
5567 /* We should start paying attention to skew. XXX */
5568 ap->serial = htonl(serial);
5569 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5570
5571 /*
5572 * First packet not yet forwarded to reader. When ACKALL has been
5573 * sent the peer has been told that all received packets will be
5574 * delivered to the reader. The value 'rnext' is used internally
5575 * to refer to the next packet in the receive queue that must be
5576 * delivered to the reader. From the perspective of the peer it
5577 * already has so report the last sequence number plus one if there
5578 * are packets in the receive queue awaiting processing.
5579 */
5580 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5581 !opr_queue_IsEmpty(&call->rq)) {
5582 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5583 } else {
5584 ap->firstPacket = htonl(call->rnext);
5585
5586 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5587
5588 /* No fear of running out of ack packet here because there can only
5589 * be at most one window full of unacknowledged packets. The window
5590 * size must be constrained to be less than the maximum ack size,
5591 * of course. Also, an ack should always fit into a single packet
5592 * -- it should not ever be fragmented. */
5593 offset = 0;
5594 for (opr_queue_Scan(&call->rq, cursor)) {
5595 struct rx_packet *rqp
5596 = opr_queue_Entry(cursor, struct rx_packet, entry);
5597
5598 if (!rqp || !call->rq.next
5599 || (rqp->header.seq > (call->rnext + call->rwind))) {
5600 #ifndef RX_ENABLE_TSFPQ
5601 if (!optionalPacket)
5602 rxi_FreePacket(p);
5603 #endif
5604 rxi_CallError(call, RX_CALL_DEAD);
5605 return optionalPacket;
5606 }
5607
5608 while (rqp->header.seq > call->rnext + offset)
5609 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5610 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5611
5612 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5613 #ifndef RX_ENABLE_TSFPQ
5614 if (!optionalPacket)
5615 rxi_FreePacket(p);
5616 #endif
5617 rxi_CallError(call, RX_CALL_DEAD);
5618 return optionalPacket;
5619 }
5620 }
5621 }
5622
5623 ap->nAcks = offset;
5624 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5625
5626 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5627 * ACK list.
5628 */
5629 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5630
5631 /* these are new for AFS 3.3 */
5632 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5633 templ = htonl(templ);
5634 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5635 templ = htonl(call->conn->peer->ifMTU);
5636 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5637 sizeof(afs_int32), &templ);
5638
5639 /* new for AFS 3.4 */
5640 templ = htonl(call->rwind);
5641 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5642 sizeof(afs_int32), &templ);
5643
5644 /* new for AFS 3.5 */
5645 templ = htonl(call->conn->peer->ifDgramPackets);
5646 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5647 sizeof(afs_int32), &templ);
5648
5649 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5650
5651 p->header.serviceId = call->conn->serviceId;
5652 p->header.cid = (call->conn->cid | call->channel);
5653 p->header.callNumber = *call->callNumber;
5654 p->header.seq = 0;
5655 p->header.securityIndex = call->conn->securityIndex;
5656 p->header.epoch = call->conn->epoch;
5657 p->header.type = RX_PACKET_TYPE_ACK;
5658 p->header.flags = RX_SLOW_START_OK;
5659 if (reason == RX_ACK_PING)
5660 p->header.flags |= RX_REQUEST_ACK;
5661
5662 while (padbytes > 0) {
5663 if (padbytes > RX_ZEROS) {
5664 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5665 p->length += RX_ZEROS;
5666 padbytes -= RX_ZEROS;
5667 } else {
5668 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5669 p->length += padbytes;
5670 padbytes = 0;
5671 }
5672 }
5673
5674 if (call->conn->type == RX_CLIENT_CONNECTION)
5675 p->header.flags |= RX_CLIENT_INITIATED;
5676
5677 #ifdef RXDEBUG
5678 #ifdef AFS_NT40_ENV
5679 if (rxdebug_active) {
5680 char msg[512];
5681 size_t len;
5682
5683 len = _snprintf(msg, sizeof(msg),
5684 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5685 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5686 ntohl(ap->serial), ntohl(ap->previousPacket),
5687 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5688 ap->nAcks, ntohs(ap->bufferSpace) );
5689 if (ap->nAcks) {
5690 int offset;
5691
5692 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5693 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5694 }
5695 msg[len++]='\n';
5696 msg[len] = '\0';
5697 OutputDebugString(msg);
5698 }
5699 #else /* AFS_NT40_ENV */
5700 if (rx_Log) {
5701 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5702 ap->reason, ntohl(ap->previousPacket),
5703 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5704 if (ap->nAcks) {
5705 for (offset = 0; offset < ap->nAcks; offset++)
5706 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5707 rx_Log);
5708 }
5709 putc('\n', rx_Log);
5710 }
5711 #endif /* AFS_NT40_ENV */
5712 #endif
5713 {
5714 int i, nbytes = p->length;
5715
5716 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5717 if (nbytes <= p->wirevec[i].iov_len) {
5718 int savelen, saven;
5719
5720 savelen = p->wirevec[i].iov_len;
5721 saven = p->niovecs;
5722 p->wirevec[i].iov_len = nbytes;
5723 p->niovecs = i + 1;
5724 rxi_Send(call, p, istack);
5725 p->wirevec[i].iov_len = savelen;
5726 p->niovecs = saven;
5727 break;
5728 } else
5729 nbytes -= p->wirevec[i].iov_len;
5730 }
5731 }
5732 if (rx_stats_active)
5733 rx_atomic_inc(&rx_stats.ackPacketsSent);
5734 #ifndef RX_ENABLE_TSFPQ
5735 if (!optionalPacket)
5736 rxi_FreePacket(p);
5737 #endif
5738 return optionalPacket; /* Return packet for re-use by caller */
5739 }
5740
5741 struct xmitlist {
5742 struct rx_packet **list;
5743 int len;
5744 int resending;
5745 };
5746
5747 /* Send all of the packets in the list in single datagram */
5748 static void
5749 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5750 int istack, int moreFlag)
5751 {
5752 int i;
5753 int requestAck = 0;
5754 int lastPacket = 0;
5755 struct clock now;
5756 struct rx_connection *conn = call->conn;
5757 struct rx_peer *peer = conn->peer;
5758
5759 MUTEX_ENTER(&peer->peer_lock);
5760 peer->nSent += xmit->len;
5761 if (xmit->resending)
5762 peer->reSends += xmit->len;
5763 MUTEX_EXIT(&peer->peer_lock);
5764
5765 if (rx_stats_active) {
5766 if (xmit->resending)
5767 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5768 else
5769 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5770 }
5771
5772 clock_GetTime(&now);
5773
5774 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5775 lastPacket = 1;
5776 }
5777
5778 /* Set the packet flags and schedule the resend events */
5779 /* Only request an ack for the last packet in the list */
5780 for (i = 0; i < xmit->len; i++) {
5781 struct rx_packet *packet = xmit->list[i];
5782
5783 /* Record the time sent */
5784 packet->timeSent = now;
5785 packet->flags |= RX_PKTFLAG_SENT;
5786
5787 /* Ask for an ack on retransmitted packets, on every other packet
5788 * if the peer doesn't support slow start. Ask for an ack on every
5789 * packet until the congestion window reaches the ack rate. */
5790 if (packet->header.serial) {
5791 requestAck = 1;
5792 } else {
5793 packet->firstSent = now;
5794 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5795 || (!(call->flags & RX_CALL_SLOW_START_OK)
5796 && (packet->header.seq & 1)))) {
5797 requestAck = 1;
5798 }
5799 }
5800
5801 /* Tag this packet as not being the last in this group,
5802 * for the receiver's benefit */
5803 if (i < xmit->len - 1 || moreFlag) {
5804 packet->header.flags |= RX_MORE_PACKETS;
5805 }
5806 }
5807
5808 if (requestAck) {
5809 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5810 }
5811
5812 /* Since we're about to send a data packet to the peer, it's
5813 * safe to nuke any scheduled end-of-packets ack */
5814 rxi_CancelDelayedAckEvent(call);
5815
5816 MUTEX_EXIT(&call->lock);
5817 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5818 if (xmit->len > 1) {
5819 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5820 } else {
5821 rxi_SendPacket(call, conn, xmit->list[0], istack);
5822 }
5823 MUTEX_ENTER(&call->lock);
5824 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5825
5826 /* Tell the RTO calculation engine that we have sent a packet, and
5827 * if it was the last one */
5828 rxi_rto_packet_sent(call, lastPacket, istack);
5829
5830 /* Update last send time for this call (for keep-alive
5831 * processing), and for the connection (so that we can discover
5832 * idle connections) */
5833 conn->lastSendTime = call->lastSendTime = clock_Sec();
5834 }
5835
5836 /* When sending packets we need to follow these rules:
5837 * 1. Never send more than maxDgramPackets in a jumbogram.
5838 * 2. Never send a packet with more than two iovecs in a jumbogram.
5839 * 3. Never send a retransmitted packet in a jumbogram.
5840 * 4. Never send more than cwind/4 packets in a jumbogram
5841 * We always keep the last list we should have sent so we
5842 * can set the RX_MORE_PACKETS flags correctly.
5843 */
5844
5845 static void
5846 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5847 int istack)
5848 {
5849 int i;
5850 int recovery;
5851 struct xmitlist working;
5852 struct xmitlist last;
5853
5854 struct rx_peer *peer = call->conn->peer;
5855 int morePackets = 0;
5856
5857 memset(&last, 0, sizeof(struct xmitlist));
5858 working.list = &list[0];
5859 working.len = 0;
5860 working.resending = 0;
5861
5862 recovery = call->flags & RX_CALL_FAST_RECOVER;
5863
5864 for (i = 0; i < len; i++) {
5865 /* Does the current packet force us to flush the current list? */
5866 if (working.len > 0
5867 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5868 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5869
5870 /* This sends the 'last' list and then rolls the current working
5871 * set into the 'last' one, and resets the working set */
5872
5873 if (last.len > 0) {
5874 rxi_SendList(call, &last, istack, 1);
5875 /* If the call enters an error state stop sending, or if
5876 * we entered congestion recovery mode, stop sending */
5877 if (call->error
5878 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5879 return;
5880 }
5881 last = working;
5882 working.len = 0;
5883 working.resending = 0;
5884 working.list = &list[i];
5885 }
5886 /* Add the current packet to the list if it hasn't been acked.
5887 * Otherwise adjust the list pointer to skip the current packet. */
5888 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5889 working.len++;
5890
5891 if (list[i]->header.serial)
5892 working.resending = 1;
5893
5894 /* Do we need to flush the list? */
5895 if (working.len >= (int)peer->maxDgramPackets
5896 || working.len >= (int)call->nDgramPackets
5897 || working.len >= (int)call->cwind
5898 || list[i]->header.serial
5899 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5900 if (last.len > 0) {
5901 rxi_SendList(call, &last, istack, 1);
5902 /* If the call enters an error state stop sending, or if
5903 * we entered congestion recovery mode, stop sending */
5904 if (call->error
5905 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5906 return;
5907 }
5908 last = working;
5909 working.len = 0;
5910 working.resending = 0;
5911 working.list = &list[i + 1];
5912 }
5913 } else {
5914 if (working.len != 0) {
5915 osi_Panic("rxi_SendList error");
5916 }
5917 working.list = &list[i + 1];
5918 }
5919 }
5920
5921 /* Send the whole list when the call is in receive mode, when
5922 * the call is in eof mode, when we are in fast recovery mode,
5923 * and when we have the last packet */
5924 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5925 * the listener or event threads
5926 */
5927 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5928 || (call->flags & RX_CALL_FLUSH)
5929 || (call->flags & RX_CALL_FAST_RECOVER)) {
5930 /* Check for the case where the current list contains
5931 * an acked packet. Since we always send retransmissions
5932 * in a separate packet, we only need to check the first
5933 * packet in the list */
5934 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5935 morePackets = 1;
5936 }
5937 if (last.len > 0) {
5938 rxi_SendList(call, &last, istack, morePackets);
5939 /* If the call enters an error state stop sending, or if
5940 * we entered congestion recovery mode, stop sending */
5941 if (call->error
5942 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5943 return;
5944 }
5945 if (morePackets) {
5946 rxi_SendList(call, &working, istack, 0);
5947 }
5948 } else if (last.len > 0) {
5949 rxi_SendList(call, &last, istack, 0);
5950 /* Packets which are in 'working' are not sent by this call */
5951 }
5952 }
5953
5954 /**
5955 * Check if the peer for the given call is known to be dead
5956 *
5957 * If the call's peer appears dead (it has encountered fatal network errors
5958 * since the call started) the call is killed with RX_CALL_DEAD if the call
5959 * is active. Otherwise, we do nothing.
5960 *
5961 * @param[in] call The call to check
5962 *
5963 * @return status
5964 * @retval 0 The call is fine, and we haven't done anything to the call
5965 * @retval nonzero The call's peer appears dead, and the call has been
5966 * terminated if it was active
5967 *
5968 * @pre call->lock must be locked
5969 */
5970 static int
5971 rxi_CheckPeerDead(struct rx_call *call)
5972 {
5973 #ifdef AFS_RXERRQ_ENV
5974 int peererrs;
5975
5976 if (call->state == RX_STATE_DALLY) {
5977 return 0;
5978 }
5979
5980 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
5981 if (call->neterr_gen < peererrs) {
5982 /* we have received network errors since this call started; kill
5983 * the call */
5984 if (call->state == RX_STATE_ACTIVE) {
5985 rxi_CallError(call, RX_CALL_DEAD);
5986 }
5987 return -1;
5988 }
5989 if (call->neterr_gen > peererrs) {
5990 /* someone has reset the number of peer errors; set the call error gen
5991 * so we can detect if more errors are encountered */
5992 call->neterr_gen = peererrs;
5993 }
5994 #endif
5995 return 0;
5996 }
5997
5998 static void
5999 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6000 {
6001 struct rx_call *call = arg0;
6002 struct rx_peer *peer;
6003 struct opr_queue *cursor;
6004 struct clock maxTimeout = { 60, 0 };
6005
6006 MUTEX_ENTER(&call->lock);
6007
6008 peer = call->conn->peer;
6009
6010 /* Make sure that the event pointer is removed from the call
6011 * structure, since there is no longer a per-call retransmission
6012 * event pending. */
6013 if (event == call->resendEvent)
6014 rxevent_Put(&call->resendEvent);
6015
6016 rxi_CheckPeerDead(call);
6017
6018 if (opr_queue_IsEmpty(&call->tq)) {
6019 /* Nothing to do. This means that we've been raced, and that an
6020 * ACK has come in between when we were triggered, and when we
6021 * actually got to run. */
6022 goto out;
6023 }
6024
6025 /* We're in loss recovery */
6026 call->flags |= RX_CALL_FAST_RECOVER;
6027
6028 /* Mark all of the pending packets in the queue as being lost */
6029 for (opr_queue_Scan(&call->tq, cursor)) {
6030 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6031 if (!(p->flags & RX_PKTFLAG_ACKED))
6032 p->flags &= ~RX_PKTFLAG_SENT;
6033 }
6034
6035 /* We're resending, so we double the timeout of the call. This will be
6036 * dropped back down by the first successful ACK that we receive.
6037 *
6038 * We apply a maximum value here of 60 seconds
6039 */
6040 clock_Add(&call->rto, &call->rto);
6041 if (clock_Gt(&call->rto, &maxTimeout))
6042 call->rto = maxTimeout;
6043
6044 /* Packet loss is most likely due to congestion, so drop our window size
6045 * and start again from the beginning */
6046 if (peer->maxDgramPackets >1) {
6047 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6048 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6049 }
6050 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6051 call->nDgramPackets = 1;
6052 call->cwind = 1;
6053 call->nextCwind = 1;
6054 call->nAcks = 0;
6055 call->nNacks = 0;
6056 MUTEX_ENTER(&peer->peer_lock);
6057 peer->MTU = call->MTU;
6058 peer->cwind = call->cwind;
6059 peer->nDgramPackets = 1;
6060 peer->congestSeq++;
6061 call->congestSeq = peer->congestSeq;
6062 MUTEX_EXIT(&peer->peer_lock);
6063
6064 rxi_Start(call, istack);
6065
6066 out:
6067 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6068 MUTEX_EXIT(&call->lock);
6069 }
6070
6071 /* This routine is called when new packets are readied for
6072 * transmission and when retransmission may be necessary, or when the
6073 * transmission window or burst count are favourable. This should be
6074 * better optimized for new packets, the usual case, now that we've
6075 * got rid of queues of send packets. XXXXXXXXXXX */
6076 void
6077 rxi_Start(struct rx_call *call, int istack)
6078 {
6079 struct opr_queue *cursor;
6080 #ifdef RX_ENABLE_LOCKS
6081 struct opr_queue *store;
6082 #endif
6083 int nXmitPackets;
6084 int maxXmitPackets;
6085
6086 if (call->error) {
6087 #ifdef RX_ENABLE_LOCKS
6088 if (rx_stats_active)
6089 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6090 #endif
6091 return;
6092 }
6093
6094 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6095 /* Send (or resend) any packets that need it, subject to
6096 * window restrictions and congestion burst control
6097 * restrictions. Ask for an ack on the last packet sent in
6098 * this burst. For now, we're relying upon the window being
6099 * considerably bigger than the largest number of packets that
6100 * are typically sent at once by one initial call to
6101 * rxi_Start. This is probably bogus (perhaps we should ask
6102 * for an ack when we're half way through the current
6103 * window?). Also, for non file transfer applications, this
6104 * may end up asking for an ack for every packet. Bogus. XXXX
6105 */
6106 /*
6107 * But check whether we're here recursively, and let the other guy
6108 * do the work.
6109 */
6110 #ifdef RX_ENABLE_LOCKS
6111 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6112 call->flags |= RX_CALL_TQ_BUSY;
6113 do {
6114 #endif /* RX_ENABLE_LOCKS */
6115 restart:
6116 #ifdef RX_ENABLE_LOCKS
6117 call->flags &= ~RX_CALL_NEED_START;
6118 #endif /* RX_ENABLE_LOCKS */
6119 nXmitPackets = 0;
6120 maxXmitPackets = MIN(call->twind, call->cwind);
6121 for (opr_queue_Scan(&call->tq, cursor)) {
6122 struct rx_packet *p
6123 = opr_queue_Entry(cursor, struct rx_packet, entry);
6124
6125 if (p->flags & RX_PKTFLAG_ACKED) {
6126 /* Since we may block, don't trust this */
6127 if (rx_stats_active)
6128 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6129 continue; /* Ignore this packet if it has been acknowledged */
6130 }
6131
6132 /* Turn off all flags except these ones, which are the same
6133 * on each transmission */
6134 p->header.flags &= RX_PRESET_FLAGS;
6135
6136 if (p->header.seq >=
6137 call->tfirst + MIN((int)call->twind,
6138 (int)(call->nSoftAcked +
6139 call->cwind))) {
6140 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6141 /* Note: if we're waiting for more window space, we can
6142 * still send retransmits; hence we don't return here, but
6143 * break out to schedule a retransmit event */
6144 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6145 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6146 call->cwind));
6147 break;
6148 }
6149
6150 /* Transmit the packet if it needs to be sent. */
6151 if (!(p->flags & RX_PKTFLAG_SENT)) {
6152 if (nXmitPackets == maxXmitPackets) {
6153 rxi_SendXmitList(call, call->xmitList,
6154 nXmitPackets, istack);
6155 goto restart;
6156 }
6157 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6158 *(call->callNumber), p));
6159 call->xmitList[nXmitPackets++] = p;
6160 }
6161 } /* end of the queue_Scan */
6162
6163 /* xmitList now hold pointers to all of the packets that are
6164 * ready to send. Now we loop to send the packets */
6165 if (nXmitPackets > 0) {
6166 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6167 istack);
6168 }
6169
6170 #ifdef RX_ENABLE_LOCKS
6171 if (call->error) {
6172 /* We went into the error state while sending packets. Now is
6173 * the time to reset the call. This will also inform the using
6174 * process that the call is in an error state.
6175 */
6176 if (rx_stats_active)
6177 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6178 call->flags &= ~RX_CALL_TQ_BUSY;
6179 rxi_WakeUpTransmitQueue(call);
6180 rxi_CallError(call, call->error);
6181 return;
6182 }
6183
6184 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6185 int missing;
6186 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6187 /* Some packets have received acks. If they all have, we can clear
6188 * the transmit queue.
6189 */
6190 missing = 0;
6191 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6192 struct rx_packet *p
6193 = opr_queue_Entry(cursor, struct rx_packet, entry);
6194
6195 if (p->header.seq < call->tfirst
6196 && (p->flags & RX_PKTFLAG_ACKED)) {
6197 opr_queue_Remove(&p->entry);
6198 #ifdef RX_TRACK_PACKETS
6199 p->flags &= ~RX_PKTFLAG_TQ;
6200 #endif
6201 #ifdef RXDEBUG_PACKET
6202 call->tqc--;
6203 #endif
6204 rxi_FreePacket(p);
6205 } else
6206 missing = 1;
6207 }
6208 if (!missing)
6209 call->flags |= RX_CALL_TQ_CLEARME;
6210 }
6211 if (call->flags & RX_CALL_TQ_CLEARME)
6212 rxi_ClearTransmitQueue(call, 1);
6213 } while (call->flags & RX_CALL_NEED_START);
6214 /*
6215 * TQ references no longer protected by this flag; they must remain
6216 * protected by the call lock.
6217 */
6218 call->flags &= ~RX_CALL_TQ_BUSY;
6219 rxi_WakeUpTransmitQueue(call);
6220 } else {
6221 call->flags |= RX_CALL_NEED_START;
6222 }
6223 #endif /* RX_ENABLE_LOCKS */
6224 } else {
6225 rxi_rto_cancel(call);
6226 }
6227 }
6228
6229 /* Also adjusts the keep alive parameters for the call, to reflect
6230 * that we have just sent a packet (so keep alives aren't sent
6231 * immediately) */
6232 void
6233 rxi_Send(struct rx_call *call, struct rx_packet *p,
6234 int istack)
6235 {
6236 struct rx_connection *conn = call->conn;
6237
6238 /* Stamp each packet with the user supplied status */
6239 p->header.userStatus = call->localStatus;
6240
6241 /* Allow the security object controlling this call's security to
6242 * make any last-minute changes to the packet */
6243 RXS_SendPacket(conn->securityObject, call, p);
6244
6245 /* Since we're about to send SOME sort of packet to the peer, it's
6246 * safe to nuke any scheduled end-of-packets ack */
6247 rxi_CancelDelayedAckEvent(call);
6248
6249 /* Actually send the packet, filling in more connection-specific fields */
6250 MUTEX_EXIT(&call->lock);
6251 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6252 rxi_SendPacket(call, conn, p, istack);
6253 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6254 MUTEX_ENTER(&call->lock);
6255
6256 /* Update last send time for this call (for keep-alive
6257 * processing), and for the connection (so that we can discover
6258 * idle connections) */
6259 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6260 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6261 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6262 {
6263 conn->lastSendTime = call->lastSendTime = clock_Sec();
6264 }
6265 }
6266
6267 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6268 * that things are fine. Also called periodically to guarantee that nothing
6269 * falls through the cracks (e.g. (error + dally) connections have keepalive
6270 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6271 * may be freed!
6272 * haveCTLock Set if calling from rxi_ReapConnections
6273 */
6274 static int
6275 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6276 {
6277 struct rx_connection *conn = call->conn;
6278 afs_uint32 now;
6279 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6280 afs_uint32 fudgeFactor;
6281 int cerror = 0;
6282 int newmtu = 0;
6283 int idle_timeout = 0;
6284 afs_int32 clock_diff = 0;
6285
6286 if (rxi_CheckPeerDead(call)) {
6287 return -1;
6288 }
6289
6290 now = clock_Sec();
6291
6292 /* Large swings in the clock can have a significant impact on
6293 * the performance of RX call processing. Forward clock shifts
6294 * will result in premature event triggering or timeouts.
6295 * Backward shifts can result in calls not completing until
6296 * the clock catches up with the original start clock value.
6297 *
6298 * If a backward clock shift of more than five minutes is noticed,
6299 * just fail the call.
6300 */
6301 if (now < call->lastSendTime)
6302 clock_diff = call->lastSendTime - now;
6303 if (now < call->startWait)
6304 clock_diff = MAX(clock_diff, call->startWait - now);
6305 if (now < call->lastReceiveTime)
6306 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6307 if (clock_diff > 5 * 60)
6308 {
6309 if (call->state == RX_STATE_ACTIVE)
6310 rxi_CallError(call, RX_CALL_TIMEOUT);
6311 return -1;
6312 }
6313
6314 #ifdef RX_ENABLE_LOCKS
6315 if (call->flags & RX_CALL_TQ_BUSY) {
6316 /* Call is active and will be reset by rxi_Start if it's
6317 * in an error state.
6318 */
6319 return 0;
6320 }
6321 #endif
6322 /* RTT + 8*MDEV, rounded up to the next second. */
6323 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6324 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6325
6326 deadTime = conn->secondsUntilDead + fudgeFactor;
6327 /* These are computed to the second (+- 1 second). But that's
6328 * good enough for these values, which should be a significant
6329 * number of seconds. */
6330 if (now > (call->lastReceiveTime + deadTime)) {
6331 if (call->state == RX_STATE_ACTIVE) {
6332 cerror = RX_CALL_DEAD;
6333 goto mtuout;
6334 } else {
6335 #ifdef RX_ENABLE_LOCKS
6336 /* Cancel pending events */
6337 rxi_CancelDelayedAckEvent(call);
6338 rxi_rto_cancel(call);
6339 rxi_CancelKeepAliveEvent(call);
6340 rxi_CancelGrowMTUEvent(call);
6341 MUTEX_ENTER(&rx_refcnt_mutex);
6342 /* if rxi_FreeCall returns 1 it has freed the call */
6343 if (call->refCount == 0 &&
6344 rxi_FreeCall(call, haveCTLock))
6345 {
6346 MUTEX_EXIT(&rx_refcnt_mutex);
6347 return -2;
6348 }
6349 MUTEX_EXIT(&rx_refcnt_mutex);
6350 return -1;
6351 #else /* RX_ENABLE_LOCKS */
6352 rxi_FreeCall(call, 0);
6353 return -2;
6354 #endif /* RX_ENABLE_LOCKS */
6355 }
6356 /* Non-active calls are destroyed if they are not responding
6357 * to pings; active calls are simply flagged in error, so the
6358 * attached process can die reasonably gracefully. */
6359 }
6360
6361 if (conn->idleDeadTime) {
6362 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6363 }
6364
6365 if (idleDeadTime) {
6366 /* see if we have a non-activity timeout */
6367 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6368 if (call->state == RX_STATE_ACTIVE) {
6369 cerror = RX_CALL_TIMEOUT;
6370 goto mtuout;
6371 }
6372 }
6373 }
6374
6375 if (conn->hardDeadTime) {
6376 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6377 }
6378
6379 /* see if we have a hard timeout */
6380 if (hardDeadTime
6381 && (now > (hardDeadTime + call->startTime.sec))) {
6382 if (call->state == RX_STATE_ACTIVE)
6383 rxi_CallError(call, RX_CALL_TIMEOUT);
6384 return -1;
6385 }
6386 return 0;
6387 mtuout:
6388 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6389 call->lastReceiveTime) {
6390 int oldMTU = conn->peer->ifMTU;
6391
6392 /* If we thought we could send more, perhaps things got worse.
6393 * Shrink by 128 bytes and try again. */
6394 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6395 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6396 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6397 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6398 else
6399 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6400
6401 /* minimum capped in SetPeerMtu */
6402 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6403
6404 /* clean up */
6405 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6406
6407 /* needed so ResetCall doesn't clobber us. */
6408 call->MTU = conn->peer->ifMTU;
6409
6410 /* if we never succeeded, let the error pass out as-is */
6411 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6412 cerror = conn->msgsizeRetryErr;
6413
6414 }
6415 rxi_CallError(call, cerror);
6416 return -1;
6417 }
6418
6419 void
6420 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6421 void *dummy, int dummy2)
6422 {
6423 struct rx_connection *conn = arg1;
6424 struct rx_header theader;
6425 char tbuffer[1 + sizeof(struct rx_header)];
6426 struct sockaddr_in taddr;
6427 char *tp;
6428 char a[1] = { 0 };
6429 int resched = 0;
6430 struct iovec tmpiov[2];
6431 osi_socket socket =
6432 (conn->type ==
6433 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6434
6435
6436 tp = &tbuffer[sizeof(struct rx_header)];
6437 taddr.sin_family = AF_INET;
6438 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6439 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6440 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6441 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6442 taddr.sin_len = sizeof(struct sockaddr_in);
6443 #endif
6444 memset(&theader, 0, sizeof(theader));
6445 theader.epoch = htonl(999);
6446 theader.cid = 0;
6447 theader.callNumber = 0;
6448 theader.seq = 0;
6449 theader.serial = 0;
6450 theader.type = RX_PACKET_TYPE_VERSION;
6451 theader.flags = RX_LAST_PACKET;
6452 theader.serviceId = 0;
6453
6454 memcpy(tbuffer, &theader, sizeof(theader));
6455 memcpy(tp, &a, sizeof(a));
6456 tmpiov[0].iov_base = tbuffer;
6457 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6458
6459 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6460
6461 MUTEX_ENTER(&conn->conn_data_lock);
6462 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6463 if (event == conn->natKeepAliveEvent)
6464 rxevent_Put(&conn->natKeepAliveEvent);
6465 MUTEX_ENTER(&rx_refcnt_mutex);
6466 /* Only reschedule ourselves if the connection would not be destroyed */
6467 if (conn->refCount > 1)
6468 resched = 1;
6469 if (conn->refCount <= 0) {
6470 #ifdef RX_REFCOUNT_CHECK
6471 osi_Assert(conn->refCount == 0);
6472 #endif
6473 if (rx_stats_active) {
6474 MUTEX_ENTER(&rx_stats_mutex);
6475 rxi_lowConnRefCount++;
6476 MUTEX_EXIT(&rx_stats_mutex);
6477 }
6478 }
6479 MUTEX_EXIT(&rx_refcnt_mutex);
6480 if (resched)
6481 rxi_ScheduleNatKeepAliveEvent(conn);
6482 MUTEX_EXIT(&conn->conn_data_lock);
6483 putConnection(conn);
6484 }
6485
6486 static void
6487 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6488 {
6489 MUTEX_ASSERT(&conn->conn_data_lock);
6490 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6491 struct clock when, now;
6492 clock_GetTime(&now);
6493 when = now;
6494 when.sec += conn->secondsUntilNatPing;
6495 rx_GetConnection(conn);
6496 conn->natKeepAliveEvent =
6497 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6498 }
6499 }
6500
6501 void
6502 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6503 {
6504 MUTEX_ENTER(&conn->conn_data_lock);
6505 conn->secondsUntilNatPing = seconds;
6506 if (seconds != 0) {
6507 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6508 rxi_ScheduleNatKeepAliveEvent(conn);
6509 else
6510 conn->flags |= RX_CONN_NAT_PING;
6511 }
6512 MUTEX_EXIT(&conn->conn_data_lock);
6513 }
6514
6515 /* When a call is in progress, this routine is called occasionally to
6516 * make sure that some traffic has arrived (or been sent to) the peer.
6517 * If nothing has arrived in a reasonable amount of time, the call is
6518 * declared dead; if nothing has been sent for a while, we send a
6519 * keep-alive packet (if we're actually trying to keep the call alive)
6520 */
6521 void
6522 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6523 int dummy2)
6524 {
6525 struct rx_call *call = arg1;
6526 struct rx_connection *conn;
6527 afs_uint32 now;
6528
6529 MUTEX_ENTER(&call->lock);
6530
6531 if (event == call->keepAliveEvent)
6532 rxevent_Put(&call->keepAliveEvent);
6533
6534 now = clock_Sec();
6535
6536 if (rxi_CheckCall(call, 0)) {
6537 MUTEX_EXIT(&call->lock);
6538 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6539 return;
6540 }
6541
6542 /* Don't try to keep alive dallying calls */
6543 if (call->state == RX_STATE_DALLY) {
6544 MUTEX_EXIT(&call->lock);
6545 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6546 return;
6547 }
6548
6549 conn = call->conn;
6550 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6551 /* Don't try to send keepalives if there is unacknowledged data */
6552 /* the rexmit code should be good enough, this little hack
6553 * doesn't quite work XXX */
6554 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6555 }
6556 rxi_ScheduleKeepAliveEvent(call);
6557 MUTEX_EXIT(&call->lock);
6558 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6559 }
6560
6561 /* Does what's on the nameplate. */
6562 void
6563 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6564 {
6565 struct rx_call *call = arg1;
6566 struct rx_connection *conn;
6567
6568 MUTEX_ENTER(&call->lock);
6569
6570 if (event == call->growMTUEvent)
6571 rxevent_Put(&call->growMTUEvent);
6572
6573 if (rxi_CheckCall(call, 0))
6574 goto out;
6575
6576 /* Don't bother with dallying calls */
6577 if (call->state == RX_STATE_DALLY)
6578 goto out;
6579
6580 conn = call->conn;
6581
6582 /*
6583 * keep being scheduled, just don't do anything if we're at peak,
6584 * or we're not set up to be properly handled (idle timeout required)
6585 */
6586 if ((conn->peer->maxPacketSize != 0) &&
6587 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6588 conn->idleDeadTime)
6589 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6590 rxi_ScheduleGrowMTUEvent(call, 0);
6591 out:
6592 MUTEX_EXIT(&call->lock);
6593 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6594 }
6595
6596 static void
6597 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6598 {
6599 MUTEX_ASSERT(&call->lock);
6600 if (!call->keepAliveEvent) {
6601 struct clock when, now;
6602 clock_GetTime(&now);
6603 when = now;
6604 when.sec += call->conn->secondsUntilPing;
6605 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6606 call->keepAliveEvent =
6607 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6608 }
6609 }
6610
6611 static void
6612 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6613 MUTEX_ASSERT(&call->lock);
6614 if (rxevent_Cancel(&call->keepAliveEvent))
6615 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6616 }
6617
6618 static void
6619 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6620 {
6621 MUTEX_ASSERT(&call->lock);
6622 if (!call->growMTUEvent) {
6623 struct clock when, now;
6624
6625 clock_GetTime(&now);
6626 when = now;
6627 if (!secs) {
6628 if (call->conn->secondsUntilPing)
6629 secs = (6*call->conn->secondsUntilPing)-1;
6630
6631 if (call->conn->secondsUntilDead)
6632 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6633 }
6634
6635 when.sec += secs;
6636 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6637 call->growMTUEvent =
6638 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6639 }
6640 }
6641
6642 static void
6643 rxi_CancelGrowMTUEvent(struct rx_call *call)
6644 {
6645 MUTEX_ASSERT(&call->lock);
6646 if (rxevent_Cancel(&call->growMTUEvent))
6647 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6648 }
6649
6650 /*
6651 * Increment the counter for the next connection ID, handling overflow.
6652 */
6653 static void
6654 update_nextCid(void)
6655 {
6656 /* Overflow is technically undefined behavior; avoid it. */
6657 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6658 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6659 else
6660 rx_nextCid += 1 << RX_CIDSHIFT;
6661 }
6662
6663 static void
6664 rxi_KeepAliveOn(struct rx_call *call)
6665 {
6666 /* Pretend last packet received was received now--i.e. if another
6667 * packet isn't received within the keep alive time, then the call
6668 * will die; Initialize last send time to the current time--even
6669 * if a packet hasn't been sent yet. This will guarantee that a
6670 * keep-alive is sent within the ping time */
6671 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6672 rxi_ScheduleKeepAliveEvent(call);
6673 }
6674
6675 static void
6676 rxi_GrowMTUOn(struct rx_call *call)
6677 {
6678 struct rx_connection *conn = call->conn;
6679 MUTEX_ENTER(&conn->conn_data_lock);
6680 conn->lastPingSizeSer = conn->lastPingSize = 0;
6681 MUTEX_EXIT(&conn->conn_data_lock);
6682 rxi_ScheduleGrowMTUEvent(call, 1);
6683 }
6684
6685 /* This routine is called to send connection abort messages
6686 * that have been delayed to throttle looping clients. */
6687 static void
6688 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6689 int unused2)
6690 {
6691 struct rx_connection *conn = arg1;
6692
6693 afs_int32 error;
6694 struct rx_packet *packet;
6695
6696 MUTEX_ENTER(&conn->conn_data_lock);
6697 if (event == conn->delayedAbortEvent)
6698 rxevent_Put(&conn->delayedAbortEvent);
6699 error = htonl(conn->error);
6700 conn->abortCount++;
6701 MUTEX_EXIT(&conn->conn_data_lock);
6702 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6703 if (packet) {
6704 packet =
6705 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6706 RX_PACKET_TYPE_ABORT, (char *)&error,
6707 sizeof(error), 0);
6708 rxi_FreePacket(packet);
6709 }
6710 putConnection(conn);
6711 }
6712
6713 /* This routine is called to send call abort messages
6714 * that have been delayed to throttle looping clients. */
6715 static void
6716 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6717 int dummy2)
6718 {
6719 struct rx_call *call = arg1;
6720
6721 afs_int32 error;
6722 struct rx_packet *packet;
6723
6724 MUTEX_ENTER(&call->lock);
6725 if (event == call->delayedAbortEvent)
6726 rxevent_Put(&call->delayedAbortEvent);
6727 error = htonl(call->error);
6728 call->abortCount++;
6729 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6730 if (packet) {
6731 packet =
6732 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6733 (char *)&error, sizeof(error), 0);
6734 rxi_FreePacket(packet);
6735 }
6736 MUTEX_EXIT(&call->lock);
6737 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6738 }
6739
6740 /*
6741 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6742 * seconds) to ask the client to authenticate itself. The routine
6743 * issues a challenge to the client, which is obtained from the
6744 * security object associated with the connection
6745 *
6746 * This routine is both an event handler and a function called directly;
6747 * when called directly the passed |event| is NULL and the
6748 * conn->conn->data>lock must must not be held. Also, when called as an
6749 * an event handler, we must putConnection before we exit; but when called
6750 * directly (the first challenge), we must NOT putConnection.
6751 */
6752 static void
6753 rxi_ChallengeEvent(struct rxevent *event,
6754 void *arg0, void *arg1, int tries)
6755 {
6756 struct rx_connection *conn = arg0;
6757 int event_raised = 0; /* assume we were called directly */
6758
6759 MUTEX_ENTER(&conn->conn_data_lock);
6760 if (event != NULL && event == conn->challengeEvent) {
6761 event_raised = 1; /* called as an event */
6762 rxevent_Put(&conn->challengeEvent);
6763 }
6764 MUTEX_EXIT(&conn->conn_data_lock);
6765
6766 /* If there are no active calls it is not worth re-issuing the
6767 * challenge. If the client issues another call on this connection
6768 * the challenge can be requested at that time.
6769 */
6770 if (!rxi_HasActiveCalls(conn))
6771 goto done;
6772
6773 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6774 struct rx_packet *packet;
6775 struct clock when, now;
6776
6777 if (tries <= 0) {
6778 /* We've failed to authenticate for too long.
6779 * Reset any calls waiting for authentication;
6780 * they are all in RX_STATE_PRECALL.
6781 */
6782 int i;
6783
6784 MUTEX_ENTER(&conn->conn_call_lock);
6785 for (i = 0; i < RX_MAXCALLS; i++) {
6786 struct rx_call *call = conn->call[i];
6787 if (call) {
6788 MUTEX_ENTER(&call->lock);
6789 if (call->state == RX_STATE_PRECALL) {
6790 rxi_CallError(call, RX_CALL_DEAD);
6791 rxi_SendCallAbort(call, NULL, 0, 0);
6792 }
6793 MUTEX_EXIT(&call->lock);
6794 }
6795 }
6796 MUTEX_EXIT(&conn->conn_call_lock);
6797 goto done;
6798 }
6799
6800 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6801 if (packet) {
6802 /* If there's no packet available, do this later. */
6803 RXS_GetChallenge(conn->securityObject, conn, packet);
6804 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6805 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6806 rxi_FreePacket(packet);
6807 conn->securityChallengeSent = 1;
6808 }
6809 clock_GetTime(&now);
6810 when = now;
6811 when.sec += RX_CHALLENGE_TIMEOUT;
6812 MUTEX_ENTER(&conn->conn_data_lock);
6813 /* Only reschedule ourselves if not already pending. */
6814 if (conn->challengeEvent == NULL) {
6815 rx_GetConnection(conn);
6816 conn->challengeEvent =
6817 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6818 (tries - 1));
6819 }
6820 MUTEX_EXIT(&conn->conn_data_lock);
6821 }
6822 done:
6823 if (event_raised)
6824 putConnection(conn);
6825 }
6826
6827 /* Call this routine to start requesting the client to authenticate
6828 * itself. This will continue until authentication is established,
6829 * the call times out, or an invalid response is returned. The
6830 * security object associated with the connection is asked to create
6831 * the challenge at this time. */
6832 static void
6833 rxi_ChallengeOn(struct rx_connection *conn)
6834 {
6835 int start = 0;
6836 MUTEX_ENTER(&conn->conn_data_lock);
6837 if (!conn->challengeEvent)
6838 start = 1;
6839 MUTEX_EXIT(&conn->conn_data_lock);
6840 if (start) {
6841 RXS_CreateChallenge(conn->securityObject, conn);
6842 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6843 };
6844 }
6845
6846
6847 /* rxi_ComputeRoundTripTime is called with peer locked. */
6848 /* peer may be null */
6849 static void
6850 rxi_ComputeRoundTripTime(struct rx_packet *p,
6851 struct rx_ackPacket *ack,
6852 struct rx_call *call,
6853 struct rx_peer *peer,
6854 struct clock *now)
6855 {
6856 struct clock thisRtt, *sentp;
6857 int rtt_timeout;
6858 int serial;
6859
6860 /* If the ACK is delayed, then do nothing */
6861 if (ack->reason == RX_ACK_DELAY)
6862 return;
6863
6864 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6865 * their RTT multiple times, so only include the RTT of the last packet
6866 * in a jumbogram */
6867 if (p->flags & RX_JUMBO_PACKET)
6868 return;
6869
6870 /* Use the serial number to determine which transmission the ACK is for,
6871 * and set the sent time to match this. If we have no serial number, then
6872 * only use the ACK for RTT calculations if the packet has not been
6873 * retransmitted
6874 */
6875
6876 serial = ntohl(ack->serial);
6877 if (serial) {
6878 if (serial == p->header.serial) {
6879 sentp = &p->timeSent;
6880 } else if (serial == p->firstSerial) {
6881 sentp = &p->firstSent;
6882 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6883 sentp = &p->firstSent;
6884 } else
6885 return;
6886 } else {
6887 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6888 sentp = &p->firstSent;
6889 } else
6890 return;
6891 }
6892
6893 thisRtt = *now;
6894
6895 if (clock_Lt(&thisRtt, sentp))
6896 return; /* somebody set the clock back, don't count this time. */
6897
6898 clock_Sub(&thisRtt, sentp);
6899 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6900 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6901
6902 if (clock_IsZero(&thisRtt)) {
6903 /*
6904 * The actual round trip time is shorter than the
6905 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6906 * Since we can't tell which at the moment we will assume 1ms.
6907 */
6908 thisRtt.usec = 1000;
6909 }
6910
6911 if (rx_stats_active) {
6912 MUTEX_ENTER(&rx_stats_mutex);
6913 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6914 rx_stats.minRtt = thisRtt;
6915 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6916 if (thisRtt.sec > 60) {
6917 MUTEX_EXIT(&rx_stats_mutex);
6918 return; /* somebody set the clock ahead */
6919 }
6920 rx_stats.maxRtt = thisRtt;
6921 }
6922 clock_Add(&rx_stats.totalRtt, &thisRtt);
6923 rx_atomic_inc(&rx_stats.nRttSamples);
6924 MUTEX_EXIT(&rx_stats_mutex);
6925 }
6926
6927 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6928
6929 /* Apply VanJacobson round-trip estimations */
6930 if (call->rtt) {
6931 int delta;
6932
6933 /*
6934 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6935 * srtt is stored as fixed point with 3 bits after the binary
6936 * point (i.e., scaled by 8). The following magic is
6937 * equivalent to the smoothing algorithm in rfc793 with an
6938 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6939 * srtt'*8 = rtt + srtt*7
6940 * srtt'*8 = srtt*8 + rtt - srtt
6941 * srtt' = srtt + rtt/8 - srtt/8
6942 * srtt' = srtt + (rtt - srtt)/8
6943 */
6944
6945 delta = _8THMSEC(&thisRtt) - call->rtt;
6946 call->rtt += (delta >> 3);
6947
6948 /*
6949 * We accumulate a smoothed rtt variance (actually, a smoothed
6950 * mean difference), then set the retransmit timer to smoothed
6951 * rtt + 4 times the smoothed variance (was 2x in van's original
6952 * paper, but 4x works better for me, and apparently for him as
6953 * well).
6954 * rttvar is stored as
6955 * fixed point with 2 bits after the binary point (scaled by
6956 * 4). The following is equivalent to rfc793 smoothing with
6957 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6958 * rttvar'*4 = rttvar*3 + |delta|
6959 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6960 * rttvar' = rttvar + |delta|/4 - rttvar/4
6961 * rttvar' = rttvar + (|delta| - rttvar)/4
6962 * This replaces rfc793's wired-in beta.
6963 * dev*4 = dev*4 + (|actual - expected| - dev)
6964 */
6965
6966 if (delta < 0)
6967 delta = -delta;
6968
6969 delta -= (call->rtt_dev << 1);
6970 call->rtt_dev += (delta >> 3);
6971 } else {
6972 /* I don't have a stored RTT so I start with this value. Since I'm
6973 * probably just starting a call, and will be pushing more data down
6974 * this, I expect congestion to increase rapidly. So I fudge a
6975 * little, and I set deviance to half the rtt. In practice,
6976 * deviance tends to approach something a little less than
6977 * half the smoothed rtt. */
6978 call->rtt = _8THMSEC(&thisRtt) + 8;
6979 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6980 }
6981 /* the smoothed RTT time is RTT + 4*MDEV
6982 *
6983 * We allow a user specified minimum to be set for this, to allow clamping
6984 * at a minimum value in the same way as TCP. In addition, we have to allow
6985 * for the possibility that this packet is answered by a delayed ACK, so we
6986 * add on a fixed 200ms to account for that timer expiring.
6987 */
6988
6989 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6990 rx_minPeerTimeout) + 200;
6991 clock_Zero(&call->rto);
6992 clock_Addmsec(&call->rto, rtt_timeout);
6993
6994 /* Update the peer, so any new calls start with our values */
6995 peer->rtt_dev = call->rtt_dev;
6996 peer->rtt = call->rtt;
6997
6998 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6999 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7000 }
7001
7002
7003 /* Find all server connections that have not been active for a long time, and
7004 * toss them */
7005 static void
7006 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7007 int unused3)
7008 {
7009 struct clock now, when;
7010 struct rxevent *event;
7011 clock_GetTime(&now);
7012
7013 /* Find server connection structures that haven't been used for
7014 * greater than rx_idleConnectionTime */
7015 {
7016 struct rx_connection **conn_ptr, **conn_end;
7017 int i, havecalls = 0;
7018 MUTEX_ENTER(&rx_connHashTable_lock);
7019 for (conn_ptr = &rx_connHashTable[0], conn_end =
7020 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7021 conn_ptr++) {
7022 struct rx_connection *conn, *next;
7023 struct rx_call *call;
7024 int result;
7025
7026 rereap:
7027 for (conn = *conn_ptr; conn; conn = next) {
7028 /* XXX -- Shouldn't the connection be locked? */
7029 next = conn->next;
7030 havecalls = 0;
7031 for (i = 0; i < RX_MAXCALLS; i++) {
7032 call = conn->call[i];
7033 if (call) {
7034 int code;
7035 havecalls = 1;
7036 code = MUTEX_TRYENTER(&call->lock);
7037 if (!code)
7038 continue;
7039 result = rxi_CheckCall(call, 1);
7040 MUTEX_EXIT(&call->lock);
7041 if (result == -2) {
7042 /* If CheckCall freed the call, it might
7043 * have destroyed the connection as well,
7044 * which screws up the linked lists.
7045 */
7046 goto rereap;
7047 }
7048 }
7049 }
7050 if (conn->type == RX_SERVER_CONNECTION) {
7051 /* This only actually destroys the connection if
7052 * there are no outstanding calls */
7053 MUTEX_ENTER(&conn->conn_data_lock);
7054 MUTEX_ENTER(&rx_refcnt_mutex);
7055 if (!havecalls && !conn->refCount
7056 && ((conn->lastSendTime + rx_idleConnectionTime) <
7057 now.sec)) {
7058 conn->refCount++; /* it will be decr in rx_DestroyConn */
7059 MUTEX_EXIT(&rx_refcnt_mutex);
7060 MUTEX_EXIT(&conn->conn_data_lock);
7061 #ifdef RX_ENABLE_LOCKS
7062 rxi_DestroyConnectionNoLock(conn);
7063 #else /* RX_ENABLE_LOCKS */
7064 rxi_DestroyConnection(conn);
7065 #endif /* RX_ENABLE_LOCKS */
7066 }
7067 #ifdef RX_ENABLE_LOCKS
7068 else {
7069 MUTEX_EXIT(&rx_refcnt_mutex);
7070 MUTEX_EXIT(&conn->conn_data_lock);
7071 }
7072 #endif /* RX_ENABLE_LOCKS */
7073 }
7074 }
7075 }
7076 #ifdef RX_ENABLE_LOCKS
7077 while (rx_connCleanup_list) {
7078 struct rx_connection *conn;
7079 conn = rx_connCleanup_list;
7080 rx_connCleanup_list = rx_connCleanup_list->next;
7081 MUTEX_EXIT(&rx_connHashTable_lock);
7082 rxi_CleanupConnection(conn);
7083 MUTEX_ENTER(&rx_connHashTable_lock);
7084 }
7085 MUTEX_EXIT(&rx_connHashTable_lock);
7086 #endif /* RX_ENABLE_LOCKS */
7087 }
7088
7089 /* Find any peer structures that haven't been used (haven't had an
7090 * associated connection) for greater than rx_idlePeerTime */
7091 {
7092 struct rx_peer **peer_ptr, **peer_end;
7093 int code;
7094
7095 /*
7096 * Why do we need to hold the rx_peerHashTable_lock across
7097 * the incrementing of peer_ptr since the rx_peerHashTable
7098 * array is not changing? We don't.
7099 *
7100 * By dropping the lock periodically we can permit other
7101 * activities to be performed while a rxi_ReapConnections
7102 * call is in progress. The goal of reap connections
7103 * is to clean up quickly without causing large amounts
7104 * of contention. Therefore, it is important that global
7105 * mutexes not be held for extended periods of time.
7106 */
7107 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7108 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7109 peer_ptr++) {
7110 struct rx_peer *peer, *next, *prev;
7111
7112 MUTEX_ENTER(&rx_peerHashTable_lock);
7113 for (prev = peer = *peer_ptr; peer; peer = next) {
7114 next = peer->next;
7115 code = MUTEX_TRYENTER(&peer->peer_lock);
7116 if ((code) && (peer->refCount == 0)
7117 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7118 struct opr_queue *cursor, *store;
7119 size_t space;
7120
7121 /*
7122 * now know that this peer object is one to be
7123 * removed from the hash table. Once it is removed
7124 * it can't be referenced by other threads.
7125 * Lets remove it first and decrement the struct
7126 * nPeerStructs count.
7127 */
7128 if (peer == *peer_ptr) {
7129 *peer_ptr = next;
7130 prev = next;
7131 } else
7132 prev->next = next;
7133
7134 if (rx_stats_active)
7135 rx_atomic_dec(&rx_stats.nPeerStructs);
7136
7137 /*
7138 * Now if we hold references on 'prev' and 'next'
7139 * we can safely drop the rx_peerHashTable_lock
7140 * while we destroy this 'peer' object.
7141 */
7142 if (next)
7143 next->refCount++;
7144 if (prev)
7145 prev->refCount++;
7146 MUTEX_EXIT(&rx_peerHashTable_lock);
7147
7148 MUTEX_EXIT(&peer->peer_lock);
7149 MUTEX_DESTROY(&peer->peer_lock);
7150
7151 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7152 unsigned int num_funcs;
7153 struct rx_interface_stat *rpc_stat
7154 = opr_queue_Entry(cursor, struct rx_interface_stat,
7155 entry);
7156 if (!rpc_stat)
7157 break;
7158
7159 opr_queue_Remove(&rpc_stat->entry);
7160 opr_queue_Remove(&rpc_stat->entryPeers);
7161
7162 num_funcs = rpc_stat->stats[0].func_total;
7163 space =
7164 sizeof(rx_interface_stat_t) +
7165 rpc_stat->stats[0].func_total *
7166 sizeof(rx_function_entry_v1_t);
7167
7168 rxi_Free(rpc_stat, space);
7169
7170 MUTEX_ENTER(&rx_rpc_stats);
7171 rxi_rpc_peer_stat_cnt -= num_funcs;
7172 MUTEX_EXIT(&rx_rpc_stats);
7173 }
7174 rxi_FreePeer(peer);
7175
7176 /*
7177 * Regain the rx_peerHashTable_lock and
7178 * decrement the reference count on 'prev'
7179 * and 'next'.
7180 */
7181 MUTEX_ENTER(&rx_peerHashTable_lock);
7182 if (next)
7183 next->refCount--;
7184 if (prev)
7185 prev->refCount--;
7186 } else {
7187 if (code) {
7188 MUTEX_EXIT(&peer->peer_lock);
7189 }
7190 prev = peer;
7191 }
7192 }
7193 MUTEX_EXIT(&rx_peerHashTable_lock);
7194 }
7195 }
7196
7197 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7198 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7199 * GC, just below. Really, we shouldn't have to keep moving packets from
7200 * one place to another, but instead ought to always know if we can
7201 * afford to hold onto a packet in its particular use. */
7202 MUTEX_ENTER(&rx_freePktQ_lock);
7203 if (rx_waitingForPackets) {
7204 rx_waitingForPackets = 0;
7205 #ifdef RX_ENABLE_LOCKS
7206 CV_BROADCAST(&rx_waitingForPackets_cv);
7207 #else
7208 osi_rxWakeup(&rx_waitingForPackets);
7209 #endif
7210 }
7211 MUTEX_EXIT(&rx_freePktQ_lock);
7212
7213 when = now;
7214 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7215 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7216 rxevent_Put(&event);
7217 }
7218
7219
7220 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7221 * rx.h is sort of strange this is better. This is called with a security
7222 * object before it is discarded. Each connection using a security object has
7223 * its own refcount to the object so it won't actually be freed until the last
7224 * connection is destroyed.
7225 *
7226 * This is the only rxs module call. A hold could also be written but no one
7227 * needs it. */
7228
7229 int
7230 rxs_Release(struct rx_securityClass *aobj)
7231 {
7232 return RXS_Close(aobj);
7233 }
7234
7235 void
7236 rxi_DebugInit(void)
7237 {
7238 #ifdef RXDEBUG
7239 #ifdef AFS_NT40_ENV
7240 #define TRACE_OPTION_RX_DEBUG 16
7241 HKEY parmKey;
7242 DWORD dummyLen;
7243 DWORD TraceOption;
7244 long code;
7245
7246 rxdebug_active = 0;
7247
7248 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7249 0, KEY_QUERY_VALUE, &parmKey);
7250 if (code != ERROR_SUCCESS)
7251 return;
7252
7253 dummyLen = sizeof(TraceOption);
7254 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7255 (BYTE *) &TraceOption, &dummyLen);
7256 if (code == ERROR_SUCCESS) {
7257 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7258 }
7259 RegCloseKey (parmKey);
7260 #endif /* AFS_NT40_ENV */
7261 #endif
7262 }
7263
7264 void
7265 rx_DebugOnOff(int on)
7266 {
7267 #ifdef RXDEBUG
7268 #ifdef AFS_NT40_ENV
7269 rxdebug_active = on;
7270 #endif
7271 #endif
7272 }
7273
7274 void
7275 rx_StatsOnOff(int on)
7276 {
7277 rx_stats_active = on;
7278 }
7279
7280
7281 /* Don't call this debugging routine directly; use dpf */
7282 void
7283 rxi_DebugPrint(char *format, ...)
7284 {
7285 #ifdef RXDEBUG
7286 va_list ap;
7287 #ifdef AFS_NT40_ENV
7288 char msg[512];
7289 char tformat[256];
7290 size_t len;
7291
7292 va_start(ap, format);
7293
7294 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7295
7296 if (len > 0) {
7297 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7298 if (len > 0)
7299 OutputDebugString(msg);
7300 }
7301 va_end(ap);
7302 #else
7303 struct clock now;
7304
7305 va_start(ap, format);
7306
7307 clock_GetTime(&now);
7308 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7309 (unsigned int)now.usec);
7310 vfprintf(rx_Log, format, ap);
7311 va_end(ap);
7312 #endif
7313 #endif
7314 }
7315
7316 #ifndef KERNEL
7317 /*
7318 * This function is used to process the rx_stats structure that is local
7319 * to a process as well as an rx_stats structure received from a remote
7320 * process (via rxdebug). Therefore, it needs to do minimal version
7321 * checking.
7322 */
7323 void
7324 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7325 afs_int32 freePackets, char version)
7326 {
7327 int i;
7328
7329 if (size != sizeof(struct rx_statistics)) {
7330 fprintf(file,
7331 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7332 size, sizeof(struct rx_statistics));
7333 }
7334
7335 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7336 s->packetRequests);
7337
7338 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7339 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7340 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7341 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7342 s->specialPktAllocFailures);
7343 } else {
7344 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7345 s->receivePktAllocFailures, s->sendPktAllocFailures,
7346 s->specialPktAllocFailures);
7347 }
7348
7349 fprintf(file,
7350 " greedy %u, " "bogusReads %u (last from host %x), "
7351 "noPackets %u, " "noBuffers %u, " "selects %u, "
7352 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7353 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7354 s->selects, s->sendSelects);
7355
7356 fprintf(file, " packets read: ");
7357 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7358 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7359 }
7360 fprintf(file, "\n");
7361
7362 fprintf(file,
7363 " other read counters: data %u, " "ack %u, " "dup %u "
7364 "spurious %u " "dally %u\n", s->dataPacketsRead,
7365 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7366 s->ignorePacketDally);
7367
7368 fprintf(file, " packets sent: ");
7369 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7370 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7371 }
7372 fprintf(file, "\n");
7373
7374 fprintf(file,
7375 " other send counters: ack %u, " "data %u (not resends), "
7376 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7377 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7378 s->dataPacketsPushed, s->ignoreAckedPacket);
7379
7380 fprintf(file,
7381 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7382 s->netSendFailures, (int)s->fatalErrors);
7383
7384 if (s->nRttSamples) {
7385 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7386 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7387
7388 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7389 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7390 }
7391
7392 fprintf(file,
7393 " %d server connections, " "%d client connections, "
7394 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7395 s->nServerConns, s->nClientConns, s->nPeerStructs,
7396 s->nCallStructs, s->nFreeCallStructs);
7397
7398 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7399 fprintf(file, " %d clock updates\n", clock_nUpdates);
7400 #endif
7401 }
7402
7403 /* for backward compatibility */
7404 void
7405 rx_PrintStats(FILE * file)
7406 {
7407 MUTEX_ENTER(&rx_stats_mutex);
7408 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7409 sizeof(rx_stats), rx_nFreePackets,
7410 RX_DEBUGI_VERSION);
7411 MUTEX_EXIT(&rx_stats_mutex);
7412 }
7413
7414 void
7415 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7416 {
7417 fprintf(file, "Peer %x.%d.\n",
7418 ntohl(peer->host), (int)ntohs(peer->port));
7419
7420 fprintf(file,
7421 " Rtt %d, " "total sent %d, " "resent %d\n",
7422 peer->rtt, peer->nSent, peer->reSends);
7423
7424 fprintf(file, " Packet size %d\n", peer->ifMTU);
7425 }
7426 #endif
7427
7428 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7429 /*
7430 * This mutex protects the following static variables:
7431 * counter
7432 */
7433
7434 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7435 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7436 #else
7437 #define LOCK_RX_DEBUG
7438 #define UNLOCK_RX_DEBUG
7439 #endif /* AFS_PTHREAD_ENV */
7440
7441 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7442 static int
7443 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7444 u_char type, void *inputData, size_t inputLength,
7445 void *outputData, size_t outputLength)
7446 {
7447 static afs_int32 counter = 100;
7448 time_t waitTime, waitCount;
7449 struct rx_header theader;
7450 char tbuffer[1500];
7451 afs_int32 code;
7452 struct timeval tv_now, tv_wake, tv_delta;
7453 struct sockaddr_in taddr, faddr;
7454 #ifdef AFS_NT40_ENV
7455 int faddrLen;
7456 #else
7457 socklen_t faddrLen;
7458 #endif
7459 fd_set imask;
7460 char *tp;
7461
7462 waitTime = 1;
7463 waitCount = 5;
7464 LOCK_RX_DEBUG;
7465 counter++;
7466 UNLOCK_RX_DEBUG;
7467 tp = &tbuffer[sizeof(struct rx_header)];
7468 taddr.sin_family = AF_INET;
7469 taddr.sin_port = remotePort;
7470 taddr.sin_addr.s_addr = remoteAddr;
7471 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7472 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7473 taddr.sin_len = sizeof(struct sockaddr_in);
7474 #endif
7475 while (1) {
7476 memset(&theader, 0, sizeof(theader));
7477 theader.epoch = htonl(999);
7478 theader.cid = 0;
7479 theader.callNumber = htonl(counter);
7480 theader.seq = 0;
7481 theader.serial = 0;
7482 theader.type = type;
7483 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7484 theader.serviceId = 0;
7485
7486 memcpy(tbuffer, &theader, sizeof(theader));
7487 memcpy(tp, inputData, inputLength);
7488 code =
7489 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7490 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7491
7492 /* see if there's a packet available */
7493 gettimeofday(&tv_wake, NULL);
7494 tv_wake.tv_sec += waitTime;
7495 for (;;) {
7496 FD_ZERO(&imask);
7497 FD_SET(socket, &imask);
7498 tv_delta.tv_sec = tv_wake.tv_sec;
7499 tv_delta.tv_usec = tv_wake.tv_usec;
7500 gettimeofday(&tv_now, NULL);
7501
7502 if (tv_delta.tv_usec < tv_now.tv_usec) {
7503 /* borrow */
7504 tv_delta.tv_usec += 1000000;
7505 tv_delta.tv_sec--;
7506 }
7507 tv_delta.tv_usec -= tv_now.tv_usec;
7508
7509 if (tv_delta.tv_sec < tv_now.tv_sec) {
7510 /* time expired */
7511 break;
7512 }
7513 tv_delta.tv_sec -= tv_now.tv_sec;
7514
7515 #ifdef AFS_NT40_ENV
7516 code = select(0, &imask, 0, 0, &tv_delta);
7517 #else /* AFS_NT40_ENV */
7518 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7519 #endif /* AFS_NT40_ENV */
7520 if (code == 1 && FD_ISSET(socket, &imask)) {
7521 /* now receive a packet */
7522 faddrLen = sizeof(struct sockaddr_in);
7523 code =
7524 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7525 (struct sockaddr *)&faddr, &faddrLen);
7526
7527 if (code > 0) {
7528 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7529 if (counter == ntohl(theader.callNumber))
7530 goto success;
7531 continue;
7532 }
7533 }
7534 break;
7535 }
7536
7537 /* see if we've timed out */
7538 if (!--waitCount) {
7539 return -1;
7540 }
7541 waitTime <<= 1;
7542 }
7543
7544 success:
7545 code -= sizeof(struct rx_header);
7546 if (code > outputLength)
7547 code = outputLength;
7548 memcpy(outputData, tp, code);
7549 return code;
7550 }
7551 #endif /* RXDEBUG */
7552
7553 afs_int32
7554 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7555 afs_uint16 remotePort, struct rx_debugStats * stat,
7556 afs_uint32 * supportedValues)
7557 {
7558 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7559 afs_int32 rc = 0;
7560 struct rx_debugIn in;
7561
7562 *supportedValues = 0;
7563 in.type = htonl(RX_DEBUGI_GETSTATS);
7564 in.index = 0;
7565
7566 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7567 &in, sizeof(in), stat, sizeof(*stat));
7568
7569 /*
7570 * If the call was successful, fixup the version and indicate
7571 * what contents of the stat structure are valid.
7572 * Also do net to host conversion of fields here.
7573 */
7574
7575 if (rc >= 0) {
7576 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7577 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7578 }
7579 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7580 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7581 }
7582 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7583 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7584 }
7585 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7586 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7587 }
7588 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7589 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7590 }
7591 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7592 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7593 }
7594 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7595 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7596 }
7597 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7598 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7599 }
7600 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7601 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7602 }
7603 stat->nFreePackets = ntohl(stat->nFreePackets);
7604 stat->packetReclaims = ntohl(stat->packetReclaims);
7605 stat->callsExecuted = ntohl(stat->callsExecuted);
7606 stat->nWaiting = ntohl(stat->nWaiting);
7607 stat->idleThreads = ntohl(stat->idleThreads);
7608 stat->nWaited = ntohl(stat->nWaited);
7609 stat->nPackets = ntohl(stat->nPackets);
7610 }
7611 #else
7612 afs_int32 rc = -1;
7613 #endif
7614 return rc;
7615 }
7616
7617 afs_int32
7618 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7619 afs_uint16 remotePort, struct rx_statistics * stat,
7620 afs_uint32 * supportedValues)
7621 {
7622 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7623 afs_int32 rc = 0;
7624 struct rx_debugIn in;
7625 afs_int32 *lp = (afs_int32 *) stat;
7626 int i;
7627
7628 /*
7629 * supportedValues is currently unused, but added to allow future
7630 * versioning of this function.
7631 */
7632
7633 *supportedValues = 0;
7634 in.type = htonl(RX_DEBUGI_RXSTATS);
7635 in.index = 0;
7636 memset(stat, 0, sizeof(*stat));
7637
7638 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7639 &in, sizeof(in), stat, sizeof(*stat));
7640
7641 if (rc >= 0) {
7642
7643 /*
7644 * Do net to host conversion here
7645 */
7646
7647 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7648 *lp = ntohl(*lp);
7649 }
7650 }
7651 #else
7652 afs_int32 rc = -1;
7653 #endif
7654 return rc;
7655 }
7656
7657 afs_int32
7658 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7659 afs_uint16 remotePort, size_t version_length,
7660 char *version)
7661 {
7662 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7663 char a[1] = { 0 };
7664 return MakeDebugCall(socket, remoteAddr, remotePort,
7665 RX_PACKET_TYPE_VERSION, a, 1, version,
7666 version_length);
7667 #else
7668 return -1;
7669 #endif
7670 }
7671
7672 afs_int32
7673 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7674 afs_uint16 remotePort, afs_int32 * nextConnection,
7675 int allConnections, afs_uint32 debugSupportedValues,
7676 struct rx_debugConn * conn,
7677 afs_uint32 * supportedValues)
7678 {
7679 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7680 afs_int32 rc = 0;
7681 struct rx_debugIn in;
7682 int i;
7683
7684 /*
7685 * supportedValues is currently unused, but added to allow future
7686 * versioning of this function.
7687 */
7688
7689 *supportedValues = 0;
7690 if (allConnections) {
7691 in.type = htonl(RX_DEBUGI_GETALLCONN);
7692 } else {
7693 in.type = htonl(RX_DEBUGI_GETCONN);
7694 }
7695 in.index = htonl(*nextConnection);
7696 memset(conn, 0, sizeof(*conn));
7697
7698 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7699 &in, sizeof(in), conn, sizeof(*conn));
7700
7701 if (rc >= 0) {
7702 *nextConnection += 1;
7703
7704 /*
7705 * Convert old connection format to new structure.
7706 */
7707
7708 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7709 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7710 #define MOVEvL(a) (conn->a = vL->a)
7711
7712 /* any old or unrecognized version... */
7713 for (i = 0; i < RX_MAXCALLS; i++) {
7714 MOVEvL(callState[i]);
7715 MOVEvL(callMode[i]);
7716 MOVEvL(callFlags[i]);
7717 MOVEvL(callOther[i]);
7718 }
7719 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7720 MOVEvL(secStats.type);
7721 MOVEvL(secStats.level);
7722 MOVEvL(secStats.flags);
7723 MOVEvL(secStats.expires);
7724 MOVEvL(secStats.packetsReceived);
7725 MOVEvL(secStats.packetsSent);
7726 MOVEvL(secStats.bytesReceived);
7727 MOVEvL(secStats.bytesSent);
7728 }
7729 }
7730
7731 /*
7732 * Do net to host conversion here
7733 * NOTE:
7734 * I don't convert host or port since we are most likely
7735 * going to want these in NBO.
7736 */
7737 conn->cid = ntohl(conn->cid);
7738 conn->serial = ntohl(conn->serial);
7739 for (i = 0; i < RX_MAXCALLS; i++) {
7740 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7741 }
7742 conn->error = ntohl(conn->error);
7743 conn->secStats.flags = ntohl(conn->secStats.flags);
7744 conn->secStats.expires = ntohl(conn->secStats.expires);
7745 conn->secStats.packetsReceived =
7746 ntohl(conn->secStats.packetsReceived);
7747 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7748 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7749 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7750 conn->epoch = ntohl(conn->epoch);
7751 conn->natMTU = ntohl(conn->natMTU);
7752 }
7753 #else
7754 afs_int32 rc = -1;
7755 #endif
7756 return rc;
7757 }
7758
7759 afs_int32
7760 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7761 afs_uint16 remotePort, afs_int32 * nextPeer,
7762 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7763 afs_uint32 * supportedValues)
7764 {
7765 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7766 afs_int32 rc = 0;
7767 struct rx_debugIn in;
7768
7769 /*
7770 * supportedValues is currently unused, but added to allow future
7771 * versioning of this function.
7772 */
7773
7774 *supportedValues = 0;
7775 in.type = htonl(RX_DEBUGI_GETPEER);
7776 in.index = htonl(*nextPeer);
7777 memset(peer, 0, sizeof(*peer));
7778
7779 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7780 &in, sizeof(in), peer, sizeof(*peer));
7781
7782 if (rc >= 0) {
7783 *nextPeer += 1;
7784
7785 /*
7786 * Do net to host conversion here
7787 * NOTE:
7788 * I don't convert host or port since we are most likely
7789 * going to want these in NBO.
7790 */
7791 peer->ifMTU = ntohs(peer->ifMTU);
7792 peer->idleWhen = ntohl(peer->idleWhen);
7793 peer->refCount = ntohs(peer->refCount);
7794 peer->rtt = ntohl(peer->rtt);
7795 peer->rtt_dev = ntohl(peer->rtt_dev);
7796 peer->timeout.sec = 0;
7797 peer->timeout.usec = 0;
7798 peer->nSent = ntohl(peer->nSent);
7799 peer->reSends = ntohl(peer->reSends);
7800 peer->natMTU = ntohs(peer->natMTU);
7801 peer->maxMTU = ntohs(peer->maxMTU);
7802 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7803 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7804 peer->MTU = ntohs(peer->MTU);
7805 peer->cwind = ntohs(peer->cwind);
7806 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7807 peer->congestSeq = ntohs(peer->congestSeq);
7808 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7809 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7810 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7811 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7812 }
7813 #else
7814 afs_int32 rc = -1;
7815 #endif
7816 return rc;
7817 }
7818
7819 afs_int32
7820 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7821 struct rx_debugPeer * peerStats)
7822 {
7823 struct rx_peer *tp;
7824 afs_int32 error = 1; /* default to "did not succeed" */
7825 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7826
7827 MUTEX_ENTER(&rx_peerHashTable_lock);
7828 for(tp = rx_peerHashTable[hashValue];
7829 tp != NULL; tp = tp->next) {
7830 if (tp->host == peerHost)
7831 break;
7832 }
7833
7834 if (tp) {
7835 tp->refCount++;
7836 MUTEX_EXIT(&rx_peerHashTable_lock);
7837
7838 error = 0;
7839
7840 MUTEX_ENTER(&tp->peer_lock);
7841 peerStats->host = tp->host;
7842 peerStats->port = tp->port;
7843 peerStats->ifMTU = tp->ifMTU;
7844 peerStats->idleWhen = tp->idleWhen;
7845 peerStats->refCount = tp->refCount;
7846 peerStats->burstSize = 0;
7847 peerStats->burst = 0;
7848 peerStats->burstWait.sec = 0;
7849 peerStats->burstWait.usec = 0;
7850 peerStats->rtt = tp->rtt;
7851 peerStats->rtt_dev = tp->rtt_dev;
7852 peerStats->timeout.sec = 0;
7853 peerStats->timeout.usec = 0;
7854 peerStats->nSent = tp->nSent;
7855 peerStats->reSends = tp->reSends;
7856 peerStats->natMTU = tp->natMTU;
7857 peerStats->maxMTU = tp->maxMTU;
7858 peerStats->maxDgramPackets = tp->maxDgramPackets;
7859 peerStats->ifDgramPackets = tp->ifDgramPackets;
7860 peerStats->MTU = tp->MTU;
7861 peerStats->cwind = tp->cwind;
7862 peerStats->nDgramPackets = tp->nDgramPackets;
7863 peerStats->congestSeq = tp->congestSeq;
7864 peerStats->bytesSent.high = tp->bytesSent >> 32;
7865 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7866 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7867 peerStats->bytesReceived.low
7868 = tp->bytesReceived & MAX_AFS_UINT32;
7869 MUTEX_EXIT(&tp->peer_lock);
7870
7871 MUTEX_ENTER(&rx_peerHashTable_lock);
7872 tp->refCount--;
7873 }
7874 MUTEX_EXIT(&rx_peerHashTable_lock);
7875
7876 return error;
7877 }
7878
7879 void
7880 shutdown_rx(void)
7881 {
7882 struct rx_serverQueueEntry *np;
7883 int i, j;
7884 #ifndef KERNEL
7885 struct rx_call *call;
7886 struct rx_serverQueueEntry *sq;
7887 #endif /* KERNEL */
7888
7889 LOCK_RX_INIT;
7890 if (!rxi_IsRunning()) {
7891 UNLOCK_RX_INIT;
7892 return; /* Already shutdown. */
7893 }
7894 rx_atomic_set(&rxi_running, 0);
7895 #ifndef KERNEL
7896 rx_port = 0;
7897 #ifndef AFS_PTHREAD_ENV
7898 FD_ZERO(&rx_selectMask);
7899 #endif /* AFS_PTHREAD_ENV */
7900 rxi_dataQuota = RX_MAX_QUOTA;
7901 #ifndef AFS_PTHREAD_ENV
7902 rxi_StopListener();
7903 #endif /* AFS_PTHREAD_ENV */
7904 shutdown_rxevent();
7905 rx_epoch = 0;
7906 #ifndef AFS_PTHREAD_ENV
7907 #ifndef AFS_USE_GETTIMEOFDAY
7908 clock_UnInit();
7909 #endif /* AFS_USE_GETTIMEOFDAY */
7910 #endif /* AFS_PTHREAD_ENV */
7911
7912 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7913 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7914 opr_queue_Remove(&call->entry);
7915 rxi_Free(call, sizeof(struct rx_call));
7916 }
7917
7918 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7919 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7920 entry);
7921 opr_queue_Remove(&sq->entry);
7922 }
7923 #endif /* KERNEL */
7924
7925 {
7926 struct rx_peer **peer_ptr, **peer_end;
7927 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7928 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7929 peer_ptr++) {
7930 struct rx_peer *peer, *next;
7931
7932 MUTEX_ENTER(&rx_peerHashTable_lock);
7933 for (peer = *peer_ptr; peer; peer = next) {
7934 struct opr_queue *cursor, *store;
7935 size_t space;
7936
7937 MUTEX_ENTER(&rx_rpc_stats);
7938 MUTEX_ENTER(&peer->peer_lock);
7939 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7940 unsigned int num_funcs;
7941 struct rx_interface_stat *rpc_stat
7942 = opr_queue_Entry(cursor, struct rx_interface_stat,
7943 entry);
7944 if (!rpc_stat)
7945 break;
7946 opr_queue_Remove(&rpc_stat->entry);
7947 opr_queue_Remove(&rpc_stat->entryPeers);
7948 num_funcs = rpc_stat->stats[0].func_total;
7949 space =
7950 sizeof(rx_interface_stat_t) +
7951 rpc_stat->stats[0].func_total *
7952 sizeof(rx_function_entry_v1_t);
7953
7954 rxi_Free(rpc_stat, space);
7955
7956 /* rx_rpc_stats must be held */
7957 rxi_rpc_peer_stat_cnt -= num_funcs;
7958 }
7959 MUTEX_EXIT(&peer->peer_lock);
7960 MUTEX_EXIT(&rx_rpc_stats);
7961
7962 next = peer->next;
7963 rxi_FreePeer(peer);
7964 if (rx_stats_active)
7965 rx_atomic_dec(&rx_stats.nPeerStructs);
7966 }
7967 MUTEX_EXIT(&rx_peerHashTable_lock);
7968 }
7969 }
7970 for (i = 0; i < RX_MAX_SERVICES; i++) {
7971 if (rx_services[i])
7972 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7973 }
7974 for (i = 0; i < rx_hashTableSize; i++) {
7975 struct rx_connection *tc, *ntc;
7976 MUTEX_ENTER(&rx_connHashTable_lock);
7977 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7978 ntc = tc->next;
7979 for (j = 0; j < RX_MAXCALLS; j++) {
7980 if (tc->call[j]) {
7981 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7982 }
7983 }
7984 rxi_Free(tc, sizeof(*tc));
7985 }
7986 MUTEX_EXIT(&rx_connHashTable_lock);
7987 }
7988
7989 MUTEX_ENTER(&freeSQEList_lock);
7990
7991 while ((np = rx_FreeSQEList)) {
7992 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7993 MUTEX_DESTROY(&np->lock);
7994 rxi_Free(np, sizeof(*np));
7995 }
7996
7997 MUTEX_EXIT(&freeSQEList_lock);
7998 MUTEX_DESTROY(&freeSQEList_lock);
7999 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8000 MUTEX_DESTROY(&rx_connHashTable_lock);
8001 MUTEX_DESTROY(&rx_peerHashTable_lock);
8002 MUTEX_DESTROY(&rx_serverPool_lock);
8003
8004 osi_Free(rx_connHashTable,
8005 rx_hashTableSize * sizeof(struct rx_connection *));
8006 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8007
8008 UNPIN(rx_connHashTable,
8009 rx_hashTableSize * sizeof(struct rx_connection *));
8010 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8011
8012 MUTEX_ENTER(&rx_quota_mutex);
8013 rxi_dataQuota = RX_MAX_QUOTA;
8014 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8015 MUTEX_EXIT(&rx_quota_mutex);
8016 UNLOCK_RX_INIT;
8017 }
8018
8019 #ifndef KERNEL
8020
8021 /*
8022 * Routines to implement connection specific data.
8023 */
8024
8025 int
8026 rx_KeyCreate(rx_destructor_t rtn)
8027 {
8028 int key;
8029 MUTEX_ENTER(&rxi_keyCreate_lock);
8030 key = rxi_keyCreate_counter++;
8031 rxi_keyCreate_destructor = (rx_destructor_t *)
8032 realloc((void *)rxi_keyCreate_destructor,
8033 (key + 1) * sizeof(rx_destructor_t));
8034 rxi_keyCreate_destructor[key] = rtn;
8035 MUTEX_EXIT(&rxi_keyCreate_lock);
8036 return key;
8037 }
8038
8039 void
8040 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8041 {
8042 int i;
8043 MUTEX_ENTER(&conn->conn_data_lock);
8044 if (!conn->specific) {
8045 conn->specific = malloc((key + 1) * sizeof(void *));
8046 for (i = 0; i < key; i++)
8047 conn->specific[i] = NULL;
8048 conn->nSpecific = key + 1;
8049 conn->specific[key] = ptr;
8050 } else if (key >= conn->nSpecific) {
8051 conn->specific = (void **)
8052 realloc(conn->specific, (key + 1) * sizeof(void *));
8053 for (i = conn->nSpecific; i < key; i++)
8054 conn->specific[i] = NULL;
8055 conn->nSpecific = key + 1;
8056 conn->specific[key] = ptr;
8057 } else {
8058 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8059 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8060 conn->specific[key] = ptr;
8061 }
8062 MUTEX_EXIT(&conn->conn_data_lock);
8063 }
8064
8065 void
8066 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8067 {
8068 int i;
8069 MUTEX_ENTER(&svc->svc_data_lock);
8070 if (!svc->specific) {
8071 svc->specific = malloc((key + 1) * sizeof(void *));
8072 for (i = 0; i < key; i++)
8073 svc->specific[i] = NULL;
8074 svc->nSpecific = key + 1;
8075 svc->specific[key] = ptr;
8076 } else if (key >= svc->nSpecific) {
8077 svc->specific = (void **)
8078 realloc(svc->specific, (key + 1) * sizeof(void *));
8079 for (i = svc->nSpecific; i < key; i++)
8080 svc->specific[i] = NULL;
8081 svc->nSpecific = key + 1;
8082 svc->specific[key] = ptr;
8083 } else {
8084 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8085 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8086 svc->specific[key] = ptr;
8087 }
8088 MUTEX_EXIT(&svc->svc_data_lock);
8089 }
8090
8091 void *
8092 rx_GetSpecific(struct rx_connection *conn, int key)
8093 {
8094 void *ptr;
8095 MUTEX_ENTER(&conn->conn_data_lock);
8096 if (key >= conn->nSpecific)
8097 ptr = NULL;
8098 else
8099 ptr = conn->specific[key];
8100 MUTEX_EXIT(&conn->conn_data_lock);
8101 return ptr;
8102 }
8103
8104 void *
8105 rx_GetServiceSpecific(struct rx_service *svc, int key)
8106 {
8107 void *ptr;
8108 MUTEX_ENTER(&svc->svc_data_lock);
8109 if (key >= svc->nSpecific)
8110 ptr = NULL;
8111 else
8112 ptr = svc->specific[key];
8113 MUTEX_EXIT(&svc->svc_data_lock);
8114 return ptr;
8115 }
8116
8117
8118 #endif /* !KERNEL */
8119
8120 /*
8121 * processStats is a queue used to store the statistics for the local
8122 * process. Its contents are similar to the contents of the rpcStats
8123 * queue on a rx_peer structure, but the actual data stored within
8124 * this queue contains totals across the lifetime of the process (assuming
8125 * the stats have not been reset) - unlike the per peer structures
8126 * which can come and go based upon the peer lifetime.
8127 */
8128
8129 static struct opr_queue processStats = { &processStats, &processStats };
8130
8131 /*
8132 * peerStats is a queue used to store the statistics for all peer structs.
8133 * Its contents are the union of all the peer rpcStats queues.
8134 */
8135
8136 static struct opr_queue peerStats = { &peerStats, &peerStats };
8137
8138 /*
8139 * rxi_monitor_processStats is used to turn process wide stat collection
8140 * on and off
8141 */
8142
8143 static int rxi_monitor_processStats = 0;
8144
8145 /*
8146 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8147 */
8148
8149 static int rxi_monitor_peerStats = 0;
8150
8151
8152 void
8153 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8154 {
8155 rpc_stat->invocations = 0;
8156 rpc_stat->bytes_sent = 0;
8157 rpc_stat->bytes_rcvd = 0;
8158 rpc_stat->queue_time_sum.sec = 0;
8159 rpc_stat->queue_time_sum.usec = 0;
8160 rpc_stat->queue_time_sum_sqr.sec = 0;
8161 rpc_stat->queue_time_sum_sqr.usec = 0;
8162 rpc_stat->queue_time_min.sec = 9999999;
8163 rpc_stat->queue_time_min.usec = 9999999;
8164 rpc_stat->queue_time_max.sec = 0;
8165 rpc_stat->queue_time_max.usec = 0;
8166 rpc_stat->execution_time_sum.sec = 0;
8167 rpc_stat->execution_time_sum.usec = 0;
8168 rpc_stat->execution_time_sum_sqr.sec = 0;
8169 rpc_stat->execution_time_sum_sqr.usec = 0;
8170 rpc_stat->execution_time_min.sec = 9999999;
8171 rpc_stat->execution_time_min.usec = 9999999;
8172 rpc_stat->execution_time_max.sec = 0;
8173 rpc_stat->execution_time_max.usec = 0;
8174 }
8175
8176 /*!
8177 * Given all of the information for a particular rpc
8178 * call, find or create (if requested) the stat structure for the rpc.
8179 *
8180 * @param stats
8181 * the queue of stats that will be updated with the new value
8182 *
8183 * @param rxInterface
8184 * a unique number that identifies the rpc interface
8185 *
8186 * @param totalFunc
8187 * the total number of functions in this interface. this is only
8188 * required if create is true
8189 *
8190 * @param isServer
8191 * if true, this invocation was made to a server
8192 *
8193 * @param remoteHost
8194 * the ip address of the remote host. this is only required if create
8195 * and addToPeerList are true
8196 *
8197 * @param remotePort
8198 * the port of the remote host. this is only required if create
8199 * and addToPeerList are true
8200 *
8201 * @param addToPeerList
8202 * if != 0, add newly created stat to the global peer list
8203 *
8204 * @param counter
8205 * if a new stats structure is allocated, the counter will
8206 * be updated with the new number of allocated stat structures.
8207 * only required if create is true
8208 *
8209 * @param create
8210 * if no stats structure exists, allocate one
8211 *
8212 */
8213
8214 static rx_interface_stat_p
8215 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8216 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8217 afs_uint32 remotePort, int addToPeerList,
8218 unsigned int *counter, int create)
8219 {
8220 rx_interface_stat_p rpc_stat = NULL;
8221 struct opr_queue *cursor;
8222
8223 /*
8224 * See if there's already a structure for this interface
8225 */
8226
8227 for (opr_queue_Scan(stats, cursor)) {
8228 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8229
8230 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8231 && (rpc_stat->stats[0].remote_is_server == isServer))
8232 break;
8233 }
8234
8235 /* if they didn't ask us to create, we're done */
8236 if (!create) {
8237 if (opr_queue_IsEnd(stats, cursor))
8238 return NULL;
8239 else
8240 return rpc_stat;
8241 }
8242
8243 /* can't proceed without these */
8244 if (!totalFunc || !counter)
8245 return NULL;
8246
8247 /*
8248 * Didn't find a match so allocate a new structure and add it to the
8249 * queue.
8250 */
8251
8252 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8253 || (rpc_stat->stats[0].interfaceId != rxInterface)
8254 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8255 int i;
8256 size_t space;
8257
8258 space =
8259 sizeof(rx_interface_stat_t) +
8260 totalFunc * sizeof(rx_function_entry_v1_t);
8261
8262 rpc_stat = rxi_Alloc(space);
8263 if (rpc_stat == NULL)
8264 return NULL;
8265
8266 *counter += totalFunc;
8267 for (i = 0; i < totalFunc; i++) {
8268 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8269 rpc_stat->stats[i].remote_peer = remoteHost;
8270 rpc_stat->stats[i].remote_port = remotePort;
8271 rpc_stat->stats[i].remote_is_server = isServer;
8272 rpc_stat->stats[i].interfaceId = rxInterface;
8273 rpc_stat->stats[i].func_total = totalFunc;
8274 rpc_stat->stats[i].func_index = i;
8275 }
8276 opr_queue_Prepend(stats, &rpc_stat->entry);
8277 if (addToPeerList) {
8278 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8279 }
8280 }
8281 return rpc_stat;
8282 }
8283
8284 void
8285 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8286 {
8287 rx_interface_stat_p rpc_stat;
8288 int totalFunc, i;
8289
8290 if (rxInterface == -1)
8291 return;
8292
8293 MUTEX_ENTER(&rx_rpc_stats);
8294 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8295 0, 0, 0, 0, 0);
8296 if (rpc_stat) {
8297 totalFunc = rpc_stat->stats[0].func_total;
8298 for (i = 0; i < totalFunc; i++)
8299 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8300 }
8301 MUTEX_EXIT(&rx_rpc_stats);
8302 return;
8303 }
8304
8305 void
8306 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8307 {
8308 rx_interface_stat_p rpc_stat;
8309 int totalFunc, i;
8310 struct rx_peer * peer;
8311
8312 if (rxInterface == -1)
8313 return;
8314
8315 peer = rxi_FindPeer(peerHost, peerPort, 0);
8316 if (!peer)
8317 return;
8318
8319 MUTEX_ENTER(&rx_rpc_stats);
8320 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8321 0, 0, 0, 0, 0);
8322 if (rpc_stat) {
8323 totalFunc = rpc_stat->stats[0].func_total;
8324 for (i = 0; i < totalFunc; i++)
8325 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8326 }
8327 MUTEX_EXIT(&rx_rpc_stats);
8328 return;
8329 }
8330
8331 void *
8332 rx_CopyProcessRPCStats(afs_uint64 op)
8333 {
8334 rx_interface_stat_p rpc_stat;
8335 rx_function_entry_v1_p rpcop_stat =
8336 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8337 int currentFunc = (op & MAX_AFS_UINT32);
8338 afs_int32 rxInterface = (op >> 32);
8339
8340 if (!rxi_monitor_processStats)
8341 return NULL;
8342
8343 if (rxInterface == -1)
8344 return NULL;
8345
8346 if (rpcop_stat == NULL)
8347 return NULL;
8348
8349 MUTEX_ENTER(&rx_rpc_stats);
8350 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8351 0, 0, 0, 0, 0);
8352 if (rpc_stat)
8353 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8354 sizeof(rx_function_entry_v1_t));
8355 MUTEX_EXIT(&rx_rpc_stats);
8356 if (!rpc_stat) {
8357 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8358 return NULL;
8359 }
8360 return rpcop_stat;
8361 }
8362
8363 void *
8364 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8365 {
8366 rx_interface_stat_p rpc_stat;
8367 rx_function_entry_v1_p rpcop_stat =
8368 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8369 int currentFunc = (op & MAX_AFS_UINT32);
8370 afs_int32 rxInterface = (op >> 32);
8371 struct rx_peer *peer;
8372
8373 if (!rxi_monitor_peerStats)
8374 return NULL;
8375
8376 if (rxInterface == -1)
8377 return NULL;
8378
8379 if (rpcop_stat == NULL)
8380 return NULL;
8381
8382 peer = rxi_FindPeer(peerHost, peerPort, 0);
8383 if (!peer)
8384 return NULL;
8385
8386 MUTEX_ENTER(&rx_rpc_stats);
8387 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8388 0, 0, 0, 0, 0);
8389 if (rpc_stat)
8390 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8391 sizeof(rx_function_entry_v1_t));
8392 MUTEX_EXIT(&rx_rpc_stats);
8393 if (!rpc_stat) {
8394 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8395 return NULL;
8396 }
8397 return rpcop_stat;
8398 }
8399
8400 void
8401 rx_ReleaseRPCStats(void *stats)
8402 {
8403 if (stats)
8404 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8405 }
8406
8407 /*!
8408 * Given all of the information for a particular rpc
8409 * call, create (if needed) and update the stat totals for the rpc.
8410 *
8411 * @param stats
8412 * the queue of stats that will be updated with the new value
8413 *
8414 * @param rxInterface
8415 * a unique number that identifies the rpc interface
8416 *
8417 * @param currentFunc
8418 * the index of the function being invoked
8419 *
8420 * @param totalFunc
8421 * the total number of functions in this interface
8422 *
8423 * @param queueTime
8424 * the amount of time this function waited for a thread
8425 *
8426 * @param execTime
8427 * the amount of time this function invocation took to execute
8428 *
8429 * @param bytesSent
8430 * the number bytes sent by this invocation
8431 *
8432 * @param bytesRcvd
8433 * the number bytes received by this invocation
8434 *
8435 * @param isServer
8436 * if true, this invocation was made to a server
8437 *
8438 * @param remoteHost
8439 * the ip address of the remote host
8440 *
8441 * @param remotePort
8442 * the port of the remote host
8443 *
8444 * @param addToPeerList
8445 * if != 0, add newly created stat to the global peer list
8446 *
8447 * @param counter
8448 * if a new stats structure is allocated, the counter will
8449 * be updated with the new number of allocated stat structures
8450 *
8451 */
8452
8453 static int
8454 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8455 afs_uint32 currentFunc, afs_uint32 totalFunc,
8456 struct clock *queueTime, struct clock *execTime,
8457 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8458 afs_uint32 remoteHost, afs_uint32 remotePort,
8459 int addToPeerList, unsigned int *counter)
8460 {
8461 int rc = 0;
8462 rx_interface_stat_p rpc_stat;
8463
8464 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8465 remoteHost, remotePort, addToPeerList, counter,
8466 1);
8467 if (!rpc_stat) {
8468 rc = -1;
8469 goto fail;
8470 }
8471
8472 /*
8473 * Increment the stats for this function
8474 */
8475
8476 rpc_stat->stats[currentFunc].invocations++;
8477 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8478 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8479 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8480 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8481 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8482 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8483 }
8484 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8485 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8486 }
8487 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8488 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8489 execTime);
8490 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8491 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8492 }
8493 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8494 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8495 }
8496
8497 fail:
8498 return rc;
8499 }
8500
8501 void
8502 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8503 afs_uint32 currentFunc, afs_uint32 totalFunc,
8504 struct clock *queueTime, struct clock *execTime,
8505 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8506 int isServer)
8507 {
8508
8509 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8510 return;
8511
8512 MUTEX_ENTER(&rx_rpc_stats);
8513
8514 if (rxi_monitor_peerStats) {
8515 MUTEX_ENTER(&peer->peer_lock);
8516 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8517 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8518 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8519 MUTEX_EXIT(&peer->peer_lock);
8520 }
8521
8522 if (rxi_monitor_processStats) {
8523 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8524 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8525 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8526 }
8527
8528 MUTEX_EXIT(&rx_rpc_stats);
8529 }
8530
8531 /*!
8532 * Increment the times and count for a particular rpc function.
8533 *
8534 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8535 * call rx_RecordCallStatistics instead, so the public version of this
8536 * function is left purely for legacy callers.
8537 *
8538 * @param peer
8539 * The peer who invoked the rpc
8540 *
8541 * @param rxInterface
8542 * A unique number that identifies the rpc interface
8543 *
8544 * @param currentFunc
8545 * The index of the function being invoked
8546 *
8547 * @param totalFunc
8548 * The total number of functions in this interface
8549 *
8550 * @param queueTime
8551 * The amount of time this function waited for a thread
8552 *
8553 * @param execTime
8554 * The amount of time this function invocation took to execute
8555 *
8556 * @param bytesSent
8557 * The number bytes sent by this invocation
8558 *
8559 * @param bytesRcvd
8560 * The number bytes received by this invocation
8561 *
8562 * @param isServer
8563 * If true, this invocation was made to a server
8564 *
8565 */
8566 void
8567 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8568 afs_uint32 currentFunc, afs_uint32 totalFunc,
8569 struct clock *queueTime, struct clock *execTime,
8570 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8571 int isServer)
8572 {
8573 afs_uint64 sent64;
8574 afs_uint64 rcvd64;
8575
8576 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8577 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8578
8579 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8580 queueTime, execTime, sent64, rcvd64,
8581 isServer);
8582 }
8583
8584
8585
8586 /*
8587 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8588 *
8589 * PARAMETERS
8590 *
8591 * IN callerVersion - the rpc stat version of the caller.
8592 *
8593 * IN count - the number of entries to marshall.
8594 *
8595 * IN stats - pointer to stats to be marshalled.
8596 *
8597 * OUT ptr - Where to store the marshalled data.
8598 *
8599 * RETURN CODES
8600 *
8601 * Returns void.
8602 */
8603 void
8604 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8605 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8606 {
8607 int i;
8608 afs_uint32 *ptr;
8609
8610 /*
8611 * We only support the first version
8612 */
8613 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8614 *(ptr++) = stats->remote_peer;
8615 *(ptr++) = stats->remote_port;
8616 *(ptr++) = stats->remote_is_server;
8617 *(ptr++) = stats->interfaceId;
8618 *(ptr++) = stats->func_total;
8619 *(ptr++) = stats->func_index;
8620 *(ptr++) = stats->invocations >> 32;
8621 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8622 *(ptr++) = stats->bytes_sent >> 32;
8623 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8624 *(ptr++) = stats->bytes_rcvd >> 32;
8625 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8626 *(ptr++) = stats->queue_time_sum.sec;
8627 *(ptr++) = stats->queue_time_sum.usec;
8628 *(ptr++) = stats->queue_time_sum_sqr.sec;
8629 *(ptr++) = stats->queue_time_sum_sqr.usec;
8630 *(ptr++) = stats->queue_time_min.sec;
8631 *(ptr++) = stats->queue_time_min.usec;
8632 *(ptr++) = stats->queue_time_max.sec;
8633 *(ptr++) = stats->queue_time_max.usec;
8634 *(ptr++) = stats->execution_time_sum.sec;
8635 *(ptr++) = stats->execution_time_sum.usec;
8636 *(ptr++) = stats->execution_time_sum_sqr.sec;
8637 *(ptr++) = stats->execution_time_sum_sqr.usec;
8638 *(ptr++) = stats->execution_time_min.sec;
8639 *(ptr++) = stats->execution_time_min.usec;
8640 *(ptr++) = stats->execution_time_max.sec;
8641 *(ptr++) = stats->execution_time_max.usec;
8642 }
8643 *ptrP = ptr;
8644 }
8645
8646 /*
8647 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8648 * this process
8649 *
8650 * PARAMETERS
8651 *
8652 * IN callerVersion - the rpc stat version of the caller
8653 *
8654 * OUT myVersion - the rpc stat version of this function
8655 *
8656 * OUT clock_sec - local time seconds
8657 *
8658 * OUT clock_usec - local time microseconds
8659 *
8660 * OUT allocSize - the number of bytes allocated to contain stats
8661 *
8662 * OUT statCount - the number stats retrieved from this process.
8663 *
8664 * OUT stats - the actual stats retrieved from this process.
8665 *
8666 * RETURN CODES
8667 *
8668 * Returns void. If successful, stats will != NULL.
8669 */
8670
8671 int
8672 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8673 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8674 size_t * allocSize, afs_uint32 * statCount,
8675 afs_uint32 ** stats)
8676 {
8677 size_t space = 0;
8678 afs_uint32 *ptr;
8679 struct clock now;
8680 int rc = 0;
8681
8682 *stats = 0;
8683 *allocSize = 0;
8684 *statCount = 0;
8685 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8686
8687 /*
8688 * Check to see if stats are enabled
8689 */
8690
8691 MUTEX_ENTER(&rx_rpc_stats);
8692 if (!rxi_monitor_processStats) {
8693 MUTEX_EXIT(&rx_rpc_stats);
8694 return rc;
8695 }
8696
8697 clock_GetTime(&now);
8698 *clock_sec = now.sec;
8699 *clock_usec = now.usec;
8700
8701 /*
8702 * Allocate the space based upon the caller version
8703 *
8704 * If the client is at an older version than we are,
8705 * we return the statistic data in the older data format, but
8706 * we still return our version number so the client knows we
8707 * are maintaining more data than it can retrieve.
8708 */
8709
8710 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8711 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8712 *statCount = rxi_rpc_process_stat_cnt;
8713 } else {
8714 /*
8715 * This can't happen yet, but in the future version changes
8716 * can be handled by adding additional code here
8717 */
8718 }
8719
8720 if (space > (size_t) 0) {
8721 *allocSize = space;
8722 ptr = *stats = rxi_Alloc(space);
8723
8724 if (ptr != NULL) {
8725 struct opr_queue *cursor;
8726
8727 for (opr_queue_Scan(&processStats, cursor)) {
8728 struct rx_interface_stat *rpc_stat =
8729 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8730 /*
8731 * Copy the data based upon the caller version
8732 */
8733 rx_MarshallProcessRPCStats(callerVersion,
8734 rpc_stat->stats[0].func_total,
8735 rpc_stat->stats, &ptr);
8736 }
8737 } else {
8738 rc = ENOMEM;
8739 }
8740 }
8741 MUTEX_EXIT(&rx_rpc_stats);
8742 return rc;
8743 }
8744
8745 /*
8746 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8747 *
8748 * PARAMETERS
8749 *
8750 * IN callerVersion - the rpc stat version of the caller
8751 *
8752 * OUT myVersion - the rpc stat version of this function
8753 *
8754 * OUT clock_sec - local time seconds
8755 *
8756 * OUT clock_usec - local time microseconds
8757 *
8758 * OUT allocSize - the number of bytes allocated to contain stats
8759 *
8760 * OUT statCount - the number of stats retrieved from the individual
8761 * peer structures.
8762 *
8763 * OUT stats - the actual stats retrieved from the individual peer structures.
8764 *
8765 * RETURN CODES
8766 *
8767 * Returns void. If successful, stats will != NULL.
8768 */
8769
8770 int
8771 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8772 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8773 size_t * allocSize, afs_uint32 * statCount,
8774 afs_uint32 ** stats)
8775 {
8776 size_t space = 0;
8777 afs_uint32 *ptr;
8778 struct clock now;
8779 int rc = 0;
8780
8781 *stats = 0;
8782 *statCount = 0;
8783 *allocSize = 0;
8784 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8785
8786 /*
8787 * Check to see if stats are enabled
8788 */
8789
8790 MUTEX_ENTER(&rx_rpc_stats);
8791 if (!rxi_monitor_peerStats) {
8792 MUTEX_EXIT(&rx_rpc_stats);
8793 return rc;
8794 }
8795
8796 clock_GetTime(&now);
8797 *clock_sec = now.sec;
8798 *clock_usec = now.usec;
8799
8800 /*
8801 * Allocate the space based upon the caller version
8802 *
8803 * If the client is at an older version than we are,
8804 * we return the statistic data in the older data format, but
8805 * we still return our version number so the client knows we
8806 * are maintaining more data than it can retrieve.
8807 */
8808
8809 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8810 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8811 *statCount = rxi_rpc_peer_stat_cnt;
8812 } else {
8813 /*
8814 * This can't happen yet, but in the future version changes
8815 * can be handled by adding additional code here
8816 */
8817 }
8818
8819 if (space > (size_t) 0) {
8820 *allocSize = space;
8821 ptr = *stats = rxi_Alloc(space);
8822
8823 if (ptr != NULL) {
8824 struct opr_queue *cursor;
8825
8826 for (opr_queue_Scan(&peerStats, cursor)) {
8827 struct rx_interface_stat *rpc_stat
8828 = opr_queue_Entry(cursor, struct rx_interface_stat,
8829 entryPeers);
8830
8831 /*
8832 * Copy the data based upon the caller version
8833 */
8834 rx_MarshallProcessRPCStats(callerVersion,
8835 rpc_stat->stats[0].func_total,
8836 rpc_stat->stats, &ptr);
8837 }
8838 } else {
8839 rc = ENOMEM;
8840 }
8841 }
8842 MUTEX_EXIT(&rx_rpc_stats);
8843 return rc;
8844 }
8845
8846 /*
8847 * rx_FreeRPCStats - free memory allocated by
8848 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8849 *
8850 * PARAMETERS
8851 *
8852 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8853 * rx_RetrievePeerRPCStats
8854 *
8855 * IN allocSize - the number of bytes in stats.
8856 *
8857 * RETURN CODES
8858 *
8859 * Returns void.
8860 */
8861
8862 void
8863 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8864 {
8865 rxi_Free(stats, allocSize);
8866 }
8867
8868 /*
8869 * rx_queryProcessRPCStats - see if process rpc stat collection is
8870 * currently enabled.
8871 *
8872 * PARAMETERS
8873 *
8874 * RETURN CODES
8875 *
8876 * Returns 0 if stats are not enabled != 0 otherwise
8877 */
8878
8879 int
8880 rx_queryProcessRPCStats(void)
8881 {
8882 int rc;
8883 MUTEX_ENTER(&rx_rpc_stats);
8884 rc = rxi_monitor_processStats;
8885 MUTEX_EXIT(&rx_rpc_stats);
8886 return rc;
8887 }
8888
8889 /*
8890 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8891 *
8892 * PARAMETERS
8893 *
8894 * RETURN CODES
8895 *
8896 * Returns 0 if stats are not enabled != 0 otherwise
8897 */
8898
8899 int
8900 rx_queryPeerRPCStats(void)
8901 {
8902 int rc;
8903 MUTEX_ENTER(&rx_rpc_stats);
8904 rc = rxi_monitor_peerStats;
8905 MUTEX_EXIT(&rx_rpc_stats);
8906 return rc;
8907 }
8908
8909 /*
8910 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8911 *
8912 * PARAMETERS
8913 *
8914 * RETURN CODES
8915 *
8916 * Returns void.
8917 */
8918
8919 void
8920 rx_enableProcessRPCStats(void)
8921 {
8922 MUTEX_ENTER(&rx_rpc_stats);
8923 rx_enable_stats = 1;
8924 rxi_monitor_processStats = 1;
8925 MUTEX_EXIT(&rx_rpc_stats);
8926 }
8927
8928 /*
8929 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8930 *
8931 * PARAMETERS
8932 *
8933 * RETURN CODES
8934 *
8935 * Returns void.
8936 */
8937
8938 void
8939 rx_enablePeerRPCStats(void)
8940 {
8941 MUTEX_ENTER(&rx_rpc_stats);
8942 rx_enable_stats = 1;
8943 rxi_monitor_peerStats = 1;
8944 MUTEX_EXIT(&rx_rpc_stats);
8945 }
8946
8947 /*
8948 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8949 *
8950 * PARAMETERS
8951 *
8952 * RETURN CODES
8953 *
8954 * Returns void.
8955 */
8956
8957 void
8958 rx_disableProcessRPCStats(void)
8959 {
8960 struct opr_queue *cursor, *store;
8961 size_t space;
8962
8963 MUTEX_ENTER(&rx_rpc_stats);
8964
8965 /*
8966 * Turn off process statistics and if peer stats is also off, turn
8967 * off everything
8968 */
8969
8970 rxi_monitor_processStats = 0;
8971 if (rxi_monitor_peerStats == 0) {
8972 rx_enable_stats = 0;
8973 }
8974
8975 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
8976 unsigned int num_funcs = 0;
8977 struct rx_interface_stat *rpc_stat
8978 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8979
8980 opr_queue_Remove(&rpc_stat->entry);
8981
8982 num_funcs = rpc_stat->stats[0].func_total;
8983 space =
8984 sizeof(rx_interface_stat_t) +
8985 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8986
8987 rxi_Free(rpc_stat, space);
8988 rxi_rpc_process_stat_cnt -= num_funcs;
8989 }
8990 MUTEX_EXIT(&rx_rpc_stats);
8991 }
8992
8993 /*
8994 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8995 *
8996 * PARAMETERS
8997 *
8998 * RETURN CODES
8999 *
9000 * Returns void.
9001 */
9002
9003 void
9004 rx_disablePeerRPCStats(void)
9005 {
9006 struct rx_peer **peer_ptr, **peer_end;
9007 int code;
9008
9009 /*
9010 * Turn off peer statistics and if process stats is also off, turn
9011 * off everything
9012 */
9013
9014 rxi_monitor_peerStats = 0;
9015 if (rxi_monitor_processStats == 0) {
9016 rx_enable_stats = 0;
9017 }
9018
9019 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9020 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9021 peer_ptr++) {
9022 struct rx_peer *peer, *next, *prev;
9023
9024 MUTEX_ENTER(&rx_peerHashTable_lock);
9025 MUTEX_ENTER(&rx_rpc_stats);
9026 for (prev = peer = *peer_ptr; peer; peer = next) {
9027 next = peer->next;
9028 code = MUTEX_TRYENTER(&peer->peer_lock);
9029 if (code) {
9030 size_t space;
9031 struct opr_queue *cursor, *store;
9032
9033 if (prev == *peer_ptr) {
9034 *peer_ptr = next;
9035 prev = next;
9036 } else
9037 prev->next = next;
9038
9039 if (next)
9040 next->refCount++;
9041 if (prev)
9042 prev->refCount++;
9043 peer->refCount++;
9044 MUTEX_EXIT(&rx_peerHashTable_lock);
9045
9046 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9047 unsigned int num_funcs = 0;
9048 struct rx_interface_stat *rpc_stat
9049 = opr_queue_Entry(cursor, struct rx_interface_stat,
9050 entry);
9051
9052 opr_queue_Remove(&rpc_stat->entry);
9053 opr_queue_Remove(&rpc_stat->entryPeers);
9054 num_funcs = rpc_stat->stats[0].func_total;
9055 space =
9056 sizeof(rx_interface_stat_t) +
9057 rpc_stat->stats[0].func_total *
9058 sizeof(rx_function_entry_v1_t);
9059
9060 rxi_Free(rpc_stat, space);
9061 rxi_rpc_peer_stat_cnt -= num_funcs;
9062 }
9063 MUTEX_EXIT(&peer->peer_lock);
9064
9065 MUTEX_ENTER(&rx_peerHashTable_lock);
9066 if (next)
9067 next->refCount--;
9068 if (prev)
9069 prev->refCount--;
9070 peer->refCount--;
9071 } else {
9072 prev = peer;
9073 }
9074 }
9075 MUTEX_EXIT(&rx_rpc_stats);
9076 MUTEX_EXIT(&rx_peerHashTable_lock);
9077 }
9078 }
9079
9080 /*
9081 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9082 * to clearFlag
9083 *
9084 * PARAMETERS
9085 *
9086 * IN clearFlag - flag indicating which stats to clear
9087 *
9088 * RETURN CODES
9089 *
9090 * Returns void.
9091 */
9092
9093 void
9094 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9095 {
9096 struct opr_queue *cursor;
9097
9098 MUTEX_ENTER(&rx_rpc_stats);
9099
9100 for (opr_queue_Scan(&processStats, cursor)) {
9101 unsigned int num_funcs = 0, i;
9102 struct rx_interface_stat *rpc_stat
9103 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9104
9105 num_funcs = rpc_stat->stats[0].func_total;
9106 for (i = 0; i < num_funcs; i++) {
9107 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9108 rpc_stat->stats[i].invocations = 0;
9109 }
9110 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9111 rpc_stat->stats[i].bytes_sent = 0;
9112 }
9113 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9114 rpc_stat->stats[i].bytes_rcvd = 0;
9115 }
9116 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9117 rpc_stat->stats[i].queue_time_sum.sec = 0;
9118 rpc_stat->stats[i].queue_time_sum.usec = 0;
9119 }
9120 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9121 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9122 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9123 }
9124 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9125 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9126 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9127 }
9128 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9129 rpc_stat->stats[i].queue_time_max.sec = 0;
9130 rpc_stat->stats[i].queue_time_max.usec = 0;
9131 }
9132 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9133 rpc_stat->stats[i].execution_time_sum.sec = 0;
9134 rpc_stat->stats[i].execution_time_sum.usec = 0;
9135 }
9136 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9137 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9138 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9139 }
9140 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9141 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9142 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9143 }
9144 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9145 rpc_stat->stats[i].execution_time_max.sec = 0;
9146 rpc_stat->stats[i].execution_time_max.usec = 0;
9147 }
9148 }
9149 }
9150
9151 MUTEX_EXIT(&rx_rpc_stats);
9152 }
9153
9154 /*
9155 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9156 * to clearFlag
9157 *
9158 * PARAMETERS
9159 *
9160 * IN clearFlag - flag indicating which stats to clear
9161 *
9162 * RETURN CODES
9163 *
9164 * Returns void.
9165 */
9166
9167 void
9168 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9169 {
9170 struct opr_queue *cursor;
9171
9172 MUTEX_ENTER(&rx_rpc_stats);
9173
9174 for (opr_queue_Scan(&peerStats, cursor)) {
9175 unsigned int num_funcs, i;
9176 struct rx_interface_stat *rpc_stat
9177 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9178
9179 num_funcs = rpc_stat->stats[0].func_total;
9180 for (i = 0; i < num_funcs; i++) {
9181 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9182 rpc_stat->stats[i].invocations = 0;
9183 }
9184 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9185 rpc_stat->stats[i].bytes_sent = 0;
9186 }
9187 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9188 rpc_stat->stats[i].bytes_rcvd = 0;
9189 }
9190 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9191 rpc_stat->stats[i].queue_time_sum.sec = 0;
9192 rpc_stat->stats[i].queue_time_sum.usec = 0;
9193 }
9194 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9195 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9196 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9197 }
9198 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9199 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9200 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9201 }
9202 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9203 rpc_stat->stats[i].queue_time_max.sec = 0;
9204 rpc_stat->stats[i].queue_time_max.usec = 0;
9205 }
9206 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9207 rpc_stat->stats[i].execution_time_sum.sec = 0;
9208 rpc_stat->stats[i].execution_time_sum.usec = 0;
9209 }
9210 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9211 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9212 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9213 }
9214 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9215 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9216 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9217 }
9218 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9219 rpc_stat->stats[i].execution_time_max.sec = 0;
9220 rpc_stat->stats[i].execution_time_max.usec = 0;
9221 }
9222 }
9223 }
9224
9225 MUTEX_EXIT(&rx_rpc_stats);
9226 }
9227
9228 /*
9229 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9230 * is authorized to enable/disable/clear RX statistics.
9231 */
9232 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9233
9234 void
9235 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9236 {
9237 rxi_rxstat_userok = proc;
9238 }
9239
9240 int
9241 rx_RxStatUserOk(struct rx_call *call)
9242 {
9243 if (!rxi_rxstat_userok)
9244 return 0;
9245 return rxi_rxstat_userok(call);
9246 }
9247
9248 #ifdef AFS_NT40_ENV
9249 /*
9250 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9251 * function in the MSVC runtime DLL (msvcrt.dll).
9252 *
9253 * Note: the system serializes calls to this function.
9254 */
9255 BOOL WINAPI
9256 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9257 DWORD reason, /* reason function is being called */
9258 LPVOID reserved) /* reserved for future use */
9259 {
9260 switch (reason) {
9261 case DLL_PROCESS_ATTACH:
9262 /* library is being attached to a process */
9263 INIT_PTHREAD_LOCKS;
9264 return TRUE;
9265
9266 case DLL_PROCESS_DETACH:
9267 return TRUE;
9268
9269 default:
9270 return FALSE;
9271 }
9272 }
9273 #endif /* AFS_NT40_ENV */
9274
9275 #ifndef KERNEL
9276 int rx_DumpCalls(FILE *outputFile, char *cookie)
9277 {
9278 #ifdef RXDEBUG_PACKET
9279 #ifdef KDUMP_RX_LOCK
9280 struct rx_call_rx_lock *c;
9281 #else
9282 struct rx_call *c;
9283 #endif
9284 #ifdef AFS_NT40_ENV
9285 int zilch;
9286 char output[2048];
9287 #define RXDPRINTF sprintf
9288 #define RXDPRINTOUT output
9289 #else
9290 #define RXDPRINTF fprintf
9291 #define RXDPRINTOUT outputFile
9292 #endif
9293
9294 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9295 #ifdef AFS_NT40_ENV
9296 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9297 #endif
9298
9299 for (c = rx_allCallsp; c; c = c->allNextp) {
9300 u_short rqc, tqc, iovqc;
9301
9302 MUTEX_ENTER(&c->lock);
9303 rqc = opr_queue_Count(&c->rq);
9304 tqc = opr_queue_Count(&c->tq);
9305 iovqc = opr_queue_Count(&c->app.iovq);
9306
9307 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, "
9308 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9309 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9310 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9311 "lastSendTime=%u, lastRecvTime=%u"
9312 #ifdef RX_ENABLE_LOCKS
9313 ", refCount=%u"
9314 #endif
9315 #ifdef RX_REFCOUNT_CHECK
9316 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9317 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9318 #endif
9319 "\r\n",
9320 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,
9321 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9322 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9323 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9324 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9325 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9326 #ifdef RX_ENABLE_LOCKS
9327 , (afs_uint32)c->refCount
9328 #endif
9329 #ifdef RX_REFCOUNT_CHECK
9330 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9331 #endif
9332 );
9333 MUTEX_EXIT(&c->lock);
9334
9335 #ifdef AFS_NT40_ENV
9336 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9337 #endif
9338 }
9339 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9340 #ifdef AFS_NT40_ENV
9341 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9342 #endif
9343 #endif /* RXDEBUG_PACKET */
9344 return 0;
9345 }
9346 #endif