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