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