xref: /linux/fs/smb/server/connection.c (revision 26534ef335e92b028eb58e44d98d46a0e26af0ec)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <namjae.jeon@protocolfreedom.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6 
7 #include <linux/mutex.h>
8 #include <linux/freezer.h>
9 #include <linux/module.h>
10 
11 #include "server.h"
12 #include "smb_common.h"
13 #include "mgmt/ksmbd_ida.h"
14 #include "mgmt/user_session.h"
15 #include "connection.h"
16 #include "vfs_cache.h"
17 #include "compress.h"
18 #include "transport_tcp.h"
19 #include "transport_rdma.h"
20 #include "misc.h"
21 
22 static DEFINE_MUTEX(init_lock);
23 
24 static struct ksmbd_conn_ops default_conn_ops;
25 static struct delayed_work session_expiration_work;
26 static bool stopping_session_expiration_work;
27 
28 DEFINE_HASHTABLE(conn_list, CONN_HASH_BITS);
29 DECLARE_RWSEM(conn_list_lock);
30 
31 #ifdef CONFIG_PROC_FS
32 static struct proc_dir_entry *proc_clients;
33 
34 static const char *ksmbd_conn_state_string(struct ksmbd_conn *conn)
35 {
36 	switch (READ_ONCE(conn->status)) {
37 	case KSMBD_SESS_NEW:
38 		return "new";
39 	case KSMBD_SESS_GOOD:
40 		return "good";
41 	case KSMBD_SESS_EXITING:
42 		return "exiting";
43 	case KSMBD_SESS_NEED_RECONNECT:
44 		return "reconnect";
45 	case KSMBD_SESS_NEED_NEGOTIATE:
46 		return "negotiate";
47 	case KSMBD_SESS_NEED_SETUP:
48 		return "setup";
49 	case KSMBD_SESS_RELEASING:
50 		return "releasing";
51 	default:
52 		return "unknown";
53 	}
54 }
55 
56 static const char *ksmbd_conn_transport_string(struct ksmbd_conn *conn)
57 {
58 	if (conn->transport->ops->rdma_read || conn->transport->ops->rdma_write)
59 		return "smbdirect";
60 	return "tcp";
61 }
62 
63 static void proc_show_conn_feature(struct seq_file *m, bool *separator,
64 				   bool enabled, const char *name)
65 {
66 	if (!enabled)
67 		return;
68 	seq_printf(m, "%s%s", *separator ? "," : "", name);
69 	*separator = true;
70 }
71 
72 static void proc_show_conn_features(struct seq_file *m,
73 				    struct ksmbd_conn *conn)
74 {
75 	bool separator = false;
76 
77 	proc_show_conn_feature(m, &separator,
78 			       conn->sign || conn->signing_negotiated, "sign");
79 	proc_show_conn_feature(m, &separator, conn->cipher_type, "encrypt");
80 	proc_show_conn_feature(m, &separator,
81 			       conn->compress_algorithm != SMB3_COMPRESS_NONE,
82 			       "compress");
83 	proc_show_conn_feature(m, &separator, conn->rdma_transform_ids,
84 			       "rdma-transform");
85 	proc_show_conn_feature(m, &separator, conn->posix_ext_supported, "posix");
86 	if (!separator)
87 		seq_puts(m, "none");
88 }
89 
90 static int proc_show_clients(struct seq_file *m, void *v)
91 {
92 	struct ksmbd_conn *conn;
93 	struct timespec64 now, t;
94 	int i;
95 
96 	down_read(&conn_list_lock);
97 	hash_for_each(conn_list, i, conn, hlist) {
98 		unsigned int outstanding_credits, total_credits;
99 		unsigned long id;
100 		void *entry;
101 		unsigned int sessions = 0;
102 
103 		jiffies_to_timespec64(jiffies - conn->last_active, &t);
104 		ktime_get_real_ts64(&now);
105 		t = timespec64_sub(now, t);
106 
107 		spin_lock(&conn->credits_lock);
108 		outstanding_credits = conn->outstanding_credits;
109 		total_credits = conn->total_credits;
110 		spin_unlock(&conn->credits_lock);
111 
112 		rcu_read_lock();
113 		xa_for_each(&conn->sessions, id, entry)
114 			sessions++;
115 		rcu_read_unlock();
116 #if IS_ENABLED(CONFIG_IPV6)
117 		if (conn->is_ipv6)
118 			seq_printf(m, "client:\t%pI6c\n", &conn->inet6_addr);
119 		else
120 #endif
121 			seq_printf(m, "client:\t%pI4\n", &conn->inet_addr);
122 		seq_printf(m, "transport:\t%s\n", ksmbd_conn_transport_string(conn));
123 		seq_printf(m, "state:\t%s\n", ksmbd_conn_state_string(conn));
124 		seq_printf(m, "dialect:\t0x%04x\n", conn->dialect);
125 		seq_printf(m, "credits:\t%u/%u\n", outstanding_credits,
126 			   total_credits);
127 		seq_printf(m, "sessions:\t%u\n", sessions);
128 		seq_printf(m, "open_files:\t%d\n",
129 			   atomic_read(&conn->stats.open_files_count));
130 		seq_printf(m, "requests:\t%lld\n",
131 			   atomic64_read(&conn->stats.request_served));
132 		seq_puts(m, "features:\t");
133 		proc_show_conn_features(m, conn);
134 		seq_printf(m, "\nlast_active:\t%ptT\n\n", &t);
135 	}
136 	up_read(&conn_list_lock);
137 	return 0;
138 }
139 
140 static int create_proc_clients(void)
141 {
142 	proc_clients = ksmbd_proc_create("clients",
143 					 proc_show_clients, NULL);
144 	if (!proc_clients)
145 		return -ENOMEM;
146 	return 0;
147 }
148 
149 static void delete_proc_clients(void)
150 {
151 	if (proc_clients) {
152 		proc_remove(proc_clients);
153 		proc_clients = NULL;
154 	}
155 }
156 #else
157 static int create_proc_clients(void) { return 0; }
158 static void delete_proc_clients(void) {}
159 #endif
160 
161 static struct workqueue_struct *ksmbd_conn_wq;
162 
163 static void ksmbd_session_expiration_worker(struct work_struct *work);
164 
165 int ksmbd_conn_wq_init(void)
166 {
167 	ksmbd_conn_wq = alloc_workqueue("ksmbd-conn-release",
168 					WQ_UNBOUND | WQ_MEM_RECLAIM, 0);
169 	if (!ksmbd_conn_wq)
170 		return -ENOMEM;
171 
172 	WRITE_ONCE(stopping_session_expiration_work, false);
173 	INIT_DELAYED_WORK(&session_expiration_work,
174 			  ksmbd_session_expiration_worker);
175 	queue_delayed_work(ksmbd_conn_wq, &session_expiration_work,
176 			   KSMBD_SESSION_EXPIRATION_INTERVAL);
177 	return 0;
178 }
179 
180 void ksmbd_conn_wq_destroy(void)
181 {
182 	if (ksmbd_conn_wq) {
183 		WRITE_ONCE(stopping_session_expiration_work, true);
184 		cancel_delayed_work_sync(&session_expiration_work);
185 		destroy_workqueue(ksmbd_conn_wq);
186 		ksmbd_conn_wq = NULL;
187 	}
188 }
189 
190 /*
191  * __ksmbd_conn_release_work() - perform the final, once-per-struct cleanup
192  * of a ksmbd_conn whose refcount has just dropped to zero.
193  *
194  * This is the common release path used by ksmbd_conn_put() for the embedded
195  * state that outlives the connection thread: async_ida and the attached
196  * transport (which owns the socket and iov for TCP).  Called from a workqueue
197  * so that sleep-allowed teardown (sock_release -> tcp_close ->
198  * lock_sock_nested) never runs from an RCU softirq callback (free_opinfo_rcu)
199  * or any other non-sleeping putter context.
200  */
201 static void __ksmbd_conn_release_work(struct work_struct *work)
202 {
203 	struct ksmbd_conn *conn =
204 		container_of(work, struct ksmbd_conn, release_work);
205 
206 	ida_destroy(&conn->async_ida);
207 	conn->transport->ops->free_transport(conn->transport);
208 	kfree_sensitive(conn);
209 }
210 
211 /**
212  * ksmbd_conn_get() - take a reference on @conn and return it.
213  *
214  * @conn: connection instance to get a reference to
215  *
216  * Returns @conn unchanged so callers can write
217  * "fp->conn = ksmbd_conn_get(work->conn);" in one expression.  Returns NULL
218  * if @conn is NULL.
219  */
220 struct ksmbd_conn *ksmbd_conn_get(struct ksmbd_conn *conn)
221 {
222 	if (!conn)
223 		return NULL;
224 
225 	atomic_inc(&conn->refcnt);
226 	return conn;
227 }
228 
229 /**
230  * ksmbd_conn_put() - drop a reference and, if it was the last, queue the
231  * release onto ksmbd_conn_wq so it runs from process context.
232  *
233  * @conn: connection instance to put a reference to
234  *
235  * Callable from any context including RCU softirq callbacks and non-sleeping
236  * locks; the actual release is deferred to the workqueue.  ksmbd_conn_wq is
237  * created in ksmbd_server_init() before any conn can be allocated and is
238  * destroyed in ksmbd_server_exit() after rcu_barrier(), so it is always
239  * non-NULL while a conn reference is held.
240  */
241 void ksmbd_conn_put(struct ksmbd_conn *conn)
242 {
243 	if (!conn)
244 		return;
245 
246 	if (atomic_dec_and_test(&conn->refcnt))
247 		queue_work(ksmbd_conn_wq, &conn->release_work);
248 }
249 
250 /**
251  * ksmbd_conn_free() - free resources of the connection instance
252  *
253  * @conn:	connection instance to be cleaned up
254  *
255  * During the thread termination, the corresponding conn instance
256  * resources(sock/memory) are released and finally the conn object is freed.
257  */
258 void ksmbd_conn_free(struct ksmbd_conn *conn)
259 {
260 	down_write(&conn_list_lock);
261 	hash_del(&conn->hlist);
262 	up_write(&conn_list_lock);
263 
264 	/*
265 	 * request_buf / preauth_info / mechToken are only ever accessed by the
266 	 * connection handler thread that owns @conn.  ksmbd_conn_free() is
267 	 * called from the transport free_transport() path when that thread is
268 	 * exiting, so it is safe to release them unconditionally even when
269 	 * ksmbd_conn_put() below is not the final putter (oplock / ksmbd_file
270 	 * holders only retain the conn pointer, not these per-thread buffers).
271 	 */
272 	xa_destroy(&conn->sessions);
273 	kvfree(conn->request_buf);
274 	kfree_sensitive(conn->preauth_info);
275 	kfree(conn->mechToken);
276 	ksmbd_preauth_session_destroy(conn);
277 	ksmbd_conn_put(conn);
278 }
279 
280 /**
281  * ksmbd_conn_alloc() - initialize a new connection instance
282  *
283  * Return:	ksmbd_conn struct on success, otherwise NULL
284  */
285 struct ksmbd_conn *ksmbd_conn_alloc(void)
286 {
287 	struct ksmbd_conn *conn;
288 
289 	conn = kzalloc_obj(struct ksmbd_conn, KSMBD_DEFAULT_GFP);
290 	if (!conn)
291 		return NULL;
292 
293 	conn->need_neg = true;
294 	conn->creation_time = jiffies;
295 	ksmbd_conn_set_new(conn);
296 	conn->local_nls = load_nls("utf8");
297 	if (!conn->local_nls)
298 		conn->local_nls = load_nls_default();
299 	if (IS_ENABLED(CONFIG_UNICODE))
300 		conn->um = utf8_load(UNICODE_AGE(12, 1, 0));
301 	else
302 		conn->um = ERR_PTR(-EOPNOTSUPP);
303 	if (IS_ERR(conn->um))
304 		conn->um = NULL;
305 	INIT_WORK(&conn->release_work, __ksmbd_conn_release_work);
306 	atomic_set(&conn->req_running, 0);
307 	atomic_set(&conn->r_count, 0);
308 	atomic_set(&conn->refcnt, 1);
309 	atomic64_set(&conn->session_count, 0);
310 	conn->total_credits = 1;
311 	conn->outstanding_credits = 0;
312 
313 	/*
314 	 * The command sequence window starts as the set { 0 } when the
315 	 * connection is established.
316 	 */
317 	conn->seq_low = 0;
318 	conn->seq_high = 1;
319 	__set_bit(0, conn->seq_bitmap);
320 
321 	init_waitqueue_head(&conn->req_running_q);
322 	init_waitqueue_head(&conn->r_count_q);
323 	INIT_LIST_HEAD(&conn->requests);
324 	INIT_LIST_HEAD(&conn->async_requests);
325 	INIT_LIST_HEAD(&conn->preauth_sess_table);
326 	spin_lock_init(&conn->request_lock);
327 	spin_lock_init(&conn->credits_lock);
328 	ida_init(&conn->async_ida);
329 	xa_init(&conn->sessions);
330 
331 
332 	init_rwsem(&conn->session_lock);
333 
334 	return conn;
335 }
336 
337 bool ksmbd_conn_lookup_dialect(struct ksmbd_conn *c)
338 {
339 	struct ksmbd_conn *t;
340 	int bkt;
341 	bool ret = false;
342 
343 	down_read(&conn_list_lock);
344 	hash_for_each(conn_list, bkt, t, hlist) {
345 		if (memcmp(t->ClientGUID, c->ClientGUID, SMB2_CLIENT_GUID_SIZE))
346 			continue;
347 
348 		ret = true;
349 		break;
350 	}
351 	up_read(&conn_list_lock);
352 	return ret;
353 }
354 
355 void ksmbd_conn_enqueue_request(struct ksmbd_work *work)
356 {
357 	struct ksmbd_conn *conn = work->conn;
358 	struct list_head *requests_queue = NULL;
359 
360 	if (conn->ops->get_cmd_val(work) != SMB2_CANCEL_HE)
361 		requests_queue = &conn->requests;
362 
363 	atomic_inc(&conn->req_running);
364 	if (requests_queue) {
365 		spin_lock(&conn->request_lock);
366 		list_add_tail(&work->request_entry, requests_queue);
367 		spin_unlock(&conn->request_lock);
368 	}
369 }
370 
371 void ksmbd_conn_try_dequeue_request(struct ksmbd_work *work)
372 {
373 	struct ksmbd_conn *conn = work->conn;
374 
375 	atomic_dec(&conn->req_running);
376 	if (waitqueue_active(&conn->req_running_q))
377 		wake_up(&conn->req_running_q);
378 
379 	if (list_empty(&work->request_entry) &&
380 	    list_empty(&work->async_request_entry))
381 		return;
382 
383 	spin_lock(&conn->request_lock);
384 	list_del_init(&work->request_entry);
385 	spin_unlock(&conn->request_lock);
386 	if (work->asynchronous)
387 		release_async_work(work);
388 
389 	wake_up_all(&conn->req_running_q);
390 }
391 
392 static void ksmbd_conn_cancel_async_requests(struct ksmbd_conn *conn)
393 {
394 	struct ksmbd_work *work, *tmp;
395 
396 	ksmbd_debug(CONN, "Cancel pending async requests on releasing connection\n");
397 	spin_lock(&conn->request_lock);
398 	list_for_each_entry_safe(work, tmp, &conn->async_requests,
399 				 async_request_entry) {
400 		if (cmpxchg(&work->state, KSMBD_WORK_ACTIVE,
401 			    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
402 			continue;
403 
404 		ksmbd_debug(CONN, "Cancel async request id %d\n",
405 			    work->async_id);
406 		if (work->cancel_fn)
407 			work->cancel_fn(work->cancel_argv);
408 	}
409 	spin_unlock(&conn->request_lock);
410 }
411 
412 void ksmbd_conn_lock(struct ksmbd_conn *conn)
413 {
414 	mutex_lock(&conn->srv_mutex);
415 }
416 
417 void ksmbd_conn_unlock(struct ksmbd_conn *conn)
418 {
419 	mutex_unlock(&conn->srv_mutex);
420 }
421 
422 static bool ksmbd_session_is_bound_to_conn(struct ksmbd_session *sess,
423 					   struct ksmbd_conn *conn)
424 {
425 	bool found;
426 
427 	rcu_read_lock();
428 	found = xa_load(&conn->sessions, sess->id) == sess;
429 	rcu_read_unlock();
430 	if (found)
431 		return true;
432 
433 	down_read(&sess->chann_lock);
434 	found = xa_load(&sess->ksmbd_chann_list, (long)conn);
435 	up_read(&sess->chann_lock);
436 	return found;
437 }
438 
439 void ksmbd_all_conn_set_status(struct ksmbd_session *sess, u32 status)
440 {
441 	struct ksmbd_conn *conn;
442 	int bkt;
443 
444 	down_read(&conn_list_lock);
445 	hash_for_each(conn_list, bkt, conn, hlist) {
446 		if (ksmbd_session_is_bound_to_conn(sess, conn)) {
447 			spin_lock(&conn->request_lock);
448 			if (!ksmbd_conn_exiting(conn) &&
449 			    !ksmbd_conn_releasing(conn))
450 				WRITE_ONCE(conn->status, status);
451 			spin_unlock(&conn->request_lock);
452 		}
453 	}
454 	up_read(&conn_list_lock);
455 }
456 
457 void ksmbd_conn_abort(struct ksmbd_conn *conn)
458 {
459 	spin_lock(&conn->request_lock);
460 	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn))
461 		ksmbd_conn_set_exiting(conn);
462 	spin_unlock(&conn->request_lock);
463 	wake_up_all(&conn->req_running_q);
464 
465 	if (conn->transport->ops->shutdown)
466 		conn->transport->ops->shutdown(conn->transport);
467 }
468 
469 void ksmbd_conn_wait_idle(struct ksmbd_conn *conn)
470 {
471 	wait_event(conn->req_running_q, atomic_read(&conn->req_running) < 2);
472 }
473 
474 int ksmbd_conn_wait_idle_sess(struct ksmbd_conn *curr_conn,
475 			      struct ksmbd_session *sess)
476 {
477 	struct ksmbd_conn *conn;
478 	int rc, retry_count = 0, max_timeout = 120;
479 	int rcount, bkt;
480 
481 retry_idle:
482 	if (retry_count >= max_timeout)
483 		return -EIO;
484 
485 	/* A blocked byte-range lock cannot drain until teardown wakes it. */
486 	ksmbd_wake_session_blocked_works(sess);
487 
488 	down_read(&conn_list_lock);
489 	hash_for_each(conn_list, bkt, conn, hlist) {
490 		if (ksmbd_session_is_bound_to_conn(sess, conn)) {
491 			rcount = (conn == curr_conn) ? 2 : 1;
492 			if (atomic_read(&conn->req_running) >= rcount) {
493 				rc = wait_event_timeout(conn->req_running_q,
494 					atomic_read(&conn->req_running) < rcount,
495 					HZ);
496 				if (!rc) {
497 					up_read(&conn_list_lock);
498 					retry_count++;
499 					goto retry_idle;
500 				}
501 			}
502 		}
503 	}
504 	up_read(&conn_list_lock);
505 
506 	return 0;
507 }
508 
509 static int __ksmbd_conn_write(struct ksmbd_work *work,
510 			      struct ksmbd_transport_write *tx)
511 {
512 	struct ksmbd_conn *conn = work->conn;
513 	int sent;
514 
515 	if (!work->response_buf) {
516 		pr_err("NULL response header\n");
517 		return -EINVAL;
518 	}
519 
520 	if (work->send_no_response)
521 		return 0;
522 
523 	if (!work->iov_idx)
524 		return -EINVAL;
525 
526 	tx->iov = work->iov;
527 	tx->iov_cnt = work->iov_cnt;
528 	tx->size = get_rfc1002_len(work->iov[0].iov_base) + 4;
529 	tx->need_invalidate_rkey = work->need_invalidate_rkey;
530 	tx->remote_key = work->remote_key;
531 
532 	if (tx->tracking) {
533 		/* A busy writer must not consume the break's retry budget. */
534 		if (!mutex_trylock(&conn->srv_mutex))
535 			return -EAGAIN;
536 	} else {
537 		ksmbd_conn_lock(conn);
538 	}
539 	sent = conn->transport->ops->writev(conn->transport, tx);
540 	ksmbd_conn_unlock(conn);
541 
542 	if (sent < 0) {
543 		if (!tx->tracking || sent != -EAGAIN)
544 			pr_err("Failed to send message: %d\n", sent);
545 		return sent;
546 	}
547 
548 	return 0;
549 }
550 
551 int ksmbd_conn_write(struct ksmbd_work *work)
552 {
553 	struct ksmbd_transport_write tx = {};
554 
555 	return __ksmbd_conn_write(work, &tx);
556 }
557 
558 int ksmbd_conn_write_tracked(struct ksmbd_work *work,
559 			     struct ksmbd_tx_tracking *tracking)
560 {
561 	struct ksmbd_transport_write tx = {};
562 
563 	tracking->valid = false;
564 	/* Transports without delivery tracking keep their synchronous send path. */
565 	if (work->conn->transport->ops->is_acked) {
566 		tx.msg_flags = MSG_DONTWAIT;
567 		tx.tracking = tracking;
568 	}
569 	return __ksmbd_conn_write(work, &tx);
570 }
571 
572 int ksmbd_conn_write_eor(struct ksmbd_work *work)
573 {
574 	struct ksmbd_transport_write tx = {
575 		.msg_flags = MSG_EOR,
576 	};
577 
578 	return __ksmbd_conn_write(work, &tx);
579 }
580 
581 int ksmbd_conn_rdma_read(struct ksmbd_conn *conn,
582 			 void *buf, unsigned int buflen,
583 			 struct smbdirect_buffer_descriptor_v1 *desc,
584 			 unsigned int desc_len)
585 {
586 	int ret = -EINVAL;
587 
588 	if (conn->transport->ops->rdma_read)
589 		ret = conn->transport->ops->rdma_read(conn->transport,
590 						      buf, buflen,
591 						      desc, desc_len);
592 	return ret;
593 }
594 
595 int ksmbd_conn_rdma_write(struct ksmbd_conn *conn,
596 			  void *buf, unsigned int buflen,
597 			  struct smbdirect_buffer_descriptor_v1 *desc,
598 			  unsigned int desc_len)
599 {
600 	int ret = -EINVAL;
601 
602 	if (conn->transport->ops->rdma_write)
603 		ret = conn->transport->ops->rdma_write(conn->transport,
604 						       buf, buflen,
605 						       desc, desc_len);
606 	return ret;
607 }
608 
609 bool ksmbd_conn_alive(struct ksmbd_conn *conn)
610 {
611 	if (!ksmbd_server_running())
612 		return false;
613 
614 	if (ksmbd_conn_exiting(conn))
615 		return false;
616 
617 	if (kthread_should_stop())
618 		return false;
619 
620 	/*
621 	 * Stale connections that have not completed NEGOTIATE and SESSION_SETUP
622 	 * must be disconnected. Do not race a request that is currently
623 	 * completing authentication.
624 	 */
625 	if (!atomic_read(&conn->req_running) &&
626 	    time_after(jiffies, conn->creation_time +
627 		       KSMBD_UNAUTHENTICATED_CONN_TIMEOUT) &&
628 	    (READ_ONCE(conn->need_neg) ||
629 	     !ksmbd_conn_has_valid_or_expired_session(conn))) {
630 		ksmbd_debug(CONN, "Connection setup timed out\n");
631 		return false;
632 	}
633 
634 	if (atomic_read(&conn->stats.open_files_count) > 0)
635 		return true;
636 
637 	/*
638 	 * Stop current session if the time that get last request from client
639 	 * is bigger than deadtime user configured and opening file count is
640 	 * zero.
641 	 */
642 	if (server_conf.deadtime > 0 &&
643 	    time_after(jiffies, conn->last_active + server_conf.deadtime)) {
644 		ksmbd_debug(CONN, "No response from client in %lu minutes\n",
645 			    server_conf.deadtime / SMB_ECHO_INTERVAL);
646 		return false;
647 	}
648 	return true;
649 }
650 
651 static void ksmbd_session_expiration_worker(struct work_struct *work)
652 {
653 	struct ksmbd_conn *conn, *target;
654 	int bkt;
655 
656 	if (!ksmbd_server_running())
657 		goto reschedule;
658 
659 	ksmbd_expire_sessions();
660 	ksmbd_reclaim_ended_sessions();
661 
662 	/*
663 	 * An old connection without a Valid or Expired session must be
664 	 * disconnected. Process one connection at a time without holding
665 	 * conn_list_lock across transport shutdown.
666 	 */
667 again:
668 	target = NULL;
669 	down_read(&conn_list_lock);
670 	hash_for_each(conn_list, bkt, conn, hlist) {
671 		if (ksmbd_conn_exiting(conn) || ksmbd_conn_releasing(conn) ||
672 		    atomic_read(&conn->req_running) ||
673 		    time_before_eq(jiffies, conn->creation_time +
674 				   KSMBD_UNAUTHENTICATED_CONN_TIMEOUT) ||
675 		    (!READ_ONCE(conn->need_neg) &&
676 		     ksmbd_conn_has_valid_or_expired_session(conn)))
677 			continue;
678 
679 		target = ksmbd_conn_get(conn);
680 		break;
681 	}
682 	up_read(&conn_list_lock);
683 
684 	if (target) {
685 		ksmbd_debug(CONN, "Connection setup timed out\n");
686 		ksmbd_conn_abort(target);
687 		ksmbd_conn_put(target);
688 		goto again;
689 	}
690 
691 reschedule:
692 	if (!READ_ONCE(stopping_session_expiration_work))
693 		queue_delayed_work(ksmbd_conn_wq, &session_expiration_work,
694 				   KSMBD_SESSION_EXPIRATION_INTERVAL);
695 }
696 
697 /* "+2" for BCC field (ByteCount, 2 bytes) */
698 #define SMB1_MIN_SUPPORTED_PDU_SIZE (sizeof(struct smb_hdr) + 2)
699 #define SMB2_MIN_SUPPORTED_PDU_SIZE (sizeof(struct smb2_pdu))
700 #define SMB2_TRANSFORM_MIN_SUPPORTED_PDU_SIZE	\
701 	(sizeof(struct smb2_transform_hdr) + sizeof(struct smb2_hdr))
702 
703 /**
704  * ksmbd_conn_handler_loop() - session thread to listen on new smb requests
705  * @p:		connection instance
706  *
707  * One thread each per connection
708  *
709  * Return:	0 on success
710  */
711 int ksmbd_conn_handler_loop(void *p)
712 {
713 	struct ksmbd_conn *conn = (struct ksmbd_conn *)p;
714 	struct ksmbd_transport *t = conn->transport;
715 	unsigned int pdu_size, max_allowed_pdu_size, max_req;
716 	__le32 proto;
717 	char hdr_buf[4] = {0,};
718 	int size;
719 
720 	mutex_init(&conn->srv_mutex);
721 	__module_get(THIS_MODULE);
722 
723 	max_req = server_conf.max_inflight_req;
724 	conn->last_active = jiffies;
725 	set_freezable();
726 	while (ksmbd_conn_alive(conn)) {
727 		if (try_to_freeze())
728 			continue;
729 
730 		kvfree(conn->request_buf);
731 		conn->request_buf = NULL;
732 
733 recheck:
734 		if (atomic_read(&conn->req_running) + 1 > max_req) {
735 			wait_event_interruptible(conn->req_running_q,
736 				atomic_read(&conn->req_running) < max_req);
737 			goto recheck;
738 		}
739 
740 		size = t->ops->read(t, hdr_buf, sizeof(hdr_buf), -1);
741 		if (size != sizeof(hdr_buf))
742 			break;
743 
744 		pdu_size = get_rfc1002_len(hdr_buf);
745 		ksmbd_debug(CONN, "RFC1002 header %u bytes\n", pdu_size);
746 
747 		max_allowed_pdu_size = ksmbd_max_allowed_pdu_size(conn);
748 
749 		if (pdu_size > max_allowed_pdu_size) {
750 			pr_err_ratelimited("PDU length(%u) exceeded maximum allowed pdu size(%u) on connection(%d)\n",
751 					pdu_size, max_allowed_pdu_size,
752 					READ_ONCE(conn->status));
753 			break;
754 		}
755 
756 		/*
757 		 * Check maximum pdu size(0x00FFFFFF).
758 		 */
759 		if (pdu_size > MAX_STREAM_PROT_LEN)
760 			break;
761 
762 		if (pdu_size < SMB1_MIN_SUPPORTED_PDU_SIZE)
763 			break;
764 
765 		/* 4 for rfc1002 length field */
766 		/* 1 for implied bcc[0] */
767 		size = pdu_size + 4 + 1;
768 		conn->request_buf = kvmalloc(size, KSMBD_DEFAULT_GFP);
769 		if (!conn->request_buf)
770 			break;
771 
772 		conn->request_buf[pdu_size + 4] = 0;
773 		memcpy(conn->request_buf, hdr_buf, sizeof(hdr_buf));
774 
775 		/*
776 		 * We already read 4 bytes to find out PDU size, now
777 		 * read in PDU
778 		 */
779 		size = t->ops->read(t, conn->request_buf + 4, pdu_size, 2);
780 		if (size < 0) {
781 			pr_err("sock_read failed: %d\n", size);
782 			break;
783 		}
784 
785 		if (size != pdu_size) {
786 			pr_err("PDU error. Read: %d, Expected: %d\n",
787 			       size, pdu_size);
788 			continue;
789 		}
790 
791 		if (((struct smb2_hdr *)smb_get_msg(conn->request_buf))->ProtocolId ==
792 		    SMB2_COMPRESSION_TRANSFORM_ID) {
793 			/*
794 			 * Convert the transform into a normal RFC1002-framed SMB2
795 			 * request before protocol validation and work allocation.
796 			 */
797 			if (ksmbd_decompress_request(conn))
798 				break;
799 			pdu_size = get_rfc1002_len(conn->request_buf);
800 		}
801 
802 		if (!ksmbd_smb_request(conn))
803 			break;
804 
805 		proto = *(__le32 *)smb_get_msg(conn->request_buf);
806 		if (proto == SMB2_PROTO_NUMBER &&
807 		    pdu_size < SMB2_MIN_SUPPORTED_PDU_SIZE)
808 			break;
809 
810 		if (proto == SMB2_TRANSFORM_PROTO_NUM &&
811 		    pdu_size < SMB2_TRANSFORM_MIN_SUPPORTED_PDU_SIZE)
812 			break;
813 
814 		if (!default_conn_ops.process_fn) {
815 			pr_err("No connection request callback\n");
816 			break;
817 		}
818 
819 		if (default_conn_ops.process_fn(conn)) {
820 			pr_err("Cannot handle request\n");
821 			break;
822 		}
823 	}
824 
825 	/* Exclude new break senders before draining their work references. */
826 	spin_lock(&conn->request_lock);
827 	ksmbd_conn_set_releasing(conn);
828 	spin_unlock(&conn->request_lock);
829 	/* TCP writers waiting for queue space must release their work references. */
830 	wake_up_all(&conn->req_running_q);
831 	ksmbd_conn_cancel_async_requests(conn);
832 	/* Wait till all reference dropped to the Server object*/
833 	ksmbd_debug(CONN, "Wait for all pending requests(%d)\n", atomic_read(&conn->r_count));
834 	wait_event(conn->r_count_q, atomic_read(&conn->r_count) == 0);
835 
836 	if (IS_ENABLED(CONFIG_UNICODE))
837 		utf8_unload(conn->um);
838 	unload_nls(conn->local_nls);
839 	if (default_conn_ops.terminate_fn)
840 		default_conn_ops.terminate_fn(conn);
841 	t->ops->disconnect(t);
842 	module_put(THIS_MODULE);
843 	return 0;
844 }
845 
846 void ksmbd_conn_init_server_callbacks(struct ksmbd_conn_ops *ops)
847 {
848 	default_conn_ops.process_fn = ops->process_fn;
849 	default_conn_ops.terminate_fn = ops->terminate_fn;
850 }
851 
852 void ksmbd_conn_r_count_inc(struct ksmbd_conn *conn)
853 {
854 	atomic_inc(&conn->r_count);
855 }
856 
857 /* The caller already owns a connection reference. */
858 bool ksmbd_conn_r_count_inc_if_good(struct ksmbd_conn *conn)
859 {
860 	bool ret = false;
861 
862 	spin_lock(&conn->request_lock);
863 	if (ksmbd_conn_good(conn)) {
864 		atomic_inc(&conn->r_count);
865 		ret = true;
866 	}
867 	spin_unlock(&conn->request_lock);
868 	return ret;
869 }
870 
871 void ksmbd_conn_r_count_dec(struct ksmbd_conn *conn)
872 {
873 	/*
874 	 * Checking waitqueue to dropping pending requests on
875 	 * disconnection. waitqueue_active is safe because it
876 	 * uses atomic operation for condition.
877 	 */
878 	atomic_inc(&conn->refcnt);
879 	if (!atomic_dec_return(&conn->r_count) && waitqueue_active(&conn->r_count_q))
880 		wake_up(&conn->r_count_q);
881 
882 	ksmbd_conn_put(conn);
883 }
884 
885 int ksmbd_conn_transport_init(void)
886 {
887 	int ret;
888 
889 	mutex_lock(&init_lock);
890 	ret = ksmbd_tcp_init();
891 	if (ret) {
892 		pr_err("Failed to init TCP subsystem: %d\n", ret);
893 		goto out;
894 	}
895 
896 	ret = ksmbd_rdma_init();
897 	if (ret) {
898 		pr_err("Failed to init RDMA subsystem: %d\n", ret);
899 		goto out;
900 	}
901 out:
902 	mutex_unlock(&init_lock);
903 	if (create_proc_clients())
904 		pr_warn("Unable to create clients procfs entry\n");
905 	return ret;
906 }
907 
908 static void stop_sessions(void)
909 {
910 	struct ksmbd_conn *conn, *target;
911 	struct ksmbd_transport *t;
912 	bool any;
913 	int bkt;
914 
915 	/*
916 	 * Serialised via init_lock; no concurrent stop_sessions() can
917 	 * touch conn->stop_called, so writing it under the read lock is
918 	 * safe.
919 	 */
920 again:
921 	target = NULL;
922 	any = false;
923 	down_read(&conn_list_lock);
924 	hash_for_each(conn_list, bkt, conn, hlist) {
925 		any = true;
926 		if (conn->stop_called)
927 			continue;
928 		atomic_inc(&conn->refcnt);
929 		conn->stop_called = true;
930 		/*
931 		 * Mark the connection EXITING while still holding the
932 		 * read lock so the selection and the status transition
933 		 * happen together.  Do not regress a connection that has
934 		 * already advanced to RELEASING on its own (e.g. the
935 		 * handler exited its receive loop for an unrelated
936 		 * reason).
937 		 */
938 		spin_lock(&conn->request_lock);
939 		if (!ksmbd_conn_releasing(conn))
940 			ksmbd_conn_set_exiting(conn);
941 		spin_unlock(&conn->request_lock);
942 		target = conn;
943 		break;
944 	}
945 	up_read(&conn_list_lock);
946 
947 	if (target) {
948 		t = target->transport;
949 		if (t->ops->shutdown)
950 			t->ops->shutdown(t);
951 		if (atomic_dec_and_test(&target->refcnt)) {
952 			ida_destroy(&target->async_ida);
953 			t->ops->free_transport(t);
954 			kfree_sensitive(target);
955 		}
956 		goto again;
957 	}
958 
959 	if (any) {
960 		msleep(100);
961 		goto again;
962 	}
963 }
964 
965 void ksmbd_conn_transport_destroy(void)
966 {
967 	delete_proc_clients();
968 	mutex_lock(&init_lock);
969 	ksmbd_tcp_destroy();
970 	ksmbd_rdma_stop_listening();
971 	stop_sessions();
972 	mutex_unlock(&init_lock);
973 }
974