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