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