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