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