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