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