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