Whamcloud - gitweb
LU-14733 o2iblnd: Avoid double posting invalidate
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/klnds/o2iblnd/o2iblnd.c
33  *
34  * Author: Eric Barton <eric@bartonsoftware.com>
35  */
36
37 #include <asm/page.h>
38 #include <linux/inetdevice.h>
39
40 #include "o2iblnd.h"
41
42 static const struct lnet_lnd the_o2iblnd;
43
44 struct kib_data kiblnd_data;
45
46 static __u32
47 kiblnd_cksum (void *ptr, int nob)
48 {
49         char  *c  = ptr;
50         __u32  sum = 0;
51
52         while (nob-- > 0)
53                 sum = ((sum << 1) | (sum >> 31)) + *c++;
54
55         /* ensure I don't return 0 (== no checksum) */
56         return (sum == 0) ? 1 : sum;
57 }
58
59 static char *
60 kiblnd_msgtype2str(int type)
61 {
62         switch (type) {
63         case IBLND_MSG_CONNREQ:
64                 return "CONNREQ";
65
66         case IBLND_MSG_CONNACK:
67                 return "CONNACK";
68
69         case IBLND_MSG_NOOP:
70                 return "NOOP";
71
72         case IBLND_MSG_IMMEDIATE:
73                 return "IMMEDIATE";
74
75         case IBLND_MSG_PUT_REQ:
76                 return "PUT_REQ";
77
78         case IBLND_MSG_PUT_NAK:
79                 return "PUT_NAK";
80
81         case IBLND_MSG_PUT_ACK:
82                 return "PUT_ACK";
83
84         case IBLND_MSG_PUT_DONE:
85                 return "PUT_DONE";
86
87         case IBLND_MSG_GET_REQ:
88                 return "GET_REQ";
89
90         case IBLND_MSG_GET_DONE:
91                 return "GET_DONE";
92
93         default:
94                 return "???";
95         }
96 }
97
98 static int
99 kiblnd_msgtype2size(int type)
100 {
101         const int hdr_size = offsetof(struct kib_msg, ibm_u);
102
103         switch (type) {
104         case IBLND_MSG_CONNREQ:
105         case IBLND_MSG_CONNACK:
106                 return hdr_size + sizeof(struct kib_connparams);
107
108         case IBLND_MSG_NOOP:
109                 return hdr_size;
110
111         case IBLND_MSG_IMMEDIATE:
112                 return offsetof(struct kib_msg, ibm_u.immediate.ibim_payload[0]);
113
114         case IBLND_MSG_PUT_REQ:
115                 return hdr_size + sizeof(struct kib_putreq_msg);
116
117         case IBLND_MSG_PUT_ACK:
118                 return hdr_size + sizeof(struct kib_putack_msg);
119
120         case IBLND_MSG_GET_REQ:
121                 return hdr_size + sizeof(struct kib_get_msg);
122
123         case IBLND_MSG_PUT_NAK:
124         case IBLND_MSG_PUT_DONE:
125         case IBLND_MSG_GET_DONE:
126                 return hdr_size + sizeof(struct kib_completion_msg);
127         default:
128                 return -1;
129         }
130 }
131
132 static int kiblnd_unpack_rd(struct kib_msg *msg, int flip)
133 {
134         struct kib_rdma_desc *rd;
135         int                nob;
136         int                n;
137         int                i;
138
139         LASSERT (msg->ibm_type == IBLND_MSG_GET_REQ ||
140                  msg->ibm_type == IBLND_MSG_PUT_ACK);
141
142         rd = msg->ibm_type == IBLND_MSG_GET_REQ ?
143                               &msg->ibm_u.get.ibgm_rd :
144                               &msg->ibm_u.putack.ibpam_rd;
145
146         if (flip) {
147                 __swab32s(&rd->rd_key);
148                 __swab32s(&rd->rd_nfrags);
149         }
150
151         n = rd->rd_nfrags;
152
153         if (n <= 0 || n > IBLND_MAX_RDMA_FRAGS) {
154                 CERROR("Bad nfrags: %d, should be 0 < n <= %d\n",
155                        n, IBLND_MAX_RDMA_FRAGS);
156                 return 1;
157         }
158
159         nob = offsetof(struct kib_msg, ibm_u) +
160               kiblnd_rd_msg_size(rd, msg->ibm_type, n);
161
162         if (msg->ibm_nob < nob) {
163                 CERROR("Short %s: %d(%d)\n",
164                        kiblnd_msgtype2str(msg->ibm_type), msg->ibm_nob, nob);
165                 return 1;
166         }
167
168         if (!flip)
169                 return 0;
170
171         for (i = 0; i < n; i++) {
172                 __swab32s(&rd->rd_frags[i].rf_nob);
173                 __swab64s(&rd->rd_frags[i].rf_addr);
174         }
175
176         return 0;
177 }
178
179 void kiblnd_pack_msg(struct lnet_ni *ni, struct kib_msg *msg, int version,
180                      int credits, lnet_nid_t dstnid, __u64 dststamp)
181 {
182         struct kib_net *net = ni->ni_data;
183
184         /* CAVEAT EMPTOR! all message fields not set here should have been
185          * initialised previously. */
186         msg->ibm_magic    = IBLND_MSG_MAGIC;
187         msg->ibm_version  = version;
188         /*   ibm_type */
189         msg->ibm_credits  = credits;
190         /*   ibm_nob */
191         msg->ibm_cksum    = 0;
192         msg->ibm_srcnid   = ni->ni_nid;
193         msg->ibm_srcstamp = net->ibn_incarnation;
194         msg->ibm_dstnid   = dstnid;
195         msg->ibm_dststamp = dststamp;
196
197         if (*kiblnd_tunables.kib_cksum) {
198                 /* NB ibm_cksum zero while computing cksum */
199                 msg->ibm_cksum = kiblnd_cksum(msg, msg->ibm_nob);
200         }
201 }
202
203 int kiblnd_unpack_msg(struct kib_msg *msg, int nob)
204 {
205         const int hdr_size = offsetof(struct kib_msg, ibm_u);
206         __u32     msg_cksum;
207         __u16     version;
208         int       msg_nob;
209         int       flip;
210
211         /* 6 bytes are enough to have received magic + version */
212         if (nob < 6) {
213                 CERROR("Short message: %d\n", nob);
214                 return -EPROTO;
215         }
216
217         if (msg->ibm_magic == IBLND_MSG_MAGIC) {
218                 flip = 0;
219         } else if (msg->ibm_magic == __swab32(IBLND_MSG_MAGIC)) {
220                 flip = 1;
221         } else {
222                 CERROR("Bad magic: %08x\n", msg->ibm_magic);
223                 return -EPROTO;
224         }
225
226         version = flip ? __swab16(msg->ibm_version) : msg->ibm_version;
227         if (version != IBLND_MSG_VERSION &&
228             version != IBLND_MSG_VERSION_1) {
229                 CERROR("Bad version: %x\n", version);
230                 return -EPROTO;
231         }
232
233         if (nob < hdr_size) {
234                 CERROR("Short message: %d\n", nob);
235                 return -EPROTO;
236         }
237
238         msg_nob = flip ? __swab32(msg->ibm_nob) : msg->ibm_nob;
239         if (msg_nob > nob) {
240                 CERROR("Short message: got %d, wanted %d\n", nob, msg_nob);
241                 return -EPROTO;
242         }
243
244         /* checksum must be computed with ibm_cksum zero and BEFORE anything
245          * gets flipped */
246         msg_cksum = flip ? __swab32(msg->ibm_cksum) : msg->ibm_cksum;
247         msg->ibm_cksum = 0;
248         if (msg_cksum != 0 &&
249             msg_cksum != kiblnd_cksum(msg, msg_nob)) {
250                 CERROR("Bad checksum\n");
251                 return -EPROTO;
252         }
253
254         msg->ibm_cksum = msg_cksum;
255
256         if (flip) {
257                 /* leave magic unflipped as a clue to peer_ni endianness */
258                 msg->ibm_version = version;
259                 BUILD_BUG_ON(sizeof(msg->ibm_type) != 1);
260                 BUILD_BUG_ON(sizeof(msg->ibm_credits) != 1);
261                 msg->ibm_nob     = msg_nob;
262                 __swab64s(&msg->ibm_srcnid);
263                 __swab64s(&msg->ibm_srcstamp);
264                 __swab64s(&msg->ibm_dstnid);
265                 __swab64s(&msg->ibm_dststamp);
266         }
267
268         if (msg->ibm_srcnid == LNET_NID_ANY) {
269                 CERROR("Bad src nid: %s\n", libcfs_nid2str(msg->ibm_srcnid));
270                 return -EPROTO;
271         }
272
273         if (msg_nob < kiblnd_msgtype2size(msg->ibm_type)) {
274                 CERROR("Short %s: %d(%d)\n", kiblnd_msgtype2str(msg->ibm_type),
275                        msg_nob, kiblnd_msgtype2size(msg->ibm_type));
276                 return -EPROTO;
277         }
278
279         switch (msg->ibm_type) {
280         default:
281                 CERROR("Unknown message type %x\n", msg->ibm_type);
282                 return -EPROTO;
283
284         case IBLND_MSG_NOOP:
285         case IBLND_MSG_IMMEDIATE:
286         case IBLND_MSG_PUT_REQ:
287                 break;
288
289         case IBLND_MSG_PUT_ACK:
290         case IBLND_MSG_GET_REQ:
291                 if (kiblnd_unpack_rd(msg, flip))
292                         return -EPROTO;
293                 break;
294
295         case IBLND_MSG_PUT_NAK:
296         case IBLND_MSG_PUT_DONE:
297         case IBLND_MSG_GET_DONE:
298                 if (flip)
299                         __swab32s(&msg->ibm_u.completion.ibcm_status);
300                 break;
301
302         case IBLND_MSG_CONNREQ:
303         case IBLND_MSG_CONNACK:
304                 if (flip) {
305                         __swab16s(&msg->ibm_u.connparams.ibcp_queue_depth);
306                         __swab16s(&msg->ibm_u.connparams.ibcp_max_frags);
307                         __swab32s(&msg->ibm_u.connparams.ibcp_max_msg_size);
308                 }
309                 break;
310         }
311         return 0;
312 }
313
314 int
315 kiblnd_create_peer(struct lnet_ni *ni, struct kib_peer_ni **peerp,
316                    lnet_nid_t nid)
317 {
318         struct kib_peer_ni *peer_ni;
319         struct kib_net *net = ni->ni_data;
320         int cpt = lnet_cpt_of_nid(nid, ni);
321         unsigned long flags;
322
323         LASSERT(net != NULL);
324         LASSERT(nid != LNET_NID_ANY);
325
326         LIBCFS_CPT_ALLOC(peer_ni, lnet_cpt_table(), cpt, sizeof(*peer_ni));
327         if (peer_ni == NULL) {
328                 CERROR("Cannot allocate peer_ni\n");
329                 return -ENOMEM;
330         }
331
332         peer_ni->ibp_ni = ni;
333         peer_ni->ibp_nid = nid;
334         peer_ni->ibp_error = 0;
335         peer_ni->ibp_last_alive = 0;
336         peer_ni->ibp_max_frags = IBLND_MAX_RDMA_FRAGS;
337         peer_ni->ibp_queue_depth = ni->ni_net->net_tunables.lct_peer_tx_credits;
338         peer_ni->ibp_queue_depth_mod = 0;       /* try to use the default */
339         atomic_set(&peer_ni->ibp_refcount, 1);  /* 1 ref for caller */
340
341         INIT_LIST_HEAD(&peer_ni->ibp_list);     /* not in the peer_ni table yet */
342         INIT_LIST_HEAD(&peer_ni->ibp_conns);
343         INIT_LIST_HEAD(&peer_ni->ibp_tx_queue);
344
345         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
346
347         /* always called with a ref on ni, which prevents ni being shutdown */
348         LASSERT(net->ibn_shutdown == 0);
349
350         /* npeers only grows with the global lock held */
351         atomic_inc(&net->ibn_npeers);
352
353         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
354
355         *peerp = peer_ni;
356         return 0;
357 }
358
359 void
360 kiblnd_destroy_peer(struct kib_peer_ni *peer_ni)
361 {
362         struct kib_net *net = peer_ni->ibp_ni->ni_data;
363
364         LASSERT(net != NULL);
365         LASSERT (atomic_read(&peer_ni->ibp_refcount) == 0);
366         LASSERT(!kiblnd_peer_active(peer_ni));
367         LASSERT(kiblnd_peer_idle(peer_ni));
368         LASSERT(list_empty(&peer_ni->ibp_tx_queue));
369
370         LIBCFS_FREE(peer_ni, sizeof(*peer_ni));
371
372         /* NB a peer_ni's connections keep a reference on their peer_ni until
373          * they are destroyed, so we can be assured that _all_ state to do
374          * with this peer_ni has been cleaned up when its refcount drops to
375          * zero. */
376         if (atomic_dec_and_test(&net->ibn_npeers))
377                 wake_up_var(&net->ibn_npeers);
378 }
379
380 struct kib_peer_ni *
381 kiblnd_find_peer_locked(struct lnet_ni *ni, lnet_nid_t nid)
382 {
383         /* the caller is responsible for accounting the additional reference
384          * that this creates */
385         struct list_head        *peer_list = kiblnd_nid2peerlist(nid);
386         struct list_head        *tmp;
387         struct kib_peer_ni              *peer_ni;
388
389         list_for_each(tmp, peer_list) {
390
391                 peer_ni = list_entry(tmp, struct kib_peer_ni, ibp_list);
392                 LASSERT(!kiblnd_peer_idle(peer_ni));
393
394                 /*
395                  * Match a peer if its NID and the NID of the local NI it
396                  * communicates over are the same. Otherwise don't match
397                  * the peer, which will result in a new lnd peer being
398                  * created.
399                  */
400                 if (peer_ni->ibp_nid != nid ||
401                     peer_ni->ibp_ni->ni_nid != ni->ni_nid)
402                         continue;
403
404                 CDEBUG(D_NET, "got peer_ni [%p] -> %s (%d) version: %x\n",
405                        peer_ni, libcfs_nid2str(nid),
406                        atomic_read(&peer_ni->ibp_refcount),
407                        peer_ni->ibp_version);
408                 return peer_ni;
409         }
410         return NULL;
411 }
412
413 void
414 kiblnd_unlink_peer_locked(struct kib_peer_ni *peer_ni)
415 {
416         LASSERT(list_empty(&peer_ni->ibp_conns));
417
418         LASSERT (kiblnd_peer_active(peer_ni));
419         list_del_init(&peer_ni->ibp_list);
420         /* lose peerlist's ref */
421         kiblnd_peer_decref(peer_ni);
422 }
423
424 static int
425 kiblnd_get_peer_info(struct lnet_ni *ni, int index,
426                      lnet_nid_t *nidp, int *count)
427 {
428         struct kib_peer_ni              *peer_ni;
429         struct list_head        *ptmp;
430         int                      i;
431         unsigned long            flags;
432
433         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
434
435         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
436
437                 list_for_each(ptmp, &kiblnd_data.kib_peers[i]) {
438
439                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
440                         LASSERT(!kiblnd_peer_idle(peer_ni));
441
442                         if (peer_ni->ibp_ni != ni)
443                                 continue;
444
445                         if (index-- > 0)
446                                 continue;
447
448                         *nidp = peer_ni->ibp_nid;
449                         *count = atomic_read(&peer_ni->ibp_refcount);
450
451                         read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
452                                                flags);
453                         return 0;
454                 }
455         }
456
457         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
458         return -ENOENT;
459 }
460
461 static void
462 kiblnd_del_peer_locked(struct kib_peer_ni *peer_ni)
463 {
464         struct kib_conn *cnxt;
465         struct kib_conn *conn;
466
467         if (list_empty(&peer_ni->ibp_conns)) {
468                 kiblnd_unlink_peer_locked(peer_ni);
469         } else {
470                 list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
471                                          ibc_list)
472                         kiblnd_close_conn_locked(conn, 0);
473                 /* NB closing peer_ni's last conn unlinked it. */
474         }
475         /* NB peer_ni now unlinked; might even be freed if the peer_ni table had the
476          * last ref on it. */
477 }
478
479 static int
480 kiblnd_del_peer(struct lnet_ni *ni, lnet_nid_t nid)
481 {
482         LIST_HEAD(zombies);
483         struct list_head        *ptmp;
484         struct list_head        *pnxt;
485         struct kib_peer_ni              *peer_ni;
486         int                     lo;
487         int                     hi;
488         int                     i;
489         unsigned long           flags;
490         int                     rc = -ENOENT;
491
492         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
493
494         if (nid != LNET_NID_ANY) {
495                 lo = hi = kiblnd_nid2peerlist(nid) - kiblnd_data.kib_peers;
496         } else {
497                 lo = 0;
498                 hi = kiblnd_data.kib_peer_hash_size - 1;
499         }
500
501         for (i = lo; i <= hi; i++) {
502                 list_for_each_safe(ptmp, pnxt, &kiblnd_data.kib_peers[i]) {
503                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
504                         LASSERT(!kiblnd_peer_idle(peer_ni));
505
506                         if (peer_ni->ibp_ni != ni)
507                                 continue;
508
509                         if (!(nid == LNET_NID_ANY || peer_ni->ibp_nid == nid))
510                                 continue;
511
512                         if (!list_empty(&peer_ni->ibp_tx_queue)) {
513                                 LASSERT(list_empty(&peer_ni->ibp_conns));
514
515                                 list_splice_init(&peer_ni->ibp_tx_queue,
516                                                  &zombies);
517                         }
518
519                         kiblnd_del_peer_locked(peer_ni);
520                         rc = 0;         /* matched something */
521                 }
522         }
523
524         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
525
526         kiblnd_txlist_done(&zombies, -EIO, LNET_MSG_STATUS_LOCAL_ERROR);
527
528         return rc;
529 }
530
531 static struct kib_conn *
532 kiblnd_get_conn_by_idx(struct lnet_ni *ni, int index)
533 {
534         struct kib_peer_ni              *peer_ni;
535         struct list_head        *ptmp;
536         struct kib_conn *conn;
537         struct list_head        *ctmp;
538         int                     i;
539         unsigned long           flags;
540
541         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
542
543         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
544                 list_for_each(ptmp, &kiblnd_data.kib_peers[i]) {
545
546                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
547                         LASSERT(!kiblnd_peer_idle(peer_ni));
548
549                         if (peer_ni->ibp_ni != ni)
550                                 continue;
551
552                         list_for_each(ctmp, &peer_ni->ibp_conns) {
553                                 if (index-- > 0)
554                                         continue;
555
556                                 conn = list_entry(ctmp, struct kib_conn, ibc_list);
557                                 kiblnd_conn_addref(conn);
558                                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
559                                                        flags);
560                                 return conn;
561                         }
562                 }
563         }
564
565         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
566         return NULL;
567 }
568
569 static void
570 kiblnd_debug_rx(struct kib_rx *rx)
571 {
572         CDEBUG(D_CONSOLE, "      %p msg_type %x cred %d\n",
573                rx, rx->rx_msg->ibm_type,
574                rx->rx_msg->ibm_credits);
575 }
576
577 static void
578 kiblnd_debug_tx(struct kib_tx *tx)
579 {
580         CDEBUG(D_CONSOLE, "      %p snd %d q %d w %d rc %d dl %lld "
581                "cookie %#llx msg %s%s type %x cred %d\n",
582                tx, tx->tx_sending, tx->tx_queued, tx->tx_waiting,
583                tx->tx_status, ktime_to_ns(tx->tx_deadline), tx->tx_cookie,
584                tx->tx_lntmsg[0] == NULL ? "-" : "!",
585                tx->tx_lntmsg[1] == NULL ? "-" : "!",
586                tx->tx_msg->ibm_type, tx->tx_msg->ibm_credits);
587 }
588
589 void
590 kiblnd_debug_conn(struct kib_conn *conn)
591 {
592         struct list_head        *tmp;
593         int                     i;
594
595         spin_lock(&conn->ibc_lock);
596
597         CDEBUG(D_CONSOLE, "conn[%d] %p [version %x] -> %s:\n",
598                atomic_read(&conn->ibc_refcount), conn,
599                conn->ibc_version, libcfs_nid2str(conn->ibc_peer->ibp_nid));
600         CDEBUG(D_CONSOLE, "   state %d nposted %d/%d cred %d o_cred %d "
601                " r_cred %d\n", conn->ibc_state, conn->ibc_noops_posted,
602                conn->ibc_nsends_posted, conn->ibc_credits,
603                conn->ibc_outstanding_credits, conn->ibc_reserved_credits);
604         CDEBUG(D_CONSOLE, "   comms_err %d\n", conn->ibc_comms_error);
605
606         CDEBUG(D_CONSOLE, "   early_rxs:\n");
607         list_for_each(tmp, &conn->ibc_early_rxs)
608                 kiblnd_debug_rx(list_entry(tmp, struct kib_rx, rx_list));
609
610         CDEBUG(D_CONSOLE, "   tx_noops:\n");
611         list_for_each(tmp, &conn->ibc_tx_noops)
612                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
613
614         CDEBUG(D_CONSOLE, "   tx_queue_nocred:\n");
615         list_for_each(tmp, &conn->ibc_tx_queue_nocred)
616                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
617
618         CDEBUG(D_CONSOLE, "   tx_queue_rsrvd:\n");
619         list_for_each(tmp, &conn->ibc_tx_queue_rsrvd)
620                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
621
622         CDEBUG(D_CONSOLE, "   tx_queue:\n");
623         list_for_each(tmp, &conn->ibc_tx_queue)
624                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
625
626         CDEBUG(D_CONSOLE, "   active_txs:\n");
627         list_for_each(tmp, &conn->ibc_active_txs)
628                 kiblnd_debug_tx(list_entry(tmp, struct kib_tx, tx_list));
629
630         CDEBUG(D_CONSOLE, "   rxs:\n");
631         for (i = 0; i < IBLND_RX_MSGS(conn); i++)
632                 kiblnd_debug_rx(&conn->ibc_rxs[i]);
633
634         spin_unlock(&conn->ibc_lock);
635 }
636
637 static void
638 kiblnd_setup_mtu_locked(struct rdma_cm_id *cmid)
639 {
640         /* XXX There is no path record for iWARP, set by netdev->change_mtu? */
641         if (cmid->route.path_rec == NULL)
642                 return;
643
644         if (*kiblnd_tunables.kib_ib_mtu)
645                 cmid->route.path_rec->mtu =
646                         ib_mtu_int_to_enum(*kiblnd_tunables.kib_ib_mtu);
647 }
648
649 static int
650 kiblnd_get_completion_vector(struct kib_conn *conn, int cpt)
651 {
652         cpumask_var_t   *mask;
653         int             vectors;
654         int             off;
655         int             i;
656         lnet_nid_t      ibp_nid;
657
658         vectors = conn->ibc_cmid->device->num_comp_vectors;
659         if (vectors <= 1)
660                 return 0;
661
662         mask = cfs_cpt_cpumask(lnet_cpt_table(), cpt);
663
664         /* hash NID to CPU id in this partition... */
665         ibp_nid = conn->ibc_peer->ibp_nid;
666         off = do_div(ibp_nid, cpumask_weight(*mask));
667         for_each_cpu(i, *mask) {
668                 if (off-- == 0)
669                         return i % vectors;
670         }
671
672         LBUG();
673         return 1;
674 }
675
676 /*
677  * Get the scheduler bound to this CPT. If the scheduler has no
678  * threads, which means that the CPT has no CPUs, then grab the
679  * next scheduler that we can use.
680  *
681  * This case would be triggered if a NUMA node is configured with
682  * no associated CPUs.
683  */
684 static struct kib_sched_info *
685 kiblnd_get_scheduler(int cpt)
686 {
687         struct kib_sched_info *sched;
688         int i;
689
690         sched = kiblnd_data.kib_scheds[cpt];
691
692         if (sched->ibs_nthreads > 0)
693                 return sched;
694
695         cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds) {
696                 if (sched->ibs_nthreads > 0) {
697                         CDEBUG(D_NET, "scheduler[%d] has no threads. selected scheduler[%d]\n",
698                                         cpt, sched->ibs_cpt);
699                         return sched;
700                 }
701         }
702
703         return NULL;
704 }
705
706 static unsigned int kiblnd_send_wrs(struct kib_conn *conn)
707 {
708         /*
709          * One WR for the LNet message
710          * And ibc_max_frags for the transfer WRs
711          */
712         int ret;
713         int multiplier = 1 + conn->ibc_max_frags;
714         enum kib_dev_caps dev_caps = conn->ibc_hdev->ibh_dev->ibd_dev_caps;
715
716         /* FastReg needs two extra WRs for map and invalidate */
717         if (dev_caps & IBLND_DEV_CAPS_FASTREG_ENABLED)
718                 multiplier += 2;
719
720         /* account for a maximum of ibc_queue_depth in-flight transfers */
721         ret = multiplier * conn->ibc_queue_depth;
722
723         if (ret > conn->ibc_hdev->ibh_max_qp_wr) {
724                 CDEBUG(D_NET, "peer_credits %u will result in send work "
725                        "request size %d larger than maximum %d device "
726                        "can handle\n", conn->ibc_queue_depth, ret,
727                        conn->ibc_hdev->ibh_max_qp_wr);
728                 conn->ibc_queue_depth =
729                         conn->ibc_hdev->ibh_max_qp_wr / multiplier;
730         }
731
732         /* don't go beyond the maximum the device can handle */
733         return min(ret, conn->ibc_hdev->ibh_max_qp_wr);
734 }
735
736 struct kib_conn *
737 kiblnd_create_conn(struct kib_peer_ni *peer_ni, struct rdma_cm_id *cmid,
738                    int state, int version)
739 {
740         /* CAVEAT EMPTOR:
741          * If the new conn is created successfully it takes over the caller's
742          * ref on 'peer_ni'.  It also "owns" 'cmid' and destroys it when it itself
743          * is destroyed.  On failure, the caller's ref on 'peer_ni' remains and
744          * she must dispose of 'cmid'.  (Actually I'd block forever if I tried
745          * to destroy 'cmid' here since I'm called from the CM which still has
746          * its ref on 'cmid'). */
747         rwlock_t               *glock = &kiblnd_data.kib_global_lock;
748         struct kib_net              *net = peer_ni->ibp_ni->ni_data;
749         struct kib_dev *dev;
750         struct ib_qp_init_attr init_qp_attr = {};
751         struct kib_sched_info   *sched;
752 #ifdef HAVE_IB_CQ_INIT_ATTR
753         struct ib_cq_init_attr  cq_attr = {};
754 #endif
755         struct kib_conn *conn;
756         struct ib_cq            *cq;
757         unsigned long           flags;
758         int                     cpt;
759         int                     rc;
760         int                     i;
761
762         LASSERT(net != NULL);
763         LASSERT(!in_interrupt());
764
765         dev = net->ibn_dev;
766
767         cpt = lnet_cpt_of_nid(peer_ni->ibp_nid, peer_ni->ibp_ni);
768         sched = kiblnd_get_scheduler(cpt);
769
770         if (sched == NULL) {
771                 CERROR("no schedulers available. node is unhealthy\n");
772                 goto failed_0;
773         }
774
775         /*
776          * The cpt might have changed if we ended up selecting a non cpt
777          * native scheduler. So use the scheduler's cpt instead.
778          */
779         cpt = sched->ibs_cpt;
780
781         LIBCFS_CPT_ALLOC(conn, lnet_cpt_table(), cpt, sizeof(*conn));
782         if (conn == NULL) {
783                 CERROR("Can't allocate connection for %s\n",
784                        libcfs_nid2str(peer_ni->ibp_nid));
785                 goto failed_0;
786         }
787
788         conn->ibc_state = IBLND_CONN_INIT;
789         conn->ibc_version = version;
790         conn->ibc_peer = peer_ni;                       /* I take the caller's ref */
791         cmid->context = conn;                   /* for future CM callbacks */
792         conn->ibc_cmid = cmid;
793         conn->ibc_max_frags = peer_ni->ibp_max_frags;
794         conn->ibc_queue_depth = peer_ni->ibp_queue_depth;
795         conn->ibc_rxs = NULL;
796         conn->ibc_rx_pages = NULL;
797
798         INIT_LIST_HEAD(&conn->ibc_early_rxs);
799         INIT_LIST_HEAD(&conn->ibc_tx_noops);
800         INIT_LIST_HEAD(&conn->ibc_tx_queue);
801         INIT_LIST_HEAD(&conn->ibc_tx_queue_rsrvd);
802         INIT_LIST_HEAD(&conn->ibc_tx_queue_nocred);
803         INIT_LIST_HEAD(&conn->ibc_active_txs);
804         INIT_LIST_HEAD(&conn->ibc_zombie_txs);
805         spin_lock_init(&conn->ibc_lock);
806
807         LIBCFS_CPT_ALLOC(conn->ibc_connvars, lnet_cpt_table(), cpt,
808                          sizeof(*conn->ibc_connvars));
809         if (conn->ibc_connvars == NULL) {
810                 CERROR("Can't allocate in-progress connection state\n");
811                 goto failed_2;
812         }
813
814         write_lock_irqsave(glock, flags);
815         if (dev->ibd_failover) {
816                 write_unlock_irqrestore(glock, flags);
817                 CERROR("%s: failover in progress\n", dev->ibd_ifname);
818                 goto failed_2;
819         }
820
821         if (dev->ibd_hdev->ibh_ibdev != cmid->device) {
822                 /* wakeup failover thread and teardown connection */
823                 if (kiblnd_dev_can_failover(dev)) {
824                         list_add_tail(&dev->ibd_fail_list,
825                                       &kiblnd_data.kib_failed_devs);
826                         wake_up(&kiblnd_data.kib_failover_waitq);
827                 }
828
829                 write_unlock_irqrestore(glock, flags);
830                 CERROR("cmid HCA(%s), kib_dev(%s) need failover\n",
831                        cmid->device->name, dev->ibd_ifname);
832                 goto failed_2;
833         }
834
835         kiblnd_hdev_addref_locked(dev->ibd_hdev);
836         conn->ibc_hdev = dev->ibd_hdev;
837
838         kiblnd_setup_mtu_locked(cmid);
839
840         write_unlock_irqrestore(glock, flags);
841
842 #ifdef HAVE_IB_CQ_INIT_ATTR
843         cq_attr.cqe = IBLND_CQ_ENTRIES(conn);
844         cq_attr.comp_vector = kiblnd_get_completion_vector(conn, cpt);
845         cq = ib_create_cq(cmid->device,
846                           kiblnd_cq_completion, kiblnd_cq_event, conn,
847                           &cq_attr);
848 #else
849         cq = ib_create_cq(cmid->device,
850                           kiblnd_cq_completion, kiblnd_cq_event, conn,
851                           IBLND_CQ_ENTRIES(conn),
852                           kiblnd_get_completion_vector(conn, cpt));
853 #endif
854         if (IS_ERR(cq)) {
855                 /*
856                  * on MLX-5 (possibly MLX-4 as well) this error could be
857                  * hit if the concurrent_sends and/or peer_tx_credits is set
858                  * too high. Or due to an MLX-5 bug which tries to
859                  * allocate 256kb via kmalloc for WR cookie array
860                  */
861                 CERROR("Failed to create CQ with %d CQEs: %ld\n",
862                         IBLND_CQ_ENTRIES(conn), PTR_ERR(cq));
863                 goto failed_2;
864         }
865
866         conn->ibc_cq = cq;
867
868         rc = ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
869         if (rc != 0) {
870                 CERROR("Can't request completion notification: %d\n", rc);
871                 goto failed_2;
872         }
873
874         init_qp_attr.event_handler = kiblnd_qp_event;
875         init_qp_attr.qp_context = conn;
876         init_qp_attr.cap.max_send_sge = *kiblnd_tunables.kib_wrq_sge;
877         init_qp_attr.cap.max_recv_sge = 1;
878         init_qp_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
879         init_qp_attr.qp_type = IB_QPT_RC;
880         init_qp_attr.send_cq = cq;
881         init_qp_attr.recv_cq = cq;
882
883         if (peer_ni->ibp_queue_depth_mod &&
884             peer_ni->ibp_queue_depth_mod < peer_ni->ibp_queue_depth) {
885                 conn->ibc_queue_depth = peer_ni->ibp_queue_depth_mod;
886                 CDEBUG(D_NET, "Use reduced queue depth %u (from %u)\n",
887                        peer_ni->ibp_queue_depth_mod,
888                        peer_ni->ibp_queue_depth);
889         }
890
891         do {
892                 /* kiblnd_send_wrs() can change the connection's queue depth if
893                  * the maximum work requests for the device is maxed out
894                  */
895                 init_qp_attr.cap.max_send_wr = kiblnd_send_wrs(conn);
896                 init_qp_attr.cap.max_recv_wr = IBLND_RECV_WRS(conn);
897                 rc = rdma_create_qp(cmid, conn->ibc_hdev->ibh_pd,
898                                     &init_qp_attr);
899                 if (rc != -ENOMEM || conn->ibc_queue_depth < 2)
900                         break;
901                 conn->ibc_queue_depth--;
902         } while (rc);
903
904         if (rc) {
905                 CERROR("Can't create QP: %d, send_wr: %d, recv_wr: %d, "
906                        "send_sge: %d, recv_sge: %d\n",
907                        rc, init_qp_attr.cap.max_send_wr,
908                        init_qp_attr.cap.max_recv_wr,
909                        init_qp_attr.cap.max_send_sge,
910                        init_qp_attr.cap.max_recv_sge);
911                 goto failed_2;
912         }
913
914         conn->ibc_sched = sched;
915
916         if (!peer_ni->ibp_queue_depth_mod &&
917             conn->ibc_queue_depth != peer_ni->ibp_queue_depth) {
918                 CWARN("peer %s - queue depth reduced from %u to %u"
919                       "  to allow for qp creation\n",
920                       libcfs_nid2str(peer_ni->ibp_nid),
921                       peer_ni->ibp_queue_depth,
922                       conn->ibc_queue_depth);
923                 peer_ni->ibp_queue_depth_mod = conn->ibc_queue_depth;
924         }
925
926         LIBCFS_CPT_ALLOC(conn->ibc_rxs, lnet_cpt_table(), cpt,
927                          IBLND_RX_MSGS(conn) * sizeof(struct kib_rx));
928         if (conn->ibc_rxs == NULL) {
929                 CERROR("Cannot allocate RX buffers\n");
930                 goto failed_2;
931         }
932
933         rc = kiblnd_alloc_pages(&conn->ibc_rx_pages, cpt,
934                                 IBLND_RX_MSG_PAGES(conn));
935         if (rc != 0)
936                 goto failed_2;
937
938         kiblnd_map_rx_descs(conn);
939
940         /* 1 ref for caller and each rxmsg */
941         atomic_set(&conn->ibc_refcount, 1 + IBLND_RX_MSGS(conn));
942         conn->ibc_nrx = IBLND_RX_MSGS(conn);
943
944         /* post receives */
945         for (i = 0; i < IBLND_RX_MSGS(conn); i++) {
946                 rc = kiblnd_post_rx(&conn->ibc_rxs[i], IBLND_POSTRX_NO_CREDIT);
947                 if (rc != 0) {
948                         CERROR("Can't post rxmsg: %d\n", rc);
949
950                         /* Make posted receives complete */
951                         kiblnd_abort_receives(conn);
952
953                         /* correct # of posted buffers
954                          * NB locking needed now I'm racing with completion */
955                         spin_lock_irqsave(&sched->ibs_lock, flags);
956                         conn->ibc_nrx -= IBLND_RX_MSGS(conn) - i;
957                         spin_unlock_irqrestore(&sched->ibs_lock, flags);
958
959                         /* cmid will be destroyed by CM(ofed) after cm_callback
960                          * returned, so we can't refer it anymore
961                          * (by kiblnd_connd()->kiblnd_destroy_conn) */
962                         rdma_destroy_qp(conn->ibc_cmid);
963                         conn->ibc_cmid = NULL;
964
965                         /* Drop my own and unused rxbuffer refcounts */
966                         while (i++ <= IBLND_RX_MSGS(conn))
967                                 kiblnd_conn_decref(conn);
968
969                         return NULL;
970                 }
971         }
972
973         /* Init successful! */
974         LASSERT (state == IBLND_CONN_ACTIVE_CONNECT ||
975                  state == IBLND_CONN_PASSIVE_WAIT);
976         conn->ibc_state = state;
977
978         /* 1 more conn */
979         atomic_inc(&net->ibn_nconns);
980         return conn;
981
982  failed_2:
983         kiblnd_destroy_conn(conn);
984         LIBCFS_FREE(conn, sizeof(*conn));
985  failed_0:
986         return NULL;
987 }
988
989 void
990 kiblnd_destroy_conn(struct kib_conn *conn)
991 {
992         struct rdma_cm_id *cmid = conn->ibc_cmid;
993         struct kib_peer_ni *peer_ni = conn->ibc_peer;
994
995         LASSERT (!in_interrupt());
996         LASSERT (atomic_read(&conn->ibc_refcount) == 0);
997         LASSERT(list_empty(&conn->ibc_early_rxs));
998         LASSERT(list_empty(&conn->ibc_tx_noops));
999         LASSERT(list_empty(&conn->ibc_tx_queue));
1000         LASSERT(list_empty(&conn->ibc_tx_queue_rsrvd));
1001         LASSERT(list_empty(&conn->ibc_tx_queue_nocred));
1002         LASSERT(list_empty(&conn->ibc_active_txs));
1003         LASSERT (conn->ibc_noops_posted == 0);
1004         LASSERT (conn->ibc_nsends_posted == 0);
1005
1006         switch (conn->ibc_state) {
1007         default:
1008                 /* conn must be completely disengaged from the network */
1009                 LBUG();
1010
1011         case IBLND_CONN_DISCONNECTED:
1012                 /* connvars should have been freed already */
1013                 LASSERT (conn->ibc_connvars == NULL);
1014                 break;
1015
1016         case IBLND_CONN_INIT:
1017                 break;
1018         }
1019
1020         /* conn->ibc_cmid might be destroyed by CM already */
1021         if (cmid != NULL && cmid->qp != NULL)
1022                 rdma_destroy_qp(cmid);
1023
1024         if (conn->ibc_cq)
1025                 ib_destroy_cq(conn->ibc_cq);
1026
1027         kiblnd_txlist_done(&conn->ibc_zombie_txs, -ECONNABORTED,
1028                            LNET_MSG_STATUS_OK);
1029
1030         if (conn->ibc_rx_pages != NULL)
1031                 kiblnd_unmap_rx_descs(conn);
1032
1033         if (conn->ibc_rxs != NULL)
1034                 CFS_FREE_PTR_ARRAY(conn->ibc_rxs, IBLND_RX_MSGS(conn));
1035
1036         if (conn->ibc_connvars != NULL)
1037                 LIBCFS_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
1038
1039         if (conn->ibc_hdev != NULL)
1040                 kiblnd_hdev_decref(conn->ibc_hdev);
1041
1042         /* See CAVEAT EMPTOR above in kiblnd_create_conn */
1043         if (conn->ibc_state != IBLND_CONN_INIT) {
1044                 struct kib_net *net = peer_ni->ibp_ni->ni_data;
1045
1046                 kiblnd_peer_decref(peer_ni);
1047                 rdma_destroy_id(cmid);
1048                 atomic_dec(&net->ibn_nconns);
1049         }
1050 }
1051
1052 int
1053 kiblnd_close_peer_conns_locked(struct kib_peer_ni *peer_ni, int why)
1054 {
1055         struct kib_conn *conn;
1056         struct kib_conn *cnxt;
1057         int count = 0;
1058
1059         list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
1060                                  ibc_list) {
1061                 CDEBUG(D_NET, "Closing conn -> %s, "
1062                               "version: %x, reason: %d\n",
1063                        libcfs_nid2str(peer_ni->ibp_nid),
1064                        conn->ibc_version, why);
1065
1066                 kiblnd_close_conn_locked(conn, why);
1067                 count++;
1068         }
1069
1070         return count;
1071 }
1072
1073 int
1074 kiblnd_close_stale_conns_locked(struct kib_peer_ni *peer_ni,
1075                                 int version, __u64 incarnation)
1076 {
1077         struct kib_conn *conn;
1078         struct kib_conn *cnxt;
1079         int count = 0;
1080
1081         list_for_each_entry_safe(conn, cnxt, &peer_ni->ibp_conns,
1082                                  ibc_list) {
1083                 if (conn->ibc_version     == version &&
1084                     conn->ibc_incarnation == incarnation)
1085                         continue;
1086
1087                 CDEBUG(D_NET, "Closing stale conn -> %s version: %x, "
1088                               "incarnation:%#llx(%x, %#llx)\n",
1089                        libcfs_nid2str(peer_ni->ibp_nid),
1090                        conn->ibc_version, conn->ibc_incarnation,
1091                        version, incarnation);
1092
1093                 kiblnd_close_conn_locked(conn, -ESTALE);
1094                 count++;
1095         }
1096
1097         return count;
1098 }
1099
1100 static int
1101 kiblnd_close_matching_conns(struct lnet_ni *ni, lnet_nid_t nid)
1102 {
1103         struct kib_peer_ni              *peer_ni;
1104         struct list_head        *ptmp;
1105         struct list_head        *pnxt;
1106         int                     lo;
1107         int                     hi;
1108         int                     i;
1109         unsigned long           flags;
1110         int                     count = 0;
1111
1112         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1113
1114         if (nid != LNET_NID_ANY)
1115                 lo = hi = kiblnd_nid2peerlist(nid) - kiblnd_data.kib_peers;
1116         else {
1117                 lo = 0;
1118                 hi = kiblnd_data.kib_peer_hash_size - 1;
1119         }
1120
1121         for (i = lo; i <= hi; i++) {
1122                 list_for_each_safe(ptmp, pnxt, &kiblnd_data.kib_peers[i]) {
1123
1124                         peer_ni = list_entry(ptmp, struct kib_peer_ni, ibp_list);
1125                         LASSERT(!kiblnd_peer_idle(peer_ni));
1126
1127                         if (peer_ni->ibp_ni != ni)
1128                                 continue;
1129
1130                         if (!(nid == LNET_NID_ANY || nid == peer_ni->ibp_nid))
1131                                 continue;
1132
1133                         count += kiblnd_close_peer_conns_locked(peer_ni, 0);
1134                 }
1135         }
1136
1137         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1138
1139         /* wildcards always succeed */
1140         if (nid == LNET_NID_ANY)
1141                 return 0;
1142
1143         return (count == 0) ? -ENOENT : 0;
1144 }
1145
1146 static int
1147 kiblnd_ctl(struct lnet_ni *ni, unsigned int cmd, void *arg)
1148 {
1149         struct libcfs_ioctl_data *data = arg;
1150         int                       rc = -EINVAL;
1151
1152         switch(cmd) {
1153         case IOC_LIBCFS_GET_PEER: {
1154                 lnet_nid_t   nid = 0;
1155                 int          count = 0;
1156
1157                 rc = kiblnd_get_peer_info(ni, data->ioc_count,
1158                                           &nid, &count);
1159                 data->ioc_nid    = nid;
1160                 data->ioc_count  = count;
1161                 break;
1162         }
1163
1164         case IOC_LIBCFS_DEL_PEER: {
1165                 rc = kiblnd_del_peer(ni, data->ioc_nid);
1166                 break;
1167         }
1168         case IOC_LIBCFS_GET_CONN: {
1169                 struct kib_conn *conn;
1170
1171                 rc = 0;
1172                 conn = kiblnd_get_conn_by_idx(ni, data->ioc_count);
1173                 if (conn == NULL) {
1174                         rc = -ENOENT;
1175                         break;
1176                 }
1177
1178                 LASSERT(conn->ibc_cmid != NULL);
1179                 data->ioc_nid = conn->ibc_peer->ibp_nid;
1180                 if (conn->ibc_cmid->route.path_rec == NULL)
1181                         data->ioc_u32[0] = 0; /* iWarp has no path MTU */
1182                 else
1183                         data->ioc_u32[0] =
1184                         ib_mtu_enum_to_int(conn->ibc_cmid->route.path_rec->mtu);
1185                 kiblnd_conn_decref(conn);
1186                 break;
1187         }
1188         case IOC_LIBCFS_CLOSE_CONNECTION: {
1189                 rc = kiblnd_close_matching_conns(ni, data->ioc_nid);
1190                 break;
1191         }
1192
1193         default:
1194                 break;
1195         }
1196
1197         return rc;
1198 }
1199
1200 static void
1201 kiblnd_free_pages(struct kib_pages *p)
1202 {
1203         int     npages = p->ibp_npages;
1204         int     i;
1205
1206         for (i = 0; i < npages; i++) {
1207                 if (p->ibp_pages[i] != NULL)
1208                         __free_page(p->ibp_pages[i]);
1209         }
1210
1211         LIBCFS_FREE(p, offsetof(struct kib_pages, ibp_pages[npages]));
1212 }
1213
1214 int
1215 kiblnd_alloc_pages(struct kib_pages **pp, int cpt, int npages)
1216 {
1217         struct kib_pages *p;
1218         int i;
1219
1220         LIBCFS_CPT_ALLOC(p, lnet_cpt_table(), cpt,
1221                          offsetof(struct kib_pages, ibp_pages[npages]));
1222         if (p == NULL) {
1223                 CERROR("Can't allocate descriptor for %d pages\n", npages);
1224                 return -ENOMEM;
1225         }
1226
1227         memset(p, 0, offsetof(struct kib_pages, ibp_pages[npages]));
1228         p->ibp_npages = npages;
1229
1230         for (i = 0; i < npages; i++) {
1231                 p->ibp_pages[i] = cfs_page_cpt_alloc(lnet_cpt_table(), cpt,
1232                                                      GFP_NOFS);
1233                 if (p->ibp_pages[i] == NULL) {
1234                         CERROR("Can't allocate page %d of %d\n", i, npages);
1235                         kiblnd_free_pages(p);
1236                         return -ENOMEM;
1237                 }
1238         }
1239
1240         *pp = p;
1241         return 0;
1242 }
1243
1244 void
1245 kiblnd_unmap_rx_descs(struct kib_conn *conn)
1246 {
1247         struct kib_rx *rx;
1248         int       i;
1249
1250         LASSERT (conn->ibc_rxs != NULL);
1251         LASSERT (conn->ibc_hdev != NULL);
1252
1253         for (i = 0; i < IBLND_RX_MSGS(conn); i++) {
1254                 rx = &conn->ibc_rxs[i];
1255
1256                 LASSERT(rx->rx_nob >= 0); /* not posted */
1257
1258                 kiblnd_dma_unmap_single(conn->ibc_hdev->ibh_ibdev,
1259                                         KIBLND_UNMAP_ADDR(rx, rx_msgunmap,
1260                                                           rx->rx_msgaddr),
1261                                         IBLND_MSG_SIZE, DMA_FROM_DEVICE);
1262         }
1263
1264         kiblnd_free_pages(conn->ibc_rx_pages);
1265
1266         conn->ibc_rx_pages = NULL;
1267 }
1268
1269 void
1270 kiblnd_map_rx_descs(struct kib_conn *conn)
1271 {
1272         struct kib_rx *rx;
1273         struct page    *pg;
1274         int             pg_off;
1275         int             ipg;
1276         int             i;
1277
1278         for (pg_off = ipg = i = 0; i < IBLND_RX_MSGS(conn); i++) {
1279                 pg = conn->ibc_rx_pages->ibp_pages[ipg];
1280                 rx = &conn->ibc_rxs[i];
1281
1282                 rx->rx_conn = conn;
1283                 rx->rx_msg = (struct kib_msg *)(((char *)page_address(pg)) + pg_off);
1284
1285                 rx->rx_msgaddr =
1286                         kiblnd_dma_map_single(conn->ibc_hdev->ibh_ibdev,
1287                                               rx->rx_msg, IBLND_MSG_SIZE,
1288                                               DMA_FROM_DEVICE);
1289                 LASSERT(!kiblnd_dma_mapping_error(conn->ibc_hdev->ibh_ibdev,
1290                                                   rx->rx_msgaddr));
1291                 KIBLND_UNMAP_ADDR_SET(rx, rx_msgunmap, rx->rx_msgaddr);
1292
1293                 CDEBUG(D_NET, "rx %d: %p %#llx(%#llx)\n",
1294                        i, rx->rx_msg, rx->rx_msgaddr,
1295                        (__u64)(page_to_phys(pg) + pg_off));
1296
1297                 pg_off += IBLND_MSG_SIZE;
1298                 LASSERT(pg_off <= PAGE_SIZE);
1299
1300                 if (pg_off == PAGE_SIZE) {
1301                         pg_off = 0;
1302                         ipg++;
1303                         LASSERT(ipg <= IBLND_RX_MSG_PAGES(conn));
1304                 }
1305         }
1306 }
1307
1308 static void
1309 kiblnd_unmap_tx_pool(struct kib_tx_pool *tpo)
1310 {
1311         struct kib_hca_dev *hdev = tpo->tpo_hdev;
1312         struct kib_tx *tx;
1313         int i;
1314
1315         LASSERT (tpo->tpo_pool.po_allocated == 0);
1316
1317         if (hdev == NULL)
1318                 return;
1319
1320         for (i = 0; i < tpo->tpo_pool.po_size; i++) {
1321                 tx = &tpo->tpo_tx_descs[i];
1322                 kiblnd_dma_unmap_single(hdev->ibh_ibdev,
1323                                         KIBLND_UNMAP_ADDR(tx, tx_msgunmap,
1324                                                           tx->tx_msgaddr),
1325                                         IBLND_MSG_SIZE, DMA_TO_DEVICE);
1326         }
1327
1328         kiblnd_hdev_decref(hdev);
1329         tpo->tpo_hdev = NULL;
1330 }
1331
1332 static struct kib_hca_dev *
1333 kiblnd_current_hdev(struct kib_dev *dev)
1334 {
1335         struct kib_hca_dev *hdev;
1336         unsigned long  flags;
1337         int            i = 0;
1338
1339         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1340         while (dev->ibd_failover) {
1341                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1342                 if (i++ % 50 == 0)
1343                         CDEBUG(D_NET, "%s: Wait for failover\n",
1344                                dev->ibd_ifname);
1345                 schedule_timeout_interruptible(cfs_time_seconds(1) / 100);
1346
1347                 read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
1348         }
1349
1350         kiblnd_hdev_addref_locked(dev->ibd_hdev);
1351         hdev = dev->ibd_hdev;
1352
1353         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
1354
1355         return hdev;
1356 }
1357
1358 static void
1359 kiblnd_map_tx_pool(struct kib_tx_pool *tpo)
1360 {
1361         struct kib_pages *txpgs = tpo->tpo_tx_pages;
1362         struct kib_pool *pool = &tpo->tpo_pool;
1363         struct kib_net      *net   = pool->po_owner->ps_net;
1364         struct kib_dev *dev;
1365         struct page *page;
1366         struct kib_tx *tx;
1367         int             page_offset;
1368         int             ipage;
1369         int             i;
1370
1371         LASSERT (net != NULL);
1372
1373         dev = net->ibn_dev;
1374
1375         /* pre-mapped messages are not bigger than 1 page */
1376         BUILD_BUG_ON(IBLND_MSG_SIZE > PAGE_SIZE);
1377
1378         /* No fancy arithmetic when we do the buffer calculations */
1379         BUILD_BUG_ON(PAGE_SIZE % IBLND_MSG_SIZE != 0);
1380
1381         tpo->tpo_hdev = kiblnd_current_hdev(dev);
1382
1383         for (ipage = page_offset = i = 0; i < pool->po_size; i++) {
1384                 page = txpgs->ibp_pages[ipage];
1385                 tx = &tpo->tpo_tx_descs[i];
1386
1387                 tx->tx_msg = (struct kib_msg *)(((char *)page_address(page)) +
1388                                                 page_offset);
1389
1390                 tx->tx_msgaddr = kiblnd_dma_map_single(tpo->tpo_hdev->ibh_ibdev,
1391                                                        tx->tx_msg,
1392                                                        IBLND_MSG_SIZE,
1393                                                        DMA_TO_DEVICE);
1394                 LASSERT(!kiblnd_dma_mapping_error(tpo->tpo_hdev->ibh_ibdev,
1395                                                   tx->tx_msgaddr));
1396                 KIBLND_UNMAP_ADDR_SET(tx, tx_msgunmap, tx->tx_msgaddr);
1397
1398                 list_add(&tx->tx_list, &pool->po_free_list);
1399
1400                 page_offset += IBLND_MSG_SIZE;
1401                 LASSERT(page_offset <= PAGE_SIZE);
1402
1403                 if (page_offset == PAGE_SIZE) {
1404                         page_offset = 0;
1405                         ipage++;
1406                         LASSERT(ipage <= txpgs->ibp_npages);
1407                 }
1408         }
1409 }
1410
1411 static void
1412 kiblnd_destroy_fmr_pool(struct kib_fmr_pool *fpo)
1413 {
1414         LASSERT(fpo->fpo_map_count == 0);
1415
1416 #ifdef HAVE_FMR_POOL_API
1417         if (fpo->fpo_is_fmr && fpo->fmr.fpo_fmr_pool) {
1418                 ib_destroy_fmr_pool(fpo->fmr.fpo_fmr_pool);
1419         } else
1420 #endif /* HAVE_FMR_POOL_API */
1421         {
1422                 struct kib_fast_reg_descriptor *frd, *tmp;
1423                 int i = 0;
1424
1425                 list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1426                                          frd_list) {
1427                         list_del(&frd->frd_list);
1428 #ifndef HAVE_IB_MAP_MR_SG
1429                         ib_free_fast_reg_page_list(frd->frd_frpl);
1430 #endif
1431                         ib_dereg_mr(frd->frd_mr);
1432                         LIBCFS_FREE(frd, sizeof(*frd));
1433                         i++;
1434                 }
1435                 if (i < fpo->fast_reg.fpo_pool_size)
1436                         CERROR("FastReg pool still has %d regions registered\n",
1437                                 fpo->fast_reg.fpo_pool_size - i);
1438         }
1439
1440         if (fpo->fpo_hdev)
1441                 kiblnd_hdev_decref(fpo->fpo_hdev);
1442
1443         LIBCFS_FREE(fpo, sizeof(*fpo));
1444 }
1445
1446 static void
1447 kiblnd_destroy_fmr_pool_list(struct list_head *head)
1448 {
1449         struct kib_fmr_pool *fpo, *tmp;
1450
1451         list_for_each_entry_safe(fpo, tmp, head, fpo_list) {
1452                 list_del(&fpo->fpo_list);
1453                 kiblnd_destroy_fmr_pool(fpo);
1454         }
1455 }
1456
1457 static int
1458 kiblnd_fmr_pool_size(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1459                      int ncpts)
1460 {
1461         int size = tunables->lnd_fmr_pool_size / ncpts;
1462
1463         return max(IBLND_FMR_POOL, size);
1464 }
1465
1466 static int
1467 kiblnd_fmr_flush_trigger(struct lnet_ioctl_config_o2iblnd_tunables *tunables,
1468                          int ncpts)
1469 {
1470         int size = tunables->lnd_fmr_flush_trigger / ncpts;
1471
1472         return max(IBLND_FMR_POOL_FLUSH, size);
1473 }
1474
1475 #ifdef HAVE_FMR_POOL_API
1476 static int kiblnd_alloc_fmr_pool(struct kib_fmr_poolset *fps,
1477                                  struct kib_fmr_pool *fpo)
1478 {
1479         struct ib_fmr_pool_param param = {
1480                 .max_pages_per_fmr = LNET_MAX_IOV,
1481                 .page_shift        = PAGE_SHIFT,
1482                 .access            = (IB_ACCESS_LOCAL_WRITE |
1483                                       IB_ACCESS_REMOTE_WRITE),
1484                 .pool_size         = fps->fps_pool_size,
1485                 .dirty_watermark   = fps->fps_flush_trigger,
1486                 .flush_function    = NULL,
1487                 .flush_arg         = NULL,
1488                 .cache             = !!fps->fps_cache };
1489         int rc = 0;
1490
1491         fpo->fmr.fpo_fmr_pool = ib_create_fmr_pool(fpo->fpo_hdev->ibh_pd,
1492                                                    &param);
1493         if (IS_ERR(fpo->fmr.fpo_fmr_pool)) {
1494                 rc = PTR_ERR(fpo->fmr.fpo_fmr_pool);
1495                 if (rc != -ENOSYS)
1496                         CERROR("Failed to create FMR pool: %d\n", rc);
1497                 else
1498                         CERROR("FMRs are not supported\n");
1499         }
1500         fpo->fpo_is_fmr = true;
1501
1502         return rc;
1503 }
1504 #endif /* HAVE_FMR_POOL_API */
1505
1506 static int kiblnd_alloc_freg_pool(struct kib_fmr_poolset *fps,
1507                                   struct kib_fmr_pool *fpo,
1508                                   enum kib_dev_caps dev_caps)
1509 {
1510         struct kib_fast_reg_descriptor *frd, *tmp;
1511         int i, rc;
1512
1513 #ifdef HAVE_FMR_POOL_API
1514         fpo->fpo_is_fmr = false;
1515 #endif
1516
1517         INIT_LIST_HEAD(&fpo->fast_reg.fpo_pool_list);
1518         fpo->fast_reg.fpo_pool_size = 0;
1519         for (i = 0; i < fps->fps_pool_size; i++) {
1520                 LIBCFS_CPT_ALLOC(frd, lnet_cpt_table(), fps->fps_cpt,
1521                                  sizeof(*frd));
1522                 if (!frd) {
1523                         CERROR("Failed to allocate a new fast_reg descriptor\n");
1524                         rc = -ENOMEM;
1525                         goto out;
1526                 }
1527                 frd->frd_mr = NULL;
1528
1529 #ifndef HAVE_IB_MAP_MR_SG
1530                 frd->frd_frpl = ib_alloc_fast_reg_page_list(fpo->fpo_hdev->ibh_ibdev,
1531                                                             LNET_MAX_IOV);
1532                 if (IS_ERR(frd->frd_frpl)) {
1533                         rc = PTR_ERR(frd->frd_frpl);
1534                         CERROR("Failed to allocate ib_fast_reg_page_list: %d\n",
1535                                 rc);
1536                         frd->frd_frpl = NULL;
1537                         goto out_middle;
1538                 }
1539 #endif
1540
1541 #ifdef HAVE_IB_ALLOC_FAST_REG_MR
1542                 frd->frd_mr = ib_alloc_fast_reg_mr(fpo->fpo_hdev->ibh_pd,
1543                                                    LNET_MAX_IOV);
1544 #else
1545                 /*
1546                  * it is expected to get here if this is an MLX-5 card.
1547                  * MLX-4 cards will always use FMR and MLX-5 cards will
1548                  * always use fast_reg. It turns out that some MLX-5 cards
1549                  * (possibly due to older FW versions) do not natively support
1550                  * gaps. So we will need to track them here.
1551                  */
1552                 frd->frd_mr = ib_alloc_mr(fpo->fpo_hdev->ibh_pd,
1553 #ifdef IB_MR_TYPE_SG_GAPS
1554                                           ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1555                                            (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT)) ?
1556                                                 IB_MR_TYPE_SG_GAPS :
1557                                                 IB_MR_TYPE_MEM_REG,
1558 #else
1559                                                 IB_MR_TYPE_MEM_REG,
1560 #endif
1561                                           LNET_MAX_IOV);
1562                 if ((*kiblnd_tunables.kib_use_fastreg_gaps == 1) &&
1563                     (dev_caps & IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT))
1564                         CWARN("using IB_MR_TYPE_SG_GAPS, expect a performance drop\n");
1565 #endif
1566                 if (IS_ERR(frd->frd_mr)) {
1567                         rc = PTR_ERR(frd->frd_mr);
1568                         CERROR("Failed to allocate ib_fast_reg_mr: %d\n", rc);
1569                         frd->frd_mr = NULL;
1570                         goto out_middle;
1571                 }
1572
1573                 /* There appears to be a bug in MLX5 code where you must
1574                  * invalidate the rkey of a new FastReg pool before first
1575                  * using it. Thus, I am marking the FRD invalid here. */
1576                 frd->frd_valid = false;
1577
1578                 list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1579                 fpo->fast_reg.fpo_pool_size++;
1580         }
1581
1582         return 0;
1583
1584 out_middle:
1585         if (frd->frd_mr)
1586                 ib_dereg_mr(frd->frd_mr);
1587 #ifndef HAVE_IB_MAP_MR_SG
1588         if (frd->frd_frpl)
1589                 ib_free_fast_reg_page_list(frd->frd_frpl);
1590 #endif
1591         LIBCFS_FREE(frd, sizeof(*frd));
1592
1593 out:
1594         list_for_each_entry_safe(frd, tmp, &fpo->fast_reg.fpo_pool_list,
1595                                  frd_list) {
1596                 list_del(&frd->frd_list);
1597 #ifndef HAVE_IB_MAP_MR_SG
1598                 ib_free_fast_reg_page_list(frd->frd_frpl);
1599 #endif
1600                 ib_dereg_mr(frd->frd_mr);
1601                 LIBCFS_FREE(frd, sizeof(*frd));
1602         }
1603
1604         return rc;
1605 }
1606
1607 static int kiblnd_create_fmr_pool(struct kib_fmr_poolset *fps,
1608                                   struct kib_fmr_pool **pp_fpo)
1609 {
1610         struct kib_dev *dev = fps->fps_net->ibn_dev;
1611         struct kib_fmr_pool *fpo;
1612         int rc;
1613
1614         LIBCFS_CPT_ALLOC(fpo, lnet_cpt_table(), fps->fps_cpt, sizeof(*fpo));
1615         if (!fpo) {
1616                 return -ENOMEM;
1617         }
1618         memset(fpo, 0, sizeof(*fpo));
1619
1620         fpo->fpo_hdev = kiblnd_current_hdev(dev);
1621
1622 #ifdef HAVE_FMR_POOL_API
1623         if (dev->ibd_dev_caps & IBLND_DEV_CAPS_FMR_ENABLED)
1624                 rc = kiblnd_alloc_fmr_pool(fps, fpo);
1625         else
1626 #endif /* HAVE_FMR_POOL_API */
1627                 rc = kiblnd_alloc_freg_pool(fps, fpo, dev->ibd_dev_caps);
1628         if (rc)
1629                 goto out_fpo;
1630
1631         fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1632         fpo->fpo_owner = fps;
1633         *pp_fpo = fpo;
1634
1635         return 0;
1636
1637 out_fpo:
1638         kiblnd_hdev_decref(fpo->fpo_hdev);
1639         LIBCFS_FREE(fpo, sizeof(*fpo));
1640         return rc;
1641 }
1642
1643 static void
1644 kiblnd_fail_fmr_poolset(struct kib_fmr_poolset *fps, struct list_head *zombies)
1645 {
1646         if (fps->fps_net == NULL) /* intialized? */
1647                 return;
1648
1649         spin_lock(&fps->fps_lock);
1650
1651         while (!list_empty(&fps->fps_pool_list)) {
1652                 struct kib_fmr_pool *fpo = list_entry(fps->fps_pool_list.next,
1653                                                       struct kib_fmr_pool,
1654                                                       fpo_list);
1655
1656                 fpo->fpo_failed = 1;
1657                 if (fpo->fpo_map_count == 0)
1658                         list_move(&fpo->fpo_list, zombies);
1659                 else
1660                         list_move(&fpo->fpo_list, &fps->fps_failed_pool_list);
1661         }
1662
1663         spin_unlock(&fps->fps_lock);
1664 }
1665
1666 static void
1667 kiblnd_fini_fmr_poolset(struct kib_fmr_poolset *fps)
1668 {
1669         if (fps->fps_net != NULL) { /* initialized? */
1670                 kiblnd_destroy_fmr_pool_list(&fps->fps_failed_pool_list);
1671                 kiblnd_destroy_fmr_pool_list(&fps->fps_pool_list);
1672         }
1673 }
1674
1675 static int
1676 kiblnd_init_fmr_poolset(struct kib_fmr_poolset *fps, int cpt, int ncpts,
1677                         struct kib_net *net,
1678                         struct lnet_ioctl_config_o2iblnd_tunables *tunables)
1679 {
1680         struct kib_fmr_pool *fpo;
1681         int rc;
1682
1683         memset(fps, 0, sizeof(struct kib_fmr_poolset));
1684
1685         fps->fps_net = net;
1686         fps->fps_cpt = cpt;
1687
1688         fps->fps_pool_size = kiblnd_fmr_pool_size(tunables, ncpts);
1689         fps->fps_flush_trigger = kiblnd_fmr_flush_trigger(tunables, ncpts);
1690         fps->fps_cache = tunables->lnd_fmr_cache;
1691
1692         spin_lock_init(&fps->fps_lock);
1693         INIT_LIST_HEAD(&fps->fps_pool_list);
1694         INIT_LIST_HEAD(&fps->fps_failed_pool_list);
1695
1696         rc = kiblnd_create_fmr_pool(fps, &fpo);
1697         if (rc == 0)
1698                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
1699
1700         return rc;
1701 }
1702
1703 static int
1704 kiblnd_fmr_pool_is_idle(struct kib_fmr_pool *fpo, time64_t now)
1705 {
1706         if (fpo->fpo_map_count != 0) /* still in use */
1707                 return 0;
1708         if (fpo->fpo_failed)
1709                 return 1;
1710         return now >= fpo->fpo_deadline;
1711 }
1712
1713 #if defined(HAVE_FMR_POOL_API) || !defined(HAVE_IB_MAP_MR_SG)
1714 static int
1715 kiblnd_map_tx_pages(struct kib_tx *tx, struct kib_rdma_desc *rd)
1716 {
1717         struct kib_hca_dev *hdev;
1718         __u64           *pages = tx->tx_pages;
1719         int             npages;
1720         int             size;
1721         int             i;
1722
1723         hdev = tx->tx_pool->tpo_hdev;
1724
1725         for (i = 0, npages = 0; i < rd->rd_nfrags; i++) {
1726                 for (size = 0; size <  rd->rd_frags[i].rf_nob;
1727                         size += hdev->ibh_page_size) {
1728                         pages[npages++] = (rd->rd_frags[i].rf_addr &
1729                                            hdev->ibh_page_mask) + size;
1730                 }
1731         }
1732
1733         return npages;
1734 }
1735 #endif
1736
1737 void
1738 kiblnd_fmr_pool_unmap(struct kib_fmr *fmr, int status)
1739 {
1740         LIST_HEAD(zombies);
1741         struct kib_fmr_pool *fpo = fmr->fmr_pool;
1742         struct kib_fmr_poolset *fps;
1743         time64_t now = ktime_get_seconds();
1744         struct kib_fmr_pool *tmp;
1745
1746         if (!fpo)
1747                 return;
1748
1749         fps = fpo->fpo_owner;
1750
1751 #ifdef HAVE_FMR_POOL_API
1752         if (fpo->fpo_is_fmr) {
1753                 if (fmr->fmr_pfmr) {
1754                         ib_fmr_pool_unmap(fmr->fmr_pfmr);
1755                         fmr->fmr_pfmr = NULL;
1756                 }
1757
1758                 if (status) {
1759                         int rc = ib_flush_fmr_pool(fpo->fmr.fpo_fmr_pool);
1760                         LASSERT(!rc);
1761                 }
1762         } else
1763 #endif /* HAVE_FMR_POOL_API */
1764         {
1765                 struct kib_fast_reg_descriptor *frd = fmr->fmr_frd;
1766
1767                 if (frd) {
1768                         frd->frd_valid = false;
1769                         frd->frd_posted = false;
1770                         fmr->fmr_frd = NULL;
1771                         spin_lock(&fps->fps_lock);
1772                         list_add_tail(&frd->frd_list, &fpo->fast_reg.fpo_pool_list);
1773                         spin_unlock(&fps->fps_lock);
1774                 }
1775         }
1776         fmr->fmr_pool = NULL;
1777
1778         spin_lock(&fps->fps_lock);
1779         fpo->fpo_map_count--;   /* decref the pool */
1780
1781         list_for_each_entry_safe(fpo, tmp, &fps->fps_pool_list, fpo_list) {
1782                 /* the first pool is persistent */
1783                 if (fps->fps_pool_list.next == &fpo->fpo_list)
1784                         continue;
1785
1786                 if (kiblnd_fmr_pool_is_idle(fpo, now)) {
1787                         list_move(&fpo->fpo_list, &zombies);
1788                         fps->fps_version++;
1789                 }
1790         }
1791         spin_unlock(&fps->fps_lock);
1792
1793         if (!list_empty(&zombies))
1794                 kiblnd_destroy_fmr_pool_list(&zombies);
1795 }
1796
1797 int kiblnd_fmr_pool_map(struct kib_fmr_poolset *fps, struct kib_tx *tx,
1798                         struct kib_rdma_desc *rd, u32 nob, u64 iov,
1799                         struct kib_fmr *fmr)
1800 {
1801         struct kib_fmr_pool *fpo;
1802         __u64 version;
1803         bool is_rx = (rd != tx->tx_rd);
1804 #ifdef HAVE_FMR_POOL_API
1805         __u64 *pages = tx->tx_pages;
1806         bool tx_pages_mapped = 0;
1807         int npages = 0;
1808 #endif
1809         int rc;
1810
1811 again:
1812         spin_lock(&fps->fps_lock);
1813         version = fps->fps_version;
1814         list_for_each_entry(fpo, &fps->fps_pool_list, fpo_list) {
1815                 fpo->fpo_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
1816                 fpo->fpo_map_count++;
1817
1818 #ifdef HAVE_FMR_POOL_API
1819                 fmr->fmr_pfmr = NULL;
1820                 if (fpo->fpo_is_fmr) {
1821                         struct ib_pool_fmr *pfmr;
1822
1823                         spin_unlock(&fps->fps_lock);
1824
1825                         if (!tx_pages_mapped) {
1826                                 npages = kiblnd_map_tx_pages(tx, rd);
1827                                 tx_pages_mapped = 1;
1828                         }
1829
1830                         pfmr = kib_fmr_pool_map(fpo->fmr.fpo_fmr_pool,
1831                                                 pages, npages, iov);
1832                         if (likely(!IS_ERR(pfmr))) {
1833                                 fmr->fmr_key  = is_rx ? pfmr->fmr->rkey
1834                                                       : pfmr->fmr->lkey;
1835                                 fmr->fmr_frd  = NULL;
1836                                 fmr->fmr_pfmr = pfmr;
1837                                 fmr->fmr_pool = fpo;
1838                                 return 0;
1839                         }
1840                         rc = PTR_ERR(pfmr);
1841                 } else
1842 #endif /* HAVE_FMR_POOL_API */
1843                 {
1844                         if (!list_empty(&fpo->fast_reg.fpo_pool_list)) {
1845                                 struct kib_fast_reg_descriptor *frd;
1846 #ifdef HAVE_IB_MAP_MR_SG
1847                                 struct ib_reg_wr *wr;
1848                                 int n;
1849 #else
1850                                 struct ib_rdma_wr *wr;
1851                                 struct ib_fast_reg_page_list *frpl;
1852 #endif
1853                                 struct ib_mr *mr;
1854
1855                                 frd = list_first_entry(&fpo->fast_reg.fpo_pool_list,
1856                                                         struct kib_fast_reg_descriptor,
1857                                                         frd_list);
1858                                 list_del(&frd->frd_list);
1859                                 spin_unlock(&fps->fps_lock);
1860
1861 #ifndef HAVE_IB_MAP_MR_SG
1862                                 frpl = frd->frd_frpl;
1863 #endif
1864                                 mr   = frd->frd_mr;
1865
1866                                 if (!frd->frd_valid) {
1867                                         struct ib_rdma_wr *inv_wr;
1868                                         __u32 key = is_rx ? mr->rkey : mr->lkey;
1869
1870                                         inv_wr = &frd->frd_inv_wr;
1871                                         memset(inv_wr, 0, sizeof(*inv_wr));
1872
1873                                         inv_wr->wr.opcode = IB_WR_LOCAL_INV;
1874                                         inv_wr->wr.wr_id  = IBLND_WID_MR;
1875                                         inv_wr->wr.ex.invalidate_rkey = key;
1876
1877                                         /* Bump the key */
1878                                         key = ib_inc_rkey(key);
1879                                         ib_update_fast_reg_key(mr, key);
1880                                 }
1881
1882 #ifdef HAVE_IB_MAP_MR_SG
1883 #ifdef HAVE_IB_MAP_MR_SG_5ARGS
1884                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1885                                                  rd->rd_nfrags, NULL, PAGE_SIZE);
1886 #else
1887                                 n = ib_map_mr_sg(mr, tx->tx_frags,
1888                                                  rd->rd_nfrags, PAGE_SIZE);
1889 #endif /* HAVE_IB_MAP_MR_SG_5ARGS */
1890                                 if (unlikely(n != rd->rd_nfrags)) {
1891                                         CERROR("Failed to map mr %d/%d "
1892                                                "elements\n", n, rd->rd_nfrags);
1893                                         return n < 0 ? n : -EINVAL;
1894                                 }
1895
1896                                 wr = &frd->frd_fastreg_wr;
1897                                 memset(wr, 0, sizeof(*wr));
1898
1899                                 wr->wr.opcode = IB_WR_REG_MR;
1900                                 wr->wr.wr_id  = IBLND_WID_MR;
1901                                 wr->wr.num_sge = 0;
1902                                 wr->wr.send_flags = 0;
1903                                 wr->mr = mr;
1904                                 wr->key = is_rx ? mr->rkey : mr->lkey;
1905                                 wr->access = (IB_ACCESS_LOCAL_WRITE |
1906                                               IB_ACCESS_REMOTE_WRITE);
1907 #else /* HAVE_IB_MAP_MR_SG */
1908                                 if (!tx_pages_mapped) {
1909                                         npages = kiblnd_map_tx_pages(tx, rd);
1910                                         tx_pages_mapped = 1;
1911                                 }
1912
1913                                 LASSERT(npages <= frpl->max_page_list_len);
1914                                 memcpy(frpl->page_list, pages,
1915                                         sizeof(*pages) * npages);
1916
1917                                 /* Prepare FastReg WR */
1918                                 wr = &frd->frd_fastreg_wr;
1919                                 memset(wr, 0, sizeof(*wr));
1920
1921                                 wr->wr.opcode = IB_WR_FAST_REG_MR;
1922                                 wr->wr.wr_id  = IBLND_WID_MR;
1923
1924                                 wr->wr.wr.fast_reg.iova_start = iov;
1925                                 wr->wr.wr.fast_reg.page_list  = frpl;
1926                                 wr->wr.wr.fast_reg.page_list_len = npages;
1927                                 wr->wr.wr.fast_reg.page_shift = PAGE_SHIFT;
1928                                 wr->wr.wr.fast_reg.length = nob;
1929                                 wr->wr.wr.fast_reg.rkey =
1930                                                 is_rx ? mr->rkey : mr->lkey;
1931                                 wr->wr.wr.fast_reg.access_flags =
1932                                                 (IB_ACCESS_LOCAL_WRITE |
1933                                                  IB_ACCESS_REMOTE_WRITE);
1934 #endif /* HAVE_IB_MAP_MR_SG */
1935
1936                                 fmr->fmr_key  = is_rx ? mr->rkey : mr->lkey;
1937                                 fmr->fmr_frd  = frd;
1938                                 fmr->fmr_pool = fpo;
1939                                 frd->frd_posted = false;
1940                                 return 0;
1941                         }
1942                         spin_unlock(&fps->fps_lock);
1943                         rc = -EAGAIN;
1944                 }
1945
1946                 spin_lock(&fps->fps_lock);
1947                 fpo->fpo_map_count--;
1948                 if (rc != -EAGAIN) {
1949                         spin_unlock(&fps->fps_lock);
1950                         return rc;
1951                 }
1952
1953                 /* EAGAIN and ... */
1954                 if (version != fps->fps_version) {
1955                         spin_unlock(&fps->fps_lock);
1956                         goto again;
1957                 }
1958         }
1959
1960         if (fps->fps_increasing) {
1961                 spin_unlock(&fps->fps_lock);
1962                 CDEBUG(D_NET, "Another thread is allocating new "
1963                        "FMR pool, waiting for her to complete\n");
1964                 wait_var_event(fps, !fps->fps_increasing);
1965                 goto again;
1966
1967         }
1968
1969         if (ktime_get_seconds() < fps->fps_next_retry) {
1970                 /* someone failed recently */
1971                 spin_unlock(&fps->fps_lock);
1972                 return -EAGAIN;
1973         }
1974
1975         fps->fps_increasing = 1;
1976         spin_unlock(&fps->fps_lock);
1977
1978         CDEBUG(D_NET, "Allocate new FMR pool\n");
1979         rc = kiblnd_create_fmr_pool(fps, &fpo);
1980         spin_lock(&fps->fps_lock);
1981         fps->fps_increasing = 0;
1982         wake_up_var(fps);
1983         if (rc == 0) {
1984                 fps->fps_version++;
1985                 list_add_tail(&fpo->fpo_list, &fps->fps_pool_list);
1986         } else {
1987                 fps->fps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
1988         }
1989         spin_unlock(&fps->fps_lock);
1990
1991         goto again;
1992 }
1993
1994 static void
1995 kiblnd_fini_pool(struct kib_pool *pool)
1996 {
1997         LASSERT(list_empty(&pool->po_free_list));
1998         LASSERT(pool->po_allocated == 0);
1999
2000         CDEBUG(D_NET, "Finalize %s pool\n", pool->po_owner->ps_name);
2001 }
2002
2003 static void
2004 kiblnd_init_pool(struct kib_poolset *ps, struct kib_pool *pool, int size)
2005 {
2006         CDEBUG(D_NET, "Initialize %s pool\n", ps->ps_name);
2007
2008         memset(pool, 0, sizeof(struct kib_pool));
2009         INIT_LIST_HEAD(&pool->po_free_list);
2010         pool->po_deadline = ktime_get_seconds() + IBLND_POOL_DEADLINE;
2011         pool->po_owner = ps;
2012         pool->po_size = size;
2013 }
2014
2015 static void
2016 kiblnd_destroy_pool_list(struct list_head *head)
2017 {
2018         struct kib_pool *pool;
2019
2020         while (!list_empty(head)) {
2021                 pool = list_entry(head->next, struct kib_pool, po_list);
2022                 list_del(&pool->po_list);
2023
2024                 LASSERT(pool->po_owner != NULL);
2025                 pool->po_owner->ps_pool_destroy(pool);
2026         }
2027 }
2028
2029 static void
2030 kiblnd_fail_poolset(struct kib_poolset *ps, struct list_head *zombies)
2031 {
2032         if (ps->ps_net == NULL) /* intialized? */
2033                 return;
2034
2035         spin_lock(&ps->ps_lock);
2036         while (!list_empty(&ps->ps_pool_list)) {
2037                 struct kib_pool *po = list_entry(ps->ps_pool_list.next,
2038                                                  struct kib_pool, po_list);
2039
2040                 po->po_failed = 1;
2041                 if (po->po_allocated == 0)
2042                         list_move(&po->po_list, zombies);
2043                 else
2044                         list_move(&po->po_list, &ps->ps_failed_pool_list);
2045         }
2046         spin_unlock(&ps->ps_lock);
2047 }
2048
2049 static void
2050 kiblnd_fini_poolset(struct kib_poolset *ps)
2051 {
2052         if (ps->ps_net != NULL) { /* initialized? */
2053                 kiblnd_destroy_pool_list(&ps->ps_failed_pool_list);
2054                 kiblnd_destroy_pool_list(&ps->ps_pool_list);
2055         }
2056 }
2057
2058 static int
2059 kiblnd_init_poolset(struct kib_poolset *ps, int cpt,
2060                     struct kib_net *net, char *name, int size,
2061                     kib_ps_pool_create_t po_create,
2062                     kib_ps_pool_destroy_t po_destroy,
2063                     kib_ps_node_init_t nd_init,
2064                     kib_ps_node_fini_t nd_fini)
2065 {
2066         struct kib_pool *pool;
2067         int rc;
2068
2069         memset(ps, 0, sizeof(struct kib_poolset));
2070
2071         ps->ps_cpt          = cpt;
2072         ps->ps_net          = net;
2073         ps->ps_pool_create  = po_create;
2074         ps->ps_pool_destroy = po_destroy;
2075         ps->ps_node_init    = nd_init;
2076         ps->ps_node_fini    = nd_fini;
2077         ps->ps_pool_size    = size;
2078         if (strlcpy(ps->ps_name, name, sizeof(ps->ps_name))
2079             >= sizeof(ps->ps_name))
2080                 return -E2BIG;
2081         spin_lock_init(&ps->ps_lock);
2082         INIT_LIST_HEAD(&ps->ps_pool_list);
2083         INIT_LIST_HEAD(&ps->ps_failed_pool_list);
2084
2085         rc = ps->ps_pool_create(ps, size, &pool);
2086         if (rc == 0)
2087                 list_add(&pool->po_list, &ps->ps_pool_list);
2088         else
2089                 CERROR("Failed to create the first pool for %s\n", ps->ps_name);
2090
2091         return rc;
2092 }
2093
2094 static int
2095 kiblnd_pool_is_idle(struct kib_pool *pool, time64_t now)
2096 {
2097         if (pool->po_allocated != 0) /* still in use */
2098                 return 0;
2099         if (pool->po_failed)
2100                 return 1;
2101         return now >= pool->po_deadline;
2102 }
2103
2104 void
2105 kiblnd_pool_free_node(struct kib_pool *pool, struct list_head *node)
2106 {
2107         LIST_HEAD(zombies);
2108         struct kib_poolset *ps = pool->po_owner;
2109         struct kib_pool *tmp;
2110         time64_t now = ktime_get_seconds();
2111
2112         spin_lock(&ps->ps_lock);
2113
2114         if (ps->ps_node_fini != NULL)
2115                 ps->ps_node_fini(pool, node);
2116
2117         LASSERT(pool->po_allocated > 0);
2118         list_add(node, &pool->po_free_list);
2119         pool->po_allocated--;
2120
2121         list_for_each_entry_safe(pool, tmp, &ps->ps_pool_list, po_list) {
2122                 /* the first pool is persistent */
2123                 if (ps->ps_pool_list.next == &pool->po_list)
2124                         continue;
2125
2126                 if (kiblnd_pool_is_idle(pool, now))
2127                         list_move(&pool->po_list, &zombies);
2128         }
2129         spin_unlock(&ps->ps_lock);
2130
2131         if (!list_empty(&zombies))
2132                 kiblnd_destroy_pool_list(&zombies);
2133 }
2134
2135 struct list_head *
2136 kiblnd_pool_alloc_node(struct kib_poolset *ps)
2137 {
2138         struct list_head        *node;
2139         struct kib_pool *pool;
2140         int                     rc;
2141         unsigned int            interval = 1;
2142         ktime_t time_before;
2143         unsigned int trips = 0;
2144
2145 again:
2146         spin_lock(&ps->ps_lock);
2147         list_for_each_entry(pool, &ps->ps_pool_list, po_list) {
2148                 if (list_empty(&pool->po_free_list))
2149                         continue;
2150
2151                 pool->po_allocated++;
2152                 pool->po_deadline = ktime_get_seconds() +
2153                                     IBLND_POOL_DEADLINE;
2154                 node = pool->po_free_list.next;
2155                 list_del(node);
2156
2157                 if (ps->ps_node_init != NULL) {
2158                         /* still hold the lock */
2159                         ps->ps_node_init(pool, node);
2160                 }
2161                 spin_unlock(&ps->ps_lock);
2162                 return node;
2163         }
2164
2165         /* no available tx pool and ... */
2166         if (ps->ps_increasing) {
2167                 /* another thread is allocating a new pool */
2168                 spin_unlock(&ps->ps_lock);
2169                 trips++;
2170                 CDEBUG(D_NET,
2171                        "Another thread is allocating new %s pool, waiting %d jiffies for her to complete. trips = %d\n",
2172                        ps->ps_name, interval, trips);
2173
2174                 schedule_timeout_interruptible(interval);
2175                 if (interval < cfs_time_seconds(1))
2176                         interval *= 2;
2177
2178                 goto again;
2179         }
2180
2181         if (ktime_get_seconds() < ps->ps_next_retry) {
2182                 /* someone failed recently */
2183                 spin_unlock(&ps->ps_lock);
2184                 return NULL;
2185         }
2186
2187         ps->ps_increasing = 1;
2188         spin_unlock(&ps->ps_lock);
2189
2190         CDEBUG(D_NET, "%s pool exhausted, allocate new pool\n", ps->ps_name);
2191         time_before = ktime_get();
2192         rc = ps->ps_pool_create(ps, ps->ps_pool_size, &pool);
2193         CDEBUG(D_NET, "ps_pool_create took %lld ms to complete",
2194                ktime_ms_delta(ktime_get(), time_before));
2195
2196         spin_lock(&ps->ps_lock);
2197         ps->ps_increasing = 0;
2198         if (rc == 0) {
2199                 list_add_tail(&pool->po_list, &ps->ps_pool_list);
2200         } else {
2201                 ps->ps_next_retry = ktime_get_seconds() + IBLND_POOL_RETRY;
2202                 CERROR("Can't allocate new %s pool because out of memory\n",
2203                        ps->ps_name);
2204         }
2205         spin_unlock(&ps->ps_lock);
2206
2207         goto again;
2208 }
2209
2210 static void
2211 kiblnd_destroy_tx_pool(struct kib_pool *pool)
2212 {
2213         struct kib_tx_pool *tpo = container_of(pool, struct kib_tx_pool,
2214                                                tpo_pool);
2215         int i;
2216
2217         LASSERT (pool->po_allocated == 0);
2218
2219         if (tpo->tpo_tx_pages != NULL) {
2220                 kiblnd_unmap_tx_pool(tpo);
2221                 kiblnd_free_pages(tpo->tpo_tx_pages);
2222         }
2223
2224         if (tpo->tpo_tx_descs == NULL)
2225                 goto out;
2226
2227         for (i = 0; i < pool->po_size; i++) {
2228                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2229                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2230
2231                 list_del(&tx->tx_list);
2232                 if (tx->tx_pages != NULL)
2233                         CFS_FREE_PTR_ARRAY(tx->tx_pages, LNET_MAX_IOV);
2234                 if (tx->tx_frags != NULL)
2235                         CFS_FREE_PTR_ARRAY(tx->tx_frags,
2236                                            (1 + IBLND_MAX_RDMA_FRAGS));
2237                 if (tx->tx_wrq != NULL)
2238                         CFS_FREE_PTR_ARRAY(tx->tx_wrq,
2239                                            (1 + IBLND_MAX_RDMA_FRAGS));
2240                 if (tx->tx_sge != NULL)
2241                         CFS_FREE_PTR_ARRAY(tx->tx_sge,
2242                                            (1 + IBLND_MAX_RDMA_FRAGS) *
2243                                            wrq_sge);
2244                 if (tx->tx_rd != NULL)
2245                         LIBCFS_FREE(tx->tx_rd,
2246                                     offsetof(struct kib_rdma_desc,
2247                                              rd_frags[IBLND_MAX_RDMA_FRAGS]));
2248         }
2249
2250         CFS_FREE_PTR_ARRAY(tpo->tpo_tx_descs, pool->po_size);
2251 out:
2252         kiblnd_fini_pool(pool);
2253         CFS_FREE_PTR(tpo);
2254 }
2255
2256 static int kiblnd_tx_pool_size(struct lnet_ni *ni, int ncpts)
2257 {
2258         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2259         int ntx;
2260
2261         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2262         ntx = tunables->lnd_ntx / ncpts;
2263
2264         return max(IBLND_TX_POOL, ntx);
2265 }
2266
2267 static int
2268 kiblnd_create_tx_pool(struct kib_poolset *ps, int size, struct kib_pool **pp_po)
2269 {
2270         int            i;
2271         int            npg;
2272         struct kib_pool *pool;
2273         struct kib_tx_pool *tpo;
2274
2275         LIBCFS_CPT_ALLOC(tpo, lnet_cpt_table(), ps->ps_cpt, sizeof(*tpo));
2276         if (tpo == NULL) {
2277                 CERROR("Failed to allocate TX pool\n");
2278                 return -ENOMEM;
2279         }
2280
2281         pool = &tpo->tpo_pool;
2282         kiblnd_init_pool(ps, pool, size);
2283         tpo->tpo_tx_descs = NULL;
2284         tpo->tpo_tx_pages = NULL;
2285
2286         npg = (size * IBLND_MSG_SIZE + PAGE_SIZE - 1) / PAGE_SIZE;
2287         if (kiblnd_alloc_pages(&tpo->tpo_tx_pages, ps->ps_cpt, npg) != 0) {
2288                 CERROR("Can't allocate tx pages: %d\n", npg);
2289                 CFS_FREE_PTR(tpo);
2290                 return -ENOMEM;
2291         }
2292
2293         LIBCFS_CPT_ALLOC(tpo->tpo_tx_descs, lnet_cpt_table(), ps->ps_cpt,
2294                          size * sizeof(struct kib_tx));
2295         if (tpo->tpo_tx_descs == NULL) {
2296                 CERROR("Can't allocate %d tx descriptors\n", size);
2297                 ps->ps_pool_destroy(pool);
2298                 return -ENOMEM;
2299         }
2300
2301         memset(tpo->tpo_tx_descs, 0, size * sizeof(struct kib_tx));
2302
2303         for (i = 0; i < size; i++) {
2304                 struct kib_tx *tx = &tpo->tpo_tx_descs[i];
2305                 int       wrq_sge = *kiblnd_tunables.kib_wrq_sge;
2306
2307                 tx->tx_pool = tpo;
2308                 if (ps->ps_net->ibn_fmr_ps != NULL) {
2309                         LIBCFS_CPT_ALLOC(tx->tx_pages,
2310                                          lnet_cpt_table(), ps->ps_cpt,
2311                                          LNET_MAX_IOV * sizeof(*tx->tx_pages));
2312                         if (tx->tx_pages == NULL)
2313                                 break;
2314                 }
2315
2316                 LIBCFS_CPT_ALLOC(tx->tx_frags, lnet_cpt_table(), ps->ps_cpt,
2317                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2318                                  sizeof(*tx->tx_frags));
2319                 if (tx->tx_frags == NULL)
2320                         break;
2321
2322                 sg_init_table(tx->tx_frags, IBLND_MAX_RDMA_FRAGS + 1);
2323
2324                 LIBCFS_CPT_ALLOC(tx->tx_wrq, lnet_cpt_table(), ps->ps_cpt,
2325                                  (1 + IBLND_MAX_RDMA_FRAGS) *
2326                                  sizeof(*tx->tx_wrq));
2327                 if (tx->tx_wrq == NULL)
2328                         break;
2329
2330                 LIBCFS_CPT_ALLOC(tx->tx_sge, lnet_cpt_table(), ps->ps_cpt,
2331                                  (1 + IBLND_MAX_RDMA_FRAGS) * wrq_sge *
2332                                  sizeof(*tx->tx_sge));
2333                 if (tx->tx_sge == NULL)
2334                         break;
2335
2336                 LIBCFS_CPT_ALLOC(tx->tx_rd, lnet_cpt_table(), ps->ps_cpt,
2337                                  offsetof(struct kib_rdma_desc,
2338                                           rd_frags[IBLND_MAX_RDMA_FRAGS]));
2339                 if (tx->tx_rd == NULL)
2340                         break;
2341         }
2342
2343         if (i == size) {
2344                 kiblnd_map_tx_pool(tpo);
2345                 *pp_po = pool;
2346                 return 0;
2347         }
2348
2349         ps->ps_pool_destroy(pool);
2350         return -ENOMEM;
2351 }
2352
2353 static void
2354 kiblnd_tx_init(struct kib_pool *pool, struct list_head *node)
2355 {
2356         struct kib_tx_poolset *tps = container_of(pool->po_owner,
2357                                                   struct kib_tx_poolset,
2358                                                   tps_poolset);
2359         struct kib_tx *tx  = list_entry(node, struct kib_tx, tx_list);
2360
2361         tx->tx_cookie = tps->tps_next_tx_cookie++;
2362 }
2363
2364 static void
2365 kiblnd_net_fini_pools(struct kib_net *net)
2366 {
2367         int     i;
2368
2369         cfs_cpt_for_each(i, lnet_cpt_table()) {
2370                 struct kib_tx_poolset *tps;
2371                 struct kib_fmr_poolset *fps;
2372
2373                 if (net->ibn_tx_ps != NULL) {
2374                         tps = net->ibn_tx_ps[i];
2375                         kiblnd_fini_poolset(&tps->tps_poolset);
2376                 }
2377
2378                 if (net->ibn_fmr_ps != NULL) {
2379                         fps = net->ibn_fmr_ps[i];
2380                         kiblnd_fini_fmr_poolset(fps);
2381                 }
2382         }
2383
2384         if (net->ibn_tx_ps != NULL) {
2385                 cfs_percpt_free(net->ibn_tx_ps);
2386                 net->ibn_tx_ps = NULL;
2387         }
2388
2389         if (net->ibn_fmr_ps != NULL) {
2390                 cfs_percpt_free(net->ibn_fmr_ps);
2391                 net->ibn_fmr_ps = NULL;
2392         }
2393 }
2394
2395 static int
2396 kiblnd_net_init_pools(struct kib_net *net, struct lnet_ni *ni, __u32 *cpts,
2397                       int ncpts)
2398 {
2399         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
2400 #ifdef HAVE_IB_GET_DMA_MR
2401         unsigned long   flags;
2402 #endif
2403         int             cpt;
2404         int             rc;
2405         int             i;
2406
2407         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
2408
2409 #ifdef HAVE_IB_GET_DMA_MR
2410         read_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2411         /*
2412          * if lnd_map_on_demand is zero then we have effectively disabled
2413          * FMR or FastReg and we're using global memory regions
2414          * exclusively.
2415          */
2416         if (!tunables->lnd_map_on_demand) {
2417                 read_unlock_irqrestore(&kiblnd_data.kib_global_lock,
2418                                            flags);
2419                 goto create_tx_pool;
2420         }
2421
2422         read_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2423 #endif
2424
2425         if (tunables->lnd_fmr_pool_size < tunables->lnd_ntx / 4) {
2426                 CERROR("Can't set fmr pool size (%d) < ntx / 4(%d)\n",
2427                        tunables->lnd_fmr_pool_size,
2428                        tunables->lnd_ntx / 4);
2429                 rc = -EINVAL;
2430                 goto failed;
2431         }
2432
2433         /* TX pool must be created later than FMR, see LU-2268
2434          * for details */
2435         LASSERT(net->ibn_tx_ps == NULL);
2436
2437         /* premapping can fail if ibd_nmr > 1, so we always create
2438          * FMR pool and map-on-demand if premapping failed */
2439
2440         net->ibn_fmr_ps = cfs_percpt_alloc(lnet_cpt_table(),
2441                                            sizeof(struct kib_fmr_poolset));
2442         if (net->ibn_fmr_ps == NULL) {
2443                 CERROR("Failed to allocate FMR pool array\n");
2444                 rc = -ENOMEM;
2445                 goto failed;
2446         }
2447
2448         for (i = 0; i < ncpts; i++) {
2449                 cpt = (cpts == NULL) ? i : cpts[i];
2450                 rc = kiblnd_init_fmr_poolset(net->ibn_fmr_ps[cpt], cpt, ncpts,
2451                                              net, tunables);
2452                 if (rc != 0) {
2453                         CERROR("Can't initialize FMR pool for CPT %d: %d\n",
2454                                cpt, rc);
2455                         goto failed;
2456                 }
2457         }
2458
2459         if (i > 0)
2460                 LASSERT(i == ncpts);
2461
2462 #ifdef HAVE_IB_GET_DMA_MR
2463  create_tx_pool:
2464 #endif
2465         net->ibn_tx_ps = cfs_percpt_alloc(lnet_cpt_table(),
2466                                           sizeof(struct kib_tx_poolset));
2467         if (net->ibn_tx_ps == NULL) {
2468                 CERROR("Failed to allocate tx pool array\n");
2469                 rc = -ENOMEM;
2470                 goto failed;
2471         }
2472
2473         for (i = 0; i < ncpts; i++) {
2474                 cpt = (cpts == NULL) ? i : cpts[i];
2475                 rc = kiblnd_init_poolset(&net->ibn_tx_ps[cpt]->tps_poolset,
2476                                          cpt, net, "TX",
2477                                          kiblnd_tx_pool_size(ni, ncpts),
2478                                          kiblnd_create_tx_pool,
2479                                          kiblnd_destroy_tx_pool,
2480                                          kiblnd_tx_init, NULL);
2481                 if (rc != 0) {
2482                         CERROR("Can't initialize TX pool for CPT %d: %d\n",
2483                                cpt, rc);
2484                         goto failed;
2485                 }
2486         }
2487
2488         return 0;
2489  failed:
2490         kiblnd_net_fini_pools(net);
2491         LASSERT(rc != 0);
2492         return rc;
2493 }
2494
2495 static int
2496 kiblnd_port_get_attr(struct kib_hca_dev *hdev)
2497 {
2498         struct ib_port_attr *port_attr;
2499         int rc;
2500         unsigned long flags;
2501         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2502
2503         LIBCFS_ALLOC(port_attr, sizeof(*port_attr));
2504         if (port_attr == NULL) {
2505                 CDEBUG(D_NETERROR, "Out of memory\n");
2506                 return -ENOMEM;
2507         }
2508
2509         rc = ib_query_port(hdev->ibh_ibdev, hdev->ibh_port, port_attr);
2510
2511         write_lock_irqsave(g_lock, flags);
2512
2513         if (rc == 0)
2514                 hdev->ibh_state = port_attr->state == IB_PORT_ACTIVE
2515                                  ? IBLND_DEV_PORT_ACTIVE
2516                                  : IBLND_DEV_PORT_DOWN;
2517
2518         write_unlock_irqrestore(g_lock, flags);
2519         LIBCFS_FREE(port_attr, sizeof(*port_attr));
2520
2521         if (rc != 0) {
2522                 CDEBUG(D_NETERROR, "Failed to query IB port: %d\n", rc);
2523                 return rc;
2524         }
2525         return 0;
2526 }
2527
2528 static inline void
2529 kiblnd_set_ni_fatal_on(struct kib_hca_dev *hdev, int val)
2530 {
2531         struct kib_net  *net;
2532
2533         /* for health check */
2534         list_for_each_entry(net, &hdev->ibh_dev->ibd_nets, ibn_list) {
2535                 if (val)
2536                         CDEBUG(D_NETERROR, "Fatal device error for NI %s\n",
2537                                         libcfs_nid2str(net->ibn_ni->ni_nid));
2538                 atomic_set(&net->ibn_ni->ni_fatal_error_on, val);
2539         }
2540 }
2541
2542 void
2543 kiblnd_event_handler(struct ib_event_handler *handler, struct ib_event *event)
2544 {
2545         rwlock_t *g_lock = &kiblnd_data.kib_global_lock;
2546         struct kib_hca_dev  *hdev;
2547         unsigned long flags;
2548
2549         hdev = container_of(handler, struct kib_hca_dev, ibh_event_handler);
2550
2551         write_lock_irqsave(g_lock, flags);
2552
2553         switch (event->event) {
2554         case IB_EVENT_DEVICE_FATAL:
2555                 CDEBUG(D_NET, "IB device fatal\n");
2556                 hdev->ibh_state = IBLND_DEV_FATAL;
2557                 kiblnd_set_ni_fatal_on(hdev, 1);
2558                 break;
2559         case IB_EVENT_PORT_ACTIVE:
2560                 CDEBUG(D_NET, "IB port active\n");
2561                 if (event->element.port_num == hdev->ibh_port) {
2562                         hdev->ibh_state = IBLND_DEV_PORT_ACTIVE;
2563                         kiblnd_set_ni_fatal_on(hdev, 0);
2564                 }
2565                 break;
2566         case IB_EVENT_PORT_ERR:
2567                 CDEBUG(D_NET, "IB port err\n");
2568                 if (event->element.port_num == hdev->ibh_port) {
2569                         hdev->ibh_state = IBLND_DEV_PORT_DOWN;
2570                         kiblnd_set_ni_fatal_on(hdev, 1);
2571                 }
2572                 break;
2573         default:
2574                 break;
2575         }
2576         write_unlock_irqrestore(g_lock, flags);
2577 }
2578
2579 static int
2580 kiblnd_hdev_get_attr(struct kib_hca_dev *hdev)
2581 {
2582         struct ib_device_attr *dev_attr;
2583         int rc = 0;
2584         int rc2 = 0;
2585
2586         /* It's safe to assume a HCA can handle a page size
2587          * matching that of the native system */
2588         hdev->ibh_page_shift = PAGE_SHIFT;
2589         hdev->ibh_page_size  = 1 << PAGE_SHIFT;
2590         hdev->ibh_page_mask  = ~((__u64)hdev->ibh_page_size - 1);
2591
2592 #ifndef HAVE_IB_DEVICE_ATTRS
2593         LIBCFS_ALLOC(dev_attr, sizeof(*dev_attr));
2594         if (dev_attr == NULL) {
2595                 CERROR("Out of memory\n");
2596                 return -ENOMEM;
2597         }
2598
2599         rc = ib_query_device(hdev->ibh_ibdev, dev_attr);
2600         if (rc != 0) {
2601                 CERROR("Failed to query IB device: %d\n", rc);
2602                 goto out_clean_attr;
2603         }
2604 #else
2605         dev_attr = &hdev->ibh_ibdev->attrs;
2606 #endif
2607
2608         hdev->ibh_mr_size = dev_attr->max_mr_size;
2609         hdev->ibh_max_qp_wr = dev_attr->max_qp_wr;
2610
2611         /* Setup device Memory Registration capabilities */
2612 #ifdef HAVE_FMR_POOL_API
2613 #ifdef HAVE_IB_DEVICE_OPS
2614         if (hdev->ibh_ibdev->ops.alloc_fmr &&
2615             hdev->ibh_ibdev->ops.dealloc_fmr &&
2616             hdev->ibh_ibdev->ops.map_phys_fmr &&
2617             hdev->ibh_ibdev->ops.unmap_fmr) {
2618 #else
2619         if (hdev->ibh_ibdev->alloc_fmr &&
2620             hdev->ibh_ibdev->dealloc_fmr &&
2621             hdev->ibh_ibdev->map_phys_fmr &&
2622             hdev->ibh_ibdev->unmap_fmr) {
2623 #endif
2624                 LCONSOLE_INFO("Using FMR for registration\n");
2625                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FMR_ENABLED;
2626         } else
2627 #endif /* HAVE_FMR_POOL_API */
2628         if (dev_attr->device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS) {
2629                 LCONSOLE_INFO("Using FastReg for registration\n");
2630                 hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_ENABLED;
2631 #ifndef HAVE_IB_ALLOC_FAST_REG_MR
2632 #ifdef IB_DEVICE_SG_GAPS_REG
2633                 if (dev_attr->device_cap_flags & IB_DEVICE_SG_GAPS_REG)
2634                         hdev->ibh_dev->ibd_dev_caps |= IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT;
2635 #endif
2636 #endif
2637         } else {
2638                 rc = -ENOSYS;
2639         }
2640
2641         rc2 = kiblnd_port_get_attr(hdev);
2642         if (rc2 != 0)
2643                 return rc2;
2644
2645         if (rc != 0)
2646                 rc = -EINVAL;
2647
2648 #ifndef HAVE_IB_DEVICE_ATTRS
2649 out_clean_attr:
2650         LIBCFS_FREE(dev_attr, sizeof(*dev_attr));
2651 #endif
2652
2653         if (rc == -ENOSYS)
2654                 CERROR("IB device does not support FMRs nor FastRegs, can't "
2655                        "register memory: %d\n", rc);
2656         else if (rc == -EINVAL)
2657                 CERROR("Invalid mr size: %#llx\n", hdev->ibh_mr_size);
2658         return rc;
2659 }
2660
2661 #ifdef HAVE_IB_GET_DMA_MR
2662 static void
2663 kiblnd_hdev_cleanup_mrs(struct kib_hca_dev *hdev)
2664 {
2665         if (hdev->ibh_mrs == NULL)
2666                 return;
2667
2668         ib_dereg_mr(hdev->ibh_mrs);
2669
2670         hdev->ibh_mrs = NULL;
2671 }
2672 #endif
2673
2674 void
2675 kiblnd_hdev_destroy(struct kib_hca_dev *hdev)
2676 {
2677         if (hdev->ibh_event_handler.device != NULL)
2678                 ib_unregister_event_handler(&hdev->ibh_event_handler);
2679
2680 #ifdef HAVE_IB_GET_DMA_MR
2681         kiblnd_hdev_cleanup_mrs(hdev);
2682 #endif
2683
2684         if (hdev->ibh_pd != NULL)
2685                 ib_dealloc_pd(hdev->ibh_pd);
2686
2687         if (hdev->ibh_cmid != NULL)
2688                 rdma_destroy_id(hdev->ibh_cmid);
2689
2690         LIBCFS_FREE(hdev, sizeof(*hdev));
2691 }
2692
2693 #ifdef HAVE_IB_GET_DMA_MR
2694 static int
2695 kiblnd_hdev_setup_mrs(struct kib_hca_dev *hdev)
2696 {
2697         struct ib_mr *mr;
2698         int           acflags = IB_ACCESS_LOCAL_WRITE |
2699                                 IB_ACCESS_REMOTE_WRITE;
2700
2701         mr = ib_get_dma_mr(hdev->ibh_pd, acflags);
2702         if (IS_ERR(mr)) {
2703                 CERROR("Failed ib_get_dma_mr: %ld\n", PTR_ERR(mr));
2704                 kiblnd_hdev_cleanup_mrs(hdev);
2705                 return PTR_ERR(mr);
2706         }
2707
2708         hdev->ibh_mrs = mr;
2709
2710         return 0;
2711 }
2712 #endif
2713
2714 static int
2715 kiblnd_dummy_callback(struct rdma_cm_id *cmid, struct rdma_cm_event *event)
2716 {       /* DUMMY */
2717         return 0;
2718 }
2719
2720 static int
2721 kiblnd_dev_need_failover(struct kib_dev *dev, struct net *ns)
2722 {
2723         struct rdma_cm_id  *cmid;
2724         struct sockaddr_in  srcaddr;
2725         struct sockaddr_in  dstaddr;
2726         int                 rc;
2727
2728         if (dev->ibd_hdev == NULL || /* initializing */
2729             dev->ibd_hdev->ibh_cmid == NULL || /* listener is dead */
2730             *kiblnd_tunables.kib_dev_failover > 1) /* debugging */
2731                 return 1;
2732
2733         /* XXX: it's UGLY, but I don't have better way to find
2734          * ib-bonding HCA failover because:
2735          *
2736          * a. no reliable CM event for HCA failover...
2737          * b. no OFED API to get ib_device for current net_device...
2738          *
2739          * We have only two choices at this point:
2740          *
2741          * a. rdma_bind_addr(), it will conflict with listener cmid
2742          * b. rdma_resolve_addr() to zero addr */
2743         cmid = kiblnd_rdma_create_id(ns, kiblnd_dummy_callback, dev,
2744                                      RDMA_PS_TCP, IB_QPT_RC);
2745         if (IS_ERR(cmid)) {
2746                 rc = PTR_ERR(cmid);
2747                 CERROR("Failed to create cmid for failover: %d\n", rc);
2748                 return rc;
2749         }
2750
2751         memset(&srcaddr, 0, sizeof(srcaddr));
2752         srcaddr.sin_family      = AF_INET;
2753         srcaddr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2754
2755         memset(&dstaddr, 0, sizeof(dstaddr));
2756         dstaddr.sin_family = AF_INET;
2757         rc = rdma_resolve_addr(cmid, (struct sockaddr *)&srcaddr,
2758                                (struct sockaddr *)&dstaddr, 1);
2759         if (rc != 0 || cmid->device == NULL) {
2760                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2761                        dev->ibd_ifname, &dev->ibd_ifip,
2762                        cmid->device, rc);
2763                 rdma_destroy_id(cmid);
2764                 return rc;
2765         }
2766
2767         rc = dev->ibd_hdev->ibh_ibdev != cmid->device; /* true for failover */
2768         rdma_destroy_id(cmid);
2769         return rc;
2770 }
2771
2772 int
2773 kiblnd_dev_failover(struct kib_dev *dev, struct net *ns)
2774 {
2775         LIST_HEAD(zombie_tpo);
2776         LIST_HEAD(zombie_ppo);
2777         LIST_HEAD(zombie_fpo);
2778         struct rdma_cm_id  *cmid  = NULL;
2779         struct kib_hca_dev *hdev  = NULL;
2780         struct kib_hca_dev *old;
2781         struct ib_pd       *pd;
2782         struct kib_net *net;
2783         struct sockaddr_in  addr;
2784         unsigned long       flags;
2785         int                 rc = 0;
2786         int                 i;
2787
2788         LASSERT (*kiblnd_tunables.kib_dev_failover > 1 ||
2789                  dev->ibd_can_failover ||
2790                  dev->ibd_hdev == NULL);
2791
2792         rc = kiblnd_dev_need_failover(dev, ns);
2793         if (rc <= 0)
2794                 goto out;
2795
2796         if (dev->ibd_hdev != NULL &&
2797             dev->ibd_hdev->ibh_cmid != NULL) {
2798                 /* XXX it's not good to close old listener at here,
2799                  * because we can fail to create new listener.
2800                  * But we have to close it now, otherwise rdma_bind_addr
2801                  * will return EADDRINUSE... How crap! */
2802                 write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2803
2804                 cmid = dev->ibd_hdev->ibh_cmid;
2805                 /* make next schedule of kiblnd_dev_need_failover()
2806                  * return 1 for me */
2807                 dev->ibd_hdev->ibh_cmid  = NULL;
2808                 write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2809
2810                 rdma_destroy_id(cmid);
2811         }
2812
2813         cmid = kiblnd_rdma_create_id(ns, kiblnd_cm_callback, dev, RDMA_PS_TCP,
2814                                      IB_QPT_RC);
2815         if (IS_ERR(cmid)) {
2816                 rc = PTR_ERR(cmid);
2817                 CERROR("Failed to create cmid for failover: %d\n", rc);
2818                 goto out;
2819         }
2820
2821         memset(&addr, 0, sizeof(addr));
2822         addr.sin_family      = AF_INET;
2823         addr.sin_addr.s_addr = (__force u32)htonl(dev->ibd_ifip);
2824         addr.sin_port        = htons(*kiblnd_tunables.kib_service);
2825
2826         /* Bind to failover device or port */
2827         rc = rdma_bind_addr(cmid, (struct sockaddr *)&addr);
2828         if (rc != 0 || cmid->device == NULL) {
2829                 CERROR("Failed to bind %s:%pI4h to device(%p): %d\n",
2830                        dev->ibd_ifname, &dev->ibd_ifip,
2831                        cmid->device, rc);
2832                 rdma_destroy_id(cmid);
2833                 goto out;
2834         }
2835
2836         LIBCFS_ALLOC(hdev, sizeof(*hdev));
2837         if (hdev == NULL) {
2838                 CERROR("Failed to allocate kib_hca_dev\n");
2839                 rdma_destroy_id(cmid);
2840                 rc = -ENOMEM;
2841                 goto out;
2842         }
2843
2844         atomic_set(&hdev->ibh_ref, 1);
2845         hdev->ibh_dev   = dev;
2846         hdev->ibh_cmid  = cmid;
2847         hdev->ibh_ibdev = cmid->device;
2848         hdev->ibh_port  = cmid->port_num;
2849
2850 #ifdef HAVE_IB_ALLOC_PD_2ARGS
2851         pd = ib_alloc_pd(cmid->device, 0);
2852 #else
2853         pd = ib_alloc_pd(cmid->device);
2854 #endif
2855         if (IS_ERR(pd)) {
2856                 rc = PTR_ERR(pd);
2857                 CERROR("Can't allocate PD: %d\n", rc);
2858                 goto out;
2859         }
2860
2861         hdev->ibh_pd = pd;
2862
2863         rc = rdma_listen(cmid, 0);
2864         if (rc != 0) {
2865                 CERROR("Can't start new listener: %d\n", rc);
2866                 goto out;
2867         }
2868
2869         rc = kiblnd_hdev_get_attr(hdev);
2870         if (rc != 0) {
2871                 CERROR("Can't get device attributes: %d\n", rc);
2872                 goto out;
2873         }
2874
2875 #ifdef HAVE_IB_GET_DMA_MR
2876         rc = kiblnd_hdev_setup_mrs(hdev);
2877         if (rc != 0) {
2878                 CERROR("Can't setup device: %d\n", rc);
2879                 goto out;
2880         }
2881 #endif
2882
2883         INIT_IB_EVENT_HANDLER(&hdev->ibh_event_handler,
2884                                 hdev->ibh_ibdev, kiblnd_event_handler);
2885         ib_register_event_handler(&hdev->ibh_event_handler);
2886
2887         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
2888
2889         old = dev->ibd_hdev;
2890         dev->ibd_hdev = hdev;   /* take over the refcount */
2891         hdev = old;
2892
2893         list_for_each_entry(net, &dev->ibd_nets, ibn_list) {
2894                 cfs_cpt_for_each(i, lnet_cpt_table()) {
2895                         kiblnd_fail_poolset(&net->ibn_tx_ps[i]->tps_poolset,
2896                                             &zombie_tpo);
2897
2898                         if (net->ibn_fmr_ps != NULL)
2899                                 kiblnd_fail_fmr_poolset(net->ibn_fmr_ps[i],
2900                                                         &zombie_fpo);
2901                 }
2902         }
2903
2904         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
2905  out:
2906         if (!list_empty(&zombie_tpo))
2907                 kiblnd_destroy_pool_list(&zombie_tpo);
2908         if (!list_empty(&zombie_ppo))
2909                 kiblnd_destroy_pool_list(&zombie_ppo);
2910         if (!list_empty(&zombie_fpo))
2911                 kiblnd_destroy_fmr_pool_list(&zombie_fpo);
2912         if (hdev != NULL)
2913                 kiblnd_hdev_decref(hdev);
2914
2915         if (rc != 0)
2916                 dev->ibd_failed_failover++;
2917         else
2918                 dev->ibd_failed_failover = 0;
2919
2920         return rc;
2921 }
2922
2923 void
2924 kiblnd_destroy_dev(struct kib_dev *dev)
2925 {
2926         LASSERT(dev->ibd_nnets == 0);
2927         LASSERT(list_empty(&dev->ibd_nets));
2928
2929         list_del(&dev->ibd_fail_list);
2930         list_del(&dev->ibd_list);
2931
2932         if (dev->ibd_hdev != NULL)
2933                 kiblnd_hdev_decref(dev->ibd_hdev);
2934
2935         LIBCFS_FREE(dev, sizeof(*dev));
2936 }
2937
2938 static void
2939 kiblnd_base_shutdown(void)
2940 {
2941         struct kib_sched_info   *sched;
2942         int                     i;
2943
2944         LASSERT(list_empty(&kiblnd_data.kib_devs));
2945
2946         CDEBUG(D_MALLOC, "before LND base cleanup: kmem %lld\n",
2947                libcfs_kmem_read());
2948
2949         switch (kiblnd_data.kib_init) {
2950         default:
2951                 LBUG();
2952
2953         case IBLND_INIT_ALL:
2954         case IBLND_INIT_DATA:
2955                 LASSERT (kiblnd_data.kib_peers != NULL);
2956                 for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++) {
2957                         LASSERT(list_empty(&kiblnd_data.kib_peers[i]));
2958                 }
2959                 LASSERT(list_empty(&kiblnd_data.kib_connd_zombies));
2960                 LASSERT(list_empty(&kiblnd_data.kib_connd_conns));
2961                 LASSERT(list_empty(&kiblnd_data.kib_reconn_list));
2962                 LASSERT(list_empty(&kiblnd_data.kib_reconn_wait));
2963
2964                 /* flag threads to terminate; wake and wait for them to die */
2965                 kiblnd_data.kib_shutdown = 1;
2966
2967                 /* NB: we really want to stop scheduler threads net by net
2968                  * instead of the whole module, this should be improved
2969                  * with dynamic configuration LNet */
2970                 cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds)
2971                         wake_up_all(&sched->ibs_waitq);
2972
2973                 wake_up_all(&kiblnd_data.kib_connd_waitq);
2974                 wake_up_all(&kiblnd_data.kib_failover_waitq);
2975
2976                 wait_var_event_warning(&kiblnd_data.kib_nthreads,
2977                                        !atomic_read(&kiblnd_data.kib_nthreads),
2978                                        "Waiting for %d threads to terminate\n",
2979                                        atomic_read(&kiblnd_data.kib_nthreads));
2980                 /* fall through */
2981
2982         case IBLND_INIT_NOTHING:
2983                 break;
2984         }
2985
2986         if (kiblnd_data.kib_peers)
2987                 CFS_FREE_PTR_ARRAY(kiblnd_data.kib_peers,
2988                                    kiblnd_data.kib_peer_hash_size);
2989
2990         if (kiblnd_data.kib_scheds != NULL)
2991                 cfs_percpt_free(kiblnd_data.kib_scheds);
2992
2993         CDEBUG(D_MALLOC, "after LND base cleanup: kmem %lld\n",
2994                libcfs_kmem_read());
2995
2996         kiblnd_data.kib_init = IBLND_INIT_NOTHING;
2997         module_put(THIS_MODULE);
2998 }
2999
3000 static void
3001 kiblnd_shutdown(struct lnet_ni *ni)
3002 {
3003         struct kib_net *net = ni->ni_data;
3004         rwlock_t     *g_lock = &kiblnd_data.kib_global_lock;
3005         unsigned long     flags;
3006
3007         LASSERT(kiblnd_data.kib_init == IBLND_INIT_ALL);
3008
3009         if (net == NULL)
3010                 goto out;
3011
3012         CDEBUG(D_MALLOC, "before LND net cleanup: kmem %lld\n",
3013                libcfs_kmem_read());
3014
3015         write_lock_irqsave(g_lock, flags);
3016         net->ibn_shutdown = 1;
3017         write_unlock_irqrestore(g_lock, flags);
3018
3019         switch (net->ibn_init) {
3020         default:
3021                 LBUG();
3022
3023         case IBLND_INIT_ALL:
3024                 /* nuke all existing peers within this net */
3025                 kiblnd_del_peer(ni, LNET_NID_ANY);
3026
3027                 /* Wait for all peer_ni state to clean up */
3028                 wait_var_event_warning(&net->ibn_npeers,
3029                                        atomic_read(&net->ibn_npeers) == 0,
3030                                        "%s: waiting for %d peers to disconnect\n",
3031                                        libcfs_nid2str(ni->ni_nid),
3032                                        atomic_read(&net->ibn_npeers));
3033
3034                 kiblnd_net_fini_pools(net);
3035
3036                 write_lock_irqsave(g_lock, flags);
3037                 LASSERT(net->ibn_dev->ibd_nnets > 0);
3038                 net->ibn_dev->ibd_nnets--;
3039                 list_del(&net->ibn_list);
3040                 write_unlock_irqrestore(g_lock, flags);
3041
3042                 /* fall through */
3043
3044         case IBLND_INIT_NOTHING:
3045                 LASSERT (atomic_read(&net->ibn_nconns) == 0);
3046
3047                 if (net->ibn_dev != NULL &&
3048                     net->ibn_dev->ibd_nnets == 0)
3049                         kiblnd_destroy_dev(net->ibn_dev);
3050
3051                 break;
3052         }
3053
3054         CDEBUG(D_MALLOC, "after LND net cleanup: kmem %lld\n",
3055                libcfs_kmem_read());
3056
3057         net->ibn_init = IBLND_INIT_NOTHING;
3058         ni->ni_data = NULL;
3059
3060         LIBCFS_FREE(net, sizeof(*net));
3061
3062 out:
3063         if (list_empty(&kiblnd_data.kib_devs))
3064                 kiblnd_base_shutdown();
3065 }
3066
3067 static int
3068 kiblnd_base_startup(struct net *ns)
3069 {
3070         struct kib_sched_info   *sched;
3071         int                     rc;
3072         int                     i;
3073
3074         LASSERT(kiblnd_data.kib_init == IBLND_INIT_NOTHING);
3075
3076         if (!try_module_get(THIS_MODULE))
3077                 goto failed;
3078
3079         memset(&kiblnd_data, 0, sizeof(kiblnd_data)); /* zero pointers, flags etc */
3080
3081         rwlock_init(&kiblnd_data.kib_global_lock);
3082
3083         INIT_LIST_HEAD(&kiblnd_data.kib_devs);
3084         INIT_LIST_HEAD(&kiblnd_data.kib_failed_devs);
3085
3086         kiblnd_data.kib_peer_hash_size = IBLND_PEER_HASH_SIZE;
3087         CFS_ALLOC_PTR_ARRAY(kiblnd_data.kib_peers,
3088                             kiblnd_data.kib_peer_hash_size);
3089         if (kiblnd_data.kib_peers == NULL)
3090                 goto failed;
3091
3092         for (i = 0; i < kiblnd_data.kib_peer_hash_size; i++)
3093                 INIT_LIST_HEAD(&kiblnd_data.kib_peers[i]);
3094
3095         spin_lock_init(&kiblnd_data.kib_connd_lock);
3096         INIT_LIST_HEAD(&kiblnd_data.kib_connd_conns);
3097         INIT_LIST_HEAD(&kiblnd_data.kib_connd_waits);
3098         INIT_LIST_HEAD(&kiblnd_data.kib_connd_zombies);
3099         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_list);
3100         INIT_LIST_HEAD(&kiblnd_data.kib_reconn_wait);
3101
3102         init_waitqueue_head(&kiblnd_data.kib_connd_waitq);
3103         init_waitqueue_head(&kiblnd_data.kib_failover_waitq);
3104
3105         kiblnd_data.kib_scheds = cfs_percpt_alloc(lnet_cpt_table(),
3106                                                   sizeof(*sched));
3107         if (kiblnd_data.kib_scheds == NULL)
3108                 goto failed;
3109
3110         cfs_percpt_for_each(sched, i, kiblnd_data.kib_scheds) {
3111                 int     nthrs;
3112
3113                 spin_lock_init(&sched->ibs_lock);
3114                 INIT_LIST_HEAD(&sched->ibs_conns);
3115                 init_waitqueue_head(&sched->ibs_waitq);
3116
3117                 nthrs = cfs_cpt_weight(lnet_cpt_table(), i);
3118                 if (*kiblnd_tunables.kib_nscheds > 0) {
3119                         nthrs = min(nthrs, *kiblnd_tunables.kib_nscheds);
3120                 } else {
3121                         /* max to half of CPUs, another half is reserved for
3122                          * upper layer modules */
3123                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3124                 }
3125
3126                 sched->ibs_nthreads_max = nthrs;
3127                 sched->ibs_cpt = i;
3128         }
3129
3130         kiblnd_data.kib_error_qpa.qp_state = IB_QPS_ERR;
3131
3132         /* lists/ptrs/locks initialised */
3133         kiblnd_data.kib_init = IBLND_INIT_DATA;
3134         /*****************************************************/
3135
3136         rc = kiblnd_thread_start(kiblnd_connd, NULL, "kiblnd_connd");
3137         if (rc != 0) {
3138                 CERROR("Can't spawn o2iblnd connd: %d\n", rc);
3139                 goto failed;
3140         }
3141
3142         if (*kiblnd_tunables.kib_dev_failover != 0)
3143                 rc = kiblnd_thread_start(kiblnd_failover_thread, ns,
3144                                          "kiblnd_failover");
3145
3146         if (rc != 0) {
3147                 CERROR("Can't spawn o2iblnd failover thread: %d\n", rc);
3148                 goto failed;
3149         }
3150
3151         /* flag everything initialised */
3152         kiblnd_data.kib_init = IBLND_INIT_ALL;
3153         /*****************************************************/
3154
3155         return 0;
3156
3157  failed:
3158         kiblnd_base_shutdown();
3159         return -ENETDOWN;
3160 }
3161
3162 static int
3163 kiblnd_start_schedulers(struct kib_sched_info *sched)
3164 {
3165         int     rc = 0;
3166         int     nthrs;
3167         int     i;
3168
3169         if (sched->ibs_nthreads == 0) {
3170                 if (*kiblnd_tunables.kib_nscheds > 0) {
3171                         nthrs = sched->ibs_nthreads_max;
3172                 } else {
3173                         nthrs = cfs_cpt_weight(lnet_cpt_table(),
3174                                                sched->ibs_cpt);
3175                         nthrs = min(max(IBLND_N_SCHED, nthrs >> 1), nthrs);
3176                         nthrs = min(IBLND_N_SCHED_HIGH, nthrs);
3177                 }
3178         } else {
3179                 LASSERT(sched->ibs_nthreads <= sched->ibs_nthreads_max);
3180                 /* increase one thread if there is new interface */
3181                 nthrs = (sched->ibs_nthreads < sched->ibs_nthreads_max);
3182         }
3183
3184         for (i = 0; i < nthrs; i++) {
3185                 long    id;
3186                 char    name[20];
3187                 id = KIB_THREAD_ID(sched->ibs_cpt, sched->ibs_nthreads + i);
3188                 snprintf(name, sizeof(name), "kiblnd_sd_%02ld_%02ld",
3189                          KIB_THREAD_CPT(id), KIB_THREAD_TID(id));
3190                 rc = kiblnd_thread_start(kiblnd_scheduler, (void *)id, name);
3191                 if (rc == 0)
3192                         continue;
3193
3194                 CERROR("Can't spawn thread %d for scheduler[%d]: %d\n",
3195                        sched->ibs_cpt, sched->ibs_nthreads + i, rc);
3196                 break;
3197         }
3198
3199         sched->ibs_nthreads += i;
3200         return rc;
3201 }
3202
3203 static int kiblnd_dev_start_threads(struct kib_dev *dev, bool newdev, u32 *cpts,
3204                                     int ncpts)
3205 {
3206         int     cpt;
3207         int     rc;
3208         int     i;
3209
3210         for (i = 0; i < ncpts; i++) {
3211                 struct kib_sched_info *sched;
3212
3213                 cpt = (cpts == NULL) ? i : cpts[i];
3214                 sched = kiblnd_data.kib_scheds[cpt];
3215
3216                 if (!newdev && sched->ibs_nthreads > 0)
3217                         continue;
3218
3219                 rc = kiblnd_start_schedulers(kiblnd_data.kib_scheds[cpt]);
3220                 if (rc != 0) {
3221                         CERROR("Failed to start scheduler threads for %s\n",
3222                                dev->ibd_ifname);
3223                         return rc;
3224                 }
3225         }
3226         return 0;
3227 }
3228
3229 static struct kib_dev *
3230 kiblnd_dev_search(char *ifname)
3231 {
3232         struct kib_dev *alias = NULL;
3233         struct kib_dev *dev;
3234         char            *colon;
3235         char            *colon2;
3236
3237         colon = strchr(ifname, ':');
3238         list_for_each_entry(dev, &kiblnd_data.kib_devs, ibd_list) {
3239                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3240                         return dev;
3241
3242                 if (alias != NULL)
3243                         continue;
3244
3245                 colon2 = strchr(dev->ibd_ifname, ':');
3246                 if (colon != NULL)
3247                         *colon = 0;
3248                 if (colon2 != NULL)
3249                         *colon2 = 0;
3250
3251                 if (strcmp(&dev->ibd_ifname[0], ifname) == 0)
3252                         alias = dev;
3253
3254                 if (colon != NULL)
3255                         *colon = ':';
3256                 if (colon2 != NULL)
3257                         *colon2 = ':';
3258         }
3259         return alias;
3260 }
3261
3262 static int
3263 kiblnd_startup(struct lnet_ni *ni)
3264 {
3265         char *ifname = NULL;
3266         struct lnet_inetdev *ifaces = NULL;
3267         struct kib_dev *ibdev = NULL;
3268         struct kib_net *net = NULL;
3269         unsigned long flags;
3270         int rc;
3271         int i;
3272         bool newdev;
3273
3274         LASSERT(ni->ni_net->net_lnd == &the_o2iblnd);
3275
3276         if (kiblnd_data.kib_init == IBLND_INIT_NOTHING) {
3277                 rc = kiblnd_base_startup(ni->ni_net_ns);
3278                 if (rc != 0)
3279                         return rc;
3280         }
3281
3282         LIBCFS_ALLOC(net, sizeof(*net));
3283         ni->ni_data = net;
3284         if (net == NULL) {
3285                 rc = -ENOMEM;
3286                 goto failed;
3287         }
3288
3289         net->ibn_ni = ni;
3290         net->ibn_incarnation = ktime_get_real_ns() / NSEC_PER_USEC;
3291
3292         kiblnd_tunables_setup(ni);
3293
3294         /*
3295          * ni_interfaces is only to support legacy pre Multi-Rail
3296          * tcp bonding for ksocklnd. Multi-Rail wants each secondary
3297          * IP to be treated as an unique 'struct ni' interfaces instead.
3298          */
3299         if (ni->ni_interfaces[0] != NULL) {
3300                 /* Use the IPoIB interface specified in 'networks=' */
3301                 if (ni->ni_interfaces[1] != NULL) {
3302                         CERROR("ko2iblnd: Multiple interfaces not supported\n");
3303                         rc = -EINVAL;
3304                         goto failed;
3305                 }
3306
3307                 ifname = ni->ni_interfaces[0];
3308         } else {
3309                 ifname = *kiblnd_tunables.kib_default_ipif;
3310         }
3311
3312         if (strlen(ifname) >= sizeof(ibdev->ibd_ifname)) {
3313                 CERROR("IPoIB interface name too long: %s\n", ifname);
3314                 rc = -E2BIG;
3315                 goto failed;
3316         }
3317
3318         rc = lnet_inet_enumerate(&ifaces, ni->ni_net_ns);
3319         if (rc < 0)
3320                 goto failed;
3321
3322         for (i = 0; i < rc; i++) {
3323                 if (strcmp(ifname, ifaces[i].li_name) == 0)
3324                         break;
3325         }
3326
3327         if (i == rc) {
3328                 CERROR("ko2iblnd: No matching interfaces\n");
3329                 rc = -ENOENT;
3330                 goto failed;
3331         }
3332
3333         ibdev = kiblnd_dev_search(ifname);
3334         newdev = ibdev == NULL;
3335         /* hmm...create kib_dev even for alias */
3336         if (ibdev == NULL || strcmp(&ibdev->ibd_ifname[0], ifname) != 0) {
3337                 LIBCFS_ALLOC(ibdev, sizeof(*ibdev));
3338                 if (!ibdev) {
3339                         rc = -ENOMEM;
3340                         goto failed;
3341                 }
3342
3343                 ibdev->ibd_ifip = ifaces[i].li_ipaddr;
3344                 strlcpy(ibdev->ibd_ifname, ifaces[i].li_name,
3345                         sizeof(ibdev->ibd_ifname));
3346                 ibdev->ibd_can_failover = !!(ifaces[i].li_flags & IFF_MASTER);
3347
3348                 INIT_LIST_HEAD(&ibdev->ibd_nets);
3349                 INIT_LIST_HEAD(&ibdev->ibd_list); /* not yet in kib_devs */
3350                 INIT_LIST_HEAD(&ibdev->ibd_fail_list);
3351
3352                 /* initialize the device */
3353                 rc = kiblnd_dev_failover(ibdev, ni->ni_net_ns);
3354                 if (rc) {
3355                         CERROR("ko2iblnd: Can't initialize device: rc = %d\n",
3356                                rc);
3357                         goto failed;
3358                 }
3359
3360                 list_add_tail(&ibdev->ibd_list, &kiblnd_data.kib_devs);
3361         }
3362
3363         net->ibn_dev = ibdev;
3364         ni->ni_nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), ibdev->ibd_ifip);
3365
3366         ni->ni_dev_cpt = ifaces[i].li_cpt;
3367
3368         rc = kiblnd_dev_start_threads(ibdev, newdev, ni->ni_cpts, ni->ni_ncpts);
3369         if (rc != 0)
3370                 goto failed;
3371
3372         rc = kiblnd_net_init_pools(net, ni, ni->ni_cpts, ni->ni_ncpts);
3373         if (rc != 0) {
3374                 CERROR("Failed to initialize NI pools: %d\n", rc);
3375                 goto failed;
3376         }
3377
3378         write_lock_irqsave(&kiblnd_data.kib_global_lock, flags);
3379         ibdev->ibd_nnets++;
3380         list_add_tail(&net->ibn_list, &ibdev->ibd_nets);
3381         /* for health check */
3382         if (ibdev->ibd_hdev->ibh_state == IBLND_DEV_PORT_DOWN)
3383                 kiblnd_set_ni_fatal_on(ibdev->ibd_hdev, 1);
3384         write_unlock_irqrestore(&kiblnd_data.kib_global_lock, flags);
3385
3386         net->ibn_init = IBLND_INIT_ALL;
3387
3388         return 0;
3389
3390 failed:
3391         if (net != NULL && net->ibn_dev == NULL && ibdev != NULL)
3392                 kiblnd_destroy_dev(ibdev);
3393
3394         kfree(ifaces);
3395         kiblnd_shutdown(ni);
3396
3397         CDEBUG(D_NET, "Configuration of device %s failed: rc = %d\n",
3398                ifname ? ifname : "", rc);
3399
3400         return -ENETDOWN;
3401 }
3402
3403 static const struct lnet_lnd the_o2iblnd = {
3404         .lnd_type       = O2IBLND,
3405         .lnd_startup    = kiblnd_startup,
3406         .lnd_shutdown   = kiblnd_shutdown,
3407         .lnd_ctl        = kiblnd_ctl,
3408         .lnd_send       = kiblnd_send,
3409         .lnd_recv       = kiblnd_recv,
3410 };
3411
3412 static void __exit ko2iblnd_exit(void)
3413 {
3414         lnet_unregister_lnd(&the_o2iblnd);
3415 }
3416
3417 static int __init ko2iblnd_init(void)
3418 {
3419         int rc;
3420
3421         BUILD_BUG_ON(sizeof(struct kib_msg) > IBLND_MSG_SIZE);
3422         BUILD_BUG_ON(offsetof(struct kib_msg,
3423                      ibm_u.get.ibgm_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3424                      IBLND_MSG_SIZE);
3425         BUILD_BUG_ON(offsetof(struct kib_msg,
3426                      ibm_u.putack.ibpam_rd.rd_frags[IBLND_MAX_RDMA_FRAGS]) >
3427                      IBLND_MSG_SIZE);
3428
3429         rc = kiblnd_tunables_init();
3430         if (rc != 0)
3431                 return rc;
3432
3433         lnet_register_lnd(&the_o2iblnd);
3434
3435         return 0;
3436 }
3437
3438 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3439 MODULE_DESCRIPTION("OpenIB gen2 LNet Network Driver");
3440 MODULE_VERSION("2.8.0");
3441 MODULE_LICENSE("GPL");
3442
3443 module_init(ko2iblnd_init);
3444 module_exit(ko2iblnd_exit);