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