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