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