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