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