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