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