transport_rdma.c 54.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 *   Copyright (C) 2017, Microsoft Corporation.
 *   Copyright (C) 2018, LG Electronics.
 *
 *   Author(s): Long Li <longli@microsoft.com>,
 *		Hyunchul Lee <hyc.lee@gmail.com>
 *
 *   This program is free software;  you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY;  without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
 *   the GNU General Public License for more details.
 */

#define SUBMOD_NAME	"smb_direct"

#include <linux/kthread.h>
#include <linux/list.h>
#include <linux/mempool.h>
#include <linux/highmem.h>
#include <linux/scatterlist.h>
#include <rdma/ib_verbs.h>
#include <rdma/rdma_cm.h>
#include <rdma/rw.h>

#include "glob.h"
#include "connection.h"
#include "smb_common.h"
#include "smbstatus.h"
#include "transport_rdma.h"

#define SMB_DIRECT_PORT	5445

#define SMB_DIRECT_VERSION_LE		cpu_to_le16(0x0100)

/* SMB_DIRECT negotiation timeout in seconds */
#define SMB_DIRECT_NEGOTIATE_TIMEOUT		120

#define SMB_DIRECT_MAX_SEND_SGES		8
#define SMB_DIRECT_MAX_RECV_SGES		1

/*
 * Default maximum number of RDMA read/write outstanding on this connection
 * This value is possibly decreased during QP creation on hardware limit
 */
#define SMB_DIRECT_CM_INITIATOR_DEPTH		8

/* Maximum number of retries on data transfer operations */
#define SMB_DIRECT_CM_RETRY			6
/* No need to retry on Receiver Not Ready since SMB_DIRECT manages credits */
#define SMB_DIRECT_CM_RNR_RETRY		0

/*
 * User configurable initial values per SMB_DIRECT transport connection
N
Namjae Jeon 已提交
60
 * as defined in [MS-SMBD] 3.1.1.1
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
 * Those may change after a SMB_DIRECT negotiation
 */
/* The local peer's maximum number of credits to grant to the peer */
static int smb_direct_receive_credit_max = 255;

/* The remote peer's credit request of local peer */
static int smb_direct_send_credit_target = 255;

/* The maximum single message size can be sent to remote peer */
static int smb_direct_max_send_size = 8192;

/*  The maximum fragmented upper-layer payload receive size supported */
static int smb_direct_max_fragmented_recv_size = 1024 * 1024;

/*  The maximum single-message size which can be received */
static int smb_direct_max_receive_size = 8192;

static int smb_direct_max_read_write_size = 1024 * 1024;

static int smb_direct_max_outstanding_rw_ops = 8;

static struct smb_direct_listener {
	struct rdma_cm_id	*cm_id;
} smb_direct_listener;

static struct workqueue_struct *smb_direct_wq;

enum smb_direct_status {
	SMB_DIRECT_CS_NEW = 0,
	SMB_DIRECT_CS_CONNECTED,
	SMB_DIRECT_CS_DISCONNECTING,
	SMB_DIRECT_CS_DISCONNECTED,
};

struct smb_direct_transport {
	struct ksmbd_transport	transport;

	enum smb_direct_status	status;
	bool			full_packet_received;
	wait_queue_head_t	wait_status;

	struct rdma_cm_id	*cm_id;
	struct ib_cq		*send_cq;
	struct ib_cq		*recv_cq;
	struct ib_pd		*pd;
	struct ib_qp		*qp;

	int			max_send_size;
	int			max_recv_size;
	int			max_fragmented_send_size;
	int			max_fragmented_recv_size;
	int			max_rdma_rw_size;

	spinlock_t		reassembly_queue_lock;
	struct list_head	reassembly_queue;
	int			reassembly_data_length;
	int			reassembly_queue_length;
	int			first_entry_offset;
	wait_queue_head_t	wait_reassembly_queue;

	spinlock_t		receive_credit_lock;
	int			recv_credits;
	int			count_avail_recvmsg;
	int			recv_credit_max;
	int			recv_credit_target;

	spinlock_t		recvmsg_queue_lock;
	struct list_head	recvmsg_queue;

	spinlock_t		empty_recvmsg_queue_lock;
	struct list_head	empty_recvmsg_queue;

	int			send_credit_target;
	atomic_t		send_credits;
	spinlock_t		lock_new_recv_credits;
	int			new_recv_credits;
	atomic_t		rw_avail_ops;

	wait_queue_head_t	wait_send_credits;
	wait_queue_head_t	wait_rw_avail_ops;

	mempool_t		*sendmsg_mempool;
	struct kmem_cache	*sendmsg_cache;
	mempool_t		*recvmsg_mempool;
	struct kmem_cache	*recvmsg_cache;

	wait_queue_head_t	wait_send_payload_pending;
	atomic_t		send_payload_pending;
	wait_queue_head_t	wait_send_pending;
	atomic_t		send_pending;

	struct delayed_work	post_recv_credits_work;
	struct work_struct	send_immediate_work;
	struct work_struct	disconnect_work;

	bool			negotiation_requested;
};

#define KSMBD_TRANS(t) ((struct ksmbd_transport *)&((t)->transport))

enum {
	SMB_DIRECT_MSG_NEGOTIATE_REQ = 0,
	SMB_DIRECT_MSG_DATA_TRANSFER
};

static struct ksmbd_transport_ops ksmbd_smb_direct_transport_ops;

struct smb_direct_send_ctx {
	struct list_head	msg_list;
	int			wr_cnt;
	bool			need_invalidate_rkey;
	unsigned int		remote_key;
};

struct smb_direct_sendmsg {
	struct smb_direct_transport	*transport;
	struct ib_send_wr	wr;
	struct list_head	list;
	int			num_sge;
	struct ib_sge		sge[SMB_DIRECT_MAX_SEND_SGES];
	struct ib_cqe		cqe;
	u8			packet[];
};

struct smb_direct_recvmsg {
	struct smb_direct_transport	*transport;
	struct list_head	list;
	int			type;
	struct ib_sge		sge;
	struct ib_cqe		cqe;
	bool			first_segment;
	u8			packet[];
};

struct smb_direct_rdma_rw_msg {
	struct smb_direct_transport	*t;
	struct ib_cqe		cqe;
	struct completion	*completion;
	struct rdma_rw_ctx	rw_ctx;
	struct sg_table		sgt;
	struct scatterlist	sg_list[0];
};

204 205 206 207 208
static inline int get_buf_page_count(void *buf, int size)
{
	return DIV_ROUND_UP((uintptr_t)buf + size, PAGE_SIZE) -
		(uintptr_t)buf / PAGE_SIZE;
}
209 210 211 212

static void smb_direct_destroy_pools(struct smb_direct_transport *transport);
static void smb_direct_post_recv_credits(struct work_struct *work);
static int smb_direct_post_send_data(struct smb_direct_transport *t,
213 214 215
				     struct smb_direct_send_ctx *send_ctx,
				     struct kvec *iov, int niov,
				     int remaining_data_length);
216

217 218 219 220 221 222
static inline struct smb_direct_transport *
smb_trans_direct_transfort(struct ksmbd_transport *t)
{
	return container_of(t, struct smb_direct_transport, transport);
}

223 224 225 226 227 228 229
static inline void
*smb_direct_recvmsg_payload(struct smb_direct_recvmsg *recvmsg)
{
	return (void *)recvmsg->packet;
}

static inline bool is_receive_credit_post_required(int receive_credits,
230
						   int avail_recvmsg_count)
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
{
	return receive_credits <= (smb_direct_receive_credit_max >> 3) &&
		avail_recvmsg_count >= (receive_credits >> 2);
}

static struct
smb_direct_recvmsg *get_free_recvmsg(struct smb_direct_transport *t)
{
	struct smb_direct_recvmsg *recvmsg = NULL;

	spin_lock(&t->recvmsg_queue_lock);
	if (!list_empty(&t->recvmsg_queue)) {
		recvmsg = list_first_entry(&t->recvmsg_queue,
					   struct smb_direct_recvmsg,
					   list);
		list_del(&recvmsg->list);
	}
	spin_unlock(&t->recvmsg_queue_lock);
	return recvmsg;
}

static void put_recvmsg(struct smb_direct_transport *t,
253
			struct smb_direct_recvmsg *recvmsg)
254 255
{
	ib_dma_unmap_single(t->cm_id->device, recvmsg->sge.addr,
256
			    recvmsg->sge.length, DMA_FROM_DEVICE);
257 258 259 260 261 262 263 264 265 266 267 268 269

	spin_lock(&t->recvmsg_queue_lock);
	list_add(&recvmsg->list, &t->recvmsg_queue);
	spin_unlock(&t->recvmsg_queue_lock);
}

static struct
smb_direct_recvmsg *get_empty_recvmsg(struct smb_direct_transport *t)
{
	struct smb_direct_recvmsg *recvmsg = NULL;

	spin_lock(&t->empty_recvmsg_queue_lock);
	if (!list_empty(&t->empty_recvmsg_queue)) {
270
		recvmsg = list_first_entry(&t->empty_recvmsg_queue,
271
					   struct smb_direct_recvmsg, list);
272 273 274 275 276 277 278
		list_del(&recvmsg->list);
	}
	spin_unlock(&t->empty_recvmsg_queue_lock);
	return recvmsg;
}

static void put_empty_recvmsg(struct smb_direct_transport *t,
279
			      struct smb_direct_recvmsg *recvmsg)
280 281
{
	ib_dma_unmap_single(t->cm_id->device, recvmsg->sge.addr,
282
			    recvmsg->sge.length, DMA_FROM_DEVICE);
283 284 285 286 287 288 289

	spin_lock(&t->empty_recvmsg_queue_lock);
	list_add_tail(&recvmsg->list, &t->empty_recvmsg_queue);
	spin_unlock(&t->empty_recvmsg_queue_lock);
}

static void enqueue_reassembly(struct smb_direct_transport *t,
290 291
			       struct smb_direct_recvmsg *recvmsg,
			       int data_length)
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
{
	spin_lock(&t->reassembly_queue_lock);
	list_add_tail(&recvmsg->list, &t->reassembly_queue);
	t->reassembly_queue_length++;
	/*
	 * Make sure reassembly_data_length is updated after list and
	 * reassembly_queue_length are updated. On the dequeue side
	 * reassembly_data_length is checked without a lock to determine
	 * if reassembly_queue_length and list is up to date
	 */
	virt_wmb();
	t->reassembly_data_length += data_length;
	spin_unlock(&t->reassembly_queue_lock);
}

307
static struct smb_direct_recvmsg *get_first_reassembly(struct smb_direct_transport *t)
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
{
	if (!list_empty(&t->reassembly_queue))
		return list_first_entry(&t->reassembly_queue,
				struct smb_direct_recvmsg, list);
	else
		return NULL;
}

static void smb_direct_disconnect_rdma_work(struct work_struct *work)
{
	struct smb_direct_transport *t =
		container_of(work, struct smb_direct_transport,
			     disconnect_work);

	if (t->status == SMB_DIRECT_CS_CONNECTED) {
		t->status = SMB_DIRECT_CS_DISCONNECTING;
		rdma_disconnect(t->cm_id);
	}
}

static void
smb_direct_disconnect_rdma_connection(struct smb_direct_transport *t)
{
331 332
	if (t->status == SMB_DIRECT_CS_CONNECTED)
		queue_work(smb_direct_wq, &t->disconnect_work);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
}

static void smb_direct_send_immediate_work(struct work_struct *work)
{
	struct smb_direct_transport *t = container_of(work,
			struct smb_direct_transport, send_immediate_work);

	if (t->status != SMB_DIRECT_CS_CONNECTED)
		return;

	smb_direct_post_send_data(t, NULL, NULL, 0, 0);
}

static struct smb_direct_transport *alloc_transport(struct rdma_cm_id *cm_id)
{
	struct smb_direct_transport *t;
	struct ksmbd_conn *conn;

	t = kzalloc(sizeof(*t), GFP_KERNEL);
	if (!t)
		return NULL;

	t->cm_id = cm_id;
	cm_id->context = t;

	t->status = SMB_DIRECT_CS_NEW;
	init_waitqueue_head(&t->wait_status);

	spin_lock_init(&t->reassembly_queue_lock);
	INIT_LIST_HEAD(&t->reassembly_queue);
	t->reassembly_data_length = 0;
	t->reassembly_queue_length = 0;
	init_waitqueue_head(&t->wait_reassembly_queue);
	init_waitqueue_head(&t->wait_send_credits);
	init_waitqueue_head(&t->wait_rw_avail_ops);

	spin_lock_init(&t->receive_credit_lock);
	spin_lock_init(&t->recvmsg_queue_lock);
	INIT_LIST_HEAD(&t->recvmsg_queue);

	spin_lock_init(&t->empty_recvmsg_queue_lock);
	INIT_LIST_HEAD(&t->empty_recvmsg_queue);

	init_waitqueue_head(&t->wait_send_payload_pending);
	atomic_set(&t->send_payload_pending, 0);
	init_waitqueue_head(&t->wait_send_pending);
	atomic_set(&t->send_pending, 0);

	spin_lock_init(&t->lock_new_recv_credits);

	INIT_DELAYED_WORK(&t->post_recv_credits_work,
			  smb_direct_post_recv_credits);
	INIT_WORK(&t->send_immediate_work, smb_direct_send_immediate_work);
	INIT_WORK(&t->disconnect_work, smb_direct_disconnect_rdma_work);

	conn = ksmbd_conn_alloc();
	if (!conn)
		goto err;
	conn->transport = KSMBD_TRANS(t);
	KSMBD_TRANS(t)->conn = conn;
	KSMBD_TRANS(t)->ops = &ksmbd_smb_direct_transport_ops;
	return t;
err:
	kfree(t);
	return NULL;
}

static void free_transport(struct smb_direct_transport *t)
{
	struct smb_direct_recvmsg *recvmsg;

	wake_up_interruptible(&t->wait_send_credits);

	ksmbd_debug(RDMA, "wait for all send posted to IB to finish\n");
	wait_event(t->wait_send_payload_pending,
408
		   atomic_read(&t->send_payload_pending) == 0);
409
	wait_event(t->wait_send_pending,
410
		   atomic_read(&t->send_pending) == 0);
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

	cancel_work_sync(&t->disconnect_work);
	cancel_delayed_work_sync(&t->post_recv_credits_work);
	cancel_work_sync(&t->send_immediate_work);

	if (t->qp) {
		ib_drain_qp(t->qp);
		ib_destroy_qp(t->qp);
	}

	ksmbd_debug(RDMA, "drain the reassembly queue\n");
	do {
		spin_lock(&t->reassembly_queue_lock);
		recvmsg = get_first_reassembly(t);
		if (recvmsg) {
			list_del(&recvmsg->list);
427
			spin_unlock(&t->reassembly_queue_lock);
428
			put_recvmsg(t, recvmsg);
429
		} else {
430
			spin_unlock(&t->reassembly_queue_lock);
431
		}
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
	} while (recvmsg);
	t->reassembly_data_length = 0;

	if (t->send_cq)
		ib_free_cq(t->send_cq);
	if (t->recv_cq)
		ib_free_cq(t->recv_cq);
	if (t->pd)
		ib_dealloc_pd(t->pd);
	if (t->cm_id)
		rdma_destroy_id(t->cm_id);

	smb_direct_destroy_pools(t);
	ksmbd_conn_free(KSMBD_TRANS(t)->conn);
	kfree(t);
}

static struct smb_direct_sendmsg
*smb_direct_alloc_sendmsg(struct smb_direct_transport *t)
{
	struct smb_direct_sendmsg *msg;

	msg = mempool_alloc(t->sendmsg_mempool, GFP_KERNEL);
	if (!msg)
		return ERR_PTR(-ENOMEM);
	msg->transport = t;
	INIT_LIST_HEAD(&msg->list);
	msg->num_sge = 0;
	return msg;
}

static void smb_direct_free_sendmsg(struct smb_direct_transport *t,
464
				    struct smb_direct_sendmsg *msg)
465 466 467 468 469
{
	int i;

	if (msg->num_sge > 0) {
		ib_dma_unmap_single(t->cm_id->device,
470 471
				    msg->sge[0].addr, msg->sge[0].length,
				    DMA_TO_DEVICE);
472 473
		for (i = 1; i < msg->num_sge; i++)
			ib_dma_unmap_page(t->cm_id->device,
474 475
					  msg->sge[i].addr, msg->sge[i].length,
					  DMA_TO_DEVICE);
476 477 478 479 480 481 482 483 484
	}
	mempool_free(msg, t->sendmsg_mempool);
}

static int smb_direct_check_recvmsg(struct smb_direct_recvmsg *recvmsg)
{
	switch (recvmsg->type) {
	case SMB_DIRECT_MSG_DATA_TRANSFER: {
		struct smb_direct_data_transfer *req =
485 486
			(struct smb_direct_data_transfer *)recvmsg->packet;
		struct smb2_hdr *hdr = (struct smb2_hdr *)(recvmsg->packet
487 488
				+ le32_to_cpu(req->data_offset) - 4);
		ksmbd_debug(RDMA,
489 490 491 492 493
			    "CreditGranted: %u, CreditRequested: %u, DataLength: %u, RemainingDataLength: %u, SMB: %x, Command: %u\n",
			    le16_to_cpu(req->credits_granted),
			    le16_to_cpu(req->credits_requested),
			    req->data_length, req->remaining_data_length,
			    hdr->ProtocolId, hdr->Command);
494 495 496 497 498 499
		break;
	}
	case SMB_DIRECT_MSG_NEGOTIATE_REQ: {
		struct smb_direct_negotiate_req *req =
			(struct smb_direct_negotiate_req *)recvmsg->packet;
		ksmbd_debug(RDMA,
500 501 502 503 504 505 506
			    "MinVersion: %u, MaxVersion: %u, CreditRequested: %u, MaxSendSize: %u, MaxRecvSize: %u, MaxFragmentedSize: %u\n",
			    le16_to_cpu(req->min_version),
			    le16_to_cpu(req->max_version),
			    le16_to_cpu(req->credits_requested),
			    le32_to_cpu(req->preferred_send_size),
			    le32_to_cpu(req->max_receive_size),
			    le32_to_cpu(req->max_fragmented_size));
507
		if (le16_to_cpu(req->min_version) > 0x0100 ||
508
		    le16_to_cpu(req->max_version) < 0x0100)
509 510
			return -EOPNOTSUPP;
		if (le16_to_cpu(req->credits_requested) <= 0 ||
511 512 513
		    le32_to_cpu(req->max_receive_size) <= 128 ||
		    le32_to_cpu(req->max_fragmented_size) <=
					128 * 1024)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
			return -ECONNABORTED;

		break;
	}
	default:
		return -EINVAL;
	}
	return 0;
}

static void recv_done(struct ib_cq *cq, struct ib_wc *wc)
{
	struct smb_direct_recvmsg *recvmsg;
	struct smb_direct_transport *t;

	recvmsg = container_of(wc->wr_cqe, struct smb_direct_recvmsg, cqe);
	t = recvmsg->transport;

	if (wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV) {
		if (wc->status != IB_WC_WR_FLUSH_ERR) {
N
Namjae Jeon 已提交
534 535 536
			pr_err("Recv error. status='%s (%d)' opcode=%d\n",
			       ib_wc_status_msg(wc->status), wc->status,
			       wc->opcode);
537 538 539 540 541 542 543
			smb_direct_disconnect_rdma_connection(t);
		}
		put_empty_recvmsg(t, recvmsg);
		return;
	}

	ksmbd_debug(RDMA, "Recv completed. status='%s (%d)', opcode=%d\n",
544 545
		    ib_wc_status_msg(wc->status), wc->status,
		    wc->opcode);
546 547

	ib_dma_sync_single_for_cpu(wc->qp->device, recvmsg->sge.addr,
548
				   recvmsg->sge.length, DMA_FROM_DEVICE);
549 550 551

	switch (recvmsg->type) {
	case SMB_DIRECT_MSG_NEGOTIATE_REQ:
552 553 554 555
		if (wc->byte_len < sizeof(struct smb_direct_negotiate_req)) {
			put_empty_recvmsg(t, recvmsg);
			return;
		}
556 557 558 559 560 561 562
		t->negotiation_requested = true;
		t->full_packet_received = true;
		wake_up_interruptible(&t->wait_status);
		break;
	case SMB_DIRECT_MSG_DATA_TRANSFER: {
		struct smb_direct_data_transfer *data_transfer =
			(struct smb_direct_data_transfer *)recvmsg->packet;
563
		unsigned int data_length;
564 565
		int avail_recvmsg_count, receive_credits;

566 567 568 569 570 571 572
		if (wc->byte_len <
		    offsetof(struct smb_direct_data_transfer, padding)) {
			put_empty_recvmsg(t, recvmsg);
			return;
		}

		data_length = le32_to_cpu(data_transfer->data_length);
573
		if (data_length) {
574 575 576 577 578 579
			if (wc->byte_len < sizeof(struct smb_direct_data_transfer) +
			    (u64)data_length) {
				put_empty_recvmsg(t, recvmsg);
				return;
			}

580 581 582 583 584 585 586 587
			if (t->full_packet_received)
				recvmsg->first_segment = true;

			if (le32_to_cpu(data_transfer->remaining_data_length))
				t->full_packet_received = false;
			else
				t->full_packet_received = true;

588
			enqueue_reassembly(t, recvmsg, (int)data_length);
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
			wake_up_interruptible(&t->wait_reassembly_queue);

			spin_lock(&t->receive_credit_lock);
			receive_credits = --(t->recv_credits);
			avail_recvmsg_count = t->count_avail_recvmsg;
			spin_unlock(&t->receive_credit_lock);
		} else {
			put_empty_recvmsg(t, recvmsg);

			spin_lock(&t->receive_credit_lock);
			receive_credits = --(t->recv_credits);
			avail_recvmsg_count = ++(t->count_avail_recvmsg);
			spin_unlock(&t->receive_credit_lock);
		}

		t->recv_credit_target =
				le16_to_cpu(data_transfer->credits_requested);
		atomic_add(le16_to_cpu(data_transfer->credits_granted),
607
			   &t->send_credits);
608 609

		if (le16_to_cpu(data_transfer->flags) &
610
		    SMB_DIRECT_RESPONSE_REQUESTED)
611 612 613 614 615
			queue_work(smb_direct_wq, &t->send_immediate_work);

		if (atomic_read(&t->send_credits) > 0)
			wake_up_interruptible(&t->wait_send_credits);

616
		if (is_receive_credit_post_required(receive_credits, avail_recvmsg_count))
617
			mod_delayed_work(smb_direct_wq,
618
					 &t->post_recv_credits_work, 0);
619 620 621 622 623 624 625 626
		break;
	}
	default:
		break;
	}
}

static int smb_direct_post_recv(struct smb_direct_transport *t,
627
				struct smb_direct_recvmsg *recvmsg)
628 629 630 631 632
{
	struct ib_recv_wr wr;
	int ret;

	recvmsg->sge.addr = ib_dma_map_single(t->cm_id->device,
633 634
					      recvmsg->packet, t->max_recv_size,
					      DMA_FROM_DEVICE);
635 636 637 638 639 640 641 642 643 644 645 646 647 648
	ret = ib_dma_mapping_error(t->cm_id->device, recvmsg->sge.addr);
	if (ret)
		return ret;
	recvmsg->sge.length = t->max_recv_size;
	recvmsg->sge.lkey = t->pd->local_dma_lkey;
	recvmsg->cqe.done = recv_done;

	wr.wr_cqe = &recvmsg->cqe;
	wr.next = NULL;
	wr.sg_list = &recvmsg->sge;
	wr.num_sge = 1;

	ret = ib_post_recv(t->qp, &wr, NULL);
	if (ret) {
N
Namjae Jeon 已提交
649
		pr_err("Can't post recv: %d\n", ret);
650
		ib_dma_unmap_single(t->cm_id->device,
651 652
				    recvmsg->sge.addr, recvmsg->sge.length,
				    DMA_FROM_DEVICE);
653 654 655 656 657 658 659
		smb_direct_disconnect_rdma_connection(t);
		return ret;
	}
	return ret;
}

static int smb_direct_read(struct ksmbd_transport *t, char *buf,
660
			   unsigned int size)
661 662 663 664 665 666
{
	struct smb_direct_recvmsg *recvmsg;
	struct smb_direct_data_transfer *data_transfer;
	int to_copy, to_read, data_read, offset;
	u32 data_length, remaining_data_length, data_offset;
	int rc;
667
	struct smb_direct_transport *st = smb_trans_direct_transfort(t);
668 669 670

again:
	if (st->status != SMB_DIRECT_CS_CONNECTED) {
N
Namjae Jeon 已提交
671
		pr_err("disconnected\n");
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		return -ENOTCONN;
	}

	/*
	 * No need to hold the reassembly queue lock all the time as we are
	 * the only one reading from the front of the queue. The transport
	 * may add more entries to the back of the queue at the same time
	 */
	if (st->reassembly_data_length >= size) {
		int queue_length;
		int queue_removed = 0;

		/*
		 * Need to make sure reassembly_data_length is read before
		 * reading reassembly_queue_length and calling
		 * get_first_reassembly. This call is lock free
		 * as we never read at the end of the queue which are being
		 * updated in SOFTIRQ as more data is received
		 */
		virt_rmb();
		queue_length = st->reassembly_queue_length;
		data_read = 0;
		to_read = size;
		offset = st->first_entry_offset;
		while (data_read < size) {
			recvmsg = get_first_reassembly(st);
			data_transfer = smb_direct_recvmsg_payload(recvmsg);
			data_length = le32_to_cpu(data_transfer->data_length);
			remaining_data_length =
701
				le32_to_cpu(data_transfer->remaining_data_length);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
			data_offset = le32_to_cpu(data_transfer->data_offset);

			/*
			 * The upper layer expects RFC1002 length at the
			 * beginning of the payload. Return it to indicate
			 * the total length of the packet. This minimize the
			 * change to upper layer packet processing logic. This
			 * will be eventually remove when an intermediate
			 * transport layer is added
			 */
			if (recvmsg->first_segment && size == 4) {
				unsigned int rfc1002_len =
					data_length + remaining_data_length;
				*((__be32 *)buf) = cpu_to_be32(rfc1002_len);
				data_read = 4;
				recvmsg->first_segment = false;
				ksmbd_debug(RDMA,
719 720
					    "returning rfc1002 length %d\n",
					    rfc1002_len);
721 722 723 724
				goto read_rfc1002_done;
			}

			to_copy = min_t(int, data_length - offset, to_read);
725
			memcpy(buf + data_read, (char *)data_transfer + data_offset + offset,
726
			       to_copy);
727 728 729 730 731 732 733 734

			/* move on to the next buffer? */
			if (to_copy == data_length - offset) {
				queue_length--;
				/*
				 * No need to lock if we are not at the
				 * end of the queue
				 */
735
				if (queue_length) {
736
					list_del(&recvmsg->list);
737 738
				} else {
					spin_lock_irq(&st->reassembly_queue_lock);
739
					list_del(&recvmsg->list);
740
					spin_unlock_irq(&st->reassembly_queue_lock);
741 742 743 744
				}
				queue_removed++;
				put_recvmsg(st, recvmsg);
				offset = 0;
745
			} else {
746
				offset += to_copy;
747
			}
748 749 750 751 752 753 754 755 756 757 758 759

			to_read -= to_copy;
			data_read += to_copy;
		}

		spin_lock_irq(&st->reassembly_queue_lock);
		st->reassembly_data_length -= data_read;
		st->reassembly_queue_length -= queue_removed;
		spin_unlock_irq(&st->reassembly_queue_lock);

		spin_lock(&st->receive_credit_lock);
		st->count_avail_recvmsg += queue_removed;
760
		if (is_receive_credit_post_required(st->recv_credits, st->count_avail_recvmsg)) {
761 762
			spin_unlock(&st->receive_credit_lock);
			mod_delayed_work(smb_direct_wq,
763
					 &st->post_recv_credits_work, 0);
764
		} else {
765
			spin_unlock(&st->receive_credit_lock);
766
		}
767 768 769

		st->first_entry_offset = offset;
		ksmbd_debug(RDMA,
770 771 772
			    "returning to thread data_read=%d reassembly_data_length=%d first_entry_offset=%d\n",
			    data_read, st->reassembly_data_length,
			    st->first_entry_offset);
773 774 775 776 777
read_rfc1002_done:
		return data_read;
	}

	ksmbd_debug(RDMA, "wait_event on more data\n");
778
	rc = wait_event_interruptible(st->wait_reassembly_queue,
779 780
				      st->reassembly_data_length >= size ||
				       st->status != SMB_DIRECT_CS_CONNECTED);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
	if (rc)
		return -EINTR;

	goto again;
}

static void smb_direct_post_recv_credits(struct work_struct *work)
{
	struct smb_direct_transport *t = container_of(work,
		struct smb_direct_transport, post_recv_credits_work.work);
	struct smb_direct_recvmsg *recvmsg;
	int receive_credits, credits = 0;
	int ret;
	int use_free = 1;

	spin_lock(&t->receive_credit_lock);
	receive_credits = t->recv_credits;
	spin_unlock(&t->receive_credit_lock);

	if (receive_credits < t->recv_credit_target) {
		while (true) {
			if (use_free)
				recvmsg = get_free_recvmsg(t);
			else
				recvmsg = get_empty_recvmsg(t);
			if (!recvmsg) {
				if (use_free) {
					use_free = 0;
					continue;
810
				} else {
811
					break;
812
				}
813 814 815 816 817 818 819
			}

			recvmsg->type = SMB_DIRECT_MSG_DATA_TRANSFER;
			recvmsg->first_segment = false;

			ret = smb_direct_post_recv(t, recvmsg);
			if (ret) {
N
Namjae Jeon 已提交
820
				pr_err("Can't post recv: %d\n", ret);
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
				put_recvmsg(t, recvmsg);
				break;
			}
			credits++;
		}
	}

	spin_lock(&t->receive_credit_lock);
	t->recv_credits += credits;
	t->count_avail_recvmsg -= credits;
	spin_unlock(&t->receive_credit_lock);

	spin_lock(&t->lock_new_recv_credits);
	t->new_recv_credits += credits;
	spin_unlock(&t->lock_new_recv_credits);

	if (credits)
		queue_work(smb_direct_wq, &t->send_immediate_work);
}

static void send_done(struct ib_cq *cq, struct ib_wc *wc)
{
	struct smb_direct_sendmsg *sendmsg, *sibling;
	struct smb_direct_transport *t;
	struct list_head *pos, *prev, *end;

	sendmsg = container_of(wc->wr_cqe, struct smb_direct_sendmsg, cqe);
	t = sendmsg->transport;

	ksmbd_debug(RDMA, "Send completed. status='%s (%d)', opcode=%d\n",
851 852
		    ib_wc_status_msg(wc->status), wc->status,
		    wc->opcode);
853 854

	if (wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_SEND) {
N
Namjae Jeon 已提交
855 856 857
		pr_err("Send error. status='%s (%d)', opcode=%d\n",
		       ib_wc_status_msg(wc->status), wc->status,
		       wc->opcode);
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
		smb_direct_disconnect_rdma_connection(t);
	}

	if (sendmsg->num_sge > 1) {
		if (atomic_dec_and_test(&t->send_payload_pending))
			wake_up(&t->wait_send_payload_pending);
	} else {
		if (atomic_dec_and_test(&t->send_pending))
			wake_up(&t->wait_send_pending);
	}

	/* iterate and free the list of messages in reverse. the list's head
	 * is invalid.
	 */
	for (pos = &sendmsg->list, prev = pos->prev, end = sendmsg->list.next;
873
	     prev != end; pos = prev, prev = prev->prev) {
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
		sibling = container_of(pos, struct smb_direct_sendmsg, list);
		smb_direct_free_sendmsg(t, sibling);
	}

	sibling = container_of(pos, struct smb_direct_sendmsg, list);
	smb_direct_free_sendmsg(t, sibling);
}

static int manage_credits_prior_sending(struct smb_direct_transport *t)
{
	int new_credits;

	spin_lock(&t->lock_new_recv_credits);
	new_credits = t->new_recv_credits;
	t->new_recv_credits = 0;
	spin_unlock(&t->lock_new_recv_credits);

	return new_credits;
}

static int smb_direct_post_send(struct smb_direct_transport *t,
895
				struct ib_send_wr *wr)
896 897 898 899 900 901 902 903 904 905
{
	int ret;

	if (wr->num_sge > 1)
		atomic_inc(&t->send_payload_pending);
	else
		atomic_inc(&t->send_pending);

	ret = ib_post_send(t->qp, wr, NULL);
	if (ret) {
N
Namjae Jeon 已提交
906
		pr_err("failed to post send: %d\n", ret);
907 908 909 910 911 912 913 914 915 916 917 918 919
		if (wr->num_sge > 1) {
			if (atomic_dec_and_test(&t->send_payload_pending))
				wake_up(&t->wait_send_payload_pending);
		} else {
			if (atomic_dec_and_test(&t->send_pending))
				wake_up(&t->wait_send_pending);
		}
		smb_direct_disconnect_rdma_connection(t);
	}
	return ret;
}

static void smb_direct_send_ctx_init(struct smb_direct_transport *t,
920 921 922
				     struct smb_direct_send_ctx *send_ctx,
				     bool need_invalidate_rkey,
				     unsigned int remote_key)
923 924 925 926 927 928 929 930
{
	INIT_LIST_HEAD(&send_ctx->msg_list);
	send_ctx->wr_cnt = 0;
	send_ctx->need_invalidate_rkey = need_invalidate_rkey;
	send_ctx->remote_key = remote_key;
}

static int smb_direct_flush_send_list(struct smb_direct_transport *t,
931 932
				      struct smb_direct_send_ctx *send_ctx,
				      bool is_last)
933 934 935 936 937 938 939 940
{
	struct smb_direct_sendmsg *first, *last;
	int ret;

	if (list_empty(&send_ctx->msg_list))
		return 0;

	first = list_first_entry(&send_ctx->msg_list,
941 942
				 struct smb_direct_sendmsg,
				 list);
943
	last = list_last_entry(&send_ctx->msg_list,
944 945
			       struct smb_direct_sendmsg,
			       list);
946 947 948 949 950 951 952 953 954 955 956

	last->wr.send_flags = IB_SEND_SIGNALED;
	last->wr.wr_cqe = &last->cqe;
	if (is_last && send_ctx->need_invalidate_rkey) {
		last->wr.opcode = IB_WR_SEND_WITH_INV;
		last->wr.ex.invalidate_rkey = send_ctx->remote_key;
	}

	ret = smb_direct_post_send(t, &first->wr);
	if (!ret) {
		smb_direct_send_ctx_init(t, send_ctx,
957 958
					 send_ctx->need_invalidate_rkey,
					 send_ctx->remote_key);
959 960 961 962
	} else {
		atomic_add(send_ctx->wr_cnt, &t->send_credits);
		wake_up(&t->wait_send_credits);
		list_for_each_entry_safe(first, last, &send_ctx->msg_list,
963
					 list) {
964 965 966 967 968 969 970
			smb_direct_free_sendmsg(t, first);
		}
	}
	return ret;
}

static int wait_for_credits(struct smb_direct_transport *t,
971
			    wait_queue_head_t *waitq, atomic_t *credits)
972 973 974 975 976 977 978 979 980
{
	int ret;

	do {
		if (atomic_dec_return(credits) >= 0)
			return 0;

		atomic_inc(credits);
		ret = wait_event_interruptible(*waitq,
981 982
					       atomic_read(credits) > 0 ||
						t->status != SMB_DIRECT_CS_CONNECTED);
983 984 985 986 987 988 989 990 991

		if (t->status != SMB_DIRECT_CS_CONNECTED)
			return -ENOTCONN;
		else if (ret < 0)
			return ret;
	} while (true);
}

static int wait_for_send_credits(struct smb_direct_transport *t,
992
				 struct smb_direct_send_ctx *send_ctx)
993 994 995
{
	int ret;

996 997
	if (send_ctx &&
	    (send_ctx->wr_cnt >= 16 || atomic_read(&t->send_credits) <= 1)) {
998 999 1000 1001 1002 1003 1004 1005 1006
		ret = smb_direct_flush_send_list(t, send_ctx, false);
		if (ret)
			return ret;
	}

	return wait_for_credits(t, &t->wait_send_credits, &t->send_credits);
}

static int smb_direct_create_header(struct smb_direct_transport *t,
1007 1008
				    int size, int remaining_data_length,
				    struct smb_direct_sendmsg **sendmsg_out)
1009 1010 1011 1012 1013 1014 1015
{
	struct smb_direct_sendmsg *sendmsg;
	struct smb_direct_data_transfer *packet;
	int header_length;
	int ret;

	sendmsg = smb_direct_alloc_sendmsg(t);
D
Dan Carpenter 已提交
1016 1017
	if (IS_ERR(sendmsg))
		return PTR_ERR(sendmsg);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

	/* Fill in the packet header */
	packet = (struct smb_direct_data_transfer *)sendmsg->packet;
	packet->credits_requested = cpu_to_le16(t->send_credit_target);
	packet->credits_granted = cpu_to_le16(manage_credits_prior_sending(t));

	packet->flags = 0;
	packet->reserved = 0;
	if (!size)
		packet->data_offset = 0;
	else
		packet->data_offset = cpu_to_le32(24);
	packet->data_length = cpu_to_le32(size);
	packet->remaining_data_length = cpu_to_le32(remaining_data_length);
	packet->padding = 0;

	ksmbd_debug(RDMA,
1035 1036 1037 1038 1039 1040
		    "credits_requested=%d credits_granted=%d data_offset=%d data_length=%d remaining_data_length=%d\n",
		    le16_to_cpu(packet->credits_requested),
		    le16_to_cpu(packet->credits_granted),
		    le32_to_cpu(packet->data_offset),
		    le32_to_cpu(packet->data_length),
		    le32_to_cpu(packet->remaining_data_length));
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

	/* Map the packet to DMA */
	header_length = sizeof(struct smb_direct_data_transfer);
	/* If this is a packet without payload, don't send padding */
	if (!size)
		header_length =
			offsetof(struct smb_direct_data_transfer, padding);

	sendmsg->sge[0].addr = ib_dma_map_single(t->cm_id->device,
						 (void *)packet,
						 header_length,
						 DMA_TO_DEVICE);
	ret = ib_dma_mapping_error(t->cm_id->device, sendmsg->sge[0].addr);
	if (ret) {
		smb_direct_free_sendmsg(t, sendmsg);
		return ret;
	}

	sendmsg->num_sge = 1;
	sendmsg->sge[0].length = header_length;
	sendmsg->sge[0].lkey = t->pd->local_dma_lkey;

	*sendmsg_out = sendmsg;
	return 0;
}

1067
static int get_sg_list(void *buf, int size, struct scatterlist *sg_list, int nentries)
1068 1069 1070 1071 1072 1073
{
	bool high = is_vmalloc_addr(buf);
	struct page *page;
	int offset, len;
	int i = 0;

1074
	if (nentries < get_buf_page_count(buf, size))
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
		return -EINVAL;

	offset = offset_in_page(buf);
	buf -= offset;
	while (size > 0) {
		len = min_t(int, PAGE_SIZE - offset, size);
		if (high)
			page = vmalloc_to_page(buf);
		else
			page = kmap_to_page(buf);

		if (!sg_list)
			return -EINVAL;
		sg_set_page(sg_list, page, len, offset);
		sg_list = sg_next(sg_list);

		buf += PAGE_SIZE;
		size -= len;
		offset = 0;
		i++;
	}
	return i;
}

static int get_mapped_sg_list(struct ib_device *device, void *buf, int size,
1100 1101
			      struct scatterlist *sg_list, int nentries,
			      enum dma_data_direction dir)
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
{
	int npages;

	npages = get_sg_list(buf, size, sg_list, nentries);
	if (npages <= 0)
		return -EINVAL;
	return ib_dma_map_sg(device, sg_list, npages, dir);
}

static int post_sendmsg(struct smb_direct_transport *t,
1112 1113
			struct smb_direct_send_ctx *send_ctx,
			struct smb_direct_sendmsg *msg)
1114 1115 1116 1117 1118
{
	int i;

	for (i = 0; i < msg->num_sge; i++)
		ib_dma_sync_single_for_device(t->cm_id->device,
1119 1120
					      msg->sge[i].addr, msg->sge[i].length,
					      DMA_TO_DEVICE);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

	msg->cqe.done = send_done;
	msg->wr.opcode = IB_WR_SEND;
	msg->wr.sg_list = &msg->sge[0];
	msg->wr.num_sge = msg->num_sge;
	msg->wr.next = NULL;

	if (send_ctx) {
		msg->wr.wr_cqe = NULL;
		msg->wr.send_flags = 0;
		if (!list_empty(&send_ctx->msg_list)) {
			struct smb_direct_sendmsg *last;

			last = list_last_entry(&send_ctx->msg_list,
					       struct smb_direct_sendmsg,
					       list);
			last->wr.next = &msg->wr;
		}
		list_add_tail(&msg->list, &send_ctx->msg_list);
		send_ctx->wr_cnt++;
		return 0;
	}

	msg->wr.wr_cqe = &msg->cqe;
	msg->wr.send_flags = IB_SEND_SIGNALED;
	return smb_direct_post_send(t, &msg->wr);
}

static int smb_direct_post_send_data(struct smb_direct_transport *t,
1150 1151 1152
				     struct smb_direct_send_ctx *send_ctx,
				     struct kvec *iov, int niov,
				     int remaining_data_length)
1153 1154 1155 1156
{
	int i, j, ret;
	struct smb_direct_sendmsg *msg;
	int data_length;
1157
	struct scatterlist sg[SMB_DIRECT_MAX_SEND_SGES - 1];
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

	ret = wait_for_send_credits(t, send_ctx);
	if (ret)
		return ret;

	data_length = 0;
	for (i = 0; i < niov; i++)
		data_length += iov[i].iov_len;

	ret = smb_direct_create_header(t, data_length, remaining_data_length,
				       &msg);
	if (ret) {
		atomic_inc(&t->send_credits);
		return ret;
	}

	for (i = 0; i < niov; i++) {
		struct ib_sge *sge;
		int sg_cnt;

1178
		sg_init_table(sg, SMB_DIRECT_MAX_SEND_SGES - 1);
1179
		sg_cnt = get_mapped_sg_list(t->cm_id->device,
1180 1181 1182
					    iov[i].iov_base, iov[i].iov_len,
					    sg, SMB_DIRECT_MAX_SEND_SGES - 1,
					    DMA_TO_DEVICE);
1183
		if (sg_cnt <= 0) {
N
Namjae Jeon 已提交
1184
			pr_err("failed to map buffer\n");
1185
			ret = -ENOMEM;
1186
			goto err;
1187
		} else if (sg_cnt + msg->num_sge > SMB_DIRECT_MAX_SEND_SGES) {
N
Namjae Jeon 已提交
1188
			pr_err("buffer not fitted into sges\n");
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
			ret = -E2BIG;
			ib_dma_unmap_sg(t->cm_id->device, sg, sg_cnt,
					DMA_TO_DEVICE);
			goto err;
		}

		for (j = 0; j < sg_cnt; j++) {
			sge = &msg->sge[msg->num_sge];
			sge->addr = sg_dma_address(&sg[j]);
			sge->length = sg_dma_len(&sg[j]);
			sge->lkey  = t->pd->local_dma_lkey;
			msg->num_sge++;
		}
	}

	ret = post_sendmsg(t, send_ctx, msg);
	if (ret)
		goto err;
	return 0;
err:
	smb_direct_free_sendmsg(t, msg);
	atomic_inc(&t->send_credits);
	return ret;
}

static int smb_direct_writev(struct ksmbd_transport *t,
1215 1216
			     struct kvec *iov, int niovs, int buflen,
			     bool need_invalidate, unsigned int remote_key)
1217
{
1218
	struct smb_direct_transport *st = smb_trans_direct_transfort(t);
1219 1220 1221 1222 1223 1224 1225 1226
	int remaining_data_length;
	int start, i, j;
	int max_iov_size = st->max_send_size -
			sizeof(struct smb_direct_data_transfer);
	int ret;
	struct kvec vec;
	struct smb_direct_send_ctx send_ctx;

1227 1228
	if (st->status != SMB_DIRECT_CS_CONNECTED)
		return -ENOTCONN;
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245

	//FIXME: skip RFC1002 header..
	buflen -= 4;
	iov[0].iov_base += 4;
	iov[0].iov_len -= 4;

	remaining_data_length = buflen;
	ksmbd_debug(RDMA, "Sending smb (RDMA): smb_len=%u\n", buflen);

	smb_direct_send_ctx_init(st, &send_ctx, need_invalidate, remote_key);
	start = i = 0;
	buflen = 0;
	while (true) {
		buflen += iov[i].iov_len;
		if (buflen > max_iov_size) {
			if (i > start) {
				remaining_data_length -=
1246
					(buflen - iov[i].iov_len);
1247
				ret = smb_direct_post_send_data(st, &send_ctx,
1248 1249
								&iov[start], i - start,
								remaining_data_length);
1250 1251 1252 1253
				if (ret)
					goto done;
			} else {
				/* iov[start] is too big, break it */
1254
				int nvec  = (buflen + max_iov_size - 1) /
1255 1256 1257 1258 1259
						max_iov_size;

				for (j = 0; j < nvec; j++) {
					vec.iov_base =
						(char *)iov[start].iov_base +
1260
						j * max_iov_size;
1261 1262
					vec.iov_len =
						min_t(int, max_iov_size,
1263
						      buflen - max_iov_size * j);
1264
					remaining_data_length -= vec.iov_len;
1265 1266
					ret = smb_direct_post_send_data(st, &send_ctx, &vec, 1,
									remaining_data_length);
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
					if (ret)
						goto done;
				}
				i++;
				if (i == niovs)
					break;
			}
			start = i;
			buflen = 0;
		} else {
			i++;
			if (i == niovs) {
				/* send out all remaining vecs */
				remaining_data_length -= buflen;
				ret = smb_direct_post_send_data(st, &send_ctx,
1282 1283
								&iov[start], i - start,
								remaining_data_length);
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
				if (ret)
					goto done;
				break;
			}
		}
	}

done:
	ret = smb_direct_flush_send_list(st, &send_ctx, true);

	/*
	 * As an optimization, we don't wait for individual I/O to finish
	 * before sending the next one.
	 * Send them all and wait for pending send count to get to 0
	 * that means all the I/Os have been out and we are good to return
	 */

	wait_event(st->wait_send_payload_pending,
1302
		   atomic_read(&st->send_payload_pending) == 0);
1303 1304 1305 1306
	return ret;
}

static void read_write_done(struct ib_cq *cq, struct ib_wc *wc,
1307
			    enum dma_data_direction dir)
1308 1309
{
	struct smb_direct_rdma_rw_msg *msg = container_of(wc->wr_cqe,
1310
							  struct smb_direct_rdma_rw_msg, cqe);
1311 1312 1313
	struct smb_direct_transport *t = msg->t;

	if (wc->status != IB_WC_SUCCESS) {
N
Namjae Jeon 已提交
1314 1315
		pr_err("read/write error. opcode = %d, status = %s(%d)\n",
		       wc->opcode, ib_wc_status_msg(wc->status), wc->status);
1316 1317 1318 1319 1320 1321 1322
		smb_direct_disconnect_rdma_connection(t);
	}

	if (atomic_inc_return(&t->rw_avail_ops) > 0)
		wake_up(&t->wait_rw_avail_ops);

	rdma_rw_ctx_destroy(&msg->rw_ctx, t->qp, t->qp->port,
1323
			    msg->sg_list, msg->sgt.nents, dir);
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	sg_free_table_chained(&msg->sgt, SG_CHUNK_SIZE);
	complete(msg->completion);
	kfree(msg);
}

static void read_done(struct ib_cq *cq, struct ib_wc *wc)
{
	read_write_done(cq, wc, DMA_FROM_DEVICE);
}

static void write_done(struct ib_cq *cq, struct ib_wc *wc)
{
	read_write_done(cq, wc, DMA_TO_DEVICE);
}

static int smb_direct_rdma_xmit(struct smb_direct_transport *t, void *buf,
1340 1341
				int buf_len, u32 remote_key, u64 remote_offset,
				u32 remote_len, bool is_read)
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
{
	struct smb_direct_rdma_rw_msg *msg;
	int ret;
	DECLARE_COMPLETION_ONSTACK(completion);
	struct ib_send_wr *first_wr = NULL;

	ret = wait_for_credits(t, &t->wait_rw_avail_ops, &t->rw_avail_ops);
	if (ret < 0)
		return ret;

	/* TODO: mempool */
	msg = kmalloc(offsetof(struct smb_direct_rdma_rw_msg, sg_list) +
1354
		      sizeof(struct scatterlist) * SG_CHUNK_SIZE, GFP_KERNEL);
1355 1356 1357 1358 1359 1360 1361
	if (!msg) {
		atomic_inc(&t->rw_avail_ops);
		return -ENOMEM;
	}

	msg->sgt.sgl = &msg->sg_list[0];
	ret = sg_alloc_table_chained(&msg->sgt,
1362
				     get_buf_page_count(buf, buf_len),
1363
				     msg->sg_list, SG_CHUNK_SIZE);
1364 1365 1366 1367 1368 1369 1370 1371
	if (ret) {
		atomic_inc(&t->rw_avail_ops);
		kfree(msg);
		return -ENOMEM;
	}

	ret = get_sg_list(buf, buf_len, msg->sgt.sgl, msg->sgt.orig_nents);
	if (ret <= 0) {
N
Namjae Jeon 已提交
1372
		pr_err("failed to get pages\n");
1373 1374 1375 1376
		goto err;
	}

	ret = rdma_rw_ctx_init(&msg->rw_ctx, t->qp, t->qp->port,
1377
			       msg->sg_list, get_buf_page_count(buf, buf_len),
1378 1379
			       0, remote_offset, remote_key,
			       is_read ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1380
	if (ret < 0) {
N
Namjae Jeon 已提交
1381
		pr_err("failed to init rdma_rw_ctx: %d\n", ret);
1382 1383 1384 1385 1386 1387 1388
		goto err;
	}

	msg->t = t;
	msg->cqe.done = is_read ? read_done : write_done;
	msg->completion = &completion;
	first_wr = rdma_rw_ctx_wrs(&msg->rw_ctx, t->qp, t->qp->port,
1389
				   &msg->cqe, NULL);
1390 1391 1392

	ret = ib_post_send(t->qp, first_wr, NULL);
	if (ret) {
N
Namjae Jeon 已提交
1393
		pr_err("failed to post send wr: %d\n", ret);
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		goto err;
	}

	wait_for_completion(&completion);
	return 0;

err:
	atomic_inc(&t->rw_avail_ops);
	if (first_wr)
		rdma_rw_ctx_destroy(&msg->rw_ctx, t->qp, t->qp->port,
1404 1405
				    msg->sg_list, msg->sgt.nents,
				    is_read ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1406 1407 1408 1409 1410
	sg_free_table_chained(&msg->sgt, SG_CHUNK_SIZE);
	kfree(msg);
	return ret;
}

1411
static int smb_direct_rdma_write(struct ksmbd_transport *t, void *buf,
1412 1413
				 unsigned int buflen, u32 remote_key,
				 u64 remote_offset, u32 remote_len)
1414
{
1415
	return smb_direct_rdma_xmit(smb_trans_direct_transfort(t), buf, buflen,
1416 1417
				    remote_key, remote_offset,
				    remote_len, false);
1418 1419
}

1420
static int smb_direct_rdma_read(struct ksmbd_transport *t, void *buf,
1421 1422
				unsigned int buflen, u32 remote_key,
				u64 remote_offset, u32 remote_len)
1423
{
1424
	return smb_direct_rdma_xmit(smb_trans_direct_transfort(t), buf, buflen,
1425 1426
				    remote_key, remote_offset,
				    remote_len, true);
1427 1428 1429 1430
}

static void smb_direct_disconnect(struct ksmbd_transport *t)
{
1431
	struct smb_direct_transport *st = smb_trans_direct_transfort(t);
1432 1433 1434

	ksmbd_debug(RDMA, "Disconnecting cm_id=%p\n", st->cm_id);

1435
	smb_direct_disconnect_rdma_work(&st->disconnect_work);
1436
	wait_event_interruptible(st->wait_status,
1437
				 st->status == SMB_DIRECT_CS_DISCONNECTED);
1438 1439 1440 1441
	free_transport(st);
}

static int smb_direct_cm_handler(struct rdma_cm_id *cm_id,
1442
				 struct rdma_cm_event *event)
1443 1444 1445 1446
{
	struct smb_direct_transport *t = cm_id->context;

	ksmbd_debug(RDMA, "RDMA CM event. cm_id=%p event=%s (%d)\n",
1447
		    cm_id, rdma_event_msg(event->event), event->event);
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

	switch (event->event) {
	case RDMA_CM_EVENT_ESTABLISHED: {
		t->status = SMB_DIRECT_CS_CONNECTED;
		wake_up_interruptible(&t->wait_status);
		break;
	}
	case RDMA_CM_EVENT_DEVICE_REMOVAL:
	case RDMA_CM_EVENT_DISCONNECTED: {
		t->status = SMB_DIRECT_CS_DISCONNECTED;
		wake_up_interruptible(&t->wait_status);
		wake_up_interruptible(&t->wait_reassembly_queue);
		wake_up(&t->wait_send_credits);
		break;
	}
	case RDMA_CM_EVENT_CONNECT_ERROR: {
		t->status = SMB_DIRECT_CS_DISCONNECTED;
		wake_up_interruptible(&t->wait_status);
		break;
	}
	default:
N
Namjae Jeon 已提交
1469 1470 1471
		pr_err("Unexpected RDMA CM event. cm_id=%p, event=%s (%d)\n",
		       cm_id, rdma_event_msg(event->event),
		       event->event);
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
		break;
	}
	return 0;
}

static void smb_direct_qpair_handler(struct ib_event *event, void *context)
{
	struct smb_direct_transport *t = context;

	ksmbd_debug(RDMA, "Received QP event. cm_id=%p, event=%s (%d)\n",
1482
		    t->cm_id, ib_event_msg(event->event), event->event);
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494

	switch (event->event) {
	case IB_EVENT_CQ_ERR:
	case IB_EVENT_QP_FATAL:
		smb_direct_disconnect_rdma_connection(t);
		break;
	default:
		break;
	}
}

static int smb_direct_send_negotiate_response(struct smb_direct_transport *t,
1495
					      int failed)
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
{
	struct smb_direct_sendmsg *sendmsg;
	struct smb_direct_negotiate_resp *resp;
	int ret;

	sendmsg = smb_direct_alloc_sendmsg(t);
	if (IS_ERR(sendmsg))
		return -ENOMEM;

	resp = (struct smb_direct_negotiate_resp *)sendmsg->packet;
	if (failed) {
		memset(resp, 0, sizeof(*resp));
		resp->min_version = cpu_to_le16(0x0100);
		resp->max_version = cpu_to_le16(0x0100);
		resp->status = STATUS_NOT_SUPPORTED;
	} else {
		resp->status = STATUS_SUCCESS;
		resp->min_version = SMB_DIRECT_VERSION_LE;
		resp->max_version = SMB_DIRECT_VERSION_LE;
		resp->negotiated_version = SMB_DIRECT_VERSION_LE;
		resp->reserved = 0;
		resp->credits_requested =
				cpu_to_le16(t->send_credit_target);
1519
		resp->credits_granted = cpu_to_le16(manage_credits_prior_sending(t));
1520 1521 1522 1523 1524 1525 1526 1527
		resp->max_readwrite_size = cpu_to_le32(t->max_rdma_rw_size);
		resp->preferred_send_size = cpu_to_le32(t->max_send_size);
		resp->max_receive_size = cpu_to_le32(t->max_recv_size);
		resp->max_fragmented_size =
				cpu_to_le32(t->max_fragmented_recv_size);
	}

	sendmsg->sge[0].addr = ib_dma_map_single(t->cm_id->device,
1528 1529 1530
						 (void *)resp, sizeof(*resp),
						 DMA_TO_DEVICE);
	ret = ib_dma_mapping_error(t->cm_id->device, sendmsg->sge[0].addr);
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
	if (ret) {
		smb_direct_free_sendmsg(t, sendmsg);
		return ret;
	}

	sendmsg->num_sge = 1;
	sendmsg->sge[0].length = sizeof(*resp);
	sendmsg->sge[0].lkey = t->pd->local_dma_lkey;

	ret = post_sendmsg(t, NULL, sendmsg);
	if (ret) {
		smb_direct_free_sendmsg(t, sendmsg);
		return ret;
	}

	wait_event(t->wait_send_pending,
1547
		   atomic_read(&t->send_pending) == 0);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
	return 0;
}

static int smb_direct_accept_client(struct smb_direct_transport *t)
{
	struct rdma_conn_param conn_param;
	struct ib_port_immutable port_immutable;
	u32 ird_ord_hdr[2];
	int ret;

	memset(&conn_param, 0, sizeof(conn_param));
1559 1560
	conn_param.initiator_depth = min_t(u8, t->cm_id->device->attrs.max_qp_rd_atom,
					   SMB_DIRECT_CM_INITIATOR_DEPTH);
1561 1562 1563
	conn_param.responder_resources = 0;

	t->cm_id->device->ops.get_port_immutable(t->cm_id->device,
1564 1565
						 t->cm_id->port_num,
						 &port_immutable);
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
	if (port_immutable.core_cap_flags & RDMA_CORE_PORT_IWARP) {
		ird_ord_hdr[0] = conn_param.responder_resources;
		ird_ord_hdr[1] = 1;
		conn_param.private_data = ird_ord_hdr;
		conn_param.private_data_len = sizeof(ird_ord_hdr);
	} else {
		conn_param.private_data = NULL;
		conn_param.private_data_len = 0;
	}
	conn_param.retry_count = SMB_DIRECT_CM_RETRY;
	conn_param.rnr_retry_count = SMB_DIRECT_CM_RNR_RETRY;
	conn_param.flow_control = 0;

	ret = rdma_accept(t->cm_id, &conn_param);
	if (ret) {
N
Namjae Jeon 已提交
1581
		pr_err("error at rdma_accept: %d\n", ret);
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
		return ret;
	}

	wait_event_interruptible(t->wait_status,
				 t->status != SMB_DIRECT_CS_NEW);
	if (t->status != SMB_DIRECT_CS_CONNECTED)
		return -ENOTCONN;
	return 0;
}

static int smb_direct_negotiate(struct smb_direct_transport *t)
{
	int ret;
	struct smb_direct_recvmsg *recvmsg;
	struct smb_direct_negotiate_req *req;

	recvmsg = get_free_recvmsg(t);
	if (!recvmsg)
		return -ENOMEM;
	recvmsg->type = SMB_DIRECT_MSG_NEGOTIATE_REQ;

	ret = smb_direct_post_recv(t, recvmsg);
	if (ret) {
N
Namjae Jeon 已提交
1605
		pr_err("Can't post recv: %d\n", ret);
1606 1607 1608 1609 1610 1611
		goto out;
	}

	t->negotiation_requested = false;
	ret = smb_direct_accept_client(t);
	if (ret) {
N
Namjae Jeon 已提交
1612
		pr_err("Can't accept client\n");
1613 1614 1615 1616 1617 1618 1619
		goto out;
	}

	smb_direct_post_recv_credits(&t->post_recv_credits_work.work);

	ksmbd_debug(RDMA, "Waiting for SMB_DIRECT negotiate request\n");
	ret = wait_event_interruptible_timeout(t->wait_status,
1620 1621 1622
					       t->negotiation_requested ||
						t->status == SMB_DIRECT_CS_DISCONNECTED,
					       SMB_DIRECT_NEGOTIATE_TIMEOUT * HZ);
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
	if (ret <= 0 || t->status == SMB_DIRECT_CS_DISCONNECTED) {
		ret = ret < 0 ? ret : -ETIMEDOUT;
		goto out;
	}

	ret = smb_direct_check_recvmsg(recvmsg);
	if (ret == -ECONNABORTED)
		goto out;

	req = (struct smb_direct_negotiate_req *)recvmsg->packet;
	t->max_recv_size = min_t(int, t->max_recv_size,
1634
				 le32_to_cpu(req->preferred_send_size));
1635
	t->max_send_size = min_t(int, t->max_send_size,
1636
				 le32_to_cpu(req->max_receive_size));
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
	t->max_fragmented_send_size =
			le32_to_cpu(req->max_fragmented_size);

	ret = smb_direct_send_negotiate_response(t, ret);
out:
	if (recvmsg)
		put_recvmsg(t, recvmsg);
	return ret;
}

static int smb_direct_init_params(struct smb_direct_transport *t,
1648
				  struct ib_qp_cap *cap)
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
{
	struct ib_device *device = t->cm_id->device;
	int max_send_sges, max_pages, max_rw_wrs, max_send_wrs;

	/* need 2 more sge. because a SMB_DIRECT header will be mapped,
	 * and maybe a send buffer could be not page aligned.
	 */
	t->max_send_size = smb_direct_max_send_size;
	max_send_sges = DIV_ROUND_UP(t->max_send_size, PAGE_SIZE) + 2;
	if (max_send_sges > SMB_DIRECT_MAX_SEND_SGES) {
N
Namjae Jeon 已提交
1659
		pr_err("max_send_size %d is too large\n", t->max_send_size);
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
		return -EINVAL;
	}

	/*
	 * allow smb_direct_max_outstanding_rw_ops of in-flight RDMA
	 * read/writes. HCA guarantees at least max_send_sge of sges for
	 * a RDMA read/write work request, and if memory registration is used,
	 * we need reg_mr, local_inv wrs for each read/write.
	 */
	t->max_rdma_rw_size = smb_direct_max_read_write_size;
	max_pages = DIV_ROUND_UP(t->max_rdma_rw_size, PAGE_SIZE) + 1;
	max_rw_wrs = DIV_ROUND_UP(max_pages, SMB_DIRECT_MAX_SEND_SGES);
	max_rw_wrs += rdma_rw_mr_factor(device, t->cm_id->port_num,
			max_pages) * 2;
	max_rw_wrs *= smb_direct_max_outstanding_rw_ops;

	max_send_wrs = smb_direct_send_credit_target + max_rw_wrs;
	if (max_send_wrs > device->attrs.max_cqe ||
1678
	    max_send_wrs > device->attrs.max_qp_wr) {
N
Namjae Jeon 已提交
1679 1680 1681 1682 1683
		pr_err("consider lowering send_credit_target = %d, or max_outstanding_rw_ops = %d\n",
		       smb_direct_send_credit_target,
		       smb_direct_max_outstanding_rw_ops);
		pr_err("Possible CQE overrun, device reporting max_cqe %d max_qp_wr %d\n",
		       device->attrs.max_cqe, device->attrs.max_qp_wr);
1684 1685 1686 1687 1688
		return -EINVAL;
	}

	if (smb_direct_receive_credit_max > device->attrs.max_cqe ||
	    smb_direct_receive_credit_max > device->attrs.max_qp_wr) {
N
Namjae Jeon 已提交
1689 1690 1691 1692
		pr_err("consider lowering receive_credit_max = %d\n",
		       smb_direct_receive_credit_max);
		pr_err("Possible CQE overrun, device reporting max_cpe %d max_qp_wr %d\n",
		       device->attrs.max_cqe, device->attrs.max_qp_wr);
1693 1694 1695 1696
		return -EINVAL;
	}

	if (device->attrs.max_send_sge < SMB_DIRECT_MAX_SEND_SGES) {
N
Namjae Jeon 已提交
1697 1698
		pr_err("warning: device max_send_sge = %d too small\n",
		       device->attrs.max_send_sge);
1699 1700 1701
		return -EINVAL;
	}
	if (device->attrs.max_recv_sge < SMB_DIRECT_MAX_RECV_SGES) {
N
Namjae Jeon 已提交
1702 1703
		pr_err("warning: device max_recv_sge = %d too small\n",
		       device->attrs.max_recv_sge);
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
		return -EINVAL;
	}

	t->recv_credits = 0;
	t->count_avail_recvmsg = 0;

	t->recv_credit_max = smb_direct_receive_credit_max;
	t->recv_credit_target = 10;
	t->new_recv_credits = 0;

	t->send_credit_target = smb_direct_send_credit_target;
	atomic_set(&t->send_credits, 0);
	atomic_set(&t->rw_avail_ops, smb_direct_max_outstanding_rw_ops);

	t->max_send_size = smb_direct_max_send_size;
	t->max_recv_size = smb_direct_max_receive_size;
	t->max_fragmented_recv_size = smb_direct_max_fragmented_recv_size;

	cap->max_send_wr = max_send_wrs;
	cap->max_recv_wr = t->recv_credit_max;
	cap->max_send_sge = SMB_DIRECT_MAX_SEND_SGES;
	cap->max_recv_sge = SMB_DIRECT_MAX_RECV_SGES;
	cap->max_inline_data = 0;
	cap->max_rdma_ctxs = 0;
	return 0;
}

static void smb_direct_destroy_pools(struct smb_direct_transport *t)
{
	struct smb_direct_recvmsg *recvmsg;

	while ((recvmsg = get_free_recvmsg(t)))
		mempool_free(recvmsg, t->recvmsg_mempool);
	while ((recvmsg = get_empty_recvmsg(t)))
		mempool_free(recvmsg, t->recvmsg_mempool);

	mempool_destroy(t->recvmsg_mempool);
	t->recvmsg_mempool = NULL;

	kmem_cache_destroy(t->recvmsg_cache);
	t->recvmsg_cache = NULL;

	mempool_destroy(t->sendmsg_mempool);
	t->sendmsg_mempool = NULL;

	kmem_cache_destroy(t->sendmsg_cache);
	t->sendmsg_cache = NULL;
}

static int smb_direct_create_pools(struct smb_direct_transport *t)
{
	char name[80];
	int i;
	struct smb_direct_recvmsg *recvmsg;

	snprintf(name, sizeof(name), "smb_direct_rqst_pool_%p", t);
	t->sendmsg_cache = kmem_cache_create(name,
1761 1762 1763
					     sizeof(struct smb_direct_sendmsg) +
					      sizeof(struct smb_direct_negotiate_resp),
					     0, SLAB_HWCACHE_ALIGN, NULL);
1764 1765 1766 1767
	if (!t->sendmsg_cache)
		return -ENOMEM;

	t->sendmsg_mempool = mempool_create(t->send_credit_target,
1768 1769
					    mempool_alloc_slab, mempool_free_slab,
					    t->sendmsg_cache);
1770 1771 1772 1773 1774
	if (!t->sendmsg_mempool)
		goto err;

	snprintf(name, sizeof(name), "smb_direct_resp_%p", t);
	t->recvmsg_cache = kmem_cache_create(name,
1775 1776 1777
					     sizeof(struct smb_direct_recvmsg) +
					      t->max_recv_size,
					     0, SLAB_HWCACHE_ALIGN, NULL);
1778 1779 1780 1781 1782
	if (!t->recvmsg_cache)
		goto err;

	t->recvmsg_mempool =
		mempool_create(t->recv_credit_max, mempool_alloc_slab,
1783
			       mempool_free_slab, t->recvmsg_cache);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
	if (!t->recvmsg_mempool)
		goto err;

	INIT_LIST_HEAD(&t->recvmsg_queue);

	for (i = 0; i < t->recv_credit_max; i++) {
		recvmsg = mempool_alloc(t->recvmsg_mempool, GFP_KERNEL);
		if (!recvmsg)
			goto err;
		recvmsg->transport = t;
		list_add(&recvmsg->list, &t->recvmsg_queue);
	}
	t->count_avail_recvmsg = t->recv_credit_max;

	return 0;
err:
	smb_direct_destroy_pools(t);
	return -ENOMEM;
}

static int smb_direct_create_qpair(struct smb_direct_transport *t,
1805
				   struct ib_qp_cap *cap)
1806 1807 1808 1809 1810 1811
{
	int ret;
	struct ib_qp_init_attr qp_attr;

	t->pd = ib_alloc_pd(t->cm_id->device, 0);
	if (IS_ERR(t->pd)) {
N
Namjae Jeon 已提交
1812
		pr_err("Can't create RDMA PD\n");
1813 1814 1815 1816 1817 1818
		ret = PTR_ERR(t->pd);
		t->pd = NULL;
		return ret;
	}

	t->send_cq = ib_alloc_cq(t->cm_id->device, t,
1819
				 t->send_credit_target, 0, IB_POLL_WORKQUEUE);
1820
	if (IS_ERR(t->send_cq)) {
N
Namjae Jeon 已提交
1821
		pr_err("Can't create RDMA send CQ\n");
1822 1823 1824 1825 1826 1827
		ret = PTR_ERR(t->send_cq);
		t->send_cq = NULL;
		goto err;
	}

	t->recv_cq = ib_alloc_cq(t->cm_id->device, t,
1828 1829
				 cap->max_send_wr + cap->max_rdma_ctxs,
				 0, IB_POLL_WORKQUEUE);
1830
	if (IS_ERR(t->recv_cq)) {
N
Namjae Jeon 已提交
1831
		pr_err("Can't create RDMA recv CQ\n");
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
		ret = PTR_ERR(t->recv_cq);
		t->recv_cq = NULL;
		goto err;
	}

	memset(&qp_attr, 0, sizeof(qp_attr));
	qp_attr.event_handler = smb_direct_qpair_handler;
	qp_attr.qp_context = t;
	qp_attr.cap = *cap;
	qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
	qp_attr.qp_type = IB_QPT_RC;
	qp_attr.send_cq = t->send_cq;
	qp_attr.recv_cq = t->recv_cq;
	qp_attr.port_num = ~0;

	ret = rdma_create_qp(t->cm_id, t->pd, &qp_attr);
	if (ret) {
N
Namjae Jeon 已提交
1849
		pr_err("Can't create RDMA QP: %d\n", ret);
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
		goto err;
	}

	t->qp = t->cm_id->qp;
	t->cm_id->event_handler = smb_direct_cm_handler;

	return 0;
err:
	if (t->qp) {
		ib_destroy_qp(t->qp);
		t->qp = NULL;
	}
	if (t->recv_cq) {
		ib_destroy_cq(t->recv_cq);
		t->recv_cq = NULL;
	}
	if (t->send_cq) {
		ib_destroy_cq(t->send_cq);
		t->send_cq = NULL;
	}
	if (t->pd) {
		ib_dealloc_pd(t->pd);
		t->pd = NULL;
	}
	return ret;
}

static int smb_direct_prepare(struct ksmbd_transport *t)
{
1879
	struct smb_direct_transport *st = smb_trans_direct_transfort(t);
1880 1881 1882 1883 1884
	int ret;
	struct ib_qp_cap qp_cap;

	ret = smb_direct_init_params(st, &qp_cap);
	if (ret) {
N
Namjae Jeon 已提交
1885
		pr_err("Can't configure RDMA parameters\n");
1886 1887 1888 1889 1890
		return ret;
	}

	ret = smb_direct_create_pools(st);
	if (ret) {
N
Namjae Jeon 已提交
1891
		pr_err("Can't init RDMA pool: %d\n", ret);
1892 1893 1894 1895 1896
		return ret;
	}

	ret = smb_direct_create_qpair(st, &qp_cap);
	if (ret) {
N
Namjae Jeon 已提交
1897
		pr_err("Can't accept RDMA client: %d\n", ret);
1898 1899 1900 1901 1902
		return ret;
	}

	ret = smb_direct_negotiate(st);
	if (ret) {
N
Namjae Jeon 已提交
1903
		pr_err("Can't negotiate: %d\n", ret);
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
		return ret;
	}

	st->status = SMB_DIRECT_CS_CONNECTED;
	return 0;
}

static bool rdma_frwr_is_supported(struct ib_device_attr *attrs)
{
	if (!(attrs->device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS))
		return false;
	if (attrs->max_fast_reg_page_list_len == 0)
		return false;
	return true;
}

static int smb_direct_handle_connect_request(struct rdma_cm_id *new_cm_id)
{
	struct smb_direct_transport *t;

	if (!rdma_frwr_is_supported(&new_cm_id->device->attrs)) {
		ksmbd_debug(RDMA,
1926 1927
			    "Fast Registration Work Requests is not supported. device capabilities=%llx\n",
			    new_cm_id->device->attrs.device_cap_flags);
1928 1929 1930 1931 1932 1933 1934 1935
		return -EPROTONOSUPPORT;
	}

	t = alloc_transport(new_cm_id);
	if (!t)
		return -ENOMEM;

	KSMBD_TRANS(t)->handler = kthread_run(ksmbd_conn_handler_loop,
1936 1937
					      KSMBD_TRANS(t)->conn, "ksmbd:r%u",
					      SMB_DIRECT_PORT);
1938 1939 1940
	if (IS_ERR(KSMBD_TRANS(t)->handler)) {
		int ret = PTR_ERR(KSMBD_TRANS(t)->handler);

N
Namjae Jeon 已提交
1941
		pr_err("Can't start thread\n");
1942 1943 1944 1945 1946 1947 1948 1949
		free_transport(t);
		return ret;
	}

	return 0;
}

static int smb_direct_listen_handler(struct rdma_cm_id *cm_id,
1950
				     struct rdma_cm_event *event)
1951 1952 1953 1954 1955 1956
{
	switch (event->event) {
	case RDMA_CM_EVENT_CONNECT_REQUEST: {
		int ret = smb_direct_handle_connect_request(cm_id);

		if (ret) {
N
Namjae Jeon 已提交
1957
			pr_err("Can't create transport: %d\n", ret);
1958 1959 1960 1961
			return ret;
		}

		ksmbd_debug(RDMA, "Received connection request. cm_id=%p\n",
1962
			    cm_id);
1963 1964 1965
		break;
	}
	default:
N
Namjae Jeon 已提交
1966 1967
		pr_err("Unexpected listen event. cm_id=%p, event=%s (%d)\n",
		       cm_id, rdma_event_msg(event->event), event->event);
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
		break;
	}
	return 0;
}

static int smb_direct_listen(int port)
{
	int ret;
	struct rdma_cm_id *cm_id;
	struct sockaddr_in sin = {
		.sin_family		= AF_INET,
		.sin_addr.s_addr	= htonl(INADDR_ANY),
		.sin_port		= htons(port),
	};

	cm_id = rdma_create_id(&init_net, smb_direct_listen_handler,
1984
			       &smb_direct_listener, RDMA_PS_TCP, IB_QPT_RC);
1985
	if (IS_ERR(cm_id)) {
N
Namjae Jeon 已提交
1986
		pr_err("Can't create cm id: %ld\n", PTR_ERR(cm_id));
1987 1988 1989 1990 1991
		return PTR_ERR(cm_id);
	}

	ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);
	if (ret) {
N
Namjae Jeon 已提交
1992
		pr_err("Can't bind: %d\n", ret);
1993 1994 1995 1996 1997 1998 1999
		goto err;
	}

	smb_direct_listener.cm_id = cm_id;

	ret = rdma_listen(cm_id, 10);
	if (ret) {
N
Namjae Jeon 已提交
2000
		pr_err("Can't listen: %d\n", ret);
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
		goto err;
	}
	return 0;
err:
	smb_direct_listener.cm_id = NULL;
	rdma_destroy_id(cm_id);
	return ret;
}

int ksmbd_rdma_init(void)
{
	int ret;

	smb_direct_listener.cm_id = NULL;

	/* When a client is running out of send credits, the credits are
	 * granted by the server's sending a packet using this queue.
	 * This avoids the situation that a clients cannot send packets
	 * for lack of credits
	 */
	smb_direct_wq = alloc_workqueue("ksmbd-smb_direct-wq",
2022
					WQ_HIGHPRI | WQ_MEM_RECLAIM, 0);
2023 2024 2025 2026 2027 2028 2029
	if (!smb_direct_wq)
		return -ENOMEM;

	ret = smb_direct_listen(SMB_DIRECT_PORT);
	if (ret) {
		destroy_workqueue(smb_direct_wq);
		smb_direct_wq = NULL;
N
Namjae Jeon 已提交
2030
		pr_err("Can't listen: %d\n", ret);
2031 2032 2033 2034
		return ret;
	}

	ksmbd_debug(RDMA, "init RDMA listener. cm_id=%p\n",
2035
		    smb_direct_listener.cm_id);
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
	return 0;
}

int ksmbd_rdma_destroy(void)
{
	if (smb_direct_listener.cm_id)
		rdma_destroy_id(smb_direct_listener.cm_id);
	smb_direct_listener.cm_id = NULL;

	if (smb_direct_wq) {
		flush_workqueue(smb_direct_wq);
		destroy_workqueue(smb_direct_wq);
		smb_direct_wq = NULL;
	}
	return 0;
}

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
bool ksmbd_rdma_capable_netdev(struct net_device *netdev)
{
	struct ib_device *ibdev;
	bool rdma_capable = false;

	ibdev = ib_device_get_by_netdev(netdev, RDMA_DRIVER_UNKNOWN);
	if (ibdev) {
		if (rdma_frwr_is_supported(&ibdev->attrs))
			rdma_capable = true;
		ib_device_put(ibdev);
	}
	return rdma_capable;
}

2067 2068 2069 2070 2071 2072 2073 2074
static struct ksmbd_transport_ops ksmbd_smb_direct_transport_ops = {
	.prepare	= smb_direct_prepare,
	.disconnect	= smb_direct_disconnect,
	.writev		= smb_direct_writev,
	.read		= smb_direct_read,
	.rdma_read	= smb_direct_rdma_read,
	.rdma_write	= smb_direct_rdma_write,
};