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