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