OSDN Git Service

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