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