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