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