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