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