xref: /linux/fs/smb/server/connection.c (revision a74668eb2c0b866d7ac4823be6006ab2e227bc03)
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 "connection.h"
15 #include "transport_tcp.h"
16 #include "transport_rdma.h"
17 #include "misc.h"
18 
19 static DEFINE_MUTEX(init_lock);
20 
21 static struct ksmbd_conn_ops default_conn_ops;
22 
23 DEFINE_HASHTABLE(conn_list, CONN_HASH_BITS);
24 DECLARE_RWSEM(conn_list_lock);
25 
26 #ifdef CONFIG_PROC_FS
27 static struct proc_dir_entry *proc_clients;
28 
29 static int proc_show_clients(struct seq_file *m, void *v)
30 {
31 	struct ksmbd_conn *conn;
32 	struct timespec64 now, t;
33 	int i;
34 
35 	seq_printf(m, "#%-20s %-10s %-10s %-10s %-10s %-10s\n",
36 			"<name>", "<dialect>", "<credits>", "<open files>",
37 			"<requests>", "<last active>");
38 
39 	down_read(&conn_list_lock);
40 	hash_for_each(conn_list, i, conn, hlist) {
41 		jiffies_to_timespec64(jiffies - conn->last_active, &t);
42 		ktime_get_real_ts64(&now);
43 		t = timespec64_sub(now, t);
44 #if IS_ENABLED(CONFIG_IPV6)
45 		if (!conn->inet_addr)
46 			seq_printf(m, "%-20pI6c", &conn->inet6_addr);
47 		else
48 #endif
49 			seq_printf(m, "%-20pI4", &conn->inet_addr);
50 		seq_printf(m, "   0x%-10x %-10u %-12d %-10d %ptT\n",
51 			   conn->dialect,
52 			   conn->total_credits,
53 			   atomic_read(&conn->stats.open_files_count),
54 			   atomic_read(&conn->req_running),
55 			   &t);
56 	}
57 	up_read(&conn_list_lock);
58 	return 0;
59 }
60 
61 static int create_proc_clients(void)
62 {
63 	proc_clients = ksmbd_proc_create("clients",
64 					 proc_show_clients, NULL);
65 	if (!proc_clients)
66 		return -ENOMEM;
67 	return 0;
68 }
69 
70 static void delete_proc_clients(void)
71 {
72 	if (proc_clients) {
73 		proc_remove(proc_clients);
74 		proc_clients = NULL;
75 	}
76 }
77 #else
78 static int create_proc_clients(void) { return 0; }
79 static void delete_proc_clients(void) {}
80 #endif
81 
82 static struct workqueue_struct *ksmbd_conn_wq;
83 
84 int ksmbd_conn_wq_init(void)
85 {
86 	ksmbd_conn_wq = alloc_workqueue("ksmbd-conn-release",
87 					WQ_UNBOUND | WQ_MEM_RECLAIM, 0);
88 	if (!ksmbd_conn_wq)
89 		return -ENOMEM;
90 	return 0;
91 }
92 
93 void ksmbd_conn_wq_destroy(void)
94 {
95 	if (ksmbd_conn_wq) {
96 		destroy_workqueue(ksmbd_conn_wq);
97 		ksmbd_conn_wq = NULL;
98 	}
99 }
100 
101 /*
102  * __ksmbd_conn_release_work() - perform the final, once-per-struct cleanup
103  * of a ksmbd_conn whose refcount has just dropped to zero.
104  *
105  * This is the common release path used by ksmbd_conn_put() for the embedded
106  * state that outlives the connection thread: async_ida and the attached
107  * transport (which owns the socket and iov for TCP).  Called from a workqueue
108  * so that sleep-allowed teardown (sock_release -> tcp_close ->
109  * lock_sock_nested) never runs from an RCU softirq callback (free_opinfo_rcu)
110  * or any other non-sleeping putter context.
111  */
112 static void __ksmbd_conn_release_work(struct work_struct *work)
113 {
114 	struct ksmbd_conn *conn =
115 		container_of(work, struct ksmbd_conn, release_work);
116 
117 	ida_destroy(&conn->async_ida);
118 	conn->transport->ops->free_transport(conn->transport);
119 	kfree(conn);
120 }
121 
122 /**
123  * ksmbd_conn_get() - take a reference on @conn and return it.
124  *
125  * Returns @conn unchanged so callers can write
126  * "fp->conn = ksmbd_conn_get(work->conn);" in one expression.  Returns NULL
127  * if @conn is NULL.
128  */
129 struct ksmbd_conn *ksmbd_conn_get(struct ksmbd_conn *conn)
130 {
131 	if (!conn)
132 		return NULL;
133 
134 	atomic_inc(&conn->refcnt);
135 	return conn;
136 }
137 
138 /**
139  * ksmbd_conn_put() - drop a reference and, if it was the last, queue the
140  * release onto ksmbd_conn_wq so it runs from process context.
141  *
142  * Callable from any context including RCU softirq callbacks and non-sleeping
143  * locks; the actual release is deferred to the workqueue.  ksmbd_conn_wq is
144  * created in ksmbd_server_init() before any conn can be allocated and is
145  * destroyed in ksmbd_server_exit() after rcu_barrier(), so it is always
146  * non-NULL while a conn reference is held.
147  */
148 void ksmbd_conn_put(struct ksmbd_conn *conn)
149 {
150 	if (!conn)
151 		return;
152 
153 	if (atomic_dec_and_test(&conn->refcnt))
154 		queue_work(ksmbd_conn_wq, &conn->release_work);
155 }
156 
157 /**
158  * ksmbd_conn_free() - free resources of the connection instance
159  *
160  * @conn:	connection instance to be cleaned up
161  *
162  * During the thread termination, the corresponding conn instance
163  * resources(sock/memory) are released and finally the conn object is freed.
164  */
165 void ksmbd_conn_free(struct ksmbd_conn *conn)
166 {
167 	down_write(&conn_list_lock);
168 	hash_del(&conn->hlist);
169 	up_write(&conn_list_lock);
170 
171 	/*
172 	 * request_buf / preauth_info / mechToken are only ever accessed by the
173 	 * connection handler thread that owns @conn.  ksmbd_conn_free() is
174 	 * called from the transport free_transport() path when that thread is
175 	 * exiting, so it is safe to release them unconditionally even when
176 	 * ksmbd_conn_put() below is not the final putter (oplock / ksmbd_file
177 	 * holders only retain the conn pointer, not these per-thread buffers).
178 	 */
179 	xa_destroy(&conn->sessions);
180 	kvfree(conn->request_buf);
181 	kfree(conn->preauth_info);
182 	kfree(conn->mechToken);
183 	ksmbd_conn_put(conn);
184 }
185 
186 /**
187  * ksmbd_conn_alloc() - initialize a new connection instance
188  *
189  * Return:	ksmbd_conn struct on success, otherwise NULL
190  */
191 struct ksmbd_conn *ksmbd_conn_alloc(void)
192 {
193 	struct ksmbd_conn *conn;
194 
195 	conn = kzalloc_obj(struct ksmbd_conn, KSMBD_DEFAULT_GFP);
196 	if (!conn)
197 		return NULL;
198 
199 	conn->need_neg = true;
200 	ksmbd_conn_set_new(conn);
201 	conn->local_nls = load_nls("utf8");
202 	if (!conn->local_nls)
203 		conn->local_nls = load_nls_default();
204 	if (IS_ENABLED(CONFIG_UNICODE))
205 		conn->um = utf8_load(UNICODE_AGE(12, 1, 0));
206 	else
207 		conn->um = ERR_PTR(-EOPNOTSUPP);
208 	if (IS_ERR(conn->um))
209 		conn->um = NULL;
210 	INIT_WORK(&conn->release_work, __ksmbd_conn_release_work);
211 	atomic_set(&conn->req_running, 0);
212 	atomic_set(&conn->r_count, 0);
213 	atomic_set(&conn->refcnt, 1);
214 	conn->total_credits = 1;
215 	conn->outstanding_credits = 0;
216 
217 	init_waitqueue_head(&conn->req_running_q);
218 	init_waitqueue_head(&conn->r_count_q);
219 	INIT_LIST_HEAD(&conn->requests);
220 	INIT_LIST_HEAD(&conn->async_requests);
221 	spin_lock_init(&conn->request_lock);
222 	spin_lock_init(&conn->credits_lock);
223 	ida_init(&conn->async_ida);
224 	xa_init(&conn->sessions);
225 
226 	spin_lock_init(&conn->llist_lock);
227 	INIT_LIST_HEAD(&conn->lock_list);
228 
229 	init_rwsem(&conn->session_lock);
230 
231 	return conn;
232 }
233 
234 bool ksmbd_conn_lookup_dialect(struct ksmbd_conn *c)
235 {
236 	struct ksmbd_conn *t;
237 	int bkt;
238 	bool ret = false;
239 
240 	down_read(&conn_list_lock);
241 	hash_for_each(conn_list, bkt, t, hlist) {
242 		if (memcmp(t->ClientGUID, c->ClientGUID, SMB2_CLIENT_GUID_SIZE))
243 			continue;
244 
245 		ret = true;
246 		break;
247 	}
248 	up_read(&conn_list_lock);
249 	return ret;
250 }
251 
252 void ksmbd_conn_enqueue_request(struct ksmbd_work *work)
253 {
254 	struct ksmbd_conn *conn = work->conn;
255 	struct list_head *requests_queue = NULL;
256 
257 	if (conn->ops->get_cmd_val(work) != SMB2_CANCEL_HE)
258 		requests_queue = &conn->requests;
259 
260 	atomic_inc(&conn->req_running);
261 	if (requests_queue) {
262 		spin_lock(&conn->request_lock);
263 		list_add_tail(&work->request_entry, requests_queue);
264 		spin_unlock(&conn->request_lock);
265 	}
266 }
267 
268 void ksmbd_conn_try_dequeue_request(struct ksmbd_work *work)
269 {
270 	struct ksmbd_conn *conn = work->conn;
271 
272 	atomic_dec(&conn->req_running);
273 	if (waitqueue_active(&conn->req_running_q))
274 		wake_up(&conn->req_running_q);
275 
276 	if (list_empty(&work->request_entry) &&
277 	    list_empty(&work->async_request_entry))
278 		return;
279 
280 	spin_lock(&conn->request_lock);
281 	list_del_init(&work->request_entry);
282 	spin_unlock(&conn->request_lock);
283 	if (work->asynchronous)
284 		release_async_work(work);
285 
286 	wake_up_all(&conn->req_running_q);
287 }
288 
289 void ksmbd_conn_lock(struct ksmbd_conn *conn)
290 {
291 	mutex_lock(&conn->srv_mutex);
292 }
293 
294 void ksmbd_conn_unlock(struct ksmbd_conn *conn)
295 {
296 	mutex_unlock(&conn->srv_mutex);
297 }
298 
299 void ksmbd_all_conn_set_status(u64 sess_id, u32 status)
300 {
301 	struct ksmbd_conn *conn;
302 	int bkt;
303 
304 	down_read(&conn_list_lock);
305 	hash_for_each(conn_list, bkt, conn, hlist) {
306 		if (conn->binding || xa_load(&conn->sessions, sess_id))
307 			WRITE_ONCE(conn->status, status);
308 	}
309 	up_read(&conn_list_lock);
310 }
311 
312 void ksmbd_conn_wait_idle(struct ksmbd_conn *conn)
313 {
314 	wait_event(conn->req_running_q, atomic_read(&conn->req_running) < 2);
315 }
316 
317 int ksmbd_conn_wait_idle_sess_id(struct ksmbd_conn *curr_conn, u64 sess_id)
318 {
319 	struct ksmbd_conn *conn;
320 	int rc, retry_count = 0, max_timeout = 120;
321 	int rcount, bkt;
322 
323 retry_idle:
324 	if (retry_count >= max_timeout)
325 		return -EIO;
326 
327 	down_read(&conn_list_lock);
328 	hash_for_each(conn_list, bkt, conn, hlist) {
329 		if (conn->binding || xa_load(&conn->sessions, sess_id)) {
330 			rcount = (conn == curr_conn) ? 2 : 1;
331 			if (atomic_read(&conn->req_running) >= rcount) {
332 				rc = wait_event_timeout(conn->req_running_q,
333 					atomic_read(&conn->req_running) < rcount,
334 					HZ);
335 				if (!rc) {
336 					up_read(&conn_list_lock);
337 					retry_count++;
338 					goto retry_idle;
339 				}
340 			}
341 		}
342 	}
343 	up_read(&conn_list_lock);
344 
345 	return 0;
346 }
347 
348 int ksmbd_conn_write(struct ksmbd_work *work)
349 {
350 	struct ksmbd_conn *conn = work->conn;
351 	int sent;
352 
353 	if (!work->response_buf) {
354 		pr_err("NULL response header\n");
355 		return -EINVAL;
356 	}
357 
358 	if (work->send_no_response)
359 		return 0;
360 
361 	if (!work->iov_idx)
362 		return -EINVAL;
363 
364 	ksmbd_conn_lock(conn);
365 	sent = conn->transport->ops->writev(conn->transport, work->iov,
366 			work->iov_cnt,
367 			get_rfc1002_len(work->iov[0].iov_base) + 4,
368 			work->need_invalidate_rkey,
369 			work->remote_key);
370 	ksmbd_conn_unlock(conn);
371 
372 	if (sent < 0) {
373 		pr_err("Failed to send message: %d\n", sent);
374 		return sent;
375 	}
376 
377 	return 0;
378 }
379 
380 int ksmbd_conn_rdma_read(struct ksmbd_conn *conn,
381 			 void *buf, unsigned int buflen,
382 			 struct smbdirect_buffer_descriptor_v1 *desc,
383 			 unsigned int desc_len)
384 {
385 	int ret = -EINVAL;
386 
387 	if (conn->transport->ops->rdma_read)
388 		ret = conn->transport->ops->rdma_read(conn->transport,
389 						      buf, buflen,
390 						      desc, desc_len);
391 	return ret;
392 }
393 
394 int ksmbd_conn_rdma_write(struct ksmbd_conn *conn,
395 			  void *buf, unsigned int buflen,
396 			  struct smbdirect_buffer_descriptor_v1 *desc,
397 			  unsigned int desc_len)
398 {
399 	int ret = -EINVAL;
400 
401 	if (conn->transport->ops->rdma_write)
402 		ret = conn->transport->ops->rdma_write(conn->transport,
403 						       buf, buflen,
404 						       desc, desc_len);
405 	return ret;
406 }
407 
408 bool ksmbd_conn_alive(struct ksmbd_conn *conn)
409 {
410 	if (!ksmbd_server_running())
411 		return false;
412 
413 	if (ksmbd_conn_exiting(conn))
414 		return false;
415 
416 	if (kthread_should_stop())
417 		return false;
418 
419 	if (atomic_read(&conn->stats.open_files_count) > 0)
420 		return true;
421 
422 	/*
423 	 * Stop current session if the time that get last request from client
424 	 * is bigger than deadtime user configured and opening file count is
425 	 * zero.
426 	 */
427 	if (server_conf.deadtime > 0 &&
428 	    time_after(jiffies, conn->last_active + server_conf.deadtime)) {
429 		ksmbd_debug(CONN, "No response from client in %lu minutes\n",
430 			    server_conf.deadtime / SMB_ECHO_INTERVAL);
431 		return false;
432 	}
433 	return true;
434 }
435 
436 /* "+2" for BCC field (ByteCount, 2 bytes) */
437 #define SMB1_MIN_SUPPORTED_PDU_SIZE (sizeof(struct smb_hdr) + 2)
438 #define SMB2_MIN_SUPPORTED_PDU_SIZE (sizeof(struct smb2_pdu))
439 
440 /**
441  * ksmbd_conn_handler_loop() - session thread to listen on new smb requests
442  * @p:		connection instance
443  *
444  * One thread each per connection
445  *
446  * Return:	0 on success
447  */
448 int ksmbd_conn_handler_loop(void *p)
449 {
450 	struct ksmbd_conn *conn = (struct ksmbd_conn *)p;
451 	struct ksmbd_transport *t = conn->transport;
452 	unsigned int pdu_size, max_allowed_pdu_size, max_req;
453 	char hdr_buf[4] = {0,};
454 	int size;
455 
456 	mutex_init(&conn->srv_mutex);
457 	__module_get(THIS_MODULE);
458 
459 	max_req = server_conf.max_inflight_req;
460 	conn->last_active = jiffies;
461 	set_freezable();
462 	while (ksmbd_conn_alive(conn)) {
463 		if (try_to_freeze())
464 			continue;
465 
466 		kvfree(conn->request_buf);
467 		conn->request_buf = NULL;
468 
469 recheck:
470 		if (atomic_read(&conn->req_running) + 1 > max_req) {
471 			wait_event_interruptible(conn->req_running_q,
472 				atomic_read(&conn->req_running) < max_req);
473 			goto recheck;
474 		}
475 
476 		size = t->ops->read(t, hdr_buf, sizeof(hdr_buf), -1);
477 		if (size != sizeof(hdr_buf))
478 			break;
479 
480 		pdu_size = get_rfc1002_len(hdr_buf);
481 		ksmbd_debug(CONN, "RFC1002 header %u bytes\n", pdu_size);
482 
483 		if (ksmbd_conn_good(conn))
484 			max_allowed_pdu_size =
485 				SMB3_MAX_MSGSIZE + conn->vals->max_write_size;
486 		else
487 			max_allowed_pdu_size = SMB3_MAX_MSGSIZE;
488 
489 		if (pdu_size > max_allowed_pdu_size) {
490 			pr_err_ratelimited("PDU length(%u) exceeded maximum allowed pdu size(%u) on connection(%d)\n",
491 					pdu_size, max_allowed_pdu_size,
492 					READ_ONCE(conn->status));
493 			break;
494 		}
495 
496 		/*
497 		 * Check maximum pdu size(0x00FFFFFF).
498 		 */
499 		if (pdu_size > MAX_STREAM_PROT_LEN)
500 			break;
501 
502 		if (pdu_size < SMB1_MIN_SUPPORTED_PDU_SIZE)
503 			break;
504 
505 		/* 4 for rfc1002 length field */
506 		/* 1 for implied bcc[0] */
507 		size = pdu_size + 4 + 1;
508 		conn->request_buf = kvmalloc(size, KSMBD_DEFAULT_GFP);
509 		if (!conn->request_buf)
510 			break;
511 
512 		memcpy(conn->request_buf, hdr_buf, sizeof(hdr_buf));
513 
514 		/*
515 		 * We already read 4 bytes to find out PDU size, now
516 		 * read in PDU
517 		 */
518 		size = t->ops->read(t, conn->request_buf + 4, pdu_size, 2);
519 		if (size < 0) {
520 			pr_err("sock_read failed: %d\n", size);
521 			break;
522 		}
523 
524 		if (size != pdu_size) {
525 			pr_err("PDU error. Read: %d, Expected: %d\n",
526 			       size, pdu_size);
527 			continue;
528 		}
529 
530 		if (!ksmbd_smb_request(conn))
531 			break;
532 
533 		if (((struct smb2_hdr *)smb_get_msg(conn->request_buf))->ProtocolId ==
534 		    SMB2_PROTO_NUMBER) {
535 			if (pdu_size < SMB2_MIN_SUPPORTED_PDU_SIZE)
536 				break;
537 		}
538 
539 		if (!default_conn_ops.process_fn) {
540 			pr_err("No connection request callback\n");
541 			break;
542 		}
543 
544 		if (default_conn_ops.process_fn(conn)) {
545 			pr_err("Cannot handle request\n");
546 			break;
547 		}
548 	}
549 
550 	ksmbd_conn_set_releasing(conn);
551 	/* Wait till all reference dropped to the Server object*/
552 	ksmbd_debug(CONN, "Wait for all pending requests(%d)\n", atomic_read(&conn->r_count));
553 	wait_event(conn->r_count_q, atomic_read(&conn->r_count) == 0);
554 
555 	if (IS_ENABLED(CONFIG_UNICODE))
556 		utf8_unload(conn->um);
557 	unload_nls(conn->local_nls);
558 	if (default_conn_ops.terminate_fn)
559 		default_conn_ops.terminate_fn(conn);
560 	t->ops->disconnect(t);
561 	module_put(THIS_MODULE);
562 	return 0;
563 }
564 
565 void ksmbd_conn_init_server_callbacks(struct ksmbd_conn_ops *ops)
566 {
567 	default_conn_ops.process_fn = ops->process_fn;
568 	default_conn_ops.terminate_fn = ops->terminate_fn;
569 }
570 
571 void ksmbd_conn_r_count_inc(struct ksmbd_conn *conn)
572 {
573 	atomic_inc(&conn->r_count);
574 }
575 
576 void ksmbd_conn_r_count_dec(struct ksmbd_conn *conn)
577 {
578 	/*
579 	 * Checking waitqueue to dropping pending requests on
580 	 * disconnection. waitqueue_active is safe because it
581 	 * uses atomic operation for condition.
582 	 */
583 	atomic_inc(&conn->refcnt);
584 	if (!atomic_dec_return(&conn->r_count) && waitqueue_active(&conn->r_count_q))
585 		wake_up(&conn->r_count_q);
586 
587 	ksmbd_conn_put(conn);
588 }
589 
590 int ksmbd_conn_transport_init(void)
591 {
592 	int ret;
593 
594 	mutex_lock(&init_lock);
595 	ret = ksmbd_tcp_init();
596 	if (ret) {
597 		pr_err("Failed to init TCP subsystem: %d\n", ret);
598 		goto out;
599 	}
600 
601 	ret = ksmbd_rdma_init();
602 	if (ret) {
603 		pr_err("Failed to init RDMA subsystem: %d\n", ret);
604 		goto out;
605 	}
606 out:
607 	mutex_unlock(&init_lock);
608 	create_proc_clients();
609 	return ret;
610 }
611 
612 static void stop_sessions(void)
613 {
614 	struct ksmbd_conn *conn, *target;
615 	struct ksmbd_transport *t;
616 	bool any;
617 	int bkt;
618 
619 	/*
620 	 * Serialised via init_lock; no concurrent stop_sessions() can
621 	 * touch conn->stop_called, so writing it under the read lock is
622 	 * safe.
623 	 */
624 again:
625 	target = NULL;
626 	any = false;
627 	down_read(&conn_list_lock);
628 	hash_for_each(conn_list, bkt, conn, hlist) {
629 		any = true;
630 		if (conn->stop_called)
631 			continue;
632 		atomic_inc(&conn->refcnt);
633 		conn->stop_called = true;
634 		/*
635 		 * Mark the connection EXITING while still holding the
636 		 * read lock so the selection and the status transition
637 		 * happen together.  Do not regress a connection that has
638 		 * already advanced to RELEASING on its own (e.g. the
639 		 * handler exited its receive loop for an unrelated
640 		 * reason).
641 		 */
642 		if (READ_ONCE(conn->status) != KSMBD_SESS_RELEASING)
643 			ksmbd_conn_set_exiting(conn);
644 		target = conn;
645 		break;
646 	}
647 	up_read(&conn_list_lock);
648 
649 	if (target) {
650 		t = target->transport;
651 		if (t->ops->shutdown)
652 			t->ops->shutdown(t);
653 		if (atomic_dec_and_test(&target->refcnt)) {
654 			ida_destroy(&target->async_ida);
655 			t->ops->free_transport(t);
656 			kfree(target);
657 		}
658 		goto again;
659 	}
660 
661 	if (any) {
662 		msleep(100);
663 		goto again;
664 	}
665 }
666 
667 void ksmbd_conn_transport_destroy(void)
668 {
669 	delete_proc_clients();
670 	mutex_lock(&init_lock);
671 	ksmbd_tcp_destroy();
672 	ksmbd_rdma_stop_listening();
673 	stop_sessions();
674 	mutex_unlock(&init_lock);
675 }
676