xref: /linux/net/rxrpc/conn_client.c (revision 320fefa9e2edc67011e235ea1d50f0d00ddfe004)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Client connection-specific management code.
3  *
4  * Copyright (C) 2016, 2020 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  *
7  * Client connections need to be cached for a little while after they've made a
8  * call so as to handle retransmitted DATA packets in case the server didn't
9  * receive the final ACK or terminating ABORT we sent it.
10  *
11  * There are flags of relevance to the cache:
12  *
13  *  (2) DONT_REUSE - The connection should be discarded as soon as possible and
14  *      should not be reused.  This is set when an exclusive connection is used
15  *      or a call ID counter overflows.
16  *
17  * The caching state may only be changed if the cache lock is held.
18  *
19  * There are two idle client connection expiry durations.  If the total number
20  * of connections is below the reap threshold, we use the normal duration; if
21  * it's above, we use the fast duration.
22  */
23 
24 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
25 
26 #include <linux/slab.h>
27 #include <linux/idr.h>
28 #include <linux/timer.h>
29 #include <linux/sched/signal.h>
30 
31 #include "ar-internal.h"
32 
33 __read_mostly unsigned int rxrpc_reap_client_connections = 900;
34 __read_mostly unsigned long rxrpc_conn_idle_client_expiry = 2 * 60 * HZ;
35 __read_mostly unsigned long rxrpc_conn_idle_client_fast_expiry = 2 * HZ;
36 
37 /*
38  * We use machine-unique IDs for our client connections.
39  */
40 DEFINE_IDR(rxrpc_client_conn_ids);
41 static DEFINE_SPINLOCK(rxrpc_conn_id_lock);
42 
43 static void rxrpc_deactivate_bundle(struct rxrpc_bundle *bundle);
44 
45 /*
46  * Get a connection ID and epoch for a client connection from the global pool.
47  * The connection struct pointer is then recorded in the idr radix tree.  The
48  * epoch doesn't change until the client is rebooted (or, at least, unless the
49  * module is unloaded).
50  */
51 static int rxrpc_get_client_connection_id(struct rxrpc_connection *conn,
52 					  gfp_t gfp)
53 {
54 	struct rxrpc_net *rxnet = conn->params.local->rxnet;
55 	int id;
56 
57 	_enter("");
58 
59 	idr_preload(gfp);
60 	spin_lock(&rxrpc_conn_id_lock);
61 
62 	id = idr_alloc_cyclic(&rxrpc_client_conn_ids, conn,
63 			      1, 0x40000000, GFP_NOWAIT);
64 	if (id < 0)
65 		goto error;
66 
67 	spin_unlock(&rxrpc_conn_id_lock);
68 	idr_preload_end();
69 
70 	conn->proto.epoch = rxnet->epoch;
71 	conn->proto.cid = id << RXRPC_CIDSHIFT;
72 	set_bit(RXRPC_CONN_HAS_IDR, &conn->flags);
73 	_leave(" [CID %x]", conn->proto.cid);
74 	return 0;
75 
76 error:
77 	spin_unlock(&rxrpc_conn_id_lock);
78 	idr_preload_end();
79 	_leave(" = %d", id);
80 	return id;
81 }
82 
83 /*
84  * Release a connection ID for a client connection from the global pool.
85  */
86 static void rxrpc_put_client_connection_id(struct rxrpc_connection *conn)
87 {
88 	if (test_bit(RXRPC_CONN_HAS_IDR, &conn->flags)) {
89 		spin_lock(&rxrpc_conn_id_lock);
90 		idr_remove(&rxrpc_client_conn_ids,
91 			   conn->proto.cid >> RXRPC_CIDSHIFT);
92 		spin_unlock(&rxrpc_conn_id_lock);
93 	}
94 }
95 
96 /*
97  * Destroy the client connection ID tree.
98  */
99 void rxrpc_destroy_client_conn_ids(void)
100 {
101 	struct rxrpc_connection *conn;
102 	int id;
103 
104 	if (!idr_is_empty(&rxrpc_client_conn_ids)) {
105 		idr_for_each_entry(&rxrpc_client_conn_ids, conn, id) {
106 			pr_err("AF_RXRPC: Leaked client conn %p {%d}\n",
107 			       conn, refcount_read(&conn->ref));
108 		}
109 		BUG();
110 	}
111 
112 	idr_destroy(&rxrpc_client_conn_ids);
113 }
114 
115 /*
116  * Allocate a connection bundle.
117  */
118 static struct rxrpc_bundle *rxrpc_alloc_bundle(struct rxrpc_conn_parameters *cp,
119 					       gfp_t gfp)
120 {
121 	struct rxrpc_bundle *bundle;
122 
123 	bundle = kzalloc(sizeof(*bundle), gfp);
124 	if (bundle) {
125 		bundle->params = *cp;
126 		rxrpc_get_peer(bundle->params.peer);
127 		refcount_set(&bundle->ref, 1);
128 		atomic_set(&bundle->active, 1);
129 		spin_lock_init(&bundle->channel_lock);
130 		INIT_LIST_HEAD(&bundle->waiting_calls);
131 	}
132 	return bundle;
133 }
134 
135 struct rxrpc_bundle *rxrpc_get_bundle(struct rxrpc_bundle *bundle)
136 {
137 	refcount_inc(&bundle->ref);
138 	return bundle;
139 }
140 
141 static void rxrpc_free_bundle(struct rxrpc_bundle *bundle)
142 {
143 	rxrpc_put_peer(bundle->params.peer);
144 	kfree(bundle);
145 }
146 
147 void rxrpc_put_bundle(struct rxrpc_bundle *bundle)
148 {
149 	unsigned int d = bundle->debug_id;
150 	bool dead;
151 	int r;
152 
153 	dead = __refcount_dec_and_test(&bundle->ref, &r);
154 
155 	_debug("PUT B=%x %d", d, r - 1);
156 	if (dead)
157 		rxrpc_free_bundle(bundle);
158 }
159 
160 /*
161  * Allocate a client connection.
162  */
163 static struct rxrpc_connection *
164 rxrpc_alloc_client_connection(struct rxrpc_bundle *bundle, gfp_t gfp)
165 {
166 	struct rxrpc_connection *conn;
167 	struct rxrpc_net *rxnet = bundle->params.local->rxnet;
168 	int ret;
169 
170 	_enter("");
171 
172 	conn = rxrpc_alloc_connection(gfp);
173 	if (!conn) {
174 		_leave(" = -ENOMEM");
175 		return ERR_PTR(-ENOMEM);
176 	}
177 
178 	refcount_set(&conn->ref, 1);
179 	conn->bundle		= bundle;
180 	conn->params		= bundle->params;
181 	conn->out_clientflag	= RXRPC_CLIENT_INITIATED;
182 	conn->state		= RXRPC_CONN_CLIENT;
183 	conn->service_id	= conn->params.service_id;
184 
185 	ret = rxrpc_get_client_connection_id(conn, gfp);
186 	if (ret < 0)
187 		goto error_0;
188 
189 	ret = rxrpc_init_client_conn_security(conn);
190 	if (ret < 0)
191 		goto error_1;
192 
193 	atomic_inc(&rxnet->nr_conns);
194 	write_lock(&rxnet->conn_lock);
195 	list_add_tail(&conn->proc_link, &rxnet->conn_proc_list);
196 	write_unlock(&rxnet->conn_lock);
197 
198 	rxrpc_get_bundle(bundle);
199 	rxrpc_get_peer(conn->params.peer);
200 	rxrpc_get_local(conn->params.local);
201 	key_get(conn->params.key);
202 
203 	trace_rxrpc_conn(conn->debug_id, rxrpc_conn_new_client,
204 			 refcount_read(&conn->ref),
205 			 __builtin_return_address(0));
206 
207 	atomic_inc(&rxnet->nr_client_conns);
208 	trace_rxrpc_client(conn, -1, rxrpc_client_alloc);
209 	_leave(" = %p", conn);
210 	return conn;
211 
212 error_1:
213 	rxrpc_put_client_connection_id(conn);
214 error_0:
215 	kfree(conn);
216 	_leave(" = %d", ret);
217 	return ERR_PTR(ret);
218 }
219 
220 /*
221  * Determine if a connection may be reused.
222  */
223 static bool rxrpc_may_reuse_conn(struct rxrpc_connection *conn)
224 {
225 	struct rxrpc_net *rxnet;
226 	int id_cursor, id, distance, limit;
227 
228 	if (!conn)
229 		goto dont_reuse;
230 
231 	rxnet = conn->params.local->rxnet;
232 	if (test_bit(RXRPC_CONN_DONT_REUSE, &conn->flags))
233 		goto dont_reuse;
234 
235 	if (conn->state != RXRPC_CONN_CLIENT ||
236 	    conn->proto.epoch != rxnet->epoch)
237 		goto mark_dont_reuse;
238 
239 	/* The IDR tree gets very expensive on memory if the connection IDs are
240 	 * widely scattered throughout the number space, so we shall want to
241 	 * kill off connections that, say, have an ID more than about four
242 	 * times the maximum number of client conns away from the current
243 	 * allocation point to try and keep the IDs concentrated.
244 	 */
245 	id_cursor = idr_get_cursor(&rxrpc_client_conn_ids);
246 	id = conn->proto.cid >> RXRPC_CIDSHIFT;
247 	distance = id - id_cursor;
248 	if (distance < 0)
249 		distance = -distance;
250 	limit = max_t(unsigned long, atomic_read(&rxnet->nr_conns) * 4, 1024);
251 	if (distance > limit)
252 		goto mark_dont_reuse;
253 
254 	return true;
255 
256 mark_dont_reuse:
257 	set_bit(RXRPC_CONN_DONT_REUSE, &conn->flags);
258 dont_reuse:
259 	return false;
260 }
261 
262 /*
263  * Look up the conn bundle that matches the connection parameters, adding it if
264  * it doesn't yet exist.
265  */
266 static struct rxrpc_bundle *rxrpc_look_up_bundle(struct rxrpc_conn_parameters *cp,
267 						 gfp_t gfp)
268 {
269 	static atomic_t rxrpc_bundle_id;
270 	struct rxrpc_bundle *bundle, *candidate;
271 	struct rxrpc_local *local = cp->local;
272 	struct rb_node *p, **pp, *parent;
273 	long diff;
274 
275 	_enter("{%px,%x,%u,%u}",
276 	       cp->peer, key_serial(cp->key), cp->security_level, cp->upgrade);
277 
278 	if (cp->exclusive)
279 		return rxrpc_alloc_bundle(cp, gfp);
280 
281 	/* First, see if the bundle is already there. */
282 	_debug("search 1");
283 	spin_lock(&local->client_bundles_lock);
284 	p = local->client_bundles.rb_node;
285 	while (p) {
286 		bundle = rb_entry(p, struct rxrpc_bundle, local_node);
287 
288 #define cmp(X) ((long)bundle->params.X - (long)cp->X)
289 		diff = (cmp(peer) ?:
290 			cmp(key) ?:
291 			cmp(security_level) ?:
292 			cmp(upgrade));
293 #undef cmp
294 		if (diff < 0)
295 			p = p->rb_left;
296 		else if (diff > 0)
297 			p = p->rb_right;
298 		else
299 			goto found_bundle;
300 	}
301 	spin_unlock(&local->client_bundles_lock);
302 	_debug("not found");
303 
304 	/* It wasn't.  We need to add one. */
305 	candidate = rxrpc_alloc_bundle(cp, gfp);
306 	if (!candidate)
307 		return NULL;
308 
309 	_debug("search 2");
310 	spin_lock(&local->client_bundles_lock);
311 	pp = &local->client_bundles.rb_node;
312 	parent = NULL;
313 	while (*pp) {
314 		parent = *pp;
315 		bundle = rb_entry(parent, struct rxrpc_bundle, local_node);
316 
317 #define cmp(X) ((long)bundle->params.X - (long)cp->X)
318 		diff = (cmp(peer) ?:
319 			cmp(key) ?:
320 			cmp(security_level) ?:
321 			cmp(upgrade));
322 #undef cmp
323 		if (diff < 0)
324 			pp = &(*pp)->rb_left;
325 		else if (diff > 0)
326 			pp = &(*pp)->rb_right;
327 		else
328 			goto found_bundle_free;
329 	}
330 
331 	_debug("new bundle");
332 	candidate->debug_id = atomic_inc_return(&rxrpc_bundle_id);
333 	rb_link_node(&candidate->local_node, parent, pp);
334 	rb_insert_color(&candidate->local_node, &local->client_bundles);
335 	rxrpc_get_bundle(candidate);
336 	spin_unlock(&local->client_bundles_lock);
337 	_leave(" = %u [new]", candidate->debug_id);
338 	return candidate;
339 
340 found_bundle_free:
341 	rxrpc_free_bundle(candidate);
342 found_bundle:
343 	rxrpc_get_bundle(bundle);
344 	atomic_inc(&bundle->active);
345 	spin_unlock(&local->client_bundles_lock);
346 	_leave(" = %u [found]", bundle->debug_id);
347 	return bundle;
348 }
349 
350 /*
351  * Create or find a client bundle to use for a call.
352  *
353  * If we return with a connection, the call will be on its waiting list.  It's
354  * left to the caller to assign a channel and wake up the call.
355  */
356 static struct rxrpc_bundle *rxrpc_prep_call(struct rxrpc_sock *rx,
357 					    struct rxrpc_call *call,
358 					    struct rxrpc_conn_parameters *cp,
359 					    struct sockaddr_rxrpc *srx,
360 					    gfp_t gfp)
361 {
362 	struct rxrpc_bundle *bundle;
363 
364 	_enter("{%d,%lx},", call->debug_id, call->user_call_ID);
365 
366 	cp->peer = rxrpc_lookup_peer(rx, cp->local, srx, gfp);
367 	if (!cp->peer)
368 		goto error;
369 
370 	call->tx_last_sent = ktime_get_real();
371 	call->cong_ssthresh = cp->peer->cong_ssthresh;
372 	if (call->cong_cwnd >= call->cong_ssthresh)
373 		call->cong_mode = RXRPC_CALL_CONGEST_AVOIDANCE;
374 	else
375 		call->cong_mode = RXRPC_CALL_SLOW_START;
376 	if (cp->upgrade)
377 		__set_bit(RXRPC_CALL_UPGRADE, &call->flags);
378 
379 	/* Find the client connection bundle. */
380 	bundle = rxrpc_look_up_bundle(cp, gfp);
381 	if (!bundle)
382 		goto error;
383 
384 	/* Get this call queued.  Someone else may activate it whilst we're
385 	 * lining up a new connection, but that's fine.
386 	 */
387 	spin_lock(&bundle->channel_lock);
388 	list_add_tail(&call->chan_wait_link, &bundle->waiting_calls);
389 	spin_unlock(&bundle->channel_lock);
390 
391 	_leave(" = [B=%x]", bundle->debug_id);
392 	return bundle;
393 
394 error:
395 	_leave(" = -ENOMEM");
396 	return ERR_PTR(-ENOMEM);
397 }
398 
399 /*
400  * Allocate a new connection and add it into a bundle.
401  */
402 static void rxrpc_add_conn_to_bundle(struct rxrpc_bundle *bundle, gfp_t gfp)
403 	__releases(bundle->channel_lock)
404 {
405 	struct rxrpc_connection *candidate = NULL, *old = NULL;
406 	bool conflict;
407 	int i;
408 
409 	_enter("");
410 
411 	conflict = bundle->alloc_conn;
412 	if (!conflict)
413 		bundle->alloc_conn = true;
414 	spin_unlock(&bundle->channel_lock);
415 	if (conflict) {
416 		_leave(" [conf]");
417 		return;
418 	}
419 
420 	candidate = rxrpc_alloc_client_connection(bundle, gfp);
421 
422 	spin_lock(&bundle->channel_lock);
423 	bundle->alloc_conn = false;
424 
425 	if (IS_ERR(candidate)) {
426 		bundle->alloc_error = PTR_ERR(candidate);
427 		spin_unlock(&bundle->channel_lock);
428 		_leave(" [err %ld]", PTR_ERR(candidate));
429 		return;
430 	}
431 
432 	bundle->alloc_error = 0;
433 
434 	for (i = 0; i < ARRAY_SIZE(bundle->conns); i++) {
435 		unsigned int shift = i * RXRPC_MAXCALLS;
436 		int j;
437 
438 		old = bundle->conns[i];
439 		if (!rxrpc_may_reuse_conn(old)) {
440 			if (old)
441 				trace_rxrpc_client(old, -1, rxrpc_client_replace);
442 			candidate->bundle_shift = shift;
443 			atomic_inc(&bundle->active);
444 			bundle->conns[i] = candidate;
445 			for (j = 0; j < RXRPC_MAXCALLS; j++)
446 				set_bit(shift + j, &bundle->avail_chans);
447 			candidate = NULL;
448 			break;
449 		}
450 
451 		old = NULL;
452 	}
453 
454 	spin_unlock(&bundle->channel_lock);
455 
456 	if (candidate) {
457 		_debug("discard C=%x", candidate->debug_id);
458 		trace_rxrpc_client(candidate, -1, rxrpc_client_duplicate);
459 		rxrpc_put_connection(candidate);
460 	}
461 
462 	rxrpc_put_connection(old);
463 	_leave("");
464 }
465 
466 /*
467  * Add a connection to a bundle if there are no usable connections or we have
468  * connections waiting for extra capacity.
469  */
470 static void rxrpc_maybe_add_conn(struct rxrpc_bundle *bundle, gfp_t gfp)
471 {
472 	struct rxrpc_call *call;
473 	int i, usable;
474 
475 	_enter("");
476 
477 	spin_lock(&bundle->channel_lock);
478 
479 	/* See if there are any usable connections. */
480 	usable = 0;
481 	for (i = 0; i < ARRAY_SIZE(bundle->conns); i++)
482 		if (rxrpc_may_reuse_conn(bundle->conns[i]))
483 			usable++;
484 
485 	if (!usable && !list_empty(&bundle->waiting_calls)) {
486 		call = list_first_entry(&bundle->waiting_calls,
487 					struct rxrpc_call, chan_wait_link);
488 		if (test_bit(RXRPC_CALL_UPGRADE, &call->flags))
489 			bundle->try_upgrade = true;
490 	}
491 
492 	if (!usable)
493 		goto alloc_conn;
494 
495 	if (!bundle->avail_chans &&
496 	    !bundle->try_upgrade &&
497 	    !list_empty(&bundle->waiting_calls) &&
498 	    usable < ARRAY_SIZE(bundle->conns))
499 		goto alloc_conn;
500 
501 	spin_unlock(&bundle->channel_lock);
502 	_leave("");
503 	return;
504 
505 alloc_conn:
506 	return rxrpc_add_conn_to_bundle(bundle, gfp);
507 }
508 
509 /*
510  * Assign a channel to the call at the front of the queue and wake the call up.
511  * We don't increment the callNumber counter until this number has been exposed
512  * to the world.
513  */
514 static void rxrpc_activate_one_channel(struct rxrpc_connection *conn,
515 				       unsigned int channel)
516 {
517 	struct rxrpc_channel *chan = &conn->channels[channel];
518 	struct rxrpc_bundle *bundle = conn->bundle;
519 	struct rxrpc_call *call = list_entry(bundle->waiting_calls.next,
520 					     struct rxrpc_call, chan_wait_link);
521 	u32 call_id = chan->call_counter + 1;
522 
523 	_enter("C=%x,%u", conn->debug_id, channel);
524 
525 	trace_rxrpc_client(conn, channel, rxrpc_client_chan_activate);
526 
527 	/* Cancel the final ACK on the previous call if it hasn't been sent yet
528 	 * as the DATA packet will implicitly ACK it.
529 	 */
530 	clear_bit(RXRPC_CONN_FINAL_ACK_0 + channel, &conn->flags);
531 	clear_bit(conn->bundle_shift + channel, &bundle->avail_chans);
532 
533 	rxrpc_see_call(call);
534 	list_del_init(&call->chan_wait_link);
535 	call->peer	= rxrpc_get_peer(conn->params.peer);
536 	call->conn	= rxrpc_get_connection(conn);
537 	call->cid	= conn->proto.cid | channel;
538 	call->call_id	= call_id;
539 	call->security	= conn->security;
540 	call->security_ix = conn->security_ix;
541 	call->service_id = conn->service_id;
542 
543 	trace_rxrpc_connect_call(call);
544 	_net("CONNECT call %08x:%08x as call %d on conn %d",
545 	     call->cid, call->call_id, call->debug_id, conn->debug_id);
546 
547 	write_lock_bh(&call->state_lock);
548 	call->state = RXRPC_CALL_CLIENT_SEND_REQUEST;
549 	write_unlock_bh(&call->state_lock);
550 
551 	/* Paired with the read barrier in rxrpc_connect_call().  This orders
552 	 * cid and epoch in the connection wrt to call_id without the need to
553 	 * take the channel_lock.
554 	 *
555 	 * We provisionally assign a callNumber at this point, but we don't
556 	 * confirm it until the call is about to be exposed.
557 	 *
558 	 * TODO: Pair with a barrier in the data_ready handler when that looks
559 	 * at the call ID through a connection channel.
560 	 */
561 	smp_wmb();
562 
563 	chan->call_id		= call_id;
564 	chan->call_debug_id	= call->debug_id;
565 	rcu_assign_pointer(chan->call, call);
566 	wake_up(&call->waitq);
567 }
568 
569 /*
570  * Remove a connection from the idle list if it's on it.
571  */
572 static void rxrpc_unidle_conn(struct rxrpc_bundle *bundle, struct rxrpc_connection *conn)
573 {
574 	struct rxrpc_net *rxnet = bundle->params.local->rxnet;
575 	bool drop_ref;
576 
577 	if (!list_empty(&conn->cache_link)) {
578 		drop_ref = false;
579 		spin_lock(&rxnet->client_conn_cache_lock);
580 		if (!list_empty(&conn->cache_link)) {
581 			list_del_init(&conn->cache_link);
582 			drop_ref = true;
583 		}
584 		spin_unlock(&rxnet->client_conn_cache_lock);
585 		if (drop_ref)
586 			rxrpc_put_connection(conn);
587 	}
588 }
589 
590 /*
591  * Assign channels and callNumbers to waiting calls with channel_lock
592  * held by caller.
593  */
594 static void rxrpc_activate_channels_locked(struct rxrpc_bundle *bundle)
595 {
596 	struct rxrpc_connection *conn;
597 	unsigned long avail, mask;
598 	unsigned int channel, slot;
599 
600 	if (bundle->try_upgrade)
601 		mask = 1;
602 	else
603 		mask = ULONG_MAX;
604 
605 	while (!list_empty(&bundle->waiting_calls)) {
606 		avail = bundle->avail_chans & mask;
607 		if (!avail)
608 			break;
609 		channel = __ffs(avail);
610 		clear_bit(channel, &bundle->avail_chans);
611 
612 		slot = channel / RXRPC_MAXCALLS;
613 		conn = bundle->conns[slot];
614 		if (!conn)
615 			break;
616 
617 		if (bundle->try_upgrade)
618 			set_bit(RXRPC_CONN_PROBING_FOR_UPGRADE, &conn->flags);
619 		rxrpc_unidle_conn(bundle, conn);
620 
621 		channel &= (RXRPC_MAXCALLS - 1);
622 		conn->act_chans	|= 1 << channel;
623 		rxrpc_activate_one_channel(conn, channel);
624 	}
625 }
626 
627 /*
628  * Assign channels and callNumbers to waiting calls.
629  */
630 static void rxrpc_activate_channels(struct rxrpc_bundle *bundle)
631 {
632 	_enter("B=%x", bundle->debug_id);
633 
634 	trace_rxrpc_client(NULL, -1, rxrpc_client_activate_chans);
635 
636 	if (!bundle->avail_chans)
637 		return;
638 
639 	spin_lock(&bundle->channel_lock);
640 	rxrpc_activate_channels_locked(bundle);
641 	spin_unlock(&bundle->channel_lock);
642 	_leave("");
643 }
644 
645 /*
646  * Wait for a callNumber and a channel to be granted to a call.
647  */
648 static int rxrpc_wait_for_channel(struct rxrpc_bundle *bundle,
649 				  struct rxrpc_call *call, gfp_t gfp)
650 {
651 	DECLARE_WAITQUEUE(myself, current);
652 	int ret = 0;
653 
654 	_enter("%d", call->debug_id);
655 
656 	if (!gfpflags_allow_blocking(gfp)) {
657 		rxrpc_maybe_add_conn(bundle, gfp);
658 		rxrpc_activate_channels(bundle);
659 		ret = bundle->alloc_error ?: -EAGAIN;
660 		goto out;
661 	}
662 
663 	add_wait_queue_exclusive(&call->waitq, &myself);
664 	for (;;) {
665 		rxrpc_maybe_add_conn(bundle, gfp);
666 		rxrpc_activate_channels(bundle);
667 		ret = bundle->alloc_error;
668 		if (ret < 0)
669 			break;
670 
671 		switch (call->interruptibility) {
672 		case RXRPC_INTERRUPTIBLE:
673 		case RXRPC_PREINTERRUPTIBLE:
674 			set_current_state(TASK_INTERRUPTIBLE);
675 			break;
676 		case RXRPC_UNINTERRUPTIBLE:
677 		default:
678 			set_current_state(TASK_UNINTERRUPTIBLE);
679 			break;
680 		}
681 		if (READ_ONCE(call->state) != RXRPC_CALL_CLIENT_AWAIT_CONN)
682 			break;
683 		if ((call->interruptibility == RXRPC_INTERRUPTIBLE ||
684 		     call->interruptibility == RXRPC_PREINTERRUPTIBLE) &&
685 		    signal_pending(current)) {
686 			ret = -ERESTARTSYS;
687 			break;
688 		}
689 		schedule();
690 	}
691 	remove_wait_queue(&call->waitq, &myself);
692 	__set_current_state(TASK_RUNNING);
693 
694 out:
695 	_leave(" = %d", ret);
696 	return ret;
697 }
698 
699 /*
700  * find a connection for a call
701  * - called in process context with IRQs enabled
702  */
703 int rxrpc_connect_call(struct rxrpc_sock *rx,
704 		       struct rxrpc_call *call,
705 		       struct rxrpc_conn_parameters *cp,
706 		       struct sockaddr_rxrpc *srx,
707 		       gfp_t gfp)
708 {
709 	struct rxrpc_bundle *bundle;
710 	struct rxrpc_net *rxnet = cp->local->rxnet;
711 	int ret = 0;
712 
713 	_enter("{%d,%lx},", call->debug_id, call->user_call_ID);
714 
715 	rxrpc_discard_expired_client_conns(&rxnet->client_conn_reaper);
716 
717 	bundle = rxrpc_prep_call(rx, call, cp, srx, gfp);
718 	if (IS_ERR(bundle)) {
719 		ret = PTR_ERR(bundle);
720 		goto out;
721 	}
722 
723 	if (call->state == RXRPC_CALL_CLIENT_AWAIT_CONN) {
724 		ret = rxrpc_wait_for_channel(bundle, call, gfp);
725 		if (ret < 0)
726 			goto wait_failed;
727 	}
728 
729 granted_channel:
730 	/* Paired with the write barrier in rxrpc_activate_one_channel(). */
731 	smp_rmb();
732 
733 out_put_bundle:
734 	rxrpc_deactivate_bundle(bundle);
735 	rxrpc_put_bundle(bundle);
736 out:
737 	_leave(" = %d", ret);
738 	return ret;
739 
740 wait_failed:
741 	spin_lock(&bundle->channel_lock);
742 	list_del_init(&call->chan_wait_link);
743 	spin_unlock(&bundle->channel_lock);
744 
745 	if (call->state != RXRPC_CALL_CLIENT_AWAIT_CONN) {
746 		ret = 0;
747 		goto granted_channel;
748 	}
749 
750 	trace_rxrpc_client(call->conn, ret, rxrpc_client_chan_wait_failed);
751 	rxrpc_set_call_completion(call, RXRPC_CALL_LOCAL_ERROR, 0, ret);
752 	rxrpc_disconnect_client_call(bundle, call);
753 	goto out_put_bundle;
754 }
755 
756 /*
757  * Note that a call, and thus a connection, is about to be exposed to the
758  * world.
759  */
760 void rxrpc_expose_client_call(struct rxrpc_call *call)
761 {
762 	unsigned int channel = call->cid & RXRPC_CHANNELMASK;
763 	struct rxrpc_connection *conn = call->conn;
764 	struct rxrpc_channel *chan = &conn->channels[channel];
765 
766 	if (!test_and_set_bit(RXRPC_CALL_EXPOSED, &call->flags)) {
767 		/* Mark the call ID as being used.  If the callNumber counter
768 		 * exceeds ~2 billion, we kill the connection after its
769 		 * outstanding calls have finished so that the counter doesn't
770 		 * wrap.
771 		 */
772 		chan->call_counter++;
773 		if (chan->call_counter >= INT_MAX)
774 			set_bit(RXRPC_CONN_DONT_REUSE, &conn->flags);
775 		trace_rxrpc_client(conn, channel, rxrpc_client_exposed);
776 	}
777 }
778 
779 /*
780  * Set the reap timer.
781  */
782 static void rxrpc_set_client_reap_timer(struct rxrpc_net *rxnet)
783 {
784 	if (!rxnet->kill_all_client_conns) {
785 		unsigned long now = jiffies;
786 		unsigned long reap_at = now + rxrpc_conn_idle_client_expiry;
787 
788 		if (rxnet->live)
789 			timer_reduce(&rxnet->client_conn_reap_timer, reap_at);
790 	}
791 }
792 
793 /*
794  * Disconnect a client call.
795  */
796 void rxrpc_disconnect_client_call(struct rxrpc_bundle *bundle, struct rxrpc_call *call)
797 {
798 	struct rxrpc_connection *conn;
799 	struct rxrpc_channel *chan = NULL;
800 	struct rxrpc_net *rxnet = bundle->params.local->rxnet;
801 	unsigned int channel;
802 	bool may_reuse;
803 	u32 cid;
804 
805 	_enter("c=%x", call->debug_id);
806 
807 	spin_lock(&bundle->channel_lock);
808 	set_bit(RXRPC_CALL_DISCONNECTED, &call->flags);
809 
810 	/* Calls that have never actually been assigned a channel can simply be
811 	 * discarded.
812 	 */
813 	conn = call->conn;
814 	if (!conn) {
815 		_debug("call is waiting");
816 		ASSERTCMP(call->call_id, ==, 0);
817 		ASSERT(!test_bit(RXRPC_CALL_EXPOSED, &call->flags));
818 		list_del_init(&call->chan_wait_link);
819 		goto out;
820 	}
821 
822 	cid = call->cid;
823 	channel = cid & RXRPC_CHANNELMASK;
824 	chan = &conn->channels[channel];
825 	trace_rxrpc_client(conn, channel, rxrpc_client_chan_disconnect);
826 
827 	if (rcu_access_pointer(chan->call) != call) {
828 		spin_unlock(&bundle->channel_lock);
829 		BUG();
830 	}
831 
832 	may_reuse = rxrpc_may_reuse_conn(conn);
833 
834 	/* If a client call was exposed to the world, we save the result for
835 	 * retransmission.
836 	 *
837 	 * We use a barrier here so that the call number and abort code can be
838 	 * read without needing to take a lock.
839 	 *
840 	 * TODO: Make the incoming packet handler check this and handle
841 	 * terminal retransmission without requiring access to the call.
842 	 */
843 	if (test_bit(RXRPC_CALL_EXPOSED, &call->flags)) {
844 		_debug("exposed %u,%u", call->call_id, call->abort_code);
845 		__rxrpc_disconnect_call(conn, call);
846 
847 		if (test_and_clear_bit(RXRPC_CONN_PROBING_FOR_UPGRADE, &conn->flags)) {
848 			trace_rxrpc_client(conn, channel, rxrpc_client_to_active);
849 			bundle->try_upgrade = false;
850 			if (may_reuse)
851 				rxrpc_activate_channels_locked(bundle);
852 		}
853 
854 	}
855 
856 	/* See if we can pass the channel directly to another call. */
857 	if (may_reuse && !list_empty(&bundle->waiting_calls)) {
858 		trace_rxrpc_client(conn, channel, rxrpc_client_chan_pass);
859 		rxrpc_activate_one_channel(conn, channel);
860 		goto out;
861 	}
862 
863 	/* Schedule the final ACK to be transmitted in a short while so that it
864 	 * can be skipped if we find a follow-on call.  The first DATA packet
865 	 * of the follow on call will implicitly ACK this call.
866 	 */
867 	if (call->completion == RXRPC_CALL_SUCCEEDED &&
868 	    test_bit(RXRPC_CALL_EXPOSED, &call->flags)) {
869 		unsigned long final_ack_at = jiffies + 2;
870 
871 		WRITE_ONCE(chan->final_ack_at, final_ack_at);
872 		smp_wmb(); /* vs rxrpc_process_delayed_final_acks() */
873 		set_bit(RXRPC_CONN_FINAL_ACK_0 + channel, &conn->flags);
874 		rxrpc_reduce_conn_timer(conn, final_ack_at);
875 	}
876 
877 	/* Deactivate the channel. */
878 	rcu_assign_pointer(chan->call, NULL);
879 	set_bit(conn->bundle_shift + channel, &conn->bundle->avail_chans);
880 	conn->act_chans	&= ~(1 << channel);
881 
882 	/* If no channels remain active, then put the connection on the idle
883 	 * list for a short while.  Give it a ref to stop it going away if it
884 	 * becomes unbundled.
885 	 */
886 	if (!conn->act_chans) {
887 		trace_rxrpc_client(conn, channel, rxrpc_client_to_idle);
888 		conn->idle_timestamp = jiffies;
889 
890 		rxrpc_get_connection(conn);
891 		spin_lock(&rxnet->client_conn_cache_lock);
892 		list_move_tail(&conn->cache_link, &rxnet->idle_client_conns);
893 		spin_unlock(&rxnet->client_conn_cache_lock);
894 
895 		rxrpc_set_client_reap_timer(rxnet);
896 	}
897 
898 out:
899 	spin_unlock(&bundle->channel_lock);
900 	_leave("");
901 	return;
902 }
903 
904 /*
905  * Remove a connection from a bundle.
906  */
907 static void rxrpc_unbundle_conn(struct rxrpc_connection *conn)
908 {
909 	struct rxrpc_bundle *bundle = conn->bundle;
910 	unsigned int bindex;
911 	bool need_drop = false;
912 	int i;
913 
914 	_enter("C=%x", conn->debug_id);
915 
916 	if (conn->flags & RXRPC_CONN_FINAL_ACK_MASK)
917 		rxrpc_process_delayed_final_acks(conn, true);
918 
919 	spin_lock(&bundle->channel_lock);
920 	bindex = conn->bundle_shift / RXRPC_MAXCALLS;
921 	if (bundle->conns[bindex] == conn) {
922 		_debug("clear slot %u", bindex);
923 		bundle->conns[bindex] = NULL;
924 		for (i = 0; i < RXRPC_MAXCALLS; i++)
925 			clear_bit(conn->bundle_shift + i, &bundle->avail_chans);
926 		need_drop = true;
927 	}
928 	spin_unlock(&bundle->channel_lock);
929 
930 	if (need_drop) {
931 		rxrpc_deactivate_bundle(bundle);
932 		rxrpc_put_connection(conn);
933 	}
934 }
935 
936 /*
937  * Drop the active count on a bundle.
938  */
939 static void rxrpc_deactivate_bundle(struct rxrpc_bundle *bundle)
940 {
941 	struct rxrpc_local *local = bundle->params.local;
942 	bool need_put = false;
943 
944 	if (atomic_dec_and_lock(&bundle->active, &local->client_bundles_lock)) {
945 		if (!bundle->params.exclusive) {
946 			_debug("erase bundle");
947 			rb_erase(&bundle->local_node, &local->client_bundles);
948 			need_put = true;
949 		}
950 
951 		spin_unlock(&local->client_bundles_lock);
952 		if (need_put)
953 			rxrpc_put_bundle(bundle);
954 	}
955 }
956 
957 /*
958  * Clean up a dead client connection.
959  */
960 static void rxrpc_kill_client_conn(struct rxrpc_connection *conn)
961 {
962 	struct rxrpc_local *local = conn->params.local;
963 	struct rxrpc_net *rxnet = local->rxnet;
964 
965 	_enter("C=%x", conn->debug_id);
966 
967 	trace_rxrpc_client(conn, -1, rxrpc_client_cleanup);
968 	atomic_dec(&rxnet->nr_client_conns);
969 
970 	rxrpc_put_client_connection_id(conn);
971 	rxrpc_kill_connection(conn);
972 }
973 
974 /*
975  * Clean up a dead client connections.
976  */
977 void rxrpc_put_client_conn(struct rxrpc_connection *conn)
978 {
979 	const void *here = __builtin_return_address(0);
980 	unsigned int debug_id = conn->debug_id;
981 	bool dead;
982 	int r;
983 
984 	dead = __refcount_dec_and_test(&conn->ref, &r);
985 	trace_rxrpc_conn(debug_id, rxrpc_conn_put_client, r - 1, here);
986 	if (dead)
987 		rxrpc_kill_client_conn(conn);
988 }
989 
990 /*
991  * Discard expired client connections from the idle list.  Each conn in the
992  * idle list has been exposed and holds an extra ref because of that.
993  *
994  * This may be called from conn setup or from a work item so cannot be
995  * considered non-reentrant.
996  */
997 void rxrpc_discard_expired_client_conns(struct work_struct *work)
998 {
999 	struct rxrpc_connection *conn;
1000 	struct rxrpc_net *rxnet =
1001 		container_of(work, struct rxrpc_net, client_conn_reaper);
1002 	unsigned long expiry, conn_expires_at, now;
1003 	unsigned int nr_conns;
1004 
1005 	_enter("");
1006 
1007 	if (list_empty(&rxnet->idle_client_conns)) {
1008 		_leave(" [empty]");
1009 		return;
1010 	}
1011 
1012 	/* Don't double up on the discarding */
1013 	if (!spin_trylock(&rxnet->client_conn_discard_lock)) {
1014 		_leave(" [already]");
1015 		return;
1016 	}
1017 
1018 	/* We keep an estimate of what the number of conns ought to be after
1019 	 * we've discarded some so that we don't overdo the discarding.
1020 	 */
1021 	nr_conns = atomic_read(&rxnet->nr_client_conns);
1022 
1023 next:
1024 	spin_lock(&rxnet->client_conn_cache_lock);
1025 
1026 	if (list_empty(&rxnet->idle_client_conns))
1027 		goto out;
1028 
1029 	conn = list_entry(rxnet->idle_client_conns.next,
1030 			  struct rxrpc_connection, cache_link);
1031 
1032 	if (!rxnet->kill_all_client_conns) {
1033 		/* If the number of connections is over the reap limit, we
1034 		 * expedite discard by reducing the expiry timeout.  We must,
1035 		 * however, have at least a short grace period to be able to do
1036 		 * final-ACK or ABORT retransmission.
1037 		 */
1038 		expiry = rxrpc_conn_idle_client_expiry;
1039 		if (nr_conns > rxrpc_reap_client_connections)
1040 			expiry = rxrpc_conn_idle_client_fast_expiry;
1041 		if (conn->params.local->service_closed)
1042 			expiry = rxrpc_closed_conn_expiry * HZ;
1043 
1044 		conn_expires_at = conn->idle_timestamp + expiry;
1045 
1046 		now = READ_ONCE(jiffies);
1047 		if (time_after(conn_expires_at, now))
1048 			goto not_yet_expired;
1049 	}
1050 
1051 	trace_rxrpc_client(conn, -1, rxrpc_client_discard);
1052 	list_del_init(&conn->cache_link);
1053 
1054 	spin_unlock(&rxnet->client_conn_cache_lock);
1055 
1056 	rxrpc_unbundle_conn(conn);
1057 	rxrpc_put_connection(conn); /* Drop the ->cache_link ref */
1058 
1059 	nr_conns--;
1060 	goto next;
1061 
1062 not_yet_expired:
1063 	/* The connection at the front of the queue hasn't yet expired, so
1064 	 * schedule the work item for that point if we discarded something.
1065 	 *
1066 	 * We don't worry if the work item is already scheduled - it can look
1067 	 * after rescheduling itself at a later time.  We could cancel it, but
1068 	 * then things get messier.
1069 	 */
1070 	_debug("not yet");
1071 	if (!rxnet->kill_all_client_conns)
1072 		timer_reduce(&rxnet->client_conn_reap_timer, conn_expires_at);
1073 
1074 out:
1075 	spin_unlock(&rxnet->client_conn_cache_lock);
1076 	spin_unlock(&rxnet->client_conn_discard_lock);
1077 	_leave("");
1078 }
1079 
1080 /*
1081  * Preemptively destroy all the client connection records rather than waiting
1082  * for them to time out
1083  */
1084 void rxrpc_destroy_all_client_connections(struct rxrpc_net *rxnet)
1085 {
1086 	_enter("");
1087 
1088 	spin_lock(&rxnet->client_conn_cache_lock);
1089 	rxnet->kill_all_client_conns = true;
1090 	spin_unlock(&rxnet->client_conn_cache_lock);
1091 
1092 	del_timer_sync(&rxnet->client_conn_reap_timer);
1093 
1094 	if (!rxrpc_queue_work(&rxnet->client_conn_reaper))
1095 		_debug("destroy: queue failed");
1096 
1097 	_leave("");
1098 }
1099 
1100 /*
1101  * Clean up the client connections on a local endpoint.
1102  */
1103 void rxrpc_clean_up_local_conns(struct rxrpc_local *local)
1104 {
1105 	struct rxrpc_connection *conn, *tmp;
1106 	struct rxrpc_net *rxnet = local->rxnet;
1107 	LIST_HEAD(graveyard);
1108 
1109 	_enter("");
1110 
1111 	spin_lock(&rxnet->client_conn_cache_lock);
1112 
1113 	list_for_each_entry_safe(conn, tmp, &rxnet->idle_client_conns,
1114 				 cache_link) {
1115 		if (conn->params.local == local) {
1116 			trace_rxrpc_client(conn, -1, rxrpc_client_discard);
1117 			list_move(&conn->cache_link, &graveyard);
1118 		}
1119 	}
1120 
1121 	spin_unlock(&rxnet->client_conn_cache_lock);
1122 
1123 	while (!list_empty(&graveyard)) {
1124 		conn = list_entry(graveyard.next,
1125 				  struct rxrpc_connection, cache_link);
1126 		list_del_init(&conn->cache_link);
1127 		rxrpc_unbundle_conn(conn);
1128 		rxrpc_put_connection(conn);
1129 	}
1130 
1131 	_leave(" [culled]");
1132 }
1133