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