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