xref: /kernel/linux/linux-5.10/fs/cifs/smbdirect.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 *   Copyright (C) 2017, Microsoft Corporation.
4 *
5 *   Author(s): Long Li <longli@microsoft.com>
6 */
7#include <linux/module.h>
8#include <linux/highmem.h>
9#include "smbdirect.h"
10#include "cifs_debug.h"
11#include "cifsproto.h"
12#include "smb2proto.h"
13
14static struct smbd_response *get_empty_queue_buffer(
15		struct smbd_connection *info);
16static struct smbd_response *get_receive_buffer(
17		struct smbd_connection *info);
18static void put_receive_buffer(
19		struct smbd_connection *info,
20		struct smbd_response *response);
21static int allocate_receive_buffers(struct smbd_connection *info, int num_buf);
22static void destroy_receive_buffers(struct smbd_connection *info);
23
24static void put_empty_packet(
25		struct smbd_connection *info, struct smbd_response *response);
26static void enqueue_reassembly(
27		struct smbd_connection *info,
28		struct smbd_response *response, int data_length);
29static struct smbd_response *_get_first_reassembly(
30		struct smbd_connection *info);
31
32static int smbd_post_recv(
33		struct smbd_connection *info,
34		struct smbd_response *response);
35
36static int smbd_post_send_empty(struct smbd_connection *info);
37static int smbd_post_send_data(
38		struct smbd_connection *info,
39		struct kvec *iov, int n_vec, int remaining_data_length);
40static int smbd_post_send_page(struct smbd_connection *info,
41		struct page *page, unsigned long offset,
42		size_t size, int remaining_data_length);
43
44static void destroy_mr_list(struct smbd_connection *info);
45static int allocate_mr_list(struct smbd_connection *info);
46
47/* SMBD version number */
48#define SMBD_V1	0x0100
49
50/* Port numbers for SMBD transport */
51#define SMB_PORT	445
52#define SMBD_PORT	5445
53
54/* Address lookup and resolve timeout in ms */
55#define RDMA_RESOLVE_TIMEOUT	5000
56
57/* SMBD negotiation timeout in seconds */
58#define SMBD_NEGOTIATE_TIMEOUT	120
59
60/* SMBD minimum receive size and fragmented sized defined in [MS-SMBD] */
61#define SMBD_MIN_RECEIVE_SIZE		128
62#define SMBD_MIN_FRAGMENTED_SIZE	131072
63
64/*
65 * Default maximum number of RDMA read/write outstanding on this connection
66 * This value is possibly decreased during QP creation on hardware limit
67 */
68#define SMBD_CM_RESPONDER_RESOURCES	32
69
70/* Maximum number of retries on data transfer operations */
71#define SMBD_CM_RETRY			6
72/* No need to retry on Receiver Not Ready since SMBD manages credits */
73#define SMBD_CM_RNR_RETRY		0
74
75/*
76 * User configurable initial values per SMBD transport connection
77 * as defined in [MS-SMBD] 3.1.1.1
78 * Those may change after a SMBD negotiation
79 */
80/* The local peer's maximum number of credits to grant to the peer */
81int smbd_receive_credit_max = 255;
82
83/* The remote peer's credit request of local peer */
84int smbd_send_credit_target = 255;
85
86/* The maximum single message size can be sent to remote peer */
87int smbd_max_send_size = 1364;
88
89/*  The maximum fragmented upper-layer payload receive size supported */
90int smbd_max_fragmented_recv_size = 1024 * 1024;
91
92/*  The maximum single-message size which can be received */
93int smbd_max_receive_size = 8192;
94
95/* The timeout to initiate send of a keepalive message on idle */
96int smbd_keep_alive_interval = 120;
97
98/*
99 * User configurable initial values for RDMA transport
100 * The actual values used may be lower and are limited to hardware capabilities
101 */
102/* Default maximum number of SGEs in a RDMA write/read */
103int smbd_max_frmr_depth = 2048;
104
105/* If payload is less than this byte, use RDMA send/recv not read/write */
106int rdma_readwrite_threshold = 4096;
107
108/* Transport logging functions
109 * Logging are defined as classes. They can be OR'ed to define the actual
110 * logging level via module parameter smbd_logging_class
111 * e.g. cifs.smbd_logging_class=0xa0 will log all log_rdma_recv() and
112 * log_rdma_event()
113 */
114#define LOG_OUTGOING			0x1
115#define LOG_INCOMING			0x2
116#define LOG_READ			0x4
117#define LOG_WRITE			0x8
118#define LOG_RDMA_SEND			0x10
119#define LOG_RDMA_RECV			0x20
120#define LOG_KEEP_ALIVE			0x40
121#define LOG_RDMA_EVENT			0x80
122#define LOG_RDMA_MR			0x100
123static unsigned int smbd_logging_class;
124module_param(smbd_logging_class, uint, 0644);
125MODULE_PARM_DESC(smbd_logging_class,
126	"Logging class for SMBD transport 0x0 to 0x100");
127
128#define ERR		0x0
129#define INFO		0x1
130static unsigned int smbd_logging_level = ERR;
131module_param(smbd_logging_level, uint, 0644);
132MODULE_PARM_DESC(smbd_logging_level,
133	"Logging level for SMBD transport, 0 (default): error, 1: info");
134
135#define log_rdma(level, class, fmt, args...)				\
136do {									\
137	if (level <= smbd_logging_level || class & smbd_logging_class)	\
138		cifs_dbg(VFS, "%s:%d " fmt, __func__, __LINE__, ##args);\
139} while (0)
140
141#define log_outgoing(level, fmt, args...) \
142		log_rdma(level, LOG_OUTGOING, fmt, ##args)
143#define log_incoming(level, fmt, args...) \
144		log_rdma(level, LOG_INCOMING, fmt, ##args)
145#define log_read(level, fmt, args...)	log_rdma(level, LOG_READ, fmt, ##args)
146#define log_write(level, fmt, args...)	log_rdma(level, LOG_WRITE, fmt, ##args)
147#define log_rdma_send(level, fmt, args...) \
148		log_rdma(level, LOG_RDMA_SEND, fmt, ##args)
149#define log_rdma_recv(level, fmt, args...) \
150		log_rdma(level, LOG_RDMA_RECV, fmt, ##args)
151#define log_keep_alive(level, fmt, args...) \
152		log_rdma(level, LOG_KEEP_ALIVE, fmt, ##args)
153#define log_rdma_event(level, fmt, args...) \
154		log_rdma(level, LOG_RDMA_EVENT, fmt, ##args)
155#define log_rdma_mr(level, fmt, args...) \
156		log_rdma(level, LOG_RDMA_MR, fmt, ##args)
157
158static void smbd_disconnect_rdma_work(struct work_struct *work)
159{
160	struct smbd_connection *info =
161		container_of(work, struct smbd_connection, disconnect_work);
162
163	if (info->transport_status == SMBD_CONNECTED) {
164		info->transport_status = SMBD_DISCONNECTING;
165		rdma_disconnect(info->id);
166	}
167}
168
169static void smbd_disconnect_rdma_connection(struct smbd_connection *info)
170{
171	queue_work(info->workqueue, &info->disconnect_work);
172}
173
174/* Upcall from RDMA CM */
175static int smbd_conn_upcall(
176		struct rdma_cm_id *id, struct rdma_cm_event *event)
177{
178	struct smbd_connection *info = id->context;
179
180	log_rdma_event(INFO, "event=%d status=%d\n",
181		event->event, event->status);
182
183	switch (event->event) {
184	case RDMA_CM_EVENT_ADDR_RESOLVED:
185	case RDMA_CM_EVENT_ROUTE_RESOLVED:
186		info->ri_rc = 0;
187		complete(&info->ri_done);
188		break;
189
190	case RDMA_CM_EVENT_ADDR_ERROR:
191		info->ri_rc = -EHOSTUNREACH;
192		complete(&info->ri_done);
193		break;
194
195	case RDMA_CM_EVENT_ROUTE_ERROR:
196		info->ri_rc = -ENETUNREACH;
197		complete(&info->ri_done);
198		break;
199
200	case RDMA_CM_EVENT_ESTABLISHED:
201		log_rdma_event(INFO, "connected event=%d\n", event->event);
202		info->transport_status = SMBD_CONNECTED;
203		wake_up_interruptible(&info->conn_wait);
204		break;
205
206	case RDMA_CM_EVENT_CONNECT_ERROR:
207	case RDMA_CM_EVENT_UNREACHABLE:
208	case RDMA_CM_EVENT_REJECTED:
209		log_rdma_event(INFO, "connecting failed event=%d\n", event->event);
210		info->transport_status = SMBD_DISCONNECTED;
211		wake_up_interruptible(&info->conn_wait);
212		break;
213
214	case RDMA_CM_EVENT_DEVICE_REMOVAL:
215	case RDMA_CM_EVENT_DISCONNECTED:
216		/* This happenes when we fail the negotiation */
217		if (info->transport_status == SMBD_NEGOTIATE_FAILED) {
218			info->transport_status = SMBD_DISCONNECTED;
219			wake_up(&info->conn_wait);
220			break;
221		}
222
223		info->transport_status = SMBD_DISCONNECTED;
224		wake_up_interruptible(&info->disconn_wait);
225		wake_up_interruptible(&info->wait_reassembly_queue);
226		wake_up_interruptible_all(&info->wait_send_queue);
227		break;
228
229	default:
230		break;
231	}
232
233	return 0;
234}
235
236/* Upcall from RDMA QP */
237static void
238smbd_qp_async_error_upcall(struct ib_event *event, void *context)
239{
240	struct smbd_connection *info = context;
241
242	log_rdma_event(ERR, "%s on device %s info %p\n",
243		ib_event_msg(event->event), event->device->name, info);
244
245	switch (event->event) {
246	case IB_EVENT_CQ_ERR:
247	case IB_EVENT_QP_FATAL:
248		smbd_disconnect_rdma_connection(info);
249
250	default:
251		break;
252	}
253}
254
255static inline void *smbd_request_payload(struct smbd_request *request)
256{
257	return (void *)request->packet;
258}
259
260static inline void *smbd_response_payload(struct smbd_response *response)
261{
262	return (void *)response->packet;
263}
264
265/* Called when a RDMA send is done */
266static void send_done(struct ib_cq *cq, struct ib_wc *wc)
267{
268	int i;
269	struct smbd_request *request =
270		container_of(wc->wr_cqe, struct smbd_request, cqe);
271
272	log_rdma_send(INFO, "smbd_request %p completed wc->status=%d\n",
273		request, wc->status);
274
275	if (wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_SEND) {
276		log_rdma_send(ERR, "wc->status=%d wc->opcode=%d\n",
277			wc->status, wc->opcode);
278		smbd_disconnect_rdma_connection(request->info);
279	}
280
281	for (i = 0; i < request->num_sge; i++)
282		ib_dma_unmap_single(request->info->id->device,
283			request->sge[i].addr,
284			request->sge[i].length,
285			DMA_TO_DEVICE);
286
287	if (atomic_dec_and_test(&request->info->send_pending))
288		wake_up(&request->info->wait_send_pending);
289
290	wake_up(&request->info->wait_post_send);
291
292	mempool_free(request, request->info->request_mempool);
293}
294
295static void dump_smbd_negotiate_resp(struct smbd_negotiate_resp *resp)
296{
297	log_rdma_event(INFO, "resp message min_version %u max_version %u negotiated_version %u credits_requested %u credits_granted %u status %u max_readwrite_size %u preferred_send_size %u max_receive_size %u max_fragmented_size %u\n",
298		       resp->min_version, resp->max_version,
299		       resp->negotiated_version, resp->credits_requested,
300		       resp->credits_granted, resp->status,
301		       resp->max_readwrite_size, resp->preferred_send_size,
302		       resp->max_receive_size, resp->max_fragmented_size);
303}
304
305/*
306 * Process a negotiation response message, according to [MS-SMBD]3.1.5.7
307 * response, packet_length: the negotiation response message
308 * return value: true if negotiation is a success, false if failed
309 */
310static bool process_negotiation_response(
311		struct smbd_response *response, int packet_length)
312{
313	struct smbd_connection *info = response->info;
314	struct smbd_negotiate_resp *packet = smbd_response_payload(response);
315
316	if (packet_length < sizeof(struct smbd_negotiate_resp)) {
317		log_rdma_event(ERR,
318			"error: packet_length=%d\n", packet_length);
319		return false;
320	}
321
322	if (le16_to_cpu(packet->negotiated_version) != SMBD_V1) {
323		log_rdma_event(ERR, "error: negotiated_version=%x\n",
324			le16_to_cpu(packet->negotiated_version));
325		return false;
326	}
327	info->protocol = le16_to_cpu(packet->negotiated_version);
328
329	if (packet->credits_requested == 0) {
330		log_rdma_event(ERR, "error: credits_requested==0\n");
331		return false;
332	}
333	info->receive_credit_target = le16_to_cpu(packet->credits_requested);
334
335	if (packet->credits_granted == 0) {
336		log_rdma_event(ERR, "error: credits_granted==0\n");
337		return false;
338	}
339	atomic_set(&info->send_credits, le16_to_cpu(packet->credits_granted));
340
341	atomic_set(&info->receive_credits, 0);
342
343	if (le32_to_cpu(packet->preferred_send_size) > info->max_receive_size) {
344		log_rdma_event(ERR, "error: preferred_send_size=%d\n",
345			le32_to_cpu(packet->preferred_send_size));
346		return false;
347	}
348	info->max_receive_size = le32_to_cpu(packet->preferred_send_size);
349
350	if (le32_to_cpu(packet->max_receive_size) < SMBD_MIN_RECEIVE_SIZE) {
351		log_rdma_event(ERR, "error: max_receive_size=%d\n",
352			le32_to_cpu(packet->max_receive_size));
353		return false;
354	}
355	info->max_send_size = min_t(int, info->max_send_size,
356					le32_to_cpu(packet->max_receive_size));
357
358	if (le32_to_cpu(packet->max_fragmented_size) <
359			SMBD_MIN_FRAGMENTED_SIZE) {
360		log_rdma_event(ERR, "error: max_fragmented_size=%d\n",
361			le32_to_cpu(packet->max_fragmented_size));
362		return false;
363	}
364	info->max_fragmented_send_size =
365		le32_to_cpu(packet->max_fragmented_size);
366	info->rdma_readwrite_threshold =
367		rdma_readwrite_threshold > info->max_fragmented_send_size ?
368		info->max_fragmented_send_size :
369		rdma_readwrite_threshold;
370
371
372	info->max_readwrite_size = min_t(u32,
373			le32_to_cpu(packet->max_readwrite_size),
374			info->max_frmr_depth * PAGE_SIZE);
375	info->max_frmr_depth = info->max_readwrite_size / PAGE_SIZE;
376
377	return true;
378}
379
380static void smbd_post_send_credits(struct work_struct *work)
381{
382	int ret = 0;
383	int use_receive_queue = 1;
384	int rc;
385	struct smbd_response *response;
386	struct smbd_connection *info =
387		container_of(work, struct smbd_connection,
388			post_send_credits_work);
389
390	if (info->transport_status != SMBD_CONNECTED) {
391		wake_up(&info->wait_receive_queues);
392		return;
393	}
394
395	if (info->receive_credit_target >
396		atomic_read(&info->receive_credits)) {
397		while (true) {
398			if (use_receive_queue)
399				response = get_receive_buffer(info);
400			else
401				response = get_empty_queue_buffer(info);
402			if (!response) {
403				/* now switch to emtpy packet queue */
404				if (use_receive_queue) {
405					use_receive_queue = 0;
406					continue;
407				} else
408					break;
409			}
410
411			response->type = SMBD_TRANSFER_DATA;
412			response->first_segment = false;
413			rc = smbd_post_recv(info, response);
414			if (rc) {
415				log_rdma_recv(ERR,
416					"post_recv failed rc=%d\n", rc);
417				put_receive_buffer(info, response);
418				break;
419			}
420
421			ret++;
422		}
423	}
424
425	spin_lock(&info->lock_new_credits_offered);
426	info->new_credits_offered += ret;
427	spin_unlock(&info->lock_new_credits_offered);
428
429	/* Promptly send an immediate packet as defined in [MS-SMBD] 3.1.1.1 */
430	info->send_immediate = true;
431	if (atomic_read(&info->receive_credits) <
432		info->receive_credit_target - 1) {
433		if (info->keep_alive_requested == KEEP_ALIVE_PENDING ||
434		    info->send_immediate) {
435			log_keep_alive(INFO, "send an empty message\n");
436			smbd_post_send_empty(info);
437		}
438	}
439}
440
441/* Called from softirq, when recv is done */
442static void recv_done(struct ib_cq *cq, struct ib_wc *wc)
443{
444	struct smbd_data_transfer *data_transfer;
445	struct smbd_response *response =
446		container_of(wc->wr_cqe, struct smbd_response, cqe);
447	struct smbd_connection *info = response->info;
448	int data_length = 0;
449
450	log_rdma_recv(INFO, "response=%p type=%d wc status=%d wc opcode %d byte_len=%d pkey_index=%x\n",
451		      response, response->type, wc->status, wc->opcode,
452		      wc->byte_len, wc->pkey_index);
453
454	if (wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV) {
455		log_rdma_recv(INFO, "wc->status=%d opcode=%d\n",
456			wc->status, wc->opcode);
457		smbd_disconnect_rdma_connection(info);
458		goto error;
459	}
460
461	ib_dma_sync_single_for_cpu(
462		wc->qp->device,
463		response->sge.addr,
464		response->sge.length,
465		DMA_FROM_DEVICE);
466
467	switch (response->type) {
468	/* SMBD negotiation response */
469	case SMBD_NEGOTIATE_RESP:
470		dump_smbd_negotiate_resp(smbd_response_payload(response));
471		info->full_packet_received = true;
472		info->negotiate_done =
473			process_negotiation_response(response, wc->byte_len);
474		complete(&info->negotiate_completion);
475		break;
476
477	/* SMBD data transfer packet */
478	case SMBD_TRANSFER_DATA:
479		data_transfer = smbd_response_payload(response);
480		data_length = le32_to_cpu(data_transfer->data_length);
481
482		/*
483		 * If this is a packet with data playload place the data in
484		 * reassembly queue and wake up the reading thread
485		 */
486		if (data_length) {
487			if (info->full_packet_received)
488				response->first_segment = true;
489
490			if (le32_to_cpu(data_transfer->remaining_data_length))
491				info->full_packet_received = false;
492			else
493				info->full_packet_received = true;
494
495			enqueue_reassembly(
496				info,
497				response,
498				data_length);
499		} else
500			put_empty_packet(info, response);
501
502		if (data_length)
503			wake_up_interruptible(&info->wait_reassembly_queue);
504
505		atomic_dec(&info->receive_credits);
506		info->receive_credit_target =
507			le16_to_cpu(data_transfer->credits_requested);
508		if (le16_to_cpu(data_transfer->credits_granted)) {
509			atomic_add(le16_to_cpu(data_transfer->credits_granted),
510				&info->send_credits);
511			/*
512			 * We have new send credits granted from remote peer
513			 * If any sender is waiting for credits, unblock it
514			 */
515			wake_up_interruptible(&info->wait_send_queue);
516		}
517
518		log_incoming(INFO, "data flags %d data_offset %d data_length %d remaining_data_length %d\n",
519			     le16_to_cpu(data_transfer->flags),
520			     le32_to_cpu(data_transfer->data_offset),
521			     le32_to_cpu(data_transfer->data_length),
522			     le32_to_cpu(data_transfer->remaining_data_length));
523
524		/* Send a KEEP_ALIVE response right away if requested */
525		info->keep_alive_requested = KEEP_ALIVE_NONE;
526		if (le16_to_cpu(data_transfer->flags) &
527				SMB_DIRECT_RESPONSE_REQUESTED) {
528			info->keep_alive_requested = KEEP_ALIVE_PENDING;
529		}
530
531		return;
532
533	default:
534		log_rdma_recv(ERR,
535			"unexpected response type=%d\n", response->type);
536	}
537
538error:
539	put_receive_buffer(info, response);
540}
541
542static struct rdma_cm_id *smbd_create_id(
543		struct smbd_connection *info,
544		struct sockaddr *dstaddr, int port)
545{
546	struct rdma_cm_id *id;
547	int rc;
548	__be16 *sport;
549
550	id = rdma_create_id(&init_net, smbd_conn_upcall, info,
551		RDMA_PS_TCP, IB_QPT_RC);
552	if (IS_ERR(id)) {
553		rc = PTR_ERR(id);
554		log_rdma_event(ERR, "rdma_create_id() failed %i\n", rc);
555		return id;
556	}
557
558	if (dstaddr->sa_family == AF_INET6)
559		sport = &((struct sockaddr_in6 *)dstaddr)->sin6_port;
560	else
561		sport = &((struct sockaddr_in *)dstaddr)->sin_port;
562
563	*sport = htons(port);
564
565	init_completion(&info->ri_done);
566	info->ri_rc = -ETIMEDOUT;
567
568	rc = rdma_resolve_addr(id, NULL, (struct sockaddr *)dstaddr,
569		RDMA_RESOLVE_TIMEOUT);
570	if (rc) {
571		log_rdma_event(ERR, "rdma_resolve_addr() failed %i\n", rc);
572		goto out;
573	}
574	rc = wait_for_completion_interruptible_timeout(
575		&info->ri_done, msecs_to_jiffies(RDMA_RESOLVE_TIMEOUT));
576	/* e.g. if interrupted returns -ERESTARTSYS */
577	if (rc < 0) {
578		log_rdma_event(ERR, "rdma_resolve_addr timeout rc: %i\n", rc);
579		goto out;
580	}
581	rc = info->ri_rc;
582	if (rc) {
583		log_rdma_event(ERR, "rdma_resolve_addr() completed %i\n", rc);
584		goto out;
585	}
586
587	info->ri_rc = -ETIMEDOUT;
588	rc = rdma_resolve_route(id, RDMA_RESOLVE_TIMEOUT);
589	if (rc) {
590		log_rdma_event(ERR, "rdma_resolve_route() failed %i\n", rc);
591		goto out;
592	}
593	rc = wait_for_completion_interruptible_timeout(
594		&info->ri_done, msecs_to_jiffies(RDMA_RESOLVE_TIMEOUT));
595	/* e.g. if interrupted returns -ERESTARTSYS */
596	if (rc < 0)  {
597		log_rdma_event(ERR, "rdma_resolve_addr timeout rc: %i\n", rc);
598		goto out;
599	}
600	rc = info->ri_rc;
601	if (rc) {
602		log_rdma_event(ERR, "rdma_resolve_route() completed %i\n", rc);
603		goto out;
604	}
605
606	return id;
607
608out:
609	rdma_destroy_id(id);
610	return ERR_PTR(rc);
611}
612
613/*
614 * Test if FRWR (Fast Registration Work Requests) is supported on the device
615 * This implementation requries FRWR on RDMA read/write
616 * return value: true if it is supported
617 */
618static bool frwr_is_supported(struct ib_device_attr *attrs)
619{
620	if (!(attrs->device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS))
621		return false;
622	if (attrs->max_fast_reg_page_list_len == 0)
623		return false;
624	return true;
625}
626
627static int smbd_ia_open(
628		struct smbd_connection *info,
629		struct sockaddr *dstaddr, int port)
630{
631	int rc;
632
633	info->id = smbd_create_id(info, dstaddr, port);
634	if (IS_ERR(info->id)) {
635		rc = PTR_ERR(info->id);
636		goto out1;
637	}
638
639	if (!frwr_is_supported(&info->id->device->attrs)) {
640		log_rdma_event(ERR, "Fast Registration Work Requests (FRWR) is not supported\n");
641		log_rdma_event(ERR, "Device capability flags = %llx max_fast_reg_page_list_len = %u\n",
642			       info->id->device->attrs.device_cap_flags,
643			       info->id->device->attrs.max_fast_reg_page_list_len);
644		rc = -EPROTONOSUPPORT;
645		goto out2;
646	}
647	info->max_frmr_depth = min_t(int,
648		smbd_max_frmr_depth,
649		info->id->device->attrs.max_fast_reg_page_list_len);
650	info->mr_type = IB_MR_TYPE_MEM_REG;
651	if (info->id->device->attrs.device_cap_flags & IB_DEVICE_SG_GAPS_REG)
652		info->mr_type = IB_MR_TYPE_SG_GAPS;
653
654	info->pd = ib_alloc_pd(info->id->device, 0);
655	if (IS_ERR(info->pd)) {
656		rc = PTR_ERR(info->pd);
657		log_rdma_event(ERR, "ib_alloc_pd() returned %d\n", rc);
658		goto out2;
659	}
660
661	return 0;
662
663out2:
664	rdma_destroy_id(info->id);
665	info->id = NULL;
666
667out1:
668	return rc;
669}
670
671/*
672 * Send a negotiation request message to the peer
673 * The negotiation procedure is in [MS-SMBD] 3.1.5.2 and 3.1.5.3
674 * After negotiation, the transport is connected and ready for
675 * carrying upper layer SMB payload
676 */
677static int smbd_post_send_negotiate_req(struct smbd_connection *info)
678{
679	struct ib_send_wr send_wr;
680	int rc = -ENOMEM;
681	struct smbd_request *request;
682	struct smbd_negotiate_req *packet;
683
684	request = mempool_alloc(info->request_mempool, GFP_KERNEL);
685	if (!request)
686		return rc;
687
688	request->info = info;
689
690	packet = smbd_request_payload(request);
691	packet->min_version = cpu_to_le16(SMBD_V1);
692	packet->max_version = cpu_to_le16(SMBD_V1);
693	packet->reserved = 0;
694	packet->credits_requested = cpu_to_le16(info->send_credit_target);
695	packet->preferred_send_size = cpu_to_le32(info->max_send_size);
696	packet->max_receive_size = cpu_to_le32(info->max_receive_size);
697	packet->max_fragmented_size =
698		cpu_to_le32(info->max_fragmented_recv_size);
699
700	request->num_sge = 1;
701	request->sge[0].addr = ib_dma_map_single(
702				info->id->device, (void *)packet,
703				sizeof(*packet), DMA_TO_DEVICE);
704	if (ib_dma_mapping_error(info->id->device, request->sge[0].addr)) {
705		rc = -EIO;
706		goto dma_mapping_failed;
707	}
708
709	request->sge[0].length = sizeof(*packet);
710	request->sge[0].lkey = info->pd->local_dma_lkey;
711
712	ib_dma_sync_single_for_device(
713		info->id->device, request->sge[0].addr,
714		request->sge[0].length, DMA_TO_DEVICE);
715
716	request->cqe.done = send_done;
717
718	send_wr.next = NULL;
719	send_wr.wr_cqe = &request->cqe;
720	send_wr.sg_list = request->sge;
721	send_wr.num_sge = request->num_sge;
722	send_wr.opcode = IB_WR_SEND;
723	send_wr.send_flags = IB_SEND_SIGNALED;
724
725	log_rdma_send(INFO, "sge addr=%llx length=%x lkey=%x\n",
726		request->sge[0].addr,
727		request->sge[0].length, request->sge[0].lkey);
728
729	atomic_inc(&info->send_pending);
730	rc = ib_post_send(info->id->qp, &send_wr, NULL);
731	if (!rc)
732		return 0;
733
734	/* if we reach here, post send failed */
735	log_rdma_send(ERR, "ib_post_send failed rc=%d\n", rc);
736	atomic_dec(&info->send_pending);
737	ib_dma_unmap_single(info->id->device, request->sge[0].addr,
738		request->sge[0].length, DMA_TO_DEVICE);
739
740	smbd_disconnect_rdma_connection(info);
741
742dma_mapping_failed:
743	mempool_free(request, info->request_mempool);
744	return rc;
745}
746
747/*
748 * Extend the credits to remote peer
749 * This implements [MS-SMBD] 3.1.5.9
750 * The idea is that we should extend credits to remote peer as quickly as
751 * it's allowed, to maintain data flow. We allocate as much receive
752 * buffer as possible, and extend the receive credits to remote peer
753 * return value: the new credtis being granted.
754 */
755static int manage_credits_prior_sending(struct smbd_connection *info)
756{
757	int new_credits;
758
759	spin_lock(&info->lock_new_credits_offered);
760	new_credits = info->new_credits_offered;
761	info->new_credits_offered = 0;
762	spin_unlock(&info->lock_new_credits_offered);
763
764	return new_credits;
765}
766
767/*
768 * Check if we need to send a KEEP_ALIVE message
769 * The idle connection timer triggers a KEEP_ALIVE message when expires
770 * SMB_DIRECT_RESPONSE_REQUESTED is set in the message flag to have peer send
771 * back a response.
772 * return value:
773 * 1 if SMB_DIRECT_RESPONSE_REQUESTED needs to be set
774 * 0: otherwise
775 */
776static int manage_keep_alive_before_sending(struct smbd_connection *info)
777{
778	if (info->keep_alive_requested == KEEP_ALIVE_PENDING) {
779		info->keep_alive_requested = KEEP_ALIVE_SENT;
780		return 1;
781	}
782	return 0;
783}
784
785/* Post the send request */
786static int smbd_post_send(struct smbd_connection *info,
787		struct smbd_request *request)
788{
789	struct ib_send_wr send_wr;
790	int rc, i;
791
792	for (i = 0; i < request->num_sge; i++) {
793		log_rdma_send(INFO,
794			"rdma_request sge[%d] addr=%llu length=%u\n",
795			i, request->sge[i].addr, request->sge[i].length);
796		ib_dma_sync_single_for_device(
797			info->id->device,
798			request->sge[i].addr,
799			request->sge[i].length,
800			DMA_TO_DEVICE);
801	}
802
803	request->cqe.done = send_done;
804
805	send_wr.next = NULL;
806	send_wr.wr_cqe = &request->cqe;
807	send_wr.sg_list = request->sge;
808	send_wr.num_sge = request->num_sge;
809	send_wr.opcode = IB_WR_SEND;
810	send_wr.send_flags = IB_SEND_SIGNALED;
811
812	rc = ib_post_send(info->id->qp, &send_wr, NULL);
813	if (rc) {
814		log_rdma_send(ERR, "ib_post_send failed rc=%d\n", rc);
815		smbd_disconnect_rdma_connection(info);
816		rc = -EAGAIN;
817	} else
818		/* Reset timer for idle connection after packet is sent */
819		mod_delayed_work(info->workqueue, &info->idle_timer_work,
820			info->keep_alive_interval*HZ);
821
822	return rc;
823}
824
825static int smbd_post_send_sgl(struct smbd_connection *info,
826	struct scatterlist *sgl, int data_length, int remaining_data_length)
827{
828	int num_sgs;
829	int i, rc;
830	int header_length;
831	struct smbd_request *request;
832	struct smbd_data_transfer *packet;
833	int new_credits;
834	struct scatterlist *sg;
835
836wait_credit:
837	/* Wait for send credits. A SMBD packet needs one credit */
838	rc = wait_event_interruptible(info->wait_send_queue,
839		atomic_read(&info->send_credits) > 0 ||
840		info->transport_status != SMBD_CONNECTED);
841	if (rc)
842		goto err_wait_credit;
843
844	if (info->transport_status != SMBD_CONNECTED) {
845		log_outgoing(ERR, "disconnected not sending on wait_credit\n");
846		rc = -EAGAIN;
847		goto err_wait_credit;
848	}
849	if (unlikely(atomic_dec_return(&info->send_credits) < 0)) {
850		atomic_inc(&info->send_credits);
851		goto wait_credit;
852	}
853
854wait_send_queue:
855	wait_event(info->wait_post_send,
856		atomic_read(&info->send_pending) < info->send_credit_target ||
857		info->transport_status != SMBD_CONNECTED);
858
859	if (info->transport_status != SMBD_CONNECTED) {
860		log_outgoing(ERR, "disconnected not sending on wait_send_queue\n");
861		rc = -EAGAIN;
862		goto err_wait_send_queue;
863	}
864
865	if (unlikely(atomic_inc_return(&info->send_pending) >
866				info->send_credit_target)) {
867		atomic_dec(&info->send_pending);
868		goto wait_send_queue;
869	}
870
871	request = mempool_alloc(info->request_mempool, GFP_KERNEL);
872	if (!request) {
873		rc = -ENOMEM;
874		goto err_alloc;
875	}
876
877	request->info = info;
878
879	/* Fill in the packet header */
880	packet = smbd_request_payload(request);
881	packet->credits_requested = cpu_to_le16(info->send_credit_target);
882
883	new_credits = manage_credits_prior_sending(info);
884	atomic_add(new_credits, &info->receive_credits);
885	packet->credits_granted = cpu_to_le16(new_credits);
886
887	info->send_immediate = false;
888
889	packet->flags = 0;
890	if (manage_keep_alive_before_sending(info))
891		packet->flags |= cpu_to_le16(SMB_DIRECT_RESPONSE_REQUESTED);
892
893	packet->reserved = 0;
894	if (!data_length)
895		packet->data_offset = 0;
896	else
897		packet->data_offset = cpu_to_le32(24);
898	packet->data_length = cpu_to_le32(data_length);
899	packet->remaining_data_length = cpu_to_le32(remaining_data_length);
900	packet->padding = 0;
901
902	log_outgoing(INFO, "credits_requested=%d credits_granted=%d data_offset=%d data_length=%d remaining_data_length=%d\n",
903		     le16_to_cpu(packet->credits_requested),
904		     le16_to_cpu(packet->credits_granted),
905		     le32_to_cpu(packet->data_offset),
906		     le32_to_cpu(packet->data_length),
907		     le32_to_cpu(packet->remaining_data_length));
908
909	/* Map the packet to DMA */
910	header_length = sizeof(struct smbd_data_transfer);
911	/* If this is a packet without payload, don't send padding */
912	if (!data_length)
913		header_length = offsetof(struct smbd_data_transfer, padding);
914
915	request->num_sge = 1;
916	request->sge[0].addr = ib_dma_map_single(info->id->device,
917						 (void *)packet,
918						 header_length,
919						 DMA_TO_DEVICE);
920	if (ib_dma_mapping_error(info->id->device, request->sge[0].addr)) {
921		rc = -EIO;
922		request->sge[0].addr = 0;
923		goto err_dma;
924	}
925
926	request->sge[0].length = header_length;
927	request->sge[0].lkey = info->pd->local_dma_lkey;
928
929	/* Fill in the packet data payload */
930	num_sgs = sgl ? sg_nents(sgl) : 0;
931	for_each_sg(sgl, sg, num_sgs, i) {
932		request->sge[i+1].addr =
933			ib_dma_map_page(info->id->device, sg_page(sg),
934			       sg->offset, sg->length, DMA_TO_DEVICE);
935		if (ib_dma_mapping_error(
936				info->id->device, request->sge[i+1].addr)) {
937			rc = -EIO;
938			request->sge[i+1].addr = 0;
939			goto err_dma;
940		}
941		request->sge[i+1].length = sg->length;
942		request->sge[i+1].lkey = info->pd->local_dma_lkey;
943		request->num_sge++;
944	}
945
946	rc = smbd_post_send(info, request);
947	if (!rc)
948		return 0;
949
950err_dma:
951	for (i = 0; i < request->num_sge; i++)
952		if (request->sge[i].addr)
953			ib_dma_unmap_single(info->id->device,
954					    request->sge[i].addr,
955					    request->sge[i].length,
956					    DMA_TO_DEVICE);
957	mempool_free(request, info->request_mempool);
958
959	/* roll back receive credits and credits to be offered */
960	spin_lock(&info->lock_new_credits_offered);
961	info->new_credits_offered += new_credits;
962	spin_unlock(&info->lock_new_credits_offered);
963	atomic_sub(new_credits, &info->receive_credits);
964
965err_alloc:
966	if (atomic_dec_and_test(&info->send_pending))
967		wake_up(&info->wait_send_pending);
968
969err_wait_send_queue:
970	/* roll back send credits and pending */
971	atomic_inc(&info->send_credits);
972
973err_wait_credit:
974	return rc;
975}
976
977/*
978 * Send a page
979 * page: the page to send
980 * offset: offset in the page to send
981 * size: length in the page to send
982 * remaining_data_length: remaining data to send in this payload
983 */
984static int smbd_post_send_page(struct smbd_connection *info, struct page *page,
985		unsigned long offset, size_t size, int remaining_data_length)
986{
987	struct scatterlist sgl;
988
989	sg_init_table(&sgl, 1);
990	sg_set_page(&sgl, page, size, offset);
991
992	return smbd_post_send_sgl(info, &sgl, size, remaining_data_length);
993}
994
995/*
996 * Send an empty message
997 * Empty message is used to extend credits to peer to for keep live
998 * while there is no upper layer payload to send at the time
999 */
1000static int smbd_post_send_empty(struct smbd_connection *info)
1001{
1002	info->count_send_empty++;
1003	return smbd_post_send_sgl(info, NULL, 0, 0);
1004}
1005
1006/*
1007 * Send a data buffer
1008 * iov: the iov array describing the data buffers
1009 * n_vec: number of iov array
1010 * remaining_data_length: remaining data to send following this packet
1011 * in segmented SMBD packet
1012 */
1013static int smbd_post_send_data(
1014	struct smbd_connection *info, struct kvec *iov, int n_vec,
1015	int remaining_data_length)
1016{
1017	int i;
1018	u32 data_length = 0;
1019	struct scatterlist sgl[SMBDIRECT_MAX_SGE];
1020
1021	if (n_vec > SMBDIRECT_MAX_SGE) {
1022		cifs_dbg(VFS, "Can't fit data to SGL, n_vec=%d\n", n_vec);
1023		return -EINVAL;
1024	}
1025
1026	sg_init_table(sgl, n_vec);
1027	for (i = 0; i < n_vec; i++) {
1028		data_length += iov[i].iov_len;
1029		sg_set_buf(&sgl[i], iov[i].iov_base, iov[i].iov_len);
1030	}
1031
1032	return smbd_post_send_sgl(info, sgl, data_length, remaining_data_length);
1033}
1034
1035/*
1036 * Post a receive request to the transport
1037 * The remote peer can only send data when a receive request is posted
1038 * The interaction is controlled by send/receive credit system
1039 */
1040static int smbd_post_recv(
1041		struct smbd_connection *info, struct smbd_response *response)
1042{
1043	struct ib_recv_wr recv_wr;
1044	int rc = -EIO;
1045
1046	response->sge.addr = ib_dma_map_single(
1047				info->id->device, response->packet,
1048				info->max_receive_size, DMA_FROM_DEVICE);
1049	if (ib_dma_mapping_error(info->id->device, response->sge.addr))
1050		return rc;
1051
1052	response->sge.length = info->max_receive_size;
1053	response->sge.lkey = info->pd->local_dma_lkey;
1054
1055	response->cqe.done = recv_done;
1056
1057	recv_wr.wr_cqe = &response->cqe;
1058	recv_wr.next = NULL;
1059	recv_wr.sg_list = &response->sge;
1060	recv_wr.num_sge = 1;
1061
1062	rc = ib_post_recv(info->id->qp, &recv_wr, NULL);
1063	if (rc) {
1064		ib_dma_unmap_single(info->id->device, response->sge.addr,
1065				    response->sge.length, DMA_FROM_DEVICE);
1066		smbd_disconnect_rdma_connection(info);
1067		log_rdma_recv(ERR, "ib_post_recv failed rc=%d\n", rc);
1068	}
1069
1070	return rc;
1071}
1072
1073/* Perform SMBD negotiate according to [MS-SMBD] 3.1.5.2 */
1074static int smbd_negotiate(struct smbd_connection *info)
1075{
1076	int rc;
1077	struct smbd_response *response = get_receive_buffer(info);
1078
1079	response->type = SMBD_NEGOTIATE_RESP;
1080	rc = smbd_post_recv(info, response);
1081	log_rdma_event(INFO, "smbd_post_recv rc=%d iov.addr=%llx iov.length=%x iov.lkey=%x\n",
1082		       rc, response->sge.addr,
1083		       response->sge.length, response->sge.lkey);
1084	if (rc)
1085		return rc;
1086
1087	init_completion(&info->negotiate_completion);
1088	info->negotiate_done = false;
1089	rc = smbd_post_send_negotiate_req(info);
1090	if (rc)
1091		return rc;
1092
1093	rc = wait_for_completion_interruptible_timeout(
1094		&info->negotiate_completion, SMBD_NEGOTIATE_TIMEOUT * HZ);
1095	log_rdma_event(INFO, "wait_for_completion_timeout rc=%d\n", rc);
1096
1097	if (info->negotiate_done)
1098		return 0;
1099
1100	if (rc == 0)
1101		rc = -ETIMEDOUT;
1102	else if (rc == -ERESTARTSYS)
1103		rc = -EINTR;
1104	else
1105		rc = -ENOTCONN;
1106
1107	return rc;
1108}
1109
1110static void put_empty_packet(
1111		struct smbd_connection *info, struct smbd_response *response)
1112{
1113	spin_lock(&info->empty_packet_queue_lock);
1114	list_add_tail(&response->list, &info->empty_packet_queue);
1115	info->count_empty_packet_queue++;
1116	spin_unlock(&info->empty_packet_queue_lock);
1117
1118	queue_work(info->workqueue, &info->post_send_credits_work);
1119}
1120
1121/*
1122 * Implement Connection.FragmentReassemblyBuffer defined in [MS-SMBD] 3.1.1.1
1123 * This is a queue for reassembling upper layer payload and present to upper
1124 * layer. All the inncoming payload go to the reassembly queue, regardless of
1125 * if reassembly is required. The uuper layer code reads from the queue for all
1126 * incoming payloads.
1127 * Put a received packet to the reassembly queue
1128 * response: the packet received
1129 * data_length: the size of payload in this packet
1130 */
1131static void enqueue_reassembly(
1132	struct smbd_connection *info,
1133	struct smbd_response *response,
1134	int data_length)
1135{
1136	spin_lock(&info->reassembly_queue_lock);
1137	list_add_tail(&response->list, &info->reassembly_queue);
1138	info->reassembly_queue_length++;
1139	/*
1140	 * Make sure reassembly_data_length is updated after list and
1141	 * reassembly_queue_length are updated. On the dequeue side
1142	 * reassembly_data_length is checked without a lock to determine
1143	 * if reassembly_queue_length and list is up to date
1144	 */
1145	virt_wmb();
1146	info->reassembly_data_length += data_length;
1147	spin_unlock(&info->reassembly_queue_lock);
1148	info->count_reassembly_queue++;
1149	info->count_enqueue_reassembly_queue++;
1150}
1151
1152/*
1153 * Get the first entry at the front of reassembly queue
1154 * Caller is responsible for locking
1155 * return value: the first entry if any, NULL if queue is empty
1156 */
1157static struct smbd_response *_get_first_reassembly(struct smbd_connection *info)
1158{
1159	struct smbd_response *ret = NULL;
1160
1161	if (!list_empty(&info->reassembly_queue)) {
1162		ret = list_first_entry(
1163			&info->reassembly_queue,
1164			struct smbd_response, list);
1165	}
1166	return ret;
1167}
1168
1169static struct smbd_response *get_empty_queue_buffer(
1170		struct smbd_connection *info)
1171{
1172	struct smbd_response *ret = NULL;
1173	unsigned long flags;
1174
1175	spin_lock_irqsave(&info->empty_packet_queue_lock, flags);
1176	if (!list_empty(&info->empty_packet_queue)) {
1177		ret = list_first_entry(
1178			&info->empty_packet_queue,
1179			struct smbd_response, list);
1180		list_del(&ret->list);
1181		info->count_empty_packet_queue--;
1182	}
1183	spin_unlock_irqrestore(&info->empty_packet_queue_lock, flags);
1184
1185	return ret;
1186}
1187
1188/*
1189 * Get a receive buffer
1190 * For each remote send, we need to post a receive. The receive buffers are
1191 * pre-allocated in advance.
1192 * return value: the receive buffer, NULL if none is available
1193 */
1194static struct smbd_response *get_receive_buffer(struct smbd_connection *info)
1195{
1196	struct smbd_response *ret = NULL;
1197	unsigned long flags;
1198
1199	spin_lock_irqsave(&info->receive_queue_lock, flags);
1200	if (!list_empty(&info->receive_queue)) {
1201		ret = list_first_entry(
1202			&info->receive_queue,
1203			struct smbd_response, list);
1204		list_del(&ret->list);
1205		info->count_receive_queue--;
1206		info->count_get_receive_buffer++;
1207	}
1208	spin_unlock_irqrestore(&info->receive_queue_lock, flags);
1209
1210	return ret;
1211}
1212
1213/*
1214 * Return a receive buffer
1215 * Upon returning of a receive buffer, we can post new receive and extend
1216 * more receive credits to remote peer. This is done immediately after a
1217 * receive buffer is returned.
1218 */
1219static void put_receive_buffer(
1220	struct smbd_connection *info, struct smbd_response *response)
1221{
1222	unsigned long flags;
1223
1224	ib_dma_unmap_single(info->id->device, response->sge.addr,
1225		response->sge.length, DMA_FROM_DEVICE);
1226
1227	spin_lock_irqsave(&info->receive_queue_lock, flags);
1228	list_add_tail(&response->list, &info->receive_queue);
1229	info->count_receive_queue++;
1230	info->count_put_receive_buffer++;
1231	spin_unlock_irqrestore(&info->receive_queue_lock, flags);
1232
1233	queue_work(info->workqueue, &info->post_send_credits_work);
1234}
1235
1236/* Preallocate all receive buffer on transport establishment */
1237static int allocate_receive_buffers(struct smbd_connection *info, int num_buf)
1238{
1239	int i;
1240	struct smbd_response *response;
1241
1242	INIT_LIST_HEAD(&info->reassembly_queue);
1243	spin_lock_init(&info->reassembly_queue_lock);
1244	info->reassembly_data_length = 0;
1245	info->reassembly_queue_length = 0;
1246
1247	INIT_LIST_HEAD(&info->receive_queue);
1248	spin_lock_init(&info->receive_queue_lock);
1249	info->count_receive_queue = 0;
1250
1251	INIT_LIST_HEAD(&info->empty_packet_queue);
1252	spin_lock_init(&info->empty_packet_queue_lock);
1253	info->count_empty_packet_queue = 0;
1254
1255	init_waitqueue_head(&info->wait_receive_queues);
1256
1257	for (i = 0; i < num_buf; i++) {
1258		response = mempool_alloc(info->response_mempool, GFP_KERNEL);
1259		if (!response)
1260			goto allocate_failed;
1261
1262		response->info = info;
1263		list_add_tail(&response->list, &info->receive_queue);
1264		info->count_receive_queue++;
1265	}
1266
1267	return 0;
1268
1269allocate_failed:
1270	while (!list_empty(&info->receive_queue)) {
1271		response = list_first_entry(
1272				&info->receive_queue,
1273				struct smbd_response, list);
1274		list_del(&response->list);
1275		info->count_receive_queue--;
1276
1277		mempool_free(response, info->response_mempool);
1278	}
1279	return -ENOMEM;
1280}
1281
1282static void destroy_receive_buffers(struct smbd_connection *info)
1283{
1284	struct smbd_response *response;
1285
1286	while ((response = get_receive_buffer(info)))
1287		mempool_free(response, info->response_mempool);
1288
1289	while ((response = get_empty_queue_buffer(info)))
1290		mempool_free(response, info->response_mempool);
1291}
1292
1293/* Implement idle connection timer [MS-SMBD] 3.1.6.2 */
1294static void idle_connection_timer(struct work_struct *work)
1295{
1296	struct smbd_connection *info = container_of(
1297					work, struct smbd_connection,
1298					idle_timer_work.work);
1299
1300	if (info->keep_alive_requested != KEEP_ALIVE_NONE) {
1301		log_keep_alive(ERR,
1302			"error status info->keep_alive_requested=%d\n",
1303			info->keep_alive_requested);
1304		smbd_disconnect_rdma_connection(info);
1305		return;
1306	}
1307
1308	log_keep_alive(INFO, "about to send an empty idle message\n");
1309	smbd_post_send_empty(info);
1310
1311	/* Setup the next idle timeout work */
1312	queue_delayed_work(info->workqueue, &info->idle_timer_work,
1313			info->keep_alive_interval*HZ);
1314}
1315
1316/*
1317 * Destroy the transport and related RDMA and memory resources
1318 * Need to go through all the pending counters and make sure on one is using
1319 * the transport while it is destroyed
1320 */
1321void smbd_destroy(struct TCP_Server_Info *server)
1322{
1323	struct smbd_connection *info = server->smbd_conn;
1324	struct smbd_response *response;
1325	unsigned long flags;
1326
1327	if (!info) {
1328		log_rdma_event(INFO, "rdma session already destroyed\n");
1329		return;
1330	}
1331
1332	log_rdma_event(INFO, "destroying rdma session\n");
1333	if (info->transport_status != SMBD_DISCONNECTED) {
1334		rdma_disconnect(server->smbd_conn->id);
1335		log_rdma_event(INFO, "wait for transport being disconnected\n");
1336		wait_event_interruptible(
1337			info->disconn_wait,
1338			info->transport_status == SMBD_DISCONNECTED);
1339	}
1340
1341	log_rdma_event(INFO, "destroying qp\n");
1342	ib_drain_qp(info->id->qp);
1343	rdma_destroy_qp(info->id);
1344
1345	log_rdma_event(INFO, "cancelling idle timer\n");
1346	cancel_delayed_work_sync(&info->idle_timer_work);
1347
1348	log_rdma_event(INFO, "wait for all send posted to IB to finish\n");
1349	wait_event(info->wait_send_pending,
1350		atomic_read(&info->send_pending) == 0);
1351
1352	/* It's not posssible for upper layer to get to reassembly */
1353	log_rdma_event(INFO, "drain the reassembly queue\n");
1354	do {
1355		spin_lock_irqsave(&info->reassembly_queue_lock, flags);
1356		response = _get_first_reassembly(info);
1357		if (response) {
1358			list_del(&response->list);
1359			spin_unlock_irqrestore(
1360				&info->reassembly_queue_lock, flags);
1361			put_receive_buffer(info, response);
1362		} else
1363			spin_unlock_irqrestore(
1364				&info->reassembly_queue_lock, flags);
1365	} while (response);
1366	info->reassembly_data_length = 0;
1367
1368	log_rdma_event(INFO, "free receive buffers\n");
1369	wait_event(info->wait_receive_queues,
1370		info->count_receive_queue + info->count_empty_packet_queue
1371			== info->receive_credit_max);
1372	destroy_receive_buffers(info);
1373
1374	/*
1375	 * For performance reasons, memory registration and deregistration
1376	 * are not locked by srv_mutex. It is possible some processes are
1377	 * blocked on transport srv_mutex while holding memory registration.
1378	 * Release the transport srv_mutex to allow them to hit the failure
1379	 * path when sending data, and then release memory registartions.
1380	 */
1381	log_rdma_event(INFO, "freeing mr list\n");
1382	wake_up_interruptible_all(&info->wait_mr);
1383	while (atomic_read(&info->mr_used_count)) {
1384		mutex_unlock(&server->srv_mutex);
1385		msleep(1000);
1386		mutex_lock(&server->srv_mutex);
1387	}
1388	destroy_mr_list(info);
1389
1390	ib_free_cq(info->send_cq);
1391	ib_free_cq(info->recv_cq);
1392	ib_dealloc_pd(info->pd);
1393	rdma_destroy_id(info->id);
1394
1395	/* free mempools */
1396	mempool_destroy(info->request_mempool);
1397	kmem_cache_destroy(info->request_cache);
1398
1399	mempool_destroy(info->response_mempool);
1400	kmem_cache_destroy(info->response_cache);
1401
1402	info->transport_status = SMBD_DESTROYED;
1403
1404	destroy_workqueue(info->workqueue);
1405	log_rdma_event(INFO,  "rdma session destroyed\n");
1406	kfree(info);
1407	server->smbd_conn = NULL;
1408}
1409
1410/*
1411 * Reconnect this SMBD connection, called from upper layer
1412 * return value: 0 on success, or actual error code
1413 */
1414int smbd_reconnect(struct TCP_Server_Info *server)
1415{
1416	log_rdma_event(INFO, "reconnecting rdma session\n");
1417
1418	if (!server->smbd_conn) {
1419		log_rdma_event(INFO, "rdma session already destroyed\n");
1420		goto create_conn;
1421	}
1422
1423	/*
1424	 * This is possible if transport is disconnected and we haven't received
1425	 * notification from RDMA, but upper layer has detected timeout
1426	 */
1427	if (server->smbd_conn->transport_status == SMBD_CONNECTED) {
1428		log_rdma_event(INFO, "disconnecting transport\n");
1429		smbd_destroy(server);
1430	}
1431
1432create_conn:
1433	log_rdma_event(INFO, "creating rdma session\n");
1434	server->smbd_conn = smbd_get_connection(
1435		server, (struct sockaddr *) &server->dstaddr);
1436
1437	if (server->smbd_conn)
1438		cifs_dbg(VFS, "RDMA transport re-established\n");
1439
1440	return server->smbd_conn ? 0 : -ENOENT;
1441}
1442
1443static void destroy_caches_and_workqueue(struct smbd_connection *info)
1444{
1445	destroy_receive_buffers(info);
1446	destroy_workqueue(info->workqueue);
1447	mempool_destroy(info->response_mempool);
1448	kmem_cache_destroy(info->response_cache);
1449	mempool_destroy(info->request_mempool);
1450	kmem_cache_destroy(info->request_cache);
1451}
1452
1453#define MAX_NAME_LEN	80
1454static int allocate_caches_and_workqueue(struct smbd_connection *info)
1455{
1456	char name[MAX_NAME_LEN];
1457	int rc;
1458
1459	scnprintf(name, MAX_NAME_LEN, "smbd_request_%p", info);
1460	info->request_cache =
1461		kmem_cache_create(
1462			name,
1463			sizeof(struct smbd_request) +
1464				sizeof(struct smbd_data_transfer),
1465			0, SLAB_HWCACHE_ALIGN, NULL);
1466	if (!info->request_cache)
1467		return -ENOMEM;
1468
1469	info->request_mempool =
1470		mempool_create(info->send_credit_target, mempool_alloc_slab,
1471			mempool_free_slab, info->request_cache);
1472	if (!info->request_mempool)
1473		goto out1;
1474
1475	scnprintf(name, MAX_NAME_LEN, "smbd_response_%p", info);
1476	info->response_cache =
1477		kmem_cache_create(
1478			name,
1479			sizeof(struct smbd_response) +
1480				info->max_receive_size,
1481			0, SLAB_HWCACHE_ALIGN, NULL);
1482	if (!info->response_cache)
1483		goto out2;
1484
1485	info->response_mempool =
1486		mempool_create(info->receive_credit_max, mempool_alloc_slab,
1487		       mempool_free_slab, info->response_cache);
1488	if (!info->response_mempool)
1489		goto out3;
1490
1491	scnprintf(name, MAX_NAME_LEN, "smbd_%p", info);
1492	info->workqueue = create_workqueue(name);
1493	if (!info->workqueue)
1494		goto out4;
1495
1496	rc = allocate_receive_buffers(info, info->receive_credit_max);
1497	if (rc) {
1498		log_rdma_event(ERR, "failed to allocate receive buffers\n");
1499		goto out5;
1500	}
1501
1502	return 0;
1503
1504out5:
1505	destroy_workqueue(info->workqueue);
1506out4:
1507	mempool_destroy(info->response_mempool);
1508out3:
1509	kmem_cache_destroy(info->response_cache);
1510out2:
1511	mempool_destroy(info->request_mempool);
1512out1:
1513	kmem_cache_destroy(info->request_cache);
1514	return -ENOMEM;
1515}
1516
1517/* Create a SMBD connection, called by upper layer */
1518static struct smbd_connection *_smbd_get_connection(
1519	struct TCP_Server_Info *server, struct sockaddr *dstaddr, int port)
1520{
1521	int rc;
1522	struct smbd_connection *info;
1523	struct rdma_conn_param conn_param;
1524	struct ib_qp_init_attr qp_attr;
1525	struct sockaddr_in *addr_in = (struct sockaddr_in *) dstaddr;
1526	struct ib_port_immutable port_immutable;
1527	u32 ird_ord_hdr[2];
1528
1529	info = kzalloc(sizeof(struct smbd_connection), GFP_KERNEL);
1530	if (!info)
1531		return NULL;
1532
1533	info->transport_status = SMBD_CONNECTING;
1534	rc = smbd_ia_open(info, dstaddr, port);
1535	if (rc) {
1536		log_rdma_event(INFO, "smbd_ia_open rc=%d\n", rc);
1537		goto create_id_failed;
1538	}
1539
1540	if (smbd_send_credit_target > info->id->device->attrs.max_cqe ||
1541	    smbd_send_credit_target > info->id->device->attrs.max_qp_wr) {
1542		log_rdma_event(ERR, "consider lowering send_credit_target = %d. Possible CQE overrun, device reporting max_cpe %d max_qp_wr %d\n",
1543			       smbd_send_credit_target,
1544			       info->id->device->attrs.max_cqe,
1545			       info->id->device->attrs.max_qp_wr);
1546		goto config_failed;
1547	}
1548
1549	if (smbd_receive_credit_max > info->id->device->attrs.max_cqe ||
1550	    smbd_receive_credit_max > info->id->device->attrs.max_qp_wr) {
1551		log_rdma_event(ERR, "consider lowering receive_credit_max = %d. Possible CQE overrun, device reporting max_cpe %d max_qp_wr %d\n",
1552			       smbd_receive_credit_max,
1553			       info->id->device->attrs.max_cqe,
1554			       info->id->device->attrs.max_qp_wr);
1555		goto config_failed;
1556	}
1557
1558	info->receive_credit_max = smbd_receive_credit_max;
1559	info->send_credit_target = smbd_send_credit_target;
1560	info->max_send_size = smbd_max_send_size;
1561	info->max_fragmented_recv_size = smbd_max_fragmented_recv_size;
1562	info->max_receive_size = smbd_max_receive_size;
1563	info->keep_alive_interval = smbd_keep_alive_interval;
1564
1565	if (info->id->device->attrs.max_send_sge < SMBDIRECT_MAX_SGE) {
1566		log_rdma_event(ERR,
1567			"warning: device max_send_sge = %d too small\n",
1568			info->id->device->attrs.max_send_sge);
1569		log_rdma_event(ERR, "Queue Pair creation may fail\n");
1570	}
1571	if (info->id->device->attrs.max_recv_sge < SMBDIRECT_MAX_SGE) {
1572		log_rdma_event(ERR,
1573			"warning: device max_recv_sge = %d too small\n",
1574			info->id->device->attrs.max_recv_sge);
1575		log_rdma_event(ERR, "Queue Pair creation may fail\n");
1576	}
1577
1578	info->send_cq = NULL;
1579	info->recv_cq = NULL;
1580	info->send_cq =
1581		ib_alloc_cq_any(info->id->device, info,
1582				info->send_credit_target, IB_POLL_SOFTIRQ);
1583	if (IS_ERR(info->send_cq)) {
1584		info->send_cq = NULL;
1585		goto alloc_cq_failed;
1586	}
1587
1588	info->recv_cq =
1589		ib_alloc_cq_any(info->id->device, info,
1590				info->receive_credit_max, IB_POLL_SOFTIRQ);
1591	if (IS_ERR(info->recv_cq)) {
1592		info->recv_cq = NULL;
1593		goto alloc_cq_failed;
1594	}
1595
1596	memset(&qp_attr, 0, sizeof(qp_attr));
1597	qp_attr.event_handler = smbd_qp_async_error_upcall;
1598	qp_attr.qp_context = info;
1599	qp_attr.cap.max_send_wr = info->send_credit_target;
1600	qp_attr.cap.max_recv_wr = info->receive_credit_max;
1601	qp_attr.cap.max_send_sge = SMBDIRECT_MAX_SGE;
1602	qp_attr.cap.max_recv_sge = SMBDIRECT_MAX_SGE;
1603	qp_attr.cap.max_inline_data = 0;
1604	qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
1605	qp_attr.qp_type = IB_QPT_RC;
1606	qp_attr.send_cq = info->send_cq;
1607	qp_attr.recv_cq = info->recv_cq;
1608	qp_attr.port_num = ~0;
1609
1610	rc = rdma_create_qp(info->id, info->pd, &qp_attr);
1611	if (rc) {
1612		log_rdma_event(ERR, "rdma_create_qp failed %i\n", rc);
1613		goto create_qp_failed;
1614	}
1615
1616	memset(&conn_param, 0, sizeof(conn_param));
1617	conn_param.initiator_depth = 0;
1618
1619	conn_param.responder_resources =
1620		info->id->device->attrs.max_qp_rd_atom
1621			< SMBD_CM_RESPONDER_RESOURCES ?
1622		info->id->device->attrs.max_qp_rd_atom :
1623		SMBD_CM_RESPONDER_RESOURCES;
1624	info->responder_resources = conn_param.responder_resources;
1625	log_rdma_mr(INFO, "responder_resources=%d\n",
1626		info->responder_resources);
1627
1628	/* Need to send IRD/ORD in private data for iWARP */
1629	info->id->device->ops.get_port_immutable(
1630		info->id->device, info->id->port_num, &port_immutable);
1631	if (port_immutable.core_cap_flags & RDMA_CORE_PORT_IWARP) {
1632		ird_ord_hdr[0] = info->responder_resources;
1633		ird_ord_hdr[1] = 1;
1634		conn_param.private_data = ird_ord_hdr;
1635		conn_param.private_data_len = sizeof(ird_ord_hdr);
1636	} else {
1637		conn_param.private_data = NULL;
1638		conn_param.private_data_len = 0;
1639	}
1640
1641	conn_param.retry_count = SMBD_CM_RETRY;
1642	conn_param.rnr_retry_count = SMBD_CM_RNR_RETRY;
1643	conn_param.flow_control = 0;
1644
1645	log_rdma_event(INFO, "connecting to IP %pI4 port %d\n",
1646		&addr_in->sin_addr, port);
1647
1648	init_waitqueue_head(&info->conn_wait);
1649	init_waitqueue_head(&info->disconn_wait);
1650	init_waitqueue_head(&info->wait_reassembly_queue);
1651	rc = rdma_connect(info->id, &conn_param);
1652	if (rc) {
1653		log_rdma_event(ERR, "rdma_connect() failed with %i\n", rc);
1654		goto rdma_connect_failed;
1655	}
1656
1657	wait_event_interruptible(
1658		info->conn_wait, info->transport_status != SMBD_CONNECTING);
1659
1660	if (info->transport_status != SMBD_CONNECTED) {
1661		log_rdma_event(ERR, "rdma_connect failed port=%d\n", port);
1662		goto rdma_connect_failed;
1663	}
1664
1665	log_rdma_event(INFO, "rdma_connect connected\n");
1666
1667	rc = allocate_caches_and_workqueue(info);
1668	if (rc) {
1669		log_rdma_event(ERR, "cache allocation failed\n");
1670		goto allocate_cache_failed;
1671	}
1672
1673	init_waitqueue_head(&info->wait_send_queue);
1674	INIT_DELAYED_WORK(&info->idle_timer_work, idle_connection_timer);
1675	queue_delayed_work(info->workqueue, &info->idle_timer_work,
1676		info->keep_alive_interval*HZ);
1677
1678	init_waitqueue_head(&info->wait_send_pending);
1679	atomic_set(&info->send_pending, 0);
1680
1681	init_waitqueue_head(&info->wait_post_send);
1682
1683	INIT_WORK(&info->disconnect_work, smbd_disconnect_rdma_work);
1684	INIT_WORK(&info->post_send_credits_work, smbd_post_send_credits);
1685	info->new_credits_offered = 0;
1686	spin_lock_init(&info->lock_new_credits_offered);
1687
1688	rc = smbd_negotiate(info);
1689	if (rc) {
1690		log_rdma_event(ERR, "smbd_negotiate rc=%d\n", rc);
1691		goto negotiation_failed;
1692	}
1693
1694	rc = allocate_mr_list(info);
1695	if (rc) {
1696		log_rdma_mr(ERR, "memory registration allocation failed\n");
1697		goto allocate_mr_failed;
1698	}
1699
1700	return info;
1701
1702allocate_mr_failed:
1703	/* At this point, need to a full transport shutdown */
1704	server->smbd_conn = info;
1705	smbd_destroy(server);
1706	return NULL;
1707
1708negotiation_failed:
1709	cancel_delayed_work_sync(&info->idle_timer_work);
1710	destroy_caches_and_workqueue(info);
1711	info->transport_status = SMBD_NEGOTIATE_FAILED;
1712	init_waitqueue_head(&info->conn_wait);
1713	rdma_disconnect(info->id);
1714	wait_event(info->conn_wait,
1715		info->transport_status == SMBD_DISCONNECTED);
1716
1717allocate_cache_failed:
1718rdma_connect_failed:
1719	rdma_destroy_qp(info->id);
1720
1721create_qp_failed:
1722alloc_cq_failed:
1723	if (info->send_cq)
1724		ib_free_cq(info->send_cq);
1725	if (info->recv_cq)
1726		ib_free_cq(info->recv_cq);
1727
1728config_failed:
1729	ib_dealloc_pd(info->pd);
1730	rdma_destroy_id(info->id);
1731
1732create_id_failed:
1733	kfree(info);
1734	return NULL;
1735}
1736
1737struct smbd_connection *smbd_get_connection(
1738	struct TCP_Server_Info *server, struct sockaddr *dstaddr)
1739{
1740	struct smbd_connection *ret;
1741	int port = SMBD_PORT;
1742
1743try_again:
1744	ret = _smbd_get_connection(server, dstaddr, port);
1745
1746	/* Try SMB_PORT if SMBD_PORT doesn't work */
1747	if (!ret && port == SMBD_PORT) {
1748		port = SMB_PORT;
1749		goto try_again;
1750	}
1751	return ret;
1752}
1753
1754/*
1755 * Receive data from receive reassembly queue
1756 * All the incoming data packets are placed in reassembly queue
1757 * buf: the buffer to read data into
1758 * size: the length of data to read
1759 * return value: actual data read
1760 * Note: this implementation copies the data from reassebmly queue to receive
1761 * buffers used by upper layer. This is not the optimal code path. A better way
1762 * to do it is to not have upper layer allocate its receive buffers but rather
1763 * borrow the buffer from reassembly queue, and return it after data is
1764 * consumed. But this will require more changes to upper layer code, and also
1765 * need to consider packet boundaries while they still being reassembled.
1766 */
1767static int smbd_recv_buf(struct smbd_connection *info, char *buf,
1768		unsigned int size)
1769{
1770	struct smbd_response *response;
1771	struct smbd_data_transfer *data_transfer;
1772	int to_copy, to_read, data_read, offset;
1773	u32 data_length, remaining_data_length, data_offset;
1774	int rc;
1775
1776again:
1777	/*
1778	 * No need to hold the reassembly queue lock all the time as we are
1779	 * the only one reading from the front of the queue. The transport
1780	 * may add more entries to the back of the queue at the same time
1781	 */
1782	log_read(INFO, "size=%d info->reassembly_data_length=%d\n", size,
1783		info->reassembly_data_length);
1784	if (info->reassembly_data_length >= size) {
1785		int queue_length;
1786		int queue_removed = 0;
1787
1788		/*
1789		 * Need to make sure reassembly_data_length is read before
1790		 * reading reassembly_queue_length and calling
1791		 * _get_first_reassembly. This call is lock free
1792		 * as we never read at the end of the queue which are being
1793		 * updated in SOFTIRQ as more data is received
1794		 */
1795		virt_rmb();
1796		queue_length = info->reassembly_queue_length;
1797		data_read = 0;
1798		to_read = size;
1799		offset = info->first_entry_offset;
1800		while (data_read < size) {
1801			response = _get_first_reassembly(info);
1802			data_transfer = smbd_response_payload(response);
1803			data_length = le32_to_cpu(data_transfer->data_length);
1804			remaining_data_length =
1805				le32_to_cpu(
1806					data_transfer->remaining_data_length);
1807			data_offset = le32_to_cpu(data_transfer->data_offset);
1808
1809			/*
1810			 * The upper layer expects RFC1002 length at the
1811			 * beginning of the payload. Return it to indicate
1812			 * the total length of the packet. This minimize the
1813			 * change to upper layer packet processing logic. This
1814			 * will be eventually remove when an intermediate
1815			 * transport layer is added
1816			 */
1817			if (response->first_segment && size == 4) {
1818				unsigned int rfc1002_len =
1819					data_length + remaining_data_length;
1820				*((__be32 *)buf) = cpu_to_be32(rfc1002_len);
1821				data_read = 4;
1822				response->first_segment = false;
1823				log_read(INFO, "returning rfc1002 length %d\n",
1824					rfc1002_len);
1825				goto read_rfc1002_done;
1826			}
1827
1828			to_copy = min_t(int, data_length - offset, to_read);
1829			memcpy(
1830				buf + data_read,
1831				(char *)data_transfer + data_offset + offset,
1832				to_copy);
1833
1834			/* move on to the next buffer? */
1835			if (to_copy == data_length - offset) {
1836				queue_length--;
1837				/*
1838				 * No need to lock if we are not at the
1839				 * end of the queue
1840				 */
1841				if (queue_length)
1842					list_del(&response->list);
1843				else {
1844					spin_lock_irq(
1845						&info->reassembly_queue_lock);
1846					list_del(&response->list);
1847					spin_unlock_irq(
1848						&info->reassembly_queue_lock);
1849				}
1850				queue_removed++;
1851				info->count_reassembly_queue--;
1852				info->count_dequeue_reassembly_queue++;
1853				put_receive_buffer(info, response);
1854				offset = 0;
1855				log_read(INFO, "put_receive_buffer offset=0\n");
1856			} else
1857				offset += to_copy;
1858
1859			to_read -= to_copy;
1860			data_read += to_copy;
1861
1862			log_read(INFO, "_get_first_reassembly memcpy %d bytes data_transfer_length-offset=%d after that to_read=%d data_read=%d offset=%d\n",
1863				 to_copy, data_length - offset,
1864				 to_read, data_read, offset);
1865		}
1866
1867		spin_lock_irq(&info->reassembly_queue_lock);
1868		info->reassembly_data_length -= data_read;
1869		info->reassembly_queue_length -= queue_removed;
1870		spin_unlock_irq(&info->reassembly_queue_lock);
1871
1872		info->first_entry_offset = offset;
1873		log_read(INFO, "returning to thread data_read=%d reassembly_data_length=%d first_entry_offset=%d\n",
1874			 data_read, info->reassembly_data_length,
1875			 info->first_entry_offset);
1876read_rfc1002_done:
1877		return data_read;
1878	}
1879
1880	log_read(INFO, "wait_event on more data\n");
1881	rc = wait_event_interruptible(
1882		info->wait_reassembly_queue,
1883		info->reassembly_data_length >= size ||
1884			info->transport_status != SMBD_CONNECTED);
1885	/* Don't return any data if interrupted */
1886	if (rc)
1887		return rc;
1888
1889	if (info->transport_status != SMBD_CONNECTED) {
1890		log_read(ERR, "disconnected\n");
1891		return -ECONNABORTED;
1892	}
1893
1894	goto again;
1895}
1896
1897/*
1898 * Receive a page from receive reassembly queue
1899 * page: the page to read data into
1900 * to_read: the length of data to read
1901 * return value: actual data read
1902 */
1903static int smbd_recv_page(struct smbd_connection *info,
1904		struct page *page, unsigned int page_offset,
1905		unsigned int to_read)
1906{
1907	int ret;
1908	char *to_address;
1909	void *page_address;
1910
1911	/* make sure we have the page ready for read */
1912	ret = wait_event_interruptible(
1913		info->wait_reassembly_queue,
1914		info->reassembly_data_length >= to_read ||
1915			info->transport_status != SMBD_CONNECTED);
1916	if (ret)
1917		return ret;
1918
1919	/* now we can read from reassembly queue and not sleep */
1920	page_address = kmap_atomic(page);
1921	to_address = (char *) page_address + page_offset;
1922
1923	log_read(INFO, "reading from page=%p address=%p to_read=%d\n",
1924		page, to_address, to_read);
1925
1926	ret = smbd_recv_buf(info, to_address, to_read);
1927	kunmap_atomic(page_address);
1928
1929	return ret;
1930}
1931
1932/*
1933 * Receive data from transport
1934 * msg: a msghdr point to the buffer, can be ITER_KVEC or ITER_BVEC
1935 * return: total bytes read, or 0. SMB Direct will not do partial read.
1936 */
1937int smbd_recv(struct smbd_connection *info, struct msghdr *msg)
1938{
1939	char *buf;
1940	struct page *page;
1941	unsigned int to_read, page_offset;
1942	int rc;
1943
1944	if (iov_iter_rw(&msg->msg_iter) == WRITE) {
1945		/* It's a bug in upper layer to get there */
1946		cifs_dbg(VFS, "Invalid msg iter dir %u\n",
1947			 iov_iter_rw(&msg->msg_iter));
1948		rc = -EINVAL;
1949		goto out;
1950	}
1951
1952	switch (iov_iter_type(&msg->msg_iter)) {
1953	case ITER_KVEC:
1954		buf = msg->msg_iter.kvec->iov_base;
1955		to_read = msg->msg_iter.kvec->iov_len;
1956		rc = smbd_recv_buf(info, buf, to_read);
1957		break;
1958
1959	case ITER_BVEC:
1960		page = msg->msg_iter.bvec->bv_page;
1961		page_offset = msg->msg_iter.bvec->bv_offset;
1962		to_read = msg->msg_iter.bvec->bv_len;
1963		rc = smbd_recv_page(info, page, page_offset, to_read);
1964		break;
1965
1966	default:
1967		/* It's a bug in upper layer to get there */
1968		cifs_dbg(VFS, "Invalid msg type %d\n",
1969			 iov_iter_type(&msg->msg_iter));
1970		rc = -EINVAL;
1971	}
1972
1973out:
1974	/* SMBDirect will read it all or nothing */
1975	if (rc > 0)
1976		msg->msg_iter.count = 0;
1977	return rc;
1978}
1979
1980/*
1981 * Send data to transport
1982 * Each rqst is transported as a SMBDirect payload
1983 * rqst: the data to write
1984 * return value: 0 if successfully write, otherwise error code
1985 */
1986int smbd_send(struct TCP_Server_Info *server,
1987	int num_rqst, struct smb_rqst *rqst_array)
1988{
1989	struct smbd_connection *info = server->smbd_conn;
1990	struct kvec vec;
1991	int nvecs;
1992	int size;
1993	unsigned int buflen, remaining_data_length;
1994	int start, i, j;
1995	int max_iov_size =
1996		info->max_send_size - sizeof(struct smbd_data_transfer);
1997	struct kvec *iov;
1998	int rc;
1999	struct smb_rqst *rqst;
2000	int rqst_idx;
2001
2002	if (info->transport_status != SMBD_CONNECTED) {
2003		rc = -EAGAIN;
2004		goto done;
2005	}
2006
2007	/*
2008	 * Add in the page array if there is one. The caller needs to set
2009	 * rq_tailsz to PAGE_SIZE when the buffer has multiple pages and
2010	 * ends at page boundary
2011	 */
2012	remaining_data_length = 0;
2013	for (i = 0; i < num_rqst; i++)
2014		remaining_data_length += smb_rqst_len(server, &rqst_array[i]);
2015
2016	if (remaining_data_length > info->max_fragmented_send_size) {
2017		log_write(ERR, "payload size %d > max size %d\n",
2018			remaining_data_length, info->max_fragmented_send_size);
2019		rc = -EINVAL;
2020		goto done;
2021	}
2022
2023	log_write(INFO, "num_rqst=%d total length=%u\n",
2024			num_rqst, remaining_data_length);
2025
2026	rqst_idx = 0;
2027next_rqst:
2028	rqst = &rqst_array[rqst_idx];
2029	iov = rqst->rq_iov;
2030
2031	cifs_dbg(FYI, "Sending smb (RDMA): idx=%d smb_len=%lu\n",
2032		rqst_idx, smb_rqst_len(server, rqst));
2033	for (i = 0; i < rqst->rq_nvec; i++)
2034		dump_smb(iov[i].iov_base, iov[i].iov_len);
2035
2036
2037	log_write(INFO, "rqst_idx=%d nvec=%d rqst->rq_npages=%d rq_pagesz=%d rq_tailsz=%d buflen=%lu\n",
2038		  rqst_idx, rqst->rq_nvec, rqst->rq_npages, rqst->rq_pagesz,
2039		  rqst->rq_tailsz, smb_rqst_len(server, rqst));
2040
2041	start = i = 0;
2042	buflen = 0;
2043	while (true) {
2044		buflen += iov[i].iov_len;
2045		if (buflen > max_iov_size) {
2046			if (i > start) {
2047				remaining_data_length -=
2048					(buflen-iov[i].iov_len);
2049				log_write(INFO, "sending iov[] from start=%d i=%d nvecs=%d remaining_data_length=%d\n",
2050					  start, i, i - start,
2051					  remaining_data_length);
2052				rc = smbd_post_send_data(
2053					info, &iov[start], i-start,
2054					remaining_data_length);
2055				if (rc)
2056					goto done;
2057			} else {
2058				/* iov[start] is too big, break it */
2059				nvecs = (buflen+max_iov_size-1)/max_iov_size;
2060				log_write(INFO, "iov[%d] iov_base=%p buflen=%d break to %d vectors\n",
2061					  start, iov[start].iov_base,
2062					  buflen, nvecs);
2063				for (j = 0; j < nvecs; j++) {
2064					vec.iov_base =
2065						(char *)iov[start].iov_base +
2066						j*max_iov_size;
2067					vec.iov_len = max_iov_size;
2068					if (j == nvecs-1)
2069						vec.iov_len =
2070							buflen -
2071							max_iov_size*(nvecs-1);
2072					remaining_data_length -= vec.iov_len;
2073					log_write(INFO,
2074						"sending vec j=%d iov_base=%p iov_len=%zu remaining_data_length=%d\n",
2075						  j, vec.iov_base, vec.iov_len,
2076						  remaining_data_length);
2077					rc = smbd_post_send_data(
2078						info, &vec, 1,
2079						remaining_data_length);
2080					if (rc)
2081						goto done;
2082				}
2083				i++;
2084				if (i == rqst->rq_nvec)
2085					break;
2086			}
2087			start = i;
2088			buflen = 0;
2089		} else {
2090			i++;
2091			if (i == rqst->rq_nvec) {
2092				/* send out all remaining vecs */
2093				remaining_data_length -= buflen;
2094				log_write(INFO, "sending iov[] from start=%d i=%d nvecs=%d remaining_data_length=%d\n",
2095					  start, i, i - start,
2096					  remaining_data_length);
2097				rc = smbd_post_send_data(info, &iov[start],
2098					i-start, remaining_data_length);
2099				if (rc)
2100					goto done;
2101				break;
2102			}
2103		}
2104		log_write(INFO, "looping i=%d buflen=%d\n", i, buflen);
2105	}
2106
2107	/* now sending pages if there are any */
2108	for (i = 0; i < rqst->rq_npages; i++) {
2109		unsigned int offset;
2110
2111		rqst_page_get_length(rqst, i, &buflen, &offset);
2112		nvecs = (buflen + max_iov_size - 1) / max_iov_size;
2113		log_write(INFO, "sending pages buflen=%d nvecs=%d\n",
2114			buflen, nvecs);
2115		for (j = 0; j < nvecs; j++) {
2116			size = max_iov_size;
2117			if (j == nvecs-1)
2118				size = buflen - j*max_iov_size;
2119			remaining_data_length -= size;
2120			log_write(INFO, "sending pages i=%d offset=%d size=%d remaining_data_length=%d\n",
2121				  i, j * max_iov_size + offset, size,
2122				  remaining_data_length);
2123			rc = smbd_post_send_page(
2124				info, rqst->rq_pages[i],
2125				j*max_iov_size + offset,
2126				size, remaining_data_length);
2127			if (rc)
2128				goto done;
2129		}
2130	}
2131
2132	rqst_idx++;
2133	if (rqst_idx < num_rqst)
2134		goto next_rqst;
2135
2136done:
2137	/*
2138	 * As an optimization, we don't wait for individual I/O to finish
2139	 * before sending the next one.
2140	 * Send them all and wait for pending send count to get to 0
2141	 * that means all the I/Os have been out and we are good to return
2142	 */
2143
2144	wait_event(info->wait_send_pending,
2145		atomic_read(&info->send_pending) == 0);
2146
2147	return rc;
2148}
2149
2150static void register_mr_done(struct ib_cq *cq, struct ib_wc *wc)
2151{
2152	struct smbd_mr *mr;
2153	struct ib_cqe *cqe;
2154
2155	if (wc->status) {
2156		log_rdma_mr(ERR, "status=%d\n", wc->status);
2157		cqe = wc->wr_cqe;
2158		mr = container_of(cqe, struct smbd_mr, cqe);
2159		smbd_disconnect_rdma_connection(mr->conn);
2160	}
2161}
2162
2163/*
2164 * The work queue function that recovers MRs
2165 * We need to call ib_dereg_mr() and ib_alloc_mr() before this MR can be used
2166 * again. Both calls are slow, so finish them in a workqueue. This will not
2167 * block I/O path.
2168 * There is one workqueue that recovers MRs, there is no need to lock as the
2169 * I/O requests calling smbd_register_mr will never update the links in the
2170 * mr_list.
2171 */
2172static void smbd_mr_recovery_work(struct work_struct *work)
2173{
2174	struct smbd_connection *info =
2175		container_of(work, struct smbd_connection, mr_recovery_work);
2176	struct smbd_mr *smbdirect_mr;
2177	int rc;
2178
2179	list_for_each_entry(smbdirect_mr, &info->mr_list, list) {
2180		if (smbdirect_mr->state == MR_ERROR) {
2181
2182			/* recover this MR entry */
2183			rc = ib_dereg_mr(smbdirect_mr->mr);
2184			if (rc) {
2185				log_rdma_mr(ERR,
2186					"ib_dereg_mr failed rc=%x\n",
2187					rc);
2188				smbd_disconnect_rdma_connection(info);
2189				continue;
2190			}
2191
2192			smbdirect_mr->mr = ib_alloc_mr(
2193				info->pd, info->mr_type,
2194				info->max_frmr_depth);
2195			if (IS_ERR(smbdirect_mr->mr)) {
2196				log_rdma_mr(ERR, "ib_alloc_mr failed mr_type=%x max_frmr_depth=%x\n",
2197					    info->mr_type,
2198					    info->max_frmr_depth);
2199				smbd_disconnect_rdma_connection(info);
2200				continue;
2201			}
2202		} else
2203			/* This MR is being used, don't recover it */
2204			continue;
2205
2206		smbdirect_mr->state = MR_READY;
2207
2208		/* smbdirect_mr->state is updated by this function
2209		 * and is read and updated by I/O issuing CPUs trying
2210		 * to get a MR, the call to atomic_inc_return
2211		 * implicates a memory barrier and guarantees this
2212		 * value is updated before waking up any calls to
2213		 * get_mr() from the I/O issuing CPUs
2214		 */
2215		if (atomic_inc_return(&info->mr_ready_count) == 1)
2216			wake_up_interruptible(&info->wait_mr);
2217	}
2218}
2219
2220static void destroy_mr_list(struct smbd_connection *info)
2221{
2222	struct smbd_mr *mr, *tmp;
2223
2224	cancel_work_sync(&info->mr_recovery_work);
2225	list_for_each_entry_safe(mr, tmp, &info->mr_list, list) {
2226		if (mr->state == MR_INVALIDATED)
2227			ib_dma_unmap_sg(info->id->device, mr->sgl,
2228				mr->sgl_count, mr->dir);
2229		ib_dereg_mr(mr->mr);
2230		kfree(mr->sgl);
2231		kfree(mr);
2232	}
2233}
2234
2235/*
2236 * Allocate MRs used for RDMA read/write
2237 * The number of MRs will not exceed hardware capability in responder_resources
2238 * All MRs are kept in mr_list. The MR can be recovered after it's used
2239 * Recovery is done in smbd_mr_recovery_work. The content of list entry changes
2240 * as MRs are used and recovered for I/O, but the list links will not change
2241 */
2242static int allocate_mr_list(struct smbd_connection *info)
2243{
2244	int i;
2245	struct smbd_mr *smbdirect_mr, *tmp;
2246
2247	INIT_LIST_HEAD(&info->mr_list);
2248	init_waitqueue_head(&info->wait_mr);
2249	spin_lock_init(&info->mr_list_lock);
2250	atomic_set(&info->mr_ready_count, 0);
2251	atomic_set(&info->mr_used_count, 0);
2252	init_waitqueue_head(&info->wait_for_mr_cleanup);
2253	INIT_WORK(&info->mr_recovery_work, smbd_mr_recovery_work);
2254	/* Allocate more MRs (2x) than hardware responder_resources */
2255	for (i = 0; i < info->responder_resources * 2; i++) {
2256		smbdirect_mr = kzalloc(sizeof(*smbdirect_mr), GFP_KERNEL);
2257		if (!smbdirect_mr)
2258			goto out;
2259		smbdirect_mr->mr = ib_alloc_mr(info->pd, info->mr_type,
2260					info->max_frmr_depth);
2261		if (IS_ERR(smbdirect_mr->mr)) {
2262			log_rdma_mr(ERR, "ib_alloc_mr failed mr_type=%x max_frmr_depth=%x\n",
2263				    info->mr_type, info->max_frmr_depth);
2264			goto out;
2265		}
2266		smbdirect_mr->sgl = kcalloc(
2267					info->max_frmr_depth,
2268					sizeof(struct scatterlist),
2269					GFP_KERNEL);
2270		if (!smbdirect_mr->sgl) {
2271			log_rdma_mr(ERR, "failed to allocate sgl\n");
2272			ib_dereg_mr(smbdirect_mr->mr);
2273			goto out;
2274		}
2275		smbdirect_mr->state = MR_READY;
2276		smbdirect_mr->conn = info;
2277
2278		list_add_tail(&smbdirect_mr->list, &info->mr_list);
2279		atomic_inc(&info->mr_ready_count);
2280	}
2281	return 0;
2282
2283out:
2284	kfree(smbdirect_mr);
2285
2286	list_for_each_entry_safe(smbdirect_mr, tmp, &info->mr_list, list) {
2287		list_del(&smbdirect_mr->list);
2288		ib_dereg_mr(smbdirect_mr->mr);
2289		kfree(smbdirect_mr->sgl);
2290		kfree(smbdirect_mr);
2291	}
2292	return -ENOMEM;
2293}
2294
2295/*
2296 * Get a MR from mr_list. This function waits until there is at least one
2297 * MR available in the list. It may access the list while the
2298 * smbd_mr_recovery_work is recovering the MR list. This doesn't need a lock
2299 * as they never modify the same places. However, there may be several CPUs
2300 * issueing I/O trying to get MR at the same time, mr_list_lock is used to
2301 * protect this situation.
2302 */
2303static struct smbd_mr *get_mr(struct smbd_connection *info)
2304{
2305	struct smbd_mr *ret;
2306	int rc;
2307again:
2308	rc = wait_event_interruptible(info->wait_mr,
2309		atomic_read(&info->mr_ready_count) ||
2310		info->transport_status != SMBD_CONNECTED);
2311	if (rc) {
2312		log_rdma_mr(ERR, "wait_event_interruptible rc=%x\n", rc);
2313		return NULL;
2314	}
2315
2316	if (info->transport_status != SMBD_CONNECTED) {
2317		log_rdma_mr(ERR, "info->transport_status=%x\n",
2318			info->transport_status);
2319		return NULL;
2320	}
2321
2322	spin_lock(&info->mr_list_lock);
2323	list_for_each_entry(ret, &info->mr_list, list) {
2324		if (ret->state == MR_READY) {
2325			ret->state = MR_REGISTERED;
2326			spin_unlock(&info->mr_list_lock);
2327			atomic_dec(&info->mr_ready_count);
2328			atomic_inc(&info->mr_used_count);
2329			return ret;
2330		}
2331	}
2332
2333	spin_unlock(&info->mr_list_lock);
2334	/*
2335	 * It is possible that we could fail to get MR because other processes may
2336	 * try to acquire a MR at the same time. If this is the case, retry it.
2337	 */
2338	goto again;
2339}
2340
2341/*
2342 * Register memory for RDMA read/write
2343 * pages[]: the list of pages to register memory with
2344 * num_pages: the number of pages to register
2345 * tailsz: if non-zero, the bytes to register in the last page
2346 * writing: true if this is a RDMA write (SMB read), false for RDMA read
2347 * need_invalidate: true if this MR needs to be locally invalidated after I/O
2348 * return value: the MR registered, NULL if failed.
2349 */
2350struct smbd_mr *smbd_register_mr(
2351	struct smbd_connection *info, struct page *pages[], int num_pages,
2352	int offset, int tailsz, bool writing, bool need_invalidate)
2353{
2354	struct smbd_mr *smbdirect_mr;
2355	int rc, i;
2356	enum dma_data_direction dir;
2357	struct ib_reg_wr *reg_wr;
2358
2359	if (num_pages > info->max_frmr_depth) {
2360		log_rdma_mr(ERR, "num_pages=%d max_frmr_depth=%d\n",
2361			num_pages, info->max_frmr_depth);
2362		return NULL;
2363	}
2364
2365	smbdirect_mr = get_mr(info);
2366	if (!smbdirect_mr) {
2367		log_rdma_mr(ERR, "get_mr returning NULL\n");
2368		return NULL;
2369	}
2370	smbdirect_mr->need_invalidate = need_invalidate;
2371	smbdirect_mr->sgl_count = num_pages;
2372	sg_init_table(smbdirect_mr->sgl, num_pages);
2373
2374	log_rdma_mr(INFO, "num_pages=0x%x offset=0x%x tailsz=0x%x\n",
2375			num_pages, offset, tailsz);
2376
2377	if (num_pages == 1) {
2378		sg_set_page(&smbdirect_mr->sgl[0], pages[0], tailsz, offset);
2379		goto skip_multiple_pages;
2380	}
2381
2382	/* We have at least two pages to register */
2383	sg_set_page(
2384		&smbdirect_mr->sgl[0], pages[0], PAGE_SIZE - offset, offset);
2385	i = 1;
2386	while (i < num_pages - 1) {
2387		sg_set_page(&smbdirect_mr->sgl[i], pages[i], PAGE_SIZE, 0);
2388		i++;
2389	}
2390	sg_set_page(&smbdirect_mr->sgl[i], pages[i],
2391		tailsz ? tailsz : PAGE_SIZE, 0);
2392
2393skip_multiple_pages:
2394	dir = writing ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
2395	smbdirect_mr->dir = dir;
2396	rc = ib_dma_map_sg(info->id->device, smbdirect_mr->sgl, num_pages, dir);
2397	if (!rc) {
2398		log_rdma_mr(ERR, "ib_dma_map_sg num_pages=%x dir=%x rc=%x\n",
2399			num_pages, dir, rc);
2400		goto dma_map_error;
2401	}
2402
2403	rc = ib_map_mr_sg(smbdirect_mr->mr, smbdirect_mr->sgl, num_pages,
2404		NULL, PAGE_SIZE);
2405	if (rc != num_pages) {
2406		log_rdma_mr(ERR,
2407			"ib_map_mr_sg failed rc = %d num_pages = %x\n",
2408			rc, num_pages);
2409		goto map_mr_error;
2410	}
2411
2412	ib_update_fast_reg_key(smbdirect_mr->mr,
2413		ib_inc_rkey(smbdirect_mr->mr->rkey));
2414	reg_wr = &smbdirect_mr->wr;
2415	reg_wr->wr.opcode = IB_WR_REG_MR;
2416	smbdirect_mr->cqe.done = register_mr_done;
2417	reg_wr->wr.wr_cqe = &smbdirect_mr->cqe;
2418	reg_wr->wr.num_sge = 0;
2419	reg_wr->wr.send_flags = IB_SEND_SIGNALED;
2420	reg_wr->mr = smbdirect_mr->mr;
2421	reg_wr->key = smbdirect_mr->mr->rkey;
2422	reg_wr->access = writing ?
2423			IB_ACCESS_REMOTE_WRITE | IB_ACCESS_LOCAL_WRITE :
2424			IB_ACCESS_REMOTE_READ;
2425
2426	/*
2427	 * There is no need for waiting for complemtion on ib_post_send
2428	 * on IB_WR_REG_MR. Hardware enforces a barrier and order of execution
2429	 * on the next ib_post_send when we actaully send I/O to remote peer
2430	 */
2431	rc = ib_post_send(info->id->qp, &reg_wr->wr, NULL);
2432	if (!rc)
2433		return smbdirect_mr;
2434
2435	log_rdma_mr(ERR, "ib_post_send failed rc=%x reg_wr->key=%x\n",
2436		rc, reg_wr->key);
2437
2438	/* If all failed, attempt to recover this MR by setting it MR_ERROR*/
2439map_mr_error:
2440	ib_dma_unmap_sg(info->id->device, smbdirect_mr->sgl,
2441		smbdirect_mr->sgl_count, smbdirect_mr->dir);
2442
2443dma_map_error:
2444	smbdirect_mr->state = MR_ERROR;
2445	if (atomic_dec_and_test(&info->mr_used_count))
2446		wake_up(&info->wait_for_mr_cleanup);
2447
2448	smbd_disconnect_rdma_connection(info);
2449
2450	return NULL;
2451}
2452
2453static void local_inv_done(struct ib_cq *cq, struct ib_wc *wc)
2454{
2455	struct smbd_mr *smbdirect_mr;
2456	struct ib_cqe *cqe;
2457
2458	cqe = wc->wr_cqe;
2459	smbdirect_mr = container_of(cqe, struct smbd_mr, cqe);
2460	smbdirect_mr->state = MR_INVALIDATED;
2461	if (wc->status != IB_WC_SUCCESS) {
2462		log_rdma_mr(ERR, "invalidate failed status=%x\n", wc->status);
2463		smbdirect_mr->state = MR_ERROR;
2464	}
2465	complete(&smbdirect_mr->invalidate_done);
2466}
2467
2468/*
2469 * Deregister a MR after I/O is done
2470 * This function may wait if remote invalidation is not used
2471 * and we have to locally invalidate the buffer to prevent data is being
2472 * modified by remote peer after upper layer consumes it
2473 */
2474int smbd_deregister_mr(struct smbd_mr *smbdirect_mr)
2475{
2476	struct ib_send_wr *wr;
2477	struct smbd_connection *info = smbdirect_mr->conn;
2478	int rc = 0;
2479
2480	if (smbdirect_mr->need_invalidate) {
2481		/* Need to finish local invalidation before returning */
2482		wr = &smbdirect_mr->inv_wr;
2483		wr->opcode = IB_WR_LOCAL_INV;
2484		smbdirect_mr->cqe.done = local_inv_done;
2485		wr->wr_cqe = &smbdirect_mr->cqe;
2486		wr->num_sge = 0;
2487		wr->ex.invalidate_rkey = smbdirect_mr->mr->rkey;
2488		wr->send_flags = IB_SEND_SIGNALED;
2489
2490		init_completion(&smbdirect_mr->invalidate_done);
2491		rc = ib_post_send(info->id->qp, wr, NULL);
2492		if (rc) {
2493			log_rdma_mr(ERR, "ib_post_send failed rc=%x\n", rc);
2494			smbd_disconnect_rdma_connection(info);
2495			goto done;
2496		}
2497		wait_for_completion(&smbdirect_mr->invalidate_done);
2498		smbdirect_mr->need_invalidate = false;
2499	} else
2500		/*
2501		 * For remote invalidation, just set it to MR_INVALIDATED
2502		 * and defer to mr_recovery_work to recover the MR for next use
2503		 */
2504		smbdirect_mr->state = MR_INVALIDATED;
2505
2506	if (smbdirect_mr->state == MR_INVALIDATED) {
2507		ib_dma_unmap_sg(
2508			info->id->device, smbdirect_mr->sgl,
2509			smbdirect_mr->sgl_count,
2510			smbdirect_mr->dir);
2511		smbdirect_mr->state = MR_READY;
2512		if (atomic_inc_return(&info->mr_ready_count) == 1)
2513			wake_up_interruptible(&info->wait_mr);
2514	} else
2515		/*
2516		 * Schedule the work to do MR recovery for future I/Os MR
2517		 * recovery is slow and don't want it to block current I/O
2518		 */
2519		queue_work(info->workqueue, &info->mr_recovery_work);
2520
2521done:
2522	if (atomic_dec_and_test(&info->mr_used_count))
2523		wake_up(&info->wait_for_mr_cleanup);
2524
2525	return rc;
2526}
2527