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