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