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