Whamcloud - gitweb
* fix for 4580 vibnal NULL deref in arp callback
[fs/lustre-release.git] / lnet / klnds / viblnd / viblnd_cb.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Copyright (C) 2004 Cluster File Systems, Inc.
5  *   Author: Eric Barton <eric@bartonsoftware.com>
6  *   Author: Frank Zago <fzago@systemfabricworks.com>
7  *
8  *   This file is part of Lustre, http://www.lustre.org.
9  *
10  *   Lustre is free software; you can redistribute it and/or
11  *   modify it under the terms of version 2 of the GNU General Public
12  *   License as published by the Free Software Foundation.
13  *
14  *   Lustre is distributed in the hope that it will be useful,
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *   GNU General Public License for more details.
18  *
19  *   You should have received a copy of the GNU General Public License
20  *   along with Lustre; if not, write to the Free Software
21  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  */
24
25 #include "vibnal.h"
26
27 void
28 kibnal_tx_done (kib_tx_t *tx)
29 {
30         ptl_err_t        ptlrc = (tx->tx_status == 0) ? PTL_OK : PTL_FAIL;
31         int              i;
32
33         LASSERT (!in_interrupt());
34         LASSERT (!tx->tx_queued);               /* mustn't be queued for sending */
35         LASSERT (tx->tx_sending == 0);          /* mustn't be awaiting sent callback */
36         LASSERT (!tx->tx_waiting);              /* mustn't be awaiting peer response */
37
38 #if !IBNAL_WHOLE_MEM
39         switch (tx->tx_mapped) {
40         default:
41                 LBUG();
42
43         case KIB_TX_UNMAPPED:
44                 break;
45
46         case KIB_TX_MAPPED: {
47                 vv_return_t      vvrc;
48
49                 vvrc = vv_mem_region_destroy(kibnal_data.kib_hca,
50                                              tx->tx_md.md_handle);
51                 LASSERT (vvrc == vv_return_ok);
52                 tx->tx_mapped = KIB_TX_UNMAPPED;
53                 break;
54         }
55         }
56 #endif
57         for (i = 0; i < 2; i++) {
58                 /* tx may have up to 2 libmsgs to finalise */
59                 if (tx->tx_libmsg[i] == NULL)
60                         continue;
61
62                 lib_finalize (&kibnal_lib, NULL, tx->tx_libmsg[i], ptlrc);
63                 tx->tx_libmsg[i] = NULL;
64         }
65         
66         if (tx->tx_conn != NULL) {
67                 kibnal_conn_decref(tx->tx_conn);
68                 tx->tx_conn = NULL;
69         }
70
71         tx->tx_nwrq = 0;
72         tx->tx_status = 0;
73
74         spin_lock(&kibnal_data.kib_tx_lock);
75
76         if (tx->tx_isnblk) {
77                 list_add_tail (&tx->tx_list, &kibnal_data.kib_idle_nblk_txs);
78         } else {
79                 list_add_tail (&tx->tx_list, &kibnal_data.kib_idle_txs);
80                 wake_up (&kibnal_data.kib_idle_tx_waitq);
81         }
82
83         spin_unlock(&kibnal_data.kib_tx_lock);
84 }
85
86 kib_tx_t *
87 kibnal_get_idle_tx (int may_block) 
88 {
89         kib_tx_t      *tx = NULL;
90         ENTRY;
91         
92         for (;;) {
93                 spin_lock(&kibnal_data.kib_tx_lock);
94
95                 /* "normal" descriptor is free */
96                 if (!list_empty (&kibnal_data.kib_idle_txs)) {
97                         tx = list_entry (kibnal_data.kib_idle_txs.next,
98                                          kib_tx_t, tx_list);
99                         break;
100                 }
101
102                 if (!may_block) {
103                         /* may dip into reserve pool */
104                         if (list_empty (&kibnal_data.kib_idle_nblk_txs)) {
105                                 CERROR ("reserved tx desc pool exhausted\n");
106                                 break;
107                         }
108
109                         tx = list_entry (kibnal_data.kib_idle_nblk_txs.next,
110                                          kib_tx_t, tx_list);
111                         break;
112                 }
113
114                 /* block for idle tx */
115                 spin_unlock(&kibnal_data.kib_tx_lock);
116
117                 wait_event (kibnal_data.kib_idle_tx_waitq,
118                             !list_empty (&kibnal_data.kib_idle_txs) ||
119                             kibnal_data.kib_shutdown);
120         }
121
122         if (tx != NULL) {
123                 list_del (&tx->tx_list);
124
125                 /* Allocate a new completion cookie.  It might not be needed,
126                  * but we've got a lock right now and we're unlikely to
127                  * wrap... */
128                 tx->tx_cookie = kibnal_data.kib_next_tx_cookie++;
129 #if IBNAL_WHOLE_MEM
130                 LASSERT (tx->tx_mapped == KIB_TX_UNMAPPED);
131 #endif
132                 LASSERT (tx->tx_nwrq == 0);
133                 LASSERT (!tx->tx_queued);
134                 LASSERT (tx->tx_sending == 0);
135                 LASSERT (!tx->tx_waiting);
136                 LASSERT (tx->tx_status == 0);
137                 LASSERT (tx->tx_conn == NULL);
138                 LASSERT (tx->tx_libmsg[0] == NULL);
139                 LASSERT (tx->tx_libmsg[1] == NULL);
140         }
141
142         spin_unlock(&kibnal_data.kib_tx_lock);
143         
144         RETURN(tx);
145 }
146
147 int
148 kibnal_post_rx (kib_rx_t *rx, int credit)
149 {
150         kib_conn_t   *conn = rx->rx_conn;
151         int           rc = 0;
152         vv_return_t   vvrc;
153
154         LASSERT (!in_interrupt());
155         
156         rx->rx_gl = (vv_scatgat_t) {
157                 .v_address = KIBNAL_ADDR2SG(KIBNAL_RX_VADDR(rx)),
158                 .l_key     = KIBNAL_RX_LKEY(rx),
159                 .length    = IBNAL_MSG_SIZE,
160         };
161
162         rx->rx_wrq = (vv_wr_t) {
163                 .wr_id                   = kibnal_ptr2wreqid(rx, IBNAL_WID_RX),
164                 .completion_notification = 1,
165                 .scatgat_list            = &rx->rx_gl,
166                 .num_of_data_segments    = 1,
167                 .wr_type                 = vv_wr_receive,
168         };
169
170         LASSERT (conn->ibc_state >= IBNAL_CONN_INIT);
171         LASSERT (!rx->rx_posted);
172
173         CDEBUG(D_NET, "posting rx [%d %x "LPX64"]\n", 
174                rx->rx_wrq.scatgat_list->length,
175                rx->rx_wrq.scatgat_list->l_key,
176                KIBNAL_SG2ADDR(rx->rx_wrq.scatgat_list->v_address));
177
178         if (conn->ibc_state > IBNAL_CONN_ESTABLISHED) {
179                 /* No more posts for this rx; so lose its ref */
180                 kibnal_conn_decref(conn);
181                 return 0;
182         }
183         
184         rx->rx_posted = 1;
185
186         spin_lock(&conn->ibc_lock);
187         /* Serialise vv_post_receive; it's not re-entrant on the same QP */
188         vvrc = vv_post_receive(kibnal_data.kib_hca,
189                                conn->ibc_qp, &rx->rx_wrq);
190         spin_unlock(&conn->ibc_lock);
191
192         if (vvrc == 0) {
193                 if (credit) {
194                         spin_lock(&conn->ibc_lock);
195                         conn->ibc_outstanding_credits++;
196                         spin_unlock(&conn->ibc_lock);
197
198                         kibnal_check_sends(conn);
199                 }
200                 return 0;
201         }
202         
203         CERROR ("post rx -> "LPX64" failed %d\n", 
204                 conn->ibc_peer->ibp_nid, vvrc);
205         rc = -EIO;
206         kibnal_close_conn(rx->rx_conn, rc);
207         /* No more posts for this rx; so lose its ref */
208         kibnal_conn_decref(conn);
209         return rc;
210 }
211
212 int
213 kibnal_post_receives (kib_conn_t *conn)
214 {
215         int    i;
216         int    rc;
217
218         LASSERT (conn->ibc_state < IBNAL_CONN_ESTABLISHED);
219         LASSERT (conn->ibc_comms_error == 0);
220
221         for (i = 0; i < IBNAL_RX_MSGS; i++) {
222                 /* +1 ref for rx desc.  This ref remains until kibnal_post_rx
223                  * fails (i.e. actual failure or we're disconnecting) */
224                 kibnal_conn_addref(conn);
225                 rc = kibnal_post_rx (&conn->ibc_rxs[i], 0);
226                 if (rc != 0)
227                         return rc;
228         }
229
230         return 0;
231 }
232
233 kib_tx_t *
234 kibnal_find_waiting_tx_locked(kib_conn_t *conn, int txtype, __u64 cookie)
235 {
236         struct list_head   *tmp;
237         
238         list_for_each(tmp, &conn->ibc_active_txs) {
239                 kib_tx_t *tx = list_entry(tmp, kib_tx_t, tx_list);
240                 
241                 LASSERT (!tx->tx_queued);
242                 LASSERT (tx->tx_sending != 0 || tx->tx_waiting);
243
244                 if (tx->tx_cookie != cookie)
245                         continue;
246
247                 if (tx->tx_waiting &&
248                     tx->tx_msg->ibm_type == txtype)
249                         return tx;
250
251                 CWARN("Bad completion: %swaiting, type %x (wanted %x)\n",
252                       tx->tx_waiting ? "" : "NOT ",
253                       tx->tx_msg->ibm_type, txtype);
254         }
255         return NULL;
256 }
257
258 void
259 kibnal_handle_completion(kib_conn_t *conn, int txtype, int status, __u64 cookie)
260 {
261         kib_tx_t    *tx;
262         int          idle;
263
264         spin_lock(&conn->ibc_lock);
265
266         tx = kibnal_find_waiting_tx_locked(conn, txtype, cookie);
267         if (tx == NULL) {
268                 spin_unlock(&conn->ibc_lock);
269
270                 CWARN("Unmatched completion type %x cookie "LPX64
271                       " from "LPX64"\n",
272                       txtype, cookie, conn->ibc_peer->ibp_nid);
273                 kibnal_close_conn (conn, -EPROTO);
274                 return;
275         }
276
277         if (tx->tx_status == 0) {               /* success so far */
278                 if (status < 0) {               /* failed? */
279                         tx->tx_status = status;
280                 } else if (txtype == IBNAL_MSG_GET_REQ) { 
281                         /* XXX layering violation: set REPLY data length */
282                         LASSERT (tx->tx_libmsg[1] != NULL);
283                         LASSERT (tx->tx_libmsg[1]->ev.type == 
284                                  PTL_EVENT_REPLY_END);
285
286                         tx->tx_libmsg[1]->ev.mlength = status;
287                 }
288         }
289         
290         tx->tx_waiting = 0;
291
292         idle = !tx->tx_queued && (tx->tx_sending == 0);
293         if (idle)
294                 list_del(&tx->tx_list);
295
296         spin_unlock(&conn->ibc_lock);
297         
298         if (idle)
299                 kibnal_tx_done(tx);
300 }
301
302 void
303 kibnal_send_completion (kib_conn_t *conn, int type, int status, __u64 cookie) 
304 {
305         kib_tx_t    *tx = kibnal_get_idle_tx(0);
306         
307         if (tx == NULL) {
308                 CERROR("Can't get tx for completion %x for "LPX64"\n",
309                        type, conn->ibc_peer->ibp_nid);
310                 return;
311         }
312         
313         tx->tx_msg->ibm_u.completion.ibcm_status = status;
314         tx->tx_msg->ibm_u.completion.ibcm_cookie = cookie;
315         kibnal_init_tx_msg(tx, type, sizeof(kib_completion_msg_t));
316         
317         kibnal_queue_tx(tx, conn);
318 }
319
320 void
321 kibnal_handle_rx (kib_rx_t *rx)
322 {
323         kib_msg_t    *msg = rx->rx_msg;
324         kib_conn_t   *conn = rx->rx_conn;
325         int           credits = msg->ibm_credits;
326         kib_tx_t     *tx;
327         int           rc;
328
329         LASSERT (conn->ibc_state >= IBNAL_CONN_ESTABLISHED);
330
331         CDEBUG (D_NET, "Received %x[%d] from "LPX64"\n",
332                 msg->ibm_type, credits, conn->ibc_peer->ibp_nid);
333         
334         if (credits != 0) {
335                 /* Have I received credits that will let me send? */
336                 spin_lock(&conn->ibc_lock);
337                 conn->ibc_credits += credits;
338                 spin_unlock(&conn->ibc_lock);
339
340                 kibnal_check_sends(conn);
341         }
342
343         switch (msg->ibm_type) {
344         default:
345                 CERROR("Bad IBNAL message type %x from "LPX64"\n",
346                        msg->ibm_type, conn->ibc_peer->ibp_nid);
347                 break;
348
349         case IBNAL_MSG_NOOP:
350                 break;
351
352         case IBNAL_MSG_IMMEDIATE:
353                 lib_parse(&kibnal_lib, &msg->ibm_u.immediate.ibim_hdr, rx);
354                 break;
355                 
356         case IBNAL_MSG_PUT_REQ:
357                 rx->rx_responded = 0;
358                 lib_parse(&kibnal_lib, &msg->ibm_u.putreq.ibprm_hdr, rx);
359                 if (rx->rx_responded)
360                         break;
361
362                 /* I wasn't asked to transfer any payload data.  This happens
363                  * if the PUT didn't match, or got truncated. */
364                 kibnal_send_completion(rx->rx_conn, IBNAL_MSG_PUT_NAK, 0,
365                                        msg->ibm_u.putreq.ibprm_cookie);
366                 break;
367
368         case IBNAL_MSG_PUT_NAK:
369                 CWARN ("PUT_NACK from "LPX64"\n", conn->ibc_peer->ibp_nid);
370                 kibnal_handle_completion(conn, IBNAL_MSG_PUT_REQ, 
371                                          msg->ibm_u.completion.ibcm_status,
372                                          msg->ibm_u.completion.ibcm_cookie);
373                 break;
374
375         case IBNAL_MSG_PUT_ACK:
376                 spin_lock(&conn->ibc_lock);
377                 tx = kibnal_find_waiting_tx_locked(conn, IBNAL_MSG_PUT_REQ,
378                                                    msg->ibm_u.putack.ibpam_src_cookie);
379                 if (tx != NULL)
380                         list_del(&tx->tx_list);
381                 spin_unlock(&conn->ibc_lock);
382
383                 if (tx == NULL) {
384                         CERROR("Unmatched PUT_ACK from "LPX64"\n",
385                                conn->ibc_peer->ibp_nid);
386                         kibnal_close_conn(conn, -EPROTO);
387                         break;
388                 }
389
390                 LASSERT (tx->tx_waiting);
391                 /* CAVEAT EMPTOR: I could be racing with tx_complete, but...
392                  * (a) I can overwrite tx_msg since my peer has received it!
393                  * (b) tx_waiting set tells tx_complete() it's not done. */
394
395                 tx->tx_nwrq = 0;                /* overwrite PUT_REQ */
396
397                 rc = kibnal_init_rdma(tx, IBNAL_MSG_PUT_DONE, 
398                                       kibnal_rd_size(&msg->ibm_u.putack.ibpam_rd),
399                                       &msg->ibm_u.putack.ibpam_rd,
400                                       msg->ibm_u.putack.ibpam_dst_cookie);
401                 if (rc < 0)
402                         CERROR("Can't setup rdma for PUT to "LPX64": %d\n",
403                                conn->ibc_peer->ibp_nid, rc);
404
405                 spin_lock(&conn->ibc_lock);
406                 if (tx->tx_status == 0 && rc < 0)
407                         tx->tx_status = rc;
408                 tx->tx_waiting = 0;             /* clear waiting and queue atomically */
409                 kibnal_queue_tx_locked(tx, conn);
410                 spin_unlock(&conn->ibc_lock);
411                 break;
412                 
413         case IBNAL_MSG_PUT_DONE:
414                 kibnal_handle_completion(conn, IBNAL_MSG_PUT_ACK,
415                                          msg->ibm_u.completion.ibcm_status,
416                                          msg->ibm_u.completion.ibcm_cookie);
417                 break;
418
419         case IBNAL_MSG_GET_REQ:
420                 rx->rx_responded = 0;
421                 lib_parse(&kibnal_lib, &msg->ibm_u.get.ibgm_hdr, rx);
422                 if (rx->rx_responded)           /* I responded to the GET_REQ */
423                         break;
424                 /* NB GET didn't match (I'd have responded even with no payload
425                  * data) */
426                 kibnal_send_completion(rx->rx_conn, IBNAL_MSG_GET_DONE, -ENODATA,
427                                        msg->ibm_u.get.ibgm_cookie);
428                 break;
429
430         case IBNAL_MSG_GET_DONE:
431                 kibnal_handle_completion(conn, IBNAL_MSG_GET_REQ,
432                                          msg->ibm_u.completion.ibcm_status,
433                                          msg->ibm_u.completion.ibcm_cookie);
434                 break;
435         }
436
437         kibnal_post_rx(rx, 1);
438 }
439
440 void
441 kibnal_rx_complete (kib_rx_t *rx, vv_comp_status_t vvrc, int nob, __u64 rxseq)
442 {
443         kib_msg_t    *msg = rx->rx_msg;
444         kib_conn_t   *conn = rx->rx_conn;
445         unsigned long flags;
446         int           rc;
447
448         CDEBUG (D_NET, "rx %p conn %p\n", rx, conn);
449         LASSERT (rx->rx_posted);
450         rx->rx_posted = 0;
451
452         if (conn->ibc_state > IBNAL_CONN_ESTABLISHED)
453                 goto ignore;
454
455         if (vvrc != vv_comp_status_success) {
456                 CERROR("Rx from "LPX64" failed: %d\n", 
457                        conn->ibc_peer->ibp_nid, vvrc);
458                 goto failed;
459         }
460
461         rc = kibnal_unpack_msg(msg, nob);
462         if (rc != 0) {
463                 CERROR ("Error %d unpacking rx from "LPX64"\n",
464                         rc, conn->ibc_peer->ibp_nid);
465                 goto failed;
466         }
467
468         if (msg->ibm_srcnid != conn->ibc_peer->ibp_nid ||
469             msg->ibm_srcstamp != conn->ibc_incarnation ||
470             msg->ibm_dstnid != kibnal_lib.libnal_ni.ni_pid.nid ||
471             msg->ibm_dststamp != kibnal_data.kib_incarnation) {
472                 CERROR ("Stale rx from "LPX64"\n",
473                         conn->ibc_peer->ibp_nid);
474                 goto failed;
475         }
476
477         if (msg->ibm_seq != rxseq) {
478                 CERROR ("Out-of-sequence rx from "LPX64
479                         ": got "LPD64" but expected "LPD64"\n",
480                         conn->ibc_peer->ibp_nid, msg->ibm_seq, rxseq);
481                 goto failed;
482         }
483
484         /* racing with connection establishment/teardown! */
485
486         if (conn->ibc_state < IBNAL_CONN_ESTABLISHED) {
487                 write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
488                 /* must check holding global lock to eliminate race */
489                 if (conn->ibc_state < IBNAL_CONN_ESTABLISHED) {
490                         list_add_tail(&rx->rx_list, &conn->ibc_early_rxs);
491                         write_unlock_irqrestore(&kibnal_data.kib_global_lock, 
492                                                 flags);
493                         return;
494                 }
495                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, 
496                                         flags);
497         }
498         kibnal_handle_rx(rx);
499         return;
500         
501  failed:
502         CDEBUG(D_NET, "rx %p conn %p\n", rx, conn);
503         kibnal_close_conn(conn, -EIO);
504  ignore:
505         /* Don't re-post rx & drop its ref on conn */
506         kibnal_conn_decref(conn);
507 }
508
509 #if IBNAL_WHOLE_MEM
510 int
511 kibnal_append_rdfrag(kib_rdma_desc_t *rd, int active, struct page *page, 
512                      unsigned long page_offset, unsigned long len)
513 {
514         kib_rdma_frag_t *frag = &rd->rd_frags[rd->rd_nfrag];
515         vv_l_key_t       l_key;
516         vv_r_key_t       r_key;
517         __u64            addr;
518         __u64            frag_addr;
519         vv_mem_reg_h_t   mem_h;
520         vv_return_t      vvrc;
521
522         if (rd->rd_nfrag >= IBNAL_MAX_RDMA_FRAGS) {
523                 CERROR ("Too many RDMA fragments\n");
524                 return -EMSGSIZE;
525         }
526
527         /* Try to create an address that adapter-tavor will munge into a valid
528          * network address, given how it maps all phys mem into 1 region */
529         addr = kibnal_page2phys(page) + page_offset + PAGE_OFFSET;
530
531         vvrc = vv_get_gen_mr_attrib(kibnal_data.kib_hca, 
532                                     (void *)((unsigned long)addr),
533                                     len, &mem_h, &l_key, &r_key);
534         LASSERT (vvrc == vv_return_ok);
535
536         if (active) {
537                 if (rd->rd_nfrag == 0) {
538                         rd->rd_key = l_key;
539                 } else if (l_key != rd->rd_key) {
540                         CERROR ("> 1 key for single RDMA desc\n");
541                         return -EINVAL;
542                 }
543                 frag_addr = addr;
544         } else {
545                 if (rd->rd_nfrag == 0) {
546                         rd->rd_key = r_key;
547                 } else if (r_key != rd->rd_key) {
548                         CERROR ("> 1 key for single RDMA desc\n");
549                         return -EINVAL;
550                 }
551
552                 frag_addr = kibnal_addr2net(addr);
553         }
554
555         kibnal_rf_set(frag, frag_addr, len);
556
557         CDEBUG(D_NET,"map frag [%d][%d %x %08x%08x] "LPX64"\n", 
558                rd->rd_nfrag, frag->rf_nob, rd->rd_key, 
559                frag->rf_addr_hi, frag->rf_addr_lo, frag_addr);
560
561         rd->rd_nfrag++;
562         return 0;
563 }
564
565 struct page *
566 kibnal_kvaddr_to_page (unsigned long vaddr)
567 {
568         struct page *page;
569
570         if (vaddr >= VMALLOC_START &&
571             vaddr < VMALLOC_END) {
572                 page = vmalloc_to_page ((void *)vaddr);
573                 LASSERT (page != NULL);
574                 return page;
575         }
576 #if CONFIG_HIGHMEM
577         if (vaddr >= PKMAP_BASE &&
578             vaddr < (PKMAP_BASE + LAST_PKMAP * PAGE_SIZE)) {
579                 /* No highmem pages only used for bulk (kiov) I/O */
580                 CERROR("find page for address in highmem\n");
581                 LBUG();
582         }
583 #endif
584         page = virt_to_page (vaddr);
585         LASSERT (page != NULL);
586         return page;
587 }
588
589 int
590 kibnal_setup_rd_iov(kib_tx_t *tx, kib_rdma_desc_t *rd, 
591                     vv_access_con_bit_mask_t access,
592                     int niov, struct iovec *iov, int offset, int nob)
593                  
594 {
595         /* active if I'm sending */
596         int           active = ((access & vv_acc_r_mem_write) == 0);
597         int           fragnob;
598         int           rc;
599         unsigned long vaddr;
600         struct page  *page;
601         int           page_offset;
602
603         LASSERT (nob > 0);
604         LASSERT (niov > 0);
605         LASSERT ((rd != tx->tx_rd) == !active);
606
607         while (offset >= iov->iov_len) {
608                 offset -= iov->iov_len;
609                 niov--;
610                 iov++;
611                 LASSERT (niov > 0);
612         }
613
614         rd->rd_nfrag = 0;
615         do {
616                 LASSERT (niov > 0);
617
618                 vaddr = ((unsigned long)iov->iov_base) + offset;
619                 page_offset = vaddr & (PAGE_SIZE - 1);
620                 page = kibnal_kvaddr_to_page(vaddr);
621                 if (page == NULL) {
622                         CERROR ("Can't find page\n");
623                         return -EFAULT;
624                 }
625
626                 fragnob = min((int)(iov->iov_len - offset), nob);
627                 fragnob = min(fragnob, (int)PAGE_SIZE - page_offset);
628
629                 rc = kibnal_append_rdfrag(rd, active, page, 
630                                           page_offset, fragnob);
631                 if (rc != 0)
632                         return rc;
633
634                 if (offset + fragnob < iov->iov_len) {
635                         offset += fragnob;
636                 } else {
637                         offset = 0;
638                         iov++;
639                         niov--;
640                 }
641                 nob -= fragnob;
642         } while (nob > 0);
643         
644         return 0;
645 }
646
647 int
648 kibnal_setup_rd_kiov (kib_tx_t *tx, kib_rdma_desc_t *rd, 
649                       vv_access_con_bit_mask_t access,
650                       int nkiov, ptl_kiov_t *kiov, int offset, int nob)
651 {
652         /* active if I'm sending */
653         int            active = ((access & vv_acc_r_mem_write) == 0);
654         int            fragnob;
655         int            rc;
656
657         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
658
659         LASSERT (nob > 0);
660         LASSERT (nkiov > 0);
661         LASSERT ((rd != tx->tx_rd) == !active);
662
663         while (offset >= kiov->kiov_len) {
664                 offset -= kiov->kiov_len;
665                 nkiov--;
666                 kiov++;
667                 LASSERT (nkiov > 0);
668         }
669
670         rd->rd_nfrag = 0;
671         do {
672                 LASSERT (nkiov > 0);
673                 fragnob = min((int)(kiov->kiov_len - offset), nob);
674                 
675                 rc = kibnal_append_rdfrag(rd, active, kiov->kiov_page,
676                                           kiov->kiov_offset + offset,
677                                           fragnob);
678                 if (rc != 0)
679                         return rc;
680
681                 offset = 0;
682                 kiov++;
683                 nkiov--;
684                 nob -= fragnob;
685         } while (nob > 0);
686
687         return 0;
688 }
689 #else
690 int
691 kibnal_setup_rd_iov (kib_tx_t *tx, kib_rdma_desc_t *rd,
692                      vv_access_con_bit_mask_t access,
693                      int niov, struct iovec *iov, int offset, int nob)
694                  
695 {
696         /* active if I'm sending */
697         int         active = ((access & vv_acc_r_mem_write) == 0);
698         void       *vaddr;
699         vv_return_t vvrc;
700
701         LASSERT (nob > 0);
702         LASSERT (niov > 0);
703         LASSERT (tx->tx_mapped == KIB_TX_UNMAPPED);
704         LASSERT ((rd != tx->tx_rd) == !active);
705
706         while (offset >= iov->iov_len) {
707                 offset -= iov->iov_len;
708                 niov--;
709                 iov++;
710                 LASSERT (niov > 0);
711         }
712
713         if (nob > iov->iov_len - offset) {
714                 CERROR ("Can't map multiple vaddr fragments\n");
715                 return (-EMSGSIZE);
716         }
717
718         vaddr = (void *)(((unsigned long)iov->iov_base) + offset);
719         tx->tx_md.md_addr = (__u64)((unsigned long)vaddr);
720
721         vvrc = vv_mem_region_register(kibnal_data.kib_hca, vaddr, nob,
722                                       kibnal_data.kib_pd, access,
723                                       &tx->tx_md.md_handle, 
724                                       &tx->tx_md.md_lkey,
725                                       &tx->tx_md.md_rkey);
726         if (vvrc != vv_return_ok) {
727                 CERROR ("Can't map vaddr %p: %d\n", vaddr, vvrc);
728                 return -EFAULT;
729         }
730
731         tx->tx_mapped = KIB_TX_MAPPED;
732
733         rd->rd_key = active ? tx->tx_md.md_lkey : tx->tx_md.md_rkey;
734         rd->rd_nfrag = 1;
735         kibnal_rf_set(&rd->rd_frags[0], tx->tx_md.md_addr, nob);
736         
737         return (0);
738 }
739
740 int
741 kibnal_setup_rd_kiov (kib_tx_t *tx, kib_rdma_desc_t *rd,
742                       vv_access_con_bit_mask_t access,
743                       int nkiov, ptl_kiov_t *kiov, int offset, int nob)
744 {
745         /* active if I'm sending */
746         int            active = ((access & vv_acc_r_mem_write) == 0);
747         vv_return_t    vvrc;
748         vv_phy_list_t  phys_pages;
749         vv_phy_buf_t  *phys;
750         int            page_offset;
751         int            nphys;
752         int            resid;
753         int            phys_size;
754         int            rc;
755
756         CDEBUG(D_NET, "niov %d offset %d nob %d\n", nkiov, offset, nob);
757
758         LASSERT (nob > 0);
759         LASSERT (nkiov > 0);
760         LASSERT (tx->tx_mapped == KIB_TX_UNMAPPED);
761         LASSERT ((rd != tx->tx_rd) == !active);
762
763         while (offset >= kiov->kiov_len) {
764                 offset -= kiov->kiov_len;
765                 nkiov--;
766                 kiov++;
767                 LASSERT (nkiov > 0);
768         }
769
770         phys_size = nkiov * sizeof (*phys);
771         PORTAL_ALLOC(phys, phys_size);
772         if (phys == NULL) {
773                 CERROR ("Can't allocate tmp phys\n");
774                 return (-ENOMEM);
775         }
776
777         page_offset = kiov->kiov_offset + offset;
778
779         phys[0].start = kibnal_page2phys(kiov->kiov_page);
780         phys[0].size = PAGE_SIZE;
781
782         nphys = 1;
783         resid = nob - (kiov->kiov_len - offset);
784
785         while (resid > 0) {
786                 kiov++;
787                 nkiov--;
788                 LASSERT (nkiov > 0);
789
790                 if (kiov->kiov_offset != 0 ||
791                     ((resid > PAGE_SIZE) && 
792                      kiov->kiov_len < PAGE_SIZE)) {
793                         int i;
794                         /* Can't have gaps */
795                         CERROR ("Can't make payload contiguous in I/O VM:"
796                                 "page %d, offset %d, len %d \n", nphys, 
797                                 kiov->kiov_offset, kiov->kiov_len);
798
799                         for (i = -nphys; i < nkiov; i++)
800                                 CERROR("kiov[%d] %p +%d for %d\n",
801                                        i, kiov[i].kiov_page, 
802                                        kiov[i].kiov_offset, 
803                                        kiov[i].kiov_len);
804                         
805                         rc = -EINVAL;
806                         goto out;
807                 }
808
809                 LASSERT (nphys * sizeof (*phys) < phys_size);
810                 phys[nphys].start = kibnal_page2phys(kiov->kiov_page);
811                 phys[nphys].size = PAGE_SIZE;
812
813                 nphys++;
814                 resid -= PAGE_SIZE;
815         }
816
817 #if 0
818         CWARN ("nphys %d, nob %d, page_offset %d\n", nphys, nob, page_offset);
819         for (i = 0; i < nphys; i++)
820                 CWARN ("   [%d] "LPX64"\n", i, phys[i]);
821 #endif
822
823         vvrc = vv_phy_mem_region_register(kibnal_data.kib_hca,
824                                           &phys_pages,
825                                           IBNAL_RDMA_BASE,
826                                           nphys,
827                                           page_offset,
828                                           kibnal_data.kib_pd,
829                                           access,
830                                           &tx->tx_md.md_handle,
831                                           &tx->tx_md.md_addr,
832                                           &tx->tx_md.md_lkey,
833                                           &tx->tx_md.md_rkey);
834
835         if (vvrc != vv_return_ok) {
836                 CERROR ("Can't map phys: %d\n", vvrc);
837                 rc = -EFAULT;
838                 goto out;
839         }
840
841         CDEBUG(D_NET, "Mapped %d pages %d bytes @ offset %d: "
842                "lkey %x, rkey %x, addr "LPX64"\n",
843                nphys, nob, page_offset, tx->tx_md.md_lkey, tx->tx_md.md_rkey,
844                tx->tx_md.md_addr);
845
846         tx->tx_mapped = KIB_TX_MAPPED;
847         rc = 0;
848
849         rd->rd_key = active ? tx->tx_md.md_lkey : tx->tx_md.md_rkey;
850         rd->rd_nfrag = 1;
851         kibnal_rf_set(&rd->rd_frags[0], tx->tx_md.md_addr, nob);
852         
853  out:
854         PORTAL_FREE(phys, phys_size);
855         return (rc);
856 }
857 #endif
858
859 kib_conn_t *
860 kibnal_find_conn_locked (kib_peer_t *peer)
861 {
862         struct list_head *tmp;
863
864         /* just return the first connection */
865         list_for_each (tmp, &peer->ibp_conns) {
866                 return (list_entry(tmp, kib_conn_t, ibc_list));
867         }
868
869         return (NULL);
870 }
871
872 void
873 kibnal_check_sends (kib_conn_t *conn)
874 {
875         kib_tx_t       *tx;
876         vv_return_t     vvrc;                        
877         int             rc;
878         int             done;
879
880         /* Don't send anything until after the connection is established */
881         if (conn->ibc_state < IBNAL_CONN_ESTABLISHED) {
882                 CDEBUG(D_NET, LPX64"too soon\n", conn->ibc_peer->ibp_nid);
883                 return;
884         }
885         
886         spin_lock(&conn->ibc_lock);
887
888         LASSERT (conn->ibc_nsends_posted <= IBNAL_MSG_QUEUE_SIZE);
889
890         if (list_empty(&conn->ibc_tx_queue) &&
891             conn->ibc_outstanding_credits >= IBNAL_CREDIT_HIGHWATER) {
892                 spin_unlock(&conn->ibc_lock);
893                 
894                 tx = kibnal_get_idle_tx(0);     /* don't block */
895                 if (tx != NULL)
896                         kibnal_init_tx_msg(tx, IBNAL_MSG_NOOP, 0);
897
898                 spin_lock(&conn->ibc_lock);
899                 
900                 if (tx != NULL)
901                         kibnal_queue_tx_locked(tx, conn);
902         }
903
904         while (!list_empty (&conn->ibc_tx_queue)) {
905                 tx = list_entry (conn->ibc_tx_queue.next, kib_tx_t, tx_list);
906
907                 LASSERT (tx->tx_queued);
908                 /* We rely on this for QP sizing */
909                 LASSERT (tx->tx_nwrq > 0 && tx->tx_nwrq <= 1 + IBNAL_MAX_RDMA_FRAGS);
910
911                 LASSERT (conn->ibc_outstanding_credits >= 0);
912                 LASSERT (conn->ibc_outstanding_credits <= IBNAL_MSG_QUEUE_SIZE);
913                 LASSERT (conn->ibc_credits >= 0);
914                 LASSERT (conn->ibc_credits <= IBNAL_MSG_QUEUE_SIZE);
915
916                 if (conn->ibc_nsends_posted == IBNAL_MSG_QUEUE_SIZE) {
917                         CDEBUG(D_NET, LPX64": posted enough\n",
918                                conn->ibc_peer->ibp_nid);
919                         break;
920                 }
921                 
922                 if (conn->ibc_credits == 0) {   /* no credits */
923                         CDEBUG(D_NET, LPX64": no credits\n",
924                                conn->ibc_peer->ibp_nid);
925                         break;
926                 }
927                 
928                 if (conn->ibc_credits == 1 &&   /* last credit reserved for */
929                     conn->ibc_outstanding_credits == 0) { /* giving back credits */
930                         CDEBUG(D_NET, LPX64": not using last credit\n",
931                                conn->ibc_peer->ibp_nid);
932                         break;
933                 }
934                 
935                 list_del (&tx->tx_list);
936                 tx->tx_queued = 0;
937
938                 /* NB don't drop ibc_lock before bumping tx_sending */
939
940                 if (tx->tx_msg->ibm_type == IBNAL_MSG_NOOP &&
941                     (!list_empty(&conn->ibc_tx_queue) ||
942                      conn->ibc_outstanding_credits < IBNAL_CREDIT_HIGHWATER)) {
943                         /* redundant NOOP */
944                         spin_unlock(&conn->ibc_lock);
945                         kibnal_tx_done(tx);
946                         spin_lock(&conn->ibc_lock);
947                         CDEBUG(D_NET, LPX64": redundant noop\n",
948                                conn->ibc_peer->ibp_nid);
949                         continue;
950                 }
951
952                 kibnal_pack_msg(tx->tx_msg, conn->ibc_outstanding_credits,
953                                 conn->ibc_peer->ibp_nid, conn->ibc_incarnation,
954                                 conn->ibc_txseq);
955
956                 conn->ibc_txseq++;
957                 conn->ibc_outstanding_credits = 0;
958                 conn->ibc_nsends_posted++;
959                 conn->ibc_credits--;
960
961                 /* CAVEAT EMPTOR!  This tx could be the PUT_DONE of an RDMA
962                  * PUT.  If so, it was first queued here as a PUT_REQ, sent and
963                  * stashed on ibc_active_txs, matched by an incoming PUT_ACK,
964                  * and then re-queued here.  It's (just) possible that
965                  * tx_sending is non-zero if we've not done the tx_complete() from
966                  * the first send; hence the ++ rather than = below. */
967                 tx->tx_sending++;
968
969                 list_add (&tx->tx_list, &conn->ibc_active_txs);
970
971                 /* Keep holding ibc_lock while posting sends on this
972                  * connection; vv_post_send() isn't re-entrant on the same
973                  * QP!! */
974
975                 LASSERT (tx->tx_nwrq > 0);
976
977                 rc = -ECONNABORTED;
978                 vvrc = vv_return_ok;
979                 if (conn->ibc_state == IBNAL_CONN_ESTABLISHED) {
980                         tx->tx_status = 0;
981                         vvrc = vv_post_send_list(kibnal_data.kib_hca,
982                                                  conn->ibc_qp,
983                                                  tx->tx_nwrq,
984                                                  tx->tx_wrq,
985                                                  vv_operation_type_send_rc);
986                         rc = (vvrc == vv_return_ok) ? 0 : -EIO;
987                 }
988
989                 if (rc != 0) {
990                         /* NB credits are transferred in the actual
991                          * message, which can only be the last work item */
992                         conn->ibc_outstanding_credits += tx->tx_msg->ibm_credits;
993                         conn->ibc_credits++;
994                         conn->ibc_nsends_posted--;
995
996                         tx->tx_status = rc;
997                         tx->tx_waiting = 0;
998                         tx->tx_sending--;
999                         
1000                         done = (tx->tx_sending == 0);
1001                         if (done)
1002                                 list_del (&tx->tx_list);
1003                         
1004                         spin_unlock(&conn->ibc_lock);
1005                         
1006                         if (conn->ibc_state == IBNAL_CONN_ESTABLISHED)
1007                                 CERROR ("Error %d posting transmit to "LPX64"\n", 
1008                                         vvrc, conn->ibc_peer->ibp_nid);
1009                         else
1010                                 CDEBUG (D_NET, "Error %d posting transmit to "
1011                                         LPX64"\n", rc, conn->ibc_peer->ibp_nid);
1012
1013                         kibnal_close_conn (conn, rc);
1014
1015                         if (done)
1016                                 kibnal_tx_done (tx);
1017                         return;
1018                 }
1019         }
1020
1021         spin_unlock(&conn->ibc_lock);
1022 }
1023
1024 void
1025 kibnal_tx_complete (kib_tx_t *tx, vv_comp_status_t vvrc)
1026 {
1027         kib_conn_t   *conn = tx->tx_conn;
1028         int           failed = (vvrc != vv_comp_status_success);
1029         int           idle;
1030
1031         CDEBUG(D_NET, "tx %p conn %p sending %d nwrq %d vvrc %d\n", 
1032                tx, conn, tx->tx_sending, tx->tx_nwrq, vvrc);
1033
1034         LASSERT (tx->tx_sending > 0);
1035
1036         if (failed &&
1037             tx->tx_status == 0 &&
1038             conn->ibc_state == IBNAL_CONN_ESTABLISHED)
1039                 CERROR("tx -> "LPX64" type %x cookie "LPX64
1040                        "sending %d waiting %d: failed %d\n", 
1041                        conn->ibc_peer->ibp_nid, tx->tx_msg->ibm_type, 
1042                        tx->tx_cookie, tx->tx_sending, tx->tx_waiting, vvrc);
1043
1044         spin_lock(&conn->ibc_lock);
1045
1046         /* I could be racing with rdma completion.  Whoever makes 'tx' idle
1047          * gets to free it, which also drops its ref on 'conn'. */
1048
1049         tx->tx_sending--;
1050         conn->ibc_nsends_posted--;
1051
1052         if (failed) {
1053                 tx->tx_waiting = 0;
1054                 tx->tx_status = -EIO;
1055         }
1056         
1057         idle = (tx->tx_sending == 0) &&         /* This is the final callback */
1058                !tx->tx_waiting &&               /* Not waiting for peer */
1059                !tx->tx_queued;                  /* Not re-queued (PUT_DONE) */
1060         if (idle)
1061                 list_del(&tx->tx_list);
1062
1063         kibnal_conn_addref(conn);               /* 1 ref for me.... */
1064
1065         spin_unlock(&conn->ibc_lock);
1066
1067         if (idle)
1068                 kibnal_tx_done (tx);
1069
1070         if (failed)
1071                 kibnal_close_conn (conn, -EIO);
1072         else
1073                 kibnal_check_sends(conn);
1074
1075         kibnal_conn_decref(conn);               /* ...until here */
1076 }
1077
1078 void
1079 kibnal_init_tx_msg (kib_tx_t *tx, int type, int body_nob)
1080 {
1081         vv_scatgat_t *gl = &tx->tx_gl[tx->tx_nwrq];
1082         vv_wr_t      *wrq = &tx->tx_wrq[tx->tx_nwrq];
1083         int           nob = offsetof (kib_msg_t, ibm_u) + body_nob;
1084
1085         LASSERT (tx->tx_nwrq >= 0 && 
1086                  tx->tx_nwrq < (1 + IBNAL_MAX_RDMA_FRAGS));
1087         LASSERT (nob <= IBNAL_MSG_SIZE);
1088
1089         kibnal_init_msg(tx->tx_msg, type, body_nob);
1090
1091         *gl = (vv_scatgat_t) {
1092                 .v_address = KIBNAL_ADDR2SG(KIBNAL_TX_VADDR(tx)),
1093                 .l_key     = KIBNAL_TX_LKEY(tx),
1094                 .length    = nob,
1095         };
1096
1097         memset(wrq, 0, sizeof(*wrq));
1098
1099         wrq->wr_id = kibnal_ptr2wreqid(tx, IBNAL_WID_TX);
1100         wrq->wr_type = vv_wr_send;
1101         wrq->scatgat_list = gl;
1102         wrq->num_of_data_segments = 1;
1103         wrq->completion_notification = 1;
1104         wrq->type.send.solicited_event = 1;
1105         wrq->type.send.immidiate_data_indicator = 0;
1106         wrq->type.send.send_qp_type.rc_type.fance_indicator = 0;
1107         
1108         tx->tx_nwrq++;
1109 }
1110
1111 int
1112 kibnal_init_rdma (kib_tx_t *tx, int type, int nob,
1113                   kib_rdma_desc_t *dstrd, __u64 dstcookie)
1114 {
1115         /* CAVEAT EMPTOR: this 'consumes' the frags in 'dstrd' */
1116         int              resid = nob;
1117         kib_msg_t       *ibmsg = tx->tx_msg;
1118         kib_rdma_desc_t *srcrd = tx->tx_rd;
1119         kib_rdma_frag_t *srcfrag;
1120         int              srcidx;
1121         kib_rdma_frag_t *dstfrag;
1122         int              dstidx;
1123         vv_scatgat_t    *gl;
1124         vv_wr_t         *wrq;
1125         int              wrknob;
1126         int              rc;
1127
1128         /* Called by scheduler */
1129         LASSERT (!in_interrupt());
1130
1131         LASSERT (type == IBNAL_MSG_GET_DONE ||
1132                  type == IBNAL_MSG_PUT_DONE);
1133
1134         srcidx = dstidx = 0;
1135         srcfrag = &srcrd->rd_frags[0];
1136         dstfrag = &dstrd->rd_frags[0];
1137         rc = resid;
1138
1139         while (resid > 0) {
1140                 if (srcidx >= srcrd->rd_nfrag) {
1141                         CERROR("Src buffer exhausted: %d frags\n", srcidx);
1142                         rc = -EPROTO;
1143                         break;
1144                 }
1145                 
1146                 if (dstidx == dstrd->rd_nfrag) {
1147                         CERROR("Dst buffer exhausted: %d frags\n", dstidx);
1148                         rc = -EPROTO;
1149                         break;
1150                 }
1151
1152                 if (tx->tx_nwrq == IBNAL_MAX_RDMA_FRAGS) {
1153                         CERROR("RDMA too fragmented: %d/%d src %d/%d dst frags\n",
1154                                srcidx, srcrd->rd_nfrag,
1155                                dstidx, dstrd->rd_nfrag);
1156                         rc = -EMSGSIZE;
1157                         break;
1158                 }
1159
1160                 wrknob = MIN(MIN(srcfrag->rf_nob, dstfrag->rf_nob), resid);
1161
1162                 gl = &tx->tx_gl[tx->tx_nwrq];
1163                 gl->v_address = KIBNAL_ADDR2SG(kibnal_rf_addr(srcfrag));
1164                 gl->length    = wrknob;
1165                 gl->l_key     = srcrd->rd_key;
1166
1167                 wrq = &tx->tx_wrq[tx->tx_nwrq];
1168
1169                 wrq->wr_id = kibnal_ptr2wreqid(tx, IBNAL_WID_RDMA);
1170                 wrq->completion_notification = 0;
1171                 wrq->scatgat_list = gl;
1172                 wrq->num_of_data_segments = 1;
1173                 wrq->wr_type = vv_wr_rdma_write;
1174                 wrq->type.send.solicited_event = 0;
1175                 wrq->type.send.send_qp_type.rc_type.fance_indicator = 0;
1176                 wrq->type.send.send_qp_type.rc_type.r_addr = kibnal_rf_addr(dstfrag);
1177                 wrq->type.send.send_qp_type.rc_type.r_r_key = dstrd->rd_key;
1178
1179                 resid -= wrknob;
1180                 if (wrknob < srcfrag->rf_nob) {
1181                         kibnal_rf_set(srcfrag, 
1182                                       kibnal_rf_addr(srcfrag) + resid, 
1183                                       srcfrag->rf_nob - wrknob);
1184                 } else {
1185                         srcfrag++;
1186                         srcidx++;
1187                 }
1188                 
1189                 if (wrknob < dstfrag->rf_nob) {
1190                         kibnal_rf_set(dstfrag,
1191                                       kibnal_rf_addr(dstfrag) + resid,
1192                                       dstfrag->rf_nob - wrknob);
1193                 } else {
1194                         dstfrag++;
1195                         dstidx++;
1196                 }
1197                 
1198                 tx->tx_nwrq++;
1199         }
1200
1201         if (rc < 0)                             /* no RDMA if completing with failure */
1202                 tx->tx_nwrq = 0;
1203         
1204         ibmsg->ibm_u.completion.ibcm_status = rc;
1205         ibmsg->ibm_u.completion.ibcm_cookie = dstcookie;
1206         kibnal_init_tx_msg(tx, type, sizeof (kib_completion_msg_t));
1207
1208         return rc;
1209 }
1210
1211 void
1212 kibnal_queue_tx (kib_tx_t *tx, kib_conn_t *conn)
1213 {
1214         spin_lock(&conn->ibc_lock);
1215         kibnal_queue_tx_locked (tx, conn);
1216         spin_unlock(&conn->ibc_lock);
1217         
1218         kibnal_check_sends(conn);
1219 }
1220
1221 void
1222 kibnal_launch_tx (kib_tx_t *tx, ptl_nid_t nid)
1223 {
1224         kib_peer_t      *peer;
1225         kib_conn_t      *conn;
1226         unsigned long    flags;
1227         rwlock_t        *g_lock = &kibnal_data.kib_global_lock;
1228
1229         /* If I get here, I've committed to send, so I complete the tx with
1230          * failure on any problems */
1231         
1232         LASSERT (tx->tx_conn == NULL);          /* only set when assigned a conn */
1233         LASSERT (tx->tx_nwrq > 0);              /* work items have been set up */
1234
1235         read_lock_irqsave(g_lock, flags);
1236         
1237         peer = kibnal_find_peer_locked (nid);
1238         if (peer == NULL) {
1239                 read_unlock_irqrestore(g_lock, flags);
1240                 tx->tx_status = -EHOSTUNREACH;
1241                 tx->tx_waiting = 0;
1242                 kibnal_tx_done (tx);
1243                 return;
1244         }
1245
1246         conn = kibnal_find_conn_locked (peer);
1247         if (conn != NULL) {
1248                 kibnal_conn_addref(conn);       /* 1 ref for me... */
1249                 read_unlock_irqrestore(g_lock, flags);
1250                 
1251                 kibnal_queue_tx (tx, conn);
1252                 kibnal_conn_decref(conn);       /* ...to here */
1253                 return;
1254         }
1255         
1256         /* Making one or more connections; I'll need a write lock... */
1257         read_unlock(g_lock);
1258         write_lock(g_lock);
1259
1260         peer = kibnal_find_peer_locked (nid);
1261         if (peer == NULL) {
1262                 write_unlock_irqrestore(g_lock, flags);
1263                 tx->tx_status = -EHOSTUNREACH;
1264                 tx->tx_waiting = 0;
1265                 kibnal_tx_done (tx);
1266                 return;
1267         }
1268
1269         conn = kibnal_find_conn_locked (peer);
1270         if (conn != NULL) {
1271                 /* Connection exists; queue message on it */
1272                 kibnal_conn_addref(conn);       /* 1 ref for me... */
1273                 write_unlock_irqrestore(g_lock, flags);
1274                 
1275                 kibnal_queue_tx (tx, conn);
1276                 kibnal_conn_decref(conn);       /* ...until here */
1277                 return;
1278         }
1279
1280         if (peer->ibp_connecting == 0) {
1281                 if (!time_after_eq(jiffies, peer->ibp_reconnect_time)) {
1282                         write_unlock_irqrestore(g_lock, flags);
1283                         tx->tx_status = -EHOSTUNREACH;
1284                         tx->tx_waiting = 0;
1285                         kibnal_tx_done (tx);
1286                         return;
1287                 }
1288         
1289                 peer->ibp_connecting = 1;
1290                 kibnal_peer_addref(peer); /* extra ref for connd */
1291         
1292                 spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
1293         
1294                 list_add_tail (&peer->ibp_connd_list,
1295                                &kibnal_data.kib_connd_peers);
1296                 wake_up (&kibnal_data.kib_connd_waitq);
1297         
1298                 spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
1299         }
1300         
1301         /* A connection is being established; queue the message... */
1302         list_add_tail (&tx->tx_list, &peer->ibp_tx_queue);
1303
1304         write_unlock_irqrestore(g_lock, flags);
1305 }
1306
1307 int
1308 kibnal_dist(lib_nal_t *nal, ptl_nid_t nid, unsigned long *dist)
1309 {
1310         /* I would guess that if kibnal_get_peer (nid) == NULL,
1311            and we're not routing, then 'nid' is very distant :) */
1312         if ( nal->libnal_ni.ni_pid.nid == nid ) {
1313                 *dist = 0;
1314         } else {
1315                 *dist = 1;
1316         }
1317
1318         return 0;
1319 }
1320
1321 ptl_err_t
1322 kibnal_sendmsg(lib_nal_t    *nal, 
1323                void         *private,
1324                lib_msg_t    *libmsg,
1325                ptl_hdr_t    *hdr, 
1326                int           type, 
1327                ptl_nid_t     nid, 
1328                ptl_pid_t     pid,
1329                unsigned int  payload_niov, 
1330                struct iovec *payload_iov, 
1331                ptl_kiov_t   *payload_kiov,
1332                int           payload_offset,
1333                int           payload_nob)
1334 {
1335         kib_msg_t  *ibmsg;
1336         kib_tx_t   *tx;
1337         int         nob;
1338         int         rc;
1339         int         n;
1340
1341         /* NB 'private' is different depending on what we're sending.... */
1342
1343         CDEBUG(D_NET, "sending %d bytes in %d frags to nid:"LPX64
1344                " pid %d\n", payload_nob, payload_niov, nid , pid);
1345
1346         LASSERT (payload_nob == 0 || payload_niov > 0);
1347         LASSERT (payload_niov <= PTL_MD_MAX_IOV);
1348
1349         /* Thread context */
1350         LASSERT (!in_interrupt());
1351         /* payload is either all vaddrs or all pages */
1352         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1353
1354         switch (type) {
1355         default:
1356                 LBUG();
1357                 return (PTL_FAIL);
1358                 
1359         case PTL_MSG_REPLY: {
1360                 /* reply's 'private' is the incoming receive */
1361                 kib_rx_t *rx = private;
1362
1363                 LASSERT(rx != NULL);
1364
1365                 if (rx->rx_msg->ibm_type == IBNAL_MSG_IMMEDIATE) {
1366                         /* RDMA not expected */
1367                         nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1368                         if (nob > IBNAL_MSG_SIZE) {
1369                                 CERROR("REPLY for "LPX64" too big (RDMA not requested):"
1370                                        "%d (max for message is %d)\n", 
1371                                        nid, payload_nob, IBNAL_MSG_SIZE);
1372                                 CERROR("Can't REPLY IMMEDIATE %d to "LPX64"\n",
1373                                        nob, nid);
1374                                 return PTL_FAIL;
1375                         }
1376                         break;
1377                 }
1378
1379                 /* Incoming message consistent with RDMA? */
1380                 if (rx->rx_msg->ibm_type != IBNAL_MSG_GET_REQ) {
1381                         CERROR("REPLY to "LPX64" bad msg type %x!!!\n",
1382                                nid, rx->rx_msg->ibm_type);
1383                         return PTL_FAIL;
1384                 }
1385
1386                 /* NB rx_complete() will send GET_NAK when I return to it from
1387                  * here, unless I set rx_responded! */
1388
1389                 tx = kibnal_get_idle_tx(0);
1390                 if (tx == NULL) {
1391                         CERROR("Can't get tx for REPLY to "LPX64"\n", nid);
1392                         return PTL_FAIL;
1393                 }
1394
1395                 if (payload_nob == 0)
1396                         rc = 0;
1397                 else if (payload_kiov == NULL)
1398                         rc = kibnal_setup_rd_iov(tx, tx->tx_rd, 0, 
1399                                                  payload_niov, payload_iov, 
1400                                                  payload_offset, payload_nob);
1401                 else
1402                         rc = kibnal_setup_rd_kiov(tx, tx->tx_rd, 0,
1403                                                   payload_niov, payload_kiov,
1404                                                   payload_offset, payload_nob);
1405                 if (rc != 0) {
1406                         CERROR("Can't setup GET src for "LPX64": %d\n", nid, rc);
1407                         kibnal_tx_done(tx);
1408                         return PTL_FAIL;
1409                 }
1410                 
1411                 rc = kibnal_init_rdma(tx, IBNAL_MSG_GET_DONE, payload_nob,
1412                                       &rx->rx_msg->ibm_u.get.ibgm_rd,
1413                                       rx->rx_msg->ibm_u.get.ibgm_cookie);
1414                 if (rc < 0) {
1415                         CERROR("Can't setup rdma for GET from "LPX64": %d\n", 
1416                                nid, rc);
1417                 } else if (rc == 0) {
1418                         /* No RDMA: local completion may happen now! */
1419                         lib_finalize (&kibnal_lib, NULL, libmsg, PTL_OK);
1420                 } else {
1421                         /* RDMA: lib_finalize(libmsg) when it completes */
1422                         tx->tx_libmsg[0] = libmsg;
1423                 }
1424
1425                 kibnal_queue_tx(tx, rx->rx_conn);
1426                 rx->rx_responded = 1;
1427                 return (rc >= 0) ? PTL_OK : PTL_FAIL;
1428         }
1429
1430         case PTL_MSG_GET:
1431                 /* will the REPLY message be small enough not to need RDMA? */
1432                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[libmsg->md->length]);
1433                 if (nob <= IBNAL_MSG_SIZE)
1434                         break;
1435
1436                 tx = kibnal_get_idle_tx(1);     /* may block; caller is an app thread */
1437                 LASSERT (tx != NULL);
1438
1439                 ibmsg = tx->tx_msg;
1440                 ibmsg->ibm_u.get.ibgm_hdr = *hdr;
1441                 ibmsg->ibm_u.get.ibgm_cookie = tx->tx_cookie;
1442
1443                 if ((libmsg->md->options & PTL_MD_KIOV) == 0)
1444                         rc = kibnal_setup_rd_iov(tx, &ibmsg->ibm_u.get.ibgm_rd,
1445                                                  vv_acc_r_mem_write,
1446                                                  libmsg->md->md_niov,
1447                                                  libmsg->md->md_iov.iov,
1448                                                  0, libmsg->md->length);
1449                 else
1450                         rc = kibnal_setup_rd_kiov(tx, &ibmsg->ibm_u.get.ibgm_rd,
1451                                                   vv_acc_r_mem_write,
1452                                                   libmsg->md->md_niov,
1453                                                   libmsg->md->md_iov.kiov,
1454                                                   0, libmsg->md->length);
1455                 if (rc != 0) {
1456                         CERROR("Can't setup GET sink for "LPX64": %d\n", nid, rc);
1457                         kibnal_tx_done(tx);
1458                         return PTL_FAIL;
1459                 }
1460
1461                 n = ibmsg->ibm_u.get.ibgm_rd.rd_nfrag;
1462                 nob = offsetof(kib_get_msg_t, ibgm_rd.rd_frags[n]);
1463                 kibnal_init_tx_msg(tx, IBNAL_MSG_GET_REQ, nob);
1464
1465                 tx->tx_libmsg[1] = lib_create_reply_msg(&kibnal_lib, nid, libmsg);
1466                 if (tx->tx_libmsg[1] == NULL) {
1467                         CERROR("Can't create reply for GET -> "LPX64"\n", nid);
1468                         kibnal_tx_done(tx);
1469                         return PTL_FAIL;
1470                 }
1471
1472                 tx->tx_libmsg[0] = libmsg;      /* finalise libmsg[0,1] on completion */
1473                 tx->tx_waiting = 1;             /* waiting for GET_DONE */
1474                 kibnal_launch_tx(tx, nid);
1475                 return PTL_OK;
1476
1477         case PTL_MSG_ACK:
1478                 LASSERT (payload_nob == 0);
1479                 break;
1480
1481         case PTL_MSG_PUT:
1482                 /* Is the payload small enough not to need RDMA? */
1483                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob]);
1484                 if (nob <= IBNAL_MSG_SIZE)
1485                         break;
1486
1487                 tx = kibnal_get_idle_tx(1);     /* may block: caller is app thread */
1488                 LASSERT (tx != NULL);
1489
1490                 if (payload_kiov == NULL)
1491                         rc = kibnal_setup_rd_iov(tx, tx->tx_rd, 0,
1492                                                  payload_niov, payload_iov,
1493                                                  payload_offset, payload_nob);
1494                 else
1495                         rc = kibnal_setup_rd_kiov(tx, tx->tx_rd, 0,
1496                                                   payload_niov, payload_kiov,
1497                                                   payload_offset, payload_nob);
1498                 if (rc != 0) {
1499                         CERROR("Can't setup PUT src for "LPX64": %d\n", nid, rc);
1500                         kibnal_tx_done(tx);
1501                         return PTL_FAIL;
1502                 }
1503
1504                 ibmsg = tx->tx_msg;
1505                 ibmsg->ibm_u.putreq.ibprm_hdr = *hdr;
1506                 ibmsg->ibm_u.putreq.ibprm_cookie = tx->tx_cookie;
1507                 kibnal_init_tx_msg(tx, IBNAL_MSG_PUT_REQ, sizeof(kib_putreq_msg_t));
1508
1509                 tx->tx_libmsg[0] = libmsg;      /* finalise libmsg on completion */
1510                 tx->tx_waiting = 1;             /* waiting for PUT_{ACK,NAK} */
1511                 kibnal_launch_tx(tx, nid);
1512                 return PTL_OK;
1513         }
1514
1515         LASSERT (offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[payload_nob])
1516                  <= IBNAL_MSG_SIZE);
1517
1518         tx = kibnal_get_idle_tx(!(type == PTL_MSG_ACK ||
1519                                   type == PTL_MSG_REPLY));
1520         if (tx == NULL) {
1521                 CERROR ("Can't send %d to "LPX64": tx descs exhausted\n", type, nid);
1522                 return PTL_NO_SPACE;
1523         }
1524
1525         ibmsg = tx->tx_msg;
1526         ibmsg->ibm_u.immediate.ibim_hdr = *hdr;
1527
1528         if (payload_nob > 0) {
1529                 if (payload_kiov != NULL)
1530                         lib_copy_kiov2buf(ibmsg->ibm_u.immediate.ibim_payload,
1531                                           payload_niov, payload_kiov,
1532                                           payload_offset, payload_nob);
1533                 else
1534                         lib_copy_iov2buf(ibmsg->ibm_u.immediate.ibim_payload,
1535                                          payload_niov, payload_iov,
1536                                          payload_offset, payload_nob);
1537         }
1538
1539         nob = offsetof(kib_immediate_msg_t, ibim_payload[payload_nob]);
1540         kibnal_init_tx_msg (tx, IBNAL_MSG_IMMEDIATE, nob);
1541
1542         tx->tx_libmsg[0] = libmsg;              /* finalise libmsg on completion */
1543         kibnal_launch_tx(tx, nid);
1544         return PTL_OK;
1545 }
1546
1547 ptl_err_t
1548 kibnal_send (lib_nal_t *nal, void *private, lib_msg_t *cookie,
1549                ptl_hdr_t *hdr, int type, ptl_nid_t nid, ptl_pid_t pid,
1550                unsigned int payload_niov, struct iovec *payload_iov,
1551                size_t payload_offset, size_t payload_len)
1552 {
1553         CDEBUG(D_NET, "  pid = %d, nid="LPU64"\n",
1554                pid, nid);
1555         return (kibnal_sendmsg(nal, private, cookie,
1556                                hdr, type, nid, pid,
1557                                payload_niov, payload_iov, NULL,
1558                                payload_offset, payload_len));
1559 }
1560
1561 ptl_err_t
1562 kibnal_send_pages (lib_nal_t *nal, void *private, lib_msg_t *cookie, 
1563                      ptl_hdr_t *hdr, int type, ptl_nid_t nid, ptl_pid_t pid,
1564                      unsigned int payload_niov, ptl_kiov_t *payload_kiov, 
1565                      size_t payload_offset, size_t payload_len)
1566 {
1567         return (kibnal_sendmsg(nal, private, cookie,
1568                                hdr, type, nid, pid,
1569                                payload_niov, NULL, payload_kiov,
1570                                payload_offset, payload_len));
1571 }
1572
1573 ptl_err_t
1574 kibnal_recvmsg (lib_nal_t *nal, void *private, lib_msg_t *libmsg,
1575                  unsigned int niov, struct iovec *iov, ptl_kiov_t *kiov,
1576                  size_t offset, int mlen, int rlen)
1577 {
1578         kib_rx_t    *rx = private;
1579         kib_msg_t   *rxmsg = rx->rx_msg;
1580         kib_conn_t  *conn = rx->rx_conn;
1581         kib_tx_t    *tx;
1582         kib_msg_t   *txmsg;
1583         int          nob;
1584         int          rc;
1585         int          n;
1586         
1587         LASSERT (mlen <= rlen);
1588         LASSERT (mlen >= 0);
1589         LASSERT (!in_interrupt());
1590         /* Either all pages or all vaddrs */
1591         LASSERT (!(kiov != NULL && iov != NULL));
1592
1593         switch (rxmsg->ibm_type) {
1594         default:
1595                 LBUG();
1596                 
1597         case IBNAL_MSG_IMMEDIATE:
1598                 nob = offsetof(kib_msg_t, ibm_u.immediate.ibim_payload[rlen]);
1599                 if (nob > IBNAL_MSG_SIZE) {
1600                         CERROR ("Immediate message from "LPX64" too big: %d\n",
1601                                 rxmsg->ibm_u.immediate.ibim_hdr.src_nid, rlen);
1602                         return (PTL_FAIL);
1603                 }
1604
1605                 if (kiov != NULL)
1606                         lib_copy_buf2kiov(niov, kiov, offset,
1607                                           rxmsg->ibm_u.immediate.ibim_payload,
1608                                           mlen);
1609                 else
1610                         lib_copy_buf2iov(niov, iov, offset,
1611                                          rxmsg->ibm_u.immediate.ibim_payload,
1612                                          mlen);
1613
1614                 lib_finalize (nal, NULL, libmsg, PTL_OK);
1615                 return (PTL_OK);
1616
1617         case IBNAL_MSG_PUT_REQ:
1618                 /* NB rx_complete() will send PUT_NAK when I return to it from
1619                  * here, unless I set rx_responded!  */
1620
1621                 if (mlen == 0) { /* No payload to RDMA */
1622                         lib_finalize(nal, NULL, libmsg, PTL_OK);
1623                         return PTL_OK;
1624                 }
1625
1626                 tx = kibnal_get_idle_tx(0);
1627                 if (tx == NULL) {
1628                         CERROR("Can't allocate tx for "LPX64"\n",
1629                                conn->ibc_peer->ibp_nid);
1630                         return PTL_FAIL;
1631                 }
1632
1633                 txmsg = tx->tx_msg;
1634                 if (kiov == NULL)
1635                         rc = kibnal_setup_rd_iov(tx, 
1636                                                  &txmsg->ibm_u.putack.ibpam_rd,
1637                                                  vv_acc_r_mem_write,
1638                                                  niov, iov, offset, mlen);
1639                 else
1640                         rc = kibnal_setup_rd_kiov(tx,
1641                                                   &txmsg->ibm_u.putack.ibpam_rd,
1642                                                   vv_acc_r_mem_write,
1643                                                   niov, kiov, offset, mlen);
1644                 if (rc != 0) {
1645                         CERROR("Can't setup PUT sink for "LPX64": %d\n",
1646                                conn->ibc_peer->ibp_nid, rc);
1647                         kibnal_tx_done(tx);
1648                         return PTL_FAIL;
1649                 }
1650
1651                 txmsg->ibm_u.putack.ibpam_src_cookie = rxmsg->ibm_u.putreq.ibprm_cookie;
1652                 txmsg->ibm_u.putack.ibpam_dst_cookie = tx->tx_cookie;
1653
1654                 n = tx->tx_msg->ibm_u.putack.ibpam_rd.rd_nfrag;
1655                 nob = offsetof(kib_putack_msg_t, ibpam_rd.rd_frags[n]);
1656                 kibnal_init_tx_msg(tx, IBNAL_MSG_PUT_ACK, nob);
1657
1658                 tx->tx_libmsg[0] = libmsg;      /* finalise libmsg on completion */
1659                 tx->tx_waiting = 1;             /* waiting for PUT_DONE */
1660                 kibnal_queue_tx(tx, conn);
1661
1662                 LASSERT (!rx->rx_responded);
1663                 rx->rx_responded = 1;
1664                 return PTL_OK;
1665
1666         case IBNAL_MSG_GET_REQ:
1667                 /* We get called here just to discard any junk after the
1668                  * GET hdr. */
1669                 LASSERT (libmsg == NULL);
1670                 lib_finalize (nal, NULL, libmsg, PTL_OK);
1671                 return (PTL_OK);
1672         }
1673 }
1674
1675 ptl_err_t
1676 kibnal_recv (lib_nal_t *nal, void *private, lib_msg_t *msg,
1677               unsigned int niov, struct iovec *iov, 
1678               size_t offset, size_t mlen, size_t rlen)
1679 {
1680         return (kibnal_recvmsg (nal, private, msg, niov, iov, NULL,
1681                                 offset, mlen, rlen));
1682 }
1683
1684 ptl_err_t
1685 kibnal_recv_pages (lib_nal_t *nal, void *private, lib_msg_t *msg,
1686                      unsigned int niov, ptl_kiov_t *kiov, 
1687                      size_t offset, size_t mlen, size_t rlen)
1688 {
1689         return (kibnal_recvmsg (nal, private, msg, niov, NULL, kiov,
1690                                 offset, mlen, rlen));
1691 }
1692
1693 int
1694 kibnal_thread_start (int (*fn)(void *arg), void *arg)
1695 {
1696         long    pid = kernel_thread (fn, arg, 0);
1697
1698         if (pid < 0)
1699                 return ((int)pid);
1700
1701         atomic_inc (&kibnal_data.kib_nthreads);
1702         return (0);
1703 }
1704
1705 void
1706 kibnal_thread_fini (void)
1707 {
1708         atomic_dec (&kibnal_data.kib_nthreads);
1709 }
1710
1711 void
1712 kibnal_close_conn_locked (kib_conn_t *conn, int error)
1713 {
1714         /* This just does the immmediate housekeeping.  'error' is zero for a
1715          * normal shutdown which can happen only after the connection has been
1716          * established.  If the connection is established, schedule the
1717          * connection to be finished off by the connd.  Otherwise the connd is
1718          * already dealing with it (either to set it up or tear it down).
1719          * Caller holds kib_global_lock exclusively in irq context */
1720         kib_peer_t       *peer = conn->ibc_peer;
1721         struct list_head *tmp;
1722         
1723         LASSERT (error != 0 || conn->ibc_state >= IBNAL_CONN_ESTABLISHED);
1724
1725         if (error != 0 && conn->ibc_comms_error == 0)
1726                 conn->ibc_comms_error = error;
1727
1728         if (conn->ibc_state != IBNAL_CONN_ESTABLISHED)
1729                 return; /* already being handled  */
1730
1731         spin_lock(&conn->ibc_lock);
1732         
1733         if (error == 0 &&
1734             list_empty(&conn->ibc_tx_queue) &&
1735             list_empty(&conn->ibc_active_txs)) {
1736                 CDEBUG(D_NET, "closing conn to "LPX64
1737                        " rx# "LPD64" tx# "LPD64"\n", 
1738                        peer->ibp_nid, conn->ibc_txseq, conn->ibc_rxseq);
1739         } else {
1740                 CERROR("Closing conn to "LPX64": error %d%s%s"
1741                        " rx# "LPD64" tx# "LPD64"\n",
1742                        peer->ibp_nid, error,
1743                        list_empty(&conn->ibc_tx_queue) ? "" : "(sending)",
1744                        list_empty(&conn->ibc_active_txs) ? "" : "(waiting)",
1745                        conn->ibc_txseq, conn->ibc_rxseq);
1746
1747                 list_for_each(tmp, &conn->ibc_tx_queue) {
1748                         kib_tx_t *tx = list_entry(tmp, kib_tx_t, tx_list);
1749                         
1750                         CERROR("   queued tx type %x cookie "LPX64
1751                                " sending %d waiting %d ticks %ld/%d\n", 
1752                                tx->tx_msg->ibm_type, tx->tx_cookie, 
1753                                tx->tx_sending, tx->tx_waiting,
1754                                (long)(tx->tx_deadline - jiffies), HZ);
1755                 }
1756
1757                 list_for_each(tmp, &conn->ibc_active_txs) {
1758                         kib_tx_t *tx = list_entry(tmp, kib_tx_t, tx_list);
1759                         
1760                         CERROR("   active tx type %x cookie "LPX64
1761                                " sending %d waiting %d ticks %ld/%d\n", 
1762                                tx->tx_msg->ibm_type, tx->tx_cookie, 
1763                                tx->tx_sending, tx->tx_waiting,
1764                                (long)(tx->tx_deadline - jiffies), HZ);
1765                 }
1766         }
1767
1768         spin_unlock(&conn->ibc_lock);
1769
1770         /* connd takes ibc_list's ref */
1771         list_del (&conn->ibc_list);
1772         
1773         if (list_empty (&peer->ibp_conns) &&    /* no more conns */
1774             peer->ibp_persistence == 0 &&       /* non-persistent peer */
1775             kibnal_peer_active(peer)) {         /* still in peer table */
1776                 kibnal_unlink_peer_locked (peer);
1777         }
1778
1779         kibnal_set_conn_state(conn, IBNAL_CONN_DISCONNECT1);
1780
1781         spin_lock(&kibnal_data.kib_connd_lock);
1782
1783         list_add_tail (&conn->ibc_list, &kibnal_data.kib_connd_conns);
1784         wake_up (&kibnal_data.kib_connd_waitq);
1785                 
1786         spin_unlock(&kibnal_data.kib_connd_lock);
1787 }
1788
1789 void
1790 kibnal_close_conn (kib_conn_t *conn, int error)
1791 {
1792         unsigned long flags;
1793         
1794         write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
1795
1796         kibnal_close_conn_locked (conn, error);
1797         
1798         write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
1799 }
1800
1801 void
1802 kibnal_handle_early_rxs(kib_conn_t *conn)
1803 {
1804         unsigned long    flags;
1805         kib_rx_t        *rx;
1806
1807         LASSERT (!in_interrupt());
1808         LASSERT (conn->ibc_state >= IBNAL_CONN_ESTABLISHED);
1809         
1810         write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
1811         while (!list_empty(&conn->ibc_early_rxs)) {
1812                 rx = list_entry(conn->ibc_early_rxs.next,
1813                                 kib_rx_t, rx_list);
1814                 list_del(&rx->rx_list);
1815                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
1816                 
1817                 kibnal_handle_rx(rx);
1818                 
1819                 write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
1820         }
1821         write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
1822 }
1823
1824 void
1825 kibnal_conn_disconnected(kib_conn_t *conn)
1826 {
1827         LIST_HEAD        (zombies); 
1828         struct list_head *tmp;
1829         struct list_head *nxt;
1830         kib_tx_t         *tx;
1831
1832         /* I'm the connd */
1833         LASSERT (!in_interrupt());
1834         LASSERT (current == kibnal_data.kib_connd);
1835         LASSERT (conn->ibc_state >= IBNAL_CONN_INIT);
1836         
1837         kibnal_set_conn_state(conn, IBNAL_CONN_DISCONNECTED);
1838
1839         /* move QP to error state to make posted work items complete */
1840         kibnal_set_qp_state(conn, vv_qp_state_error);
1841
1842         spin_lock(&conn->ibc_lock);
1843
1844         /* Complete all tx descs not waiting for sends to complete.
1845          * NB we should be safe from RDMA now that the QP has changed state */
1846
1847         list_for_each_safe (tmp, nxt, &conn->ibc_tx_queue) {
1848                 tx = list_entry (tmp, kib_tx_t, tx_list);
1849
1850                 LASSERT (tx->tx_queued);
1851
1852                 tx->tx_status = -ECONNABORTED;
1853                 tx->tx_queued = 0;
1854                 tx->tx_waiting = 0;
1855                 
1856                 if (tx->tx_sending != 0)
1857                         continue;
1858
1859                 list_del (&tx->tx_list);
1860                 list_add (&tx->tx_list, &zombies);
1861         }
1862
1863         list_for_each_safe (tmp, nxt, &conn->ibc_active_txs) {
1864                 tx = list_entry (tmp, kib_tx_t, tx_list);
1865
1866                 LASSERT (!tx->tx_queued);
1867                 LASSERT (tx->tx_waiting ||
1868                          tx->tx_sending != 0);
1869
1870                 tx->tx_status = -ECONNABORTED;
1871                 tx->tx_waiting = 0;
1872                 
1873                 if (tx->tx_sending != 0)
1874                         continue;
1875
1876                 list_del (&tx->tx_list);
1877                 list_add (&tx->tx_list, &zombies);
1878         }
1879         
1880         spin_unlock(&conn->ibc_lock);
1881
1882         while (!list_empty(&zombies)) {
1883                 tx = list_entry (zombies.next, kib_tx_t, tx_list);
1884
1885                 list_del(&tx->tx_list);
1886                 kibnal_tx_done (tx);
1887         }
1888
1889         kibnal_handle_early_rxs(conn);
1890 }
1891
1892 void
1893 kibnal_peer_connect_failed (kib_peer_t *peer, int active)
1894 {
1895         struct list_head  zombies;
1896         kib_tx_t         *tx;
1897         unsigned long     flags;
1898
1899         /* Only the connd creates conns => single threaded */
1900         LASSERT (!in_interrupt());
1901         LASSERT (current == kibnal_data.kib_connd);
1902         LASSERT (peer->ibp_reconnect_interval >= IBNAL_MIN_RECONNECT_INTERVAL);
1903
1904         write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
1905
1906         if (active) {
1907                 LASSERT (peer->ibp_connecting != 0);
1908                 peer->ibp_connecting--;
1909         } else {
1910                 LASSERT (!kibnal_peer_active(peer));
1911         }
1912         
1913         if (peer->ibp_connecting != 0) {
1914                 /* another connection attempt under way (loopback?)... */
1915                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
1916                 return;
1917         }
1918
1919         if (list_empty(&peer->ibp_conns)) {
1920                 /* Say when active connection can be re-attempted */
1921                 peer->ibp_reconnect_time = jiffies + peer->ibp_reconnect_interval;
1922                 /* Increase reconnection interval */
1923                 peer->ibp_reconnect_interval = MIN (peer->ibp_reconnect_interval * 2,
1924                                                     IBNAL_MAX_RECONNECT_INTERVAL);
1925         
1926                 /* Take peer's blocked transmits to complete with error */
1927                 list_add(&zombies, &peer->ibp_tx_queue);
1928                 list_del_init(&peer->ibp_tx_queue);
1929                 
1930                 if (kibnal_peer_active(peer) &&
1931                     (peer->ibp_persistence == 0)) {
1932                         /* failed connection attempt on non-persistent peer */
1933                         kibnal_unlink_peer_locked (peer);
1934                 }
1935         } else {
1936                 /* Can't have blocked transmits if there are connections */
1937                 LASSERT (list_empty(&peer->ibp_tx_queue));
1938         }
1939         
1940         write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
1941
1942         if (list_empty (&zombies)) 
1943                 return;
1944         
1945         CERROR ("Deleting messages for "LPX64": connection failed\n", peer->ibp_nid);
1946         do {
1947                 tx = list_entry (zombies.next, kib_tx_t, tx_list);
1948
1949                 list_del (&tx->tx_list);
1950                 /* complete now */
1951                 tx->tx_status = -EHOSTUNREACH;
1952                 kibnal_tx_done (tx);
1953         } while (!list_empty (&zombies));
1954 }
1955
1956 void
1957 kibnal_connreq_done(kib_conn_t *conn, int active, int status)
1958 {
1959         static cm_reject_data_t   rej;
1960
1961         struct list_head   txs;
1962         kib_peer_t        *peer = conn->ibc_peer;
1963         kib_peer_t        *peer2;
1964         unsigned long      flags;
1965         kib_tx_t          *tx;
1966
1967         /* Only the connd creates conns => single threaded */
1968         LASSERT (!in_interrupt());
1969         LASSERT (current == kibnal_data.kib_connd);
1970         LASSERT (conn->ibc_state < IBNAL_CONN_ESTABLISHED);
1971
1972         if (active) {
1973                 LASSERT (peer->ibp_connecting > 0);
1974         } else {
1975                 LASSERT (!kibnal_peer_active(peer));
1976         }
1977         
1978         PORTAL_FREE(conn->ibc_connvars, sizeof(*conn->ibc_connvars));
1979         conn->ibc_connvars = NULL;
1980
1981         if (status != 0) {
1982                 /* failed to establish connection */
1983                 switch (conn->ibc_state) {
1984                 default:
1985                         LBUG();
1986                 case IBNAL_CONN_ACTIVE_CHECK_REPLY:
1987                         /* got a connection reply but failed checks */
1988                         LASSERT (active);
1989                         memset(&rej, 0, sizeof(rej));
1990                         rej.reason = cm_rej_code_usr_rej;
1991                         cm_reject(conn->ibc_cep, &rej);
1992                         break;
1993
1994                 case IBNAL_CONN_ACTIVE_CONNECT:
1995                         LASSERT (active);
1996                         cm_cancel(conn->ibc_cep);
1997                         kibnal_pause(HZ/10);
1998                         /* cm_connect() failed immediately or
1999                          * callback returned failure */
2000                         break;
2001
2002                 case IBNAL_CONN_ACTIVE_ARP:
2003                         LASSERT (active);
2004                         /* ibat_get_ib_data() failed immediately 
2005                          * or callback returned failure */
2006                         break;
2007
2008                 case IBNAL_CONN_INIT:
2009                         break;
2010
2011                 case IBNAL_CONN_PASSIVE_WAIT:
2012                         LASSERT (!active);
2013                         /* cm_accept callback returned failure */
2014                         break;
2015                 }
2016
2017                 kibnal_peer_connect_failed(conn->ibc_peer, active);
2018                 kibnal_conn_disconnected(conn);
2019                 return;
2020         }
2021
2022         /* connection established */
2023         write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2024
2025         if (active) {
2026                 LASSERT(conn->ibc_state == IBNAL_CONN_ACTIVE_RTU);
2027         } else {
2028                 LASSERT(conn->ibc_state == IBNAL_CONN_PASSIVE_WAIT);
2029         }
2030         
2031         kibnal_set_conn_state(conn, IBNAL_CONN_ESTABLISHED);
2032
2033         if (!active) {
2034                 peer2 = kibnal_find_peer_locked(peer->ibp_nid);
2035                 if (peer2 != NULL) {
2036                         /* already in the peer table; swap */
2037                         conn->ibc_peer = peer2;
2038                         kibnal_peer_addref(peer2);
2039                         kibnal_peer_decref(peer);
2040                         peer = conn->ibc_peer;
2041                 } else {
2042                         /* add 'peer' to the peer table */
2043                         kibnal_peer_addref(peer);
2044                         list_add_tail(&peer->ibp_list,
2045                                       kibnal_nid2peerlist(peer->ibp_nid));
2046                 }
2047         }
2048         
2049         /* Add conn to peer's list and nuke any dangling conns from a different
2050          * peer instance... */
2051         kibnal_conn_addref(conn);               /* +1 ref for ibc_list */
2052         list_add(&conn->ibc_list, &peer->ibp_conns);
2053         kibnal_close_stale_conns_locked (conn->ibc_peer,
2054                                          conn->ibc_incarnation);
2055
2056         if (!kibnal_peer_active(peer) ||        /* peer has been deleted */
2057             conn->ibc_comms_error != 0 ||       /* comms error */
2058             conn->ibc_disconnect) {             /* need to disconnect */
2059                 
2060                 /* start to shut down connection */
2061                 kibnal_close_conn_locked(conn, -ECONNABORTED);
2062
2063                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2064                 kibnal_peer_connect_failed(peer, active);
2065                 return;
2066         }
2067
2068         if (active)
2069                 peer->ibp_connecting--;
2070
2071         /* grab pending txs while I have the lock */
2072         list_add(&txs, &peer->ibp_tx_queue);
2073         list_del_init(&peer->ibp_tx_queue);
2074         
2075         /* reset reconnect interval for next attempt */
2076         peer->ibp_reconnect_interval = IBNAL_MIN_RECONNECT_INTERVAL;
2077         write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2078
2079         /* Schedule blocked txs */
2080         spin_lock (&conn->ibc_lock);
2081         while (!list_empty (&txs)) {
2082                 tx = list_entry (txs.next, kib_tx_t, tx_list);
2083                 list_del (&tx->tx_list);
2084
2085                 kibnal_queue_tx_locked (tx, conn);
2086         }
2087         spin_unlock (&conn->ibc_lock);
2088         kibnal_check_sends (conn);
2089
2090         /* schedule blocked rxs */
2091         kibnal_handle_early_rxs(conn);
2092 }
2093
2094 void
2095 kibnal_cm_callback(cm_cep_handle_t cep, cm_conn_data_t *cmdata, void *arg)
2096 {
2097         static cm_dreply_data_t drep;           /* just zeroed space */
2098         
2099         kib_conn_t             *conn = (kib_conn_t *)arg;
2100         unsigned long           flags;
2101         
2102         /* CAVEAT EMPTOR: tasklet context */
2103
2104         switch (cmdata->status) {
2105         default:
2106                 LBUG();
2107                 
2108         case cm_event_disconn_request:
2109                 /* IBNAL_CONN_ACTIVE_RTU:  gets closed in kibnal_connreq_done
2110                  * IBNAL_CONN_ESTABLISHED: I start it closing
2111                  * otherwise:              it's closing anyway */
2112                 cm_disconnect(conn->ibc_cep, NULL, &drep);
2113                 cm_cancel(conn->ibc_cep);
2114
2115                 write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2116                 LASSERT (!conn->ibc_disconnect);
2117                 conn->ibc_disconnect = 1;
2118
2119                 switch (conn->ibc_state) {
2120                 default:
2121                         LBUG();
2122
2123                 case IBNAL_CONN_ACTIVE_RTU:
2124                         /* kibnal_connreq_done is getting there; It'll see
2125                          * ibc_disconnect set... */
2126                         kibnal_conn_decref(conn); /* lose my ref */
2127                         break;
2128
2129                 case IBNAL_CONN_ESTABLISHED:
2130                         /* kibnal_connreq_done got there already; get
2131                          * disconnect going... */
2132                         kibnal_close_conn_locked(conn, 0);
2133                         kibnal_conn_decref(conn); /* lose my ref */
2134                         break;
2135
2136                 case IBNAL_CONN_DISCONNECT1:
2137                         /* kibnal_terminate_conn is getting there; It'll see
2138                          * ibc_disconnect set... */
2139                         kibnal_conn_decref(conn); /* lose my ref */
2140                         break;
2141
2142                 case IBNAL_CONN_DISCONNECT2:
2143                         /* kibnal_terminate_conn got there already; complete
2144                          * the disconnect.  NB kib_connd_conns takes my ref */
2145                         spin_lock(&kibnal_data.kib_connd_lock);
2146                         list_add_tail(&conn->ibc_list, &kibnal_data.kib_connd_conns);
2147                         wake_up(&kibnal_data.kib_connd_waitq);
2148                         spin_unlock(&kibnal_data.kib_connd_lock);
2149                         break;
2150                 }
2151                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2152                 return;
2153                 
2154         case cm_event_disconn_timeout:
2155         case cm_event_disconn_reply:
2156                 write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2157                 LASSERT (conn->ibc_state == IBNAL_CONN_DISCONNECT2);
2158                 LASSERT (!conn->ibc_disconnect);
2159                 conn->ibc_disconnect = 1;
2160
2161                 /* kibnal_terminate_conn sent the disconnect request.  
2162                  * NB kib_connd_conns takes my ref */
2163                 spin_lock(&kibnal_data.kib_connd_lock);
2164                 list_add_tail(&conn->ibc_list, &kibnal_data.kib_connd_conns);
2165                 wake_up(&kibnal_data.kib_connd_waitq);
2166                 spin_unlock(&kibnal_data.kib_connd_lock);
2167
2168                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2169                 break;
2170                 
2171         case cm_event_connected:
2172         case cm_event_conn_timeout:
2173         case cm_event_conn_reject:
2174                 LASSERT (conn->ibc_state == IBNAL_CONN_PASSIVE_WAIT);
2175                 conn->ibc_connvars->cv_conndata = *cmdata;
2176                 
2177                 spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
2178                 list_add_tail(&conn->ibc_list, &kibnal_data.kib_connd_conns);
2179                 wake_up(&kibnal_data.kib_connd_waitq);
2180                 spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
2181                 break;
2182         }
2183 }
2184
2185 void
2186 kibnal_check_passive_wait(kib_conn_t *conn)
2187 {
2188         int     rc;
2189
2190         switch (conn->ibc_connvars->cv_conndata.status) {
2191         default:
2192                 LBUG();
2193                 
2194         case cm_event_connected:
2195                 kibnal_conn_addref(conn); /* ++ ref for CM callback */
2196                 rc = kibnal_set_qp_state(conn, vv_qp_state_rts);
2197                 if (rc != 0)
2198                         conn->ibc_comms_error = rc;
2199                 /* connection _has_ been established; it's just that we've had
2200                  * an error immediately... */
2201                 kibnal_connreq_done(conn, 0, 0);
2202                 break;
2203                 
2204         case cm_event_conn_timeout:
2205                 kibnal_connreq_done(conn, 0, -ETIMEDOUT);
2206                 break;
2207                 
2208         case cm_event_conn_reject:
2209                 kibnal_connreq_done(conn, 0, -ECONNRESET);
2210                 break;
2211         }
2212 }
2213
2214 void
2215 kibnal_recv_connreq(cm_cep_handle_t *cep, cm_request_data_t *cmreq)
2216 {
2217         static kib_msg_t        txmsg;
2218         static kib_msg_t        rxmsg;
2219         static cm_reply_data_t  reply;
2220         static cm_reject_data_t reject;
2221
2222         kib_conn_t         *conn = NULL;
2223         int                 rc = 0;
2224         int                 rxmsgnob;
2225         kib_connvars_t     *cv;
2226         kib_peer_t         *tmp_peer;
2227         cm_return_t         cmrc;
2228         vv_return_t         vvrc;
2229         
2230         /* I'm the connd executing in thread context
2231          * No concurrency problems with static data! */
2232         LASSERT (!in_interrupt());
2233         LASSERT (current == kibnal_data.kib_connd);
2234
2235         if (cmreq->sid != IBNAL_SERVICE_NUMBER) {
2236                 CERROR(LPX64" != IBNAL_SERVICE_NUMBER("LPX64")\n",
2237                        cmreq->sid, (__u64)IBNAL_SERVICE_NUMBER);
2238                 goto reject;
2239         }
2240
2241         /* copy into rxmsg to avoid alignment issues */
2242         rxmsgnob = MIN(cm_REQ_priv_data_len, sizeof(rxmsg));
2243         memcpy(&rxmsg, cmreq->priv_data, rxmsgnob);
2244
2245         rc = kibnal_unpack_msg(&rxmsg, rxmsgnob);
2246         if (rc != 0) {
2247                 CERROR("Can't parse connection request: %d\n", rc);
2248                 goto reject;
2249         }
2250
2251         if (rxmsg.ibm_type != IBNAL_MSG_CONNREQ) {
2252                 CERROR("Unexpected connreq msg type: %x from "LPX64"\n",
2253                        rxmsg.ibm_type, rxmsg.ibm_srcnid);
2254                 goto reject;
2255         }
2256
2257         if (rxmsg.ibm_dstnid != kibnal_lib.libnal_ni.ni_pid.nid) {
2258                 CERROR("Can't accept "LPX64": bad dst nid "LPX64"\n",
2259                        rxmsg.ibm_srcnid, rxmsg.ibm_dstnid);
2260                 goto reject;
2261         }
2262
2263         if (rxmsg.ibm_u.connparams.ibcp_queue_depth != IBNAL_MSG_QUEUE_SIZE) {
2264                 CERROR("Can't accept "LPX64": incompatible queue depth %d (%d wanted)\n",
2265                        rxmsg.ibm_srcnid, rxmsg.ibm_u.connparams.ibcp_queue_depth, 
2266                        IBNAL_MSG_QUEUE_SIZE);
2267                 goto reject;
2268         }
2269
2270         if (rxmsg.ibm_u.connparams.ibcp_max_msg_size > IBNAL_MSG_SIZE) {
2271                 CERROR("Can't accept "LPX64": message size %d too big (%d max)\n",
2272                        rxmsg.ibm_srcnid, rxmsg.ibm_u.connparams.ibcp_max_msg_size, 
2273                        IBNAL_MSG_SIZE);
2274                 goto reject;
2275         }
2276                 
2277         if (rxmsg.ibm_u.connparams.ibcp_max_frags > IBNAL_MAX_RDMA_FRAGS) {
2278                 CERROR("Can't accept "LPX64": max frags %d too big (%d max)\n",
2279                        rxmsg.ibm_srcnid, rxmsg.ibm_u.connparams.ibcp_max_frags, 
2280                        IBNAL_MAX_RDMA_FRAGS);
2281                 goto reject;
2282         }
2283                 
2284         conn = kibnal_create_conn(cep);
2285         if (conn == NULL) {
2286                 CERROR("Can't create conn for "LPX64"\n", rxmsg.ibm_srcnid);
2287                 goto reject;
2288         }
2289         
2290         /* assume 'rxmsg.ibm_srcnid' is a new peer */
2291         tmp_peer = kibnal_create_peer (rxmsg.ibm_srcnid);
2292         if (tmp_peer == NULL) {
2293                 CERROR("Can't create tmp peer for "LPX64"\n", rxmsg.ibm_srcnid);
2294                 kibnal_conn_decref(conn);
2295                 conn = NULL;
2296                 goto reject;
2297         }
2298
2299         conn->ibc_peer = tmp_peer;              /* conn takes over my ref */
2300         conn->ibc_incarnation = rxmsg.ibm_srcstamp;
2301         conn->ibc_credits = IBNAL_MSG_QUEUE_SIZE;
2302
2303         cv = conn->ibc_connvars;
2304
2305         cv->cv_txpsn          = cmreq->cep_data.start_psn;
2306         cv->cv_remote_qpn     = cmreq->cep_data.qpn;
2307         cv->cv_path           = cmreq->path_data.path;
2308         cv->cv_rnr_count      = cmreq->cep_data.rtr_retry_cnt;
2309         // XXX                  cmreq->cep_data.retry_cnt;
2310         cv->cv_port           = cmreq->cep_data.local_port_num;
2311
2312         vvrc = gid2gid_index(kibnal_data.kib_hca, cv->cv_port,
2313                              &cv->cv_path.sgid, &cv->cv_sgid_index);
2314         LASSERT (vvrc == vv_return_ok);
2315         
2316         vvrc = pkey2pkey_index(kibnal_data.kib_hca, cv->cv_port,
2317                                cv->cv_path.pkey, &cv->cv_pkey_index);
2318         LASSERT (vvrc == vv_return_ok);
2319
2320         rc = kibnal_set_qp_state(conn, vv_qp_state_init);
2321         if (rc != 0)
2322                 goto reject;
2323
2324         rc = kibnal_post_receives(conn);
2325         if (rc != 0) {
2326                 CERROR("Can't post receives for "LPX64"\n", rxmsg.ibm_srcnid);
2327                 goto reject;
2328         }
2329
2330         rc = kibnal_set_qp_state(conn, vv_qp_state_rtr);
2331         if (rc != 0)
2332                 goto reject;
2333         
2334         memset(&reply, 0, sizeof(reply));
2335         reply.qpn                 = cv->cv_local_qpn;
2336         reply.qkey                = IBNAL_QKEY;
2337         reply.start_psn           = cv->cv_rxpsn;
2338         reply.arb_initiator_depth = IBNAL_ARB_INITIATOR_DEPTH;
2339         reply.arb_resp_res        = IBNAL_ARB_RESP_RES;
2340         reply.failover_accepted   = IBNAL_FAILOVER_ACCEPTED;
2341         reply.rnr_retry_count     = cv->cv_rnr_count;
2342         reply.targ_ack_delay      = kibnal_data.kib_hca_attrs.ack_delay;
2343         
2344         /* setup txmsg... */
2345         memset(&txmsg, 0, sizeof(txmsg));
2346         kibnal_init_msg(&txmsg, IBNAL_MSG_CONNACK, 
2347                         sizeof(txmsg.ibm_u.connparams));
2348         LASSERT (txmsg.ibm_nob <= cm_REP_priv_data_len);
2349         txmsg.ibm_u.connparams.ibcp_queue_depth = IBNAL_MSG_QUEUE_SIZE;
2350         txmsg.ibm_u.connparams.ibcp_max_msg_size = IBNAL_MSG_SIZE;
2351         txmsg.ibm_u.connparams.ibcp_max_frags = IBNAL_MAX_RDMA_FRAGS;
2352         kibnal_pack_msg(&txmsg, 0, rxmsg.ibm_srcnid, rxmsg.ibm_srcstamp, 0);
2353
2354         /* ...and copy into reply to avoid alignment issues */
2355         memcpy(&reply.priv_data, &txmsg, txmsg.ibm_nob);
2356
2357         kibnal_set_conn_state(conn, IBNAL_CONN_PASSIVE_WAIT);
2358         
2359         cmrc = cm_accept(conn->ibc_cep, &reply, NULL,
2360                          kibnal_cm_callback, conn);
2361
2362         if (cmrc == cm_stat_success)
2363                 return;                         /* callback has got my ref on conn */
2364
2365         /* back out state change (no callback happening) */
2366         kibnal_set_conn_state(conn, IBNAL_CONN_INIT);
2367         rc = -EIO;
2368                 
2369  reject:
2370         CERROR("Rejected connreq from "LPX64"\n", rxmsg.ibm_srcnid);
2371
2372         memset(&reject, 0, sizeof(reject));
2373         reject.reason = cm_rej_code_usr_rej;
2374         cm_reject(cep, &reject);
2375
2376         if (conn != NULL) {
2377                 LASSERT (rc != 0);
2378                 kibnal_connreq_done(conn, 0, rc);
2379         } else {
2380                 cm_destroy_cep(cep);
2381         }
2382 }
2383
2384 void
2385 kibnal_listen_callback(cm_cep_handle_t cep, cm_conn_data_t *data, void *arg)
2386 {
2387         cm_request_data_t  *cmreq = &data->data.request;
2388         kib_pcreq_t        *pcr;
2389         unsigned long       flags;
2390         
2391         LASSERT (arg == NULL);
2392
2393         if (data->status != cm_event_conn_request) {
2394                 CERROR("status %d is not cm_event_conn_request\n",
2395                        data->status);
2396                 return;
2397         }
2398
2399         PORTAL_ALLOC_ATOMIC(pcr, sizeof(*pcr));
2400         if (pcr == NULL) {
2401                 CERROR("Can't allocate passive connreq\n");
2402
2403                 cm_reject(cep, &((cm_reject_data_t) /* NB RO struct */
2404                                  {.reason = cm_rej_code_no_res,}));
2405                 cm_destroy_cep(cep);
2406                 return;
2407         }
2408
2409         pcr->pcr_cep = cep;
2410         pcr->pcr_cmreq = *cmreq;
2411         
2412         spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
2413
2414         list_add_tail(&pcr->pcr_list, &kibnal_data.kib_connd_pcreqs);
2415         wake_up(&kibnal_data.kib_connd_waitq);
2416         
2417         spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
2418 }
2419
2420
2421 void
2422 kibnal_active_connect_callback (cm_cep_handle_t cep, cm_conn_data_t *cd, 
2423                                 void *arg)
2424 {
2425         /* CAVEAT EMPTOR: tasklet context */
2426         kib_conn_t       *conn = (kib_conn_t *)arg;
2427         kib_connvars_t   *cv = conn->ibc_connvars;
2428         unsigned long     flags;
2429
2430         LASSERT (conn->ibc_state == IBNAL_CONN_ACTIVE_CONNECT);
2431         cv->cv_conndata = *cd;
2432
2433         spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
2434         /* connd takes my ref */
2435         list_add_tail(&conn->ibc_list, &kibnal_data.kib_connd_conns);
2436         wake_up(&kibnal_data.kib_connd_waitq);
2437         spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
2438 }
2439
2440 void
2441 kibnal_connect_conn (kib_conn_t *conn)
2442 {
2443         static cm_request_data_t  cmreq;
2444         static kib_msg_t          msg;
2445         
2446         kib_connvars_t           *cv = conn->ibc_connvars;
2447         kib_peer_t               *peer = conn->ibc_peer;
2448         cm_return_t               cmrc;
2449         
2450         /* Only called by connd => statics OK */
2451         LASSERT (!in_interrupt());
2452         LASSERT (current == kibnal_data.kib_connd);
2453         LASSERT (conn->ibc_state == IBNAL_CONN_ACTIVE_ARP);
2454
2455         memset(&cmreq, 0, sizeof(cmreq));
2456         
2457         cmreq.sid = IBNAL_SERVICE_NUMBER;
2458
2459         cmreq.cep_data.ca_guid              = kibnal_data.kib_hca_attrs.guid;
2460         cmreq.cep_data.qpn                  = cv->cv_local_qpn;
2461         cmreq.cep_data.retry_cnt            = IBNAL_RETRY_CNT;
2462         cmreq.cep_data.rtr_retry_cnt        = IBNAL_RNR_CNT;
2463         cmreq.cep_data.start_psn            = cv->cv_rxpsn;
2464         cmreq.cep_data.end_to_end_flow_ctrl = IBNAL_EE_FLOW_CNT;
2465         // XXX ack_timeout?
2466         // offered_resp_res
2467         // offered_initiator_depth
2468
2469         cmreq.path_data.subn_local  = IBNAL_LOCAL_SUB;
2470         cmreq.path_data.path        = cv->cv_path;
2471         
2472         /* setup msg... */
2473         memset(&msg, 0, sizeof(msg));
2474         kibnal_init_msg(&msg, IBNAL_MSG_CONNREQ, sizeof(msg.ibm_u.connparams));
2475         LASSERT(msg.ibm_nob <= cm_REQ_priv_data_len);
2476         msg.ibm_u.connparams.ibcp_queue_depth = IBNAL_MSG_QUEUE_SIZE;
2477         msg.ibm_u.connparams.ibcp_max_msg_size = IBNAL_MSG_SIZE;
2478         msg.ibm_u.connparams.ibcp_max_frags = IBNAL_MAX_RDMA_FRAGS;
2479         kibnal_pack_msg(&msg, 0, peer->ibp_nid, 0, 0);
2480
2481         /* ...and copy into cmreq to avoid alignment issues */
2482         memcpy(&cmreq.priv_data, &msg, msg.ibm_nob);
2483         
2484         CDEBUG(D_NET, "Connecting %p to "LPX64"\n", conn, peer->ibp_nid);
2485
2486         kibnal_conn_addref(conn);               /* ++ref for CM callback */
2487         kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_CONNECT);
2488
2489         cmrc = cm_connect(conn->ibc_cep, &cmreq, 
2490                           kibnal_active_connect_callback, conn);
2491         if (cmrc == cm_stat_success) {
2492                 CDEBUG(D_NET, "connection REQ sent to "LPX64"\n",
2493                        peer->ibp_nid);
2494                 return;
2495         }
2496
2497         CERROR ("Connect "LPX64" failed: %d\n", peer->ibp_nid, cmrc);
2498         kibnal_conn_decref(conn);       /* drop callback's ref */
2499         kibnal_connreq_done(conn, 1, -EHOSTUNREACH);
2500 }
2501
2502 void
2503 kibnal_check_connreply (kib_conn_t *conn)
2504 {
2505         static cm_rtu_data_t  rtu;
2506         static kib_msg_t      msg;
2507
2508         kib_connvars_t   *cv = conn->ibc_connvars;
2509         cm_reply_data_t  *reply = &cv->cv_conndata.data.reply;
2510         kib_peer_t       *peer = conn->ibc_peer;
2511         int               msgnob;
2512         cm_return_t       cmrc;
2513         cm_cep_handle_t   cep;
2514         unsigned long     flags;
2515         int               rc;
2516
2517         /* Only called by connd => statics OK */
2518         LASSERT (!in_interrupt());
2519         LASSERT (current == kibnal_data.kib_connd);
2520         LASSERT (conn->ibc_state == IBNAL_CONN_ACTIVE_CONNECT);
2521
2522         if (cv->cv_conndata.status == cm_event_conn_reply) {
2523                 cv->cv_remote_qpn = reply->qpn;
2524                 cv->cv_txpsn      = reply->start_psn;
2525                 // XXX              reply->targ_ack_delay;
2526                 cv->cv_rnr_count  = reply->rnr_retry_count;
2527
2528                 kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_CHECK_REPLY);
2529
2530                 /* copy into msg to avoid alignment issues */
2531                 msgnob = MIN(cm_REP_priv_data_len, sizeof(msg));
2532                 memcpy(&msg, &reply->priv_data, msgnob);
2533
2534                 rc = kibnal_unpack_msg(&msg, msgnob);
2535                 if (rc != 0) {
2536                         CERROR("Can't unpack reply from "LPX64"\n",
2537                                peer->ibp_nid);
2538                         kibnal_connreq_done(conn, 1, rc);
2539                         return;
2540                 }
2541
2542                 if (msg.ibm_type != IBNAL_MSG_CONNACK ) {
2543                         CERROR("Unexpected message type %d from "LPX64"\n",
2544                                msg.ibm_type, peer->ibp_nid);
2545                         kibnal_connreq_done(conn, 1, -EPROTO);
2546                         return;
2547                 }
2548
2549                 if (msg.ibm_u.connparams.ibcp_queue_depth != IBNAL_MSG_QUEUE_SIZE) {
2550                         CERROR(LPX64" has incompatible queue depth %d(%d wanted)\n",
2551                                peer->ibp_nid, msg.ibm_u.connparams.ibcp_queue_depth,
2552                                IBNAL_MSG_QUEUE_SIZE);
2553                         kibnal_connreq_done(conn, 1, -EPROTO);
2554                         return;
2555                 }
2556                 
2557                 if (msg.ibm_u.connparams.ibcp_max_msg_size > IBNAL_MSG_SIZE) {
2558                         CERROR(LPX64" max message size %d too big (%d max)\n",
2559                                peer->ibp_nid, msg.ibm_u.connparams.ibcp_max_msg_size, 
2560                                IBNAL_MSG_SIZE);
2561                         kibnal_connreq_done(conn, 1, -EPROTO);
2562                         return;
2563                 }
2564
2565                 if (msg.ibm_u.connparams.ibcp_max_frags > IBNAL_MAX_RDMA_FRAGS) {
2566                         CERROR(LPX64" max frags %d too big (%d max)\n",
2567                                peer->ibp_nid, msg.ibm_u.connparams.ibcp_max_frags, 
2568                                IBNAL_MAX_RDMA_FRAGS);
2569                         kibnal_connreq_done(conn, 1, -EPROTO);
2570                         return;
2571                 }
2572                 
2573                 read_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2574                 rc = (msg.ibm_dstnid != kibnal_lib.libnal_ni.ni_pid.nid ||
2575                       msg.ibm_dststamp != kibnal_data.kib_incarnation) ?
2576                      -ESTALE : 0;
2577                 read_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2578                 if (rc != 0) {
2579                         CERROR("Stale connection reply from "LPX64"\n",
2580                                peer->ibp_nid);
2581                         kibnal_connreq_done(conn, 1, rc);
2582                         return;
2583                 }
2584
2585                 conn->ibc_incarnation = msg.ibm_srcstamp;
2586                 conn->ibc_credits = IBNAL_MSG_QUEUE_SIZE;
2587                 
2588                 rc = kibnal_post_receives(conn);
2589                 if (rc != 0) {
2590                         CERROR("Can't post receives for "LPX64"\n",
2591                                peer->ibp_nid);
2592                         kibnal_connreq_done(conn, 1, rc);
2593                         return;
2594                 }
2595                 
2596                 rc = kibnal_set_qp_state(conn, vv_qp_state_rtr);
2597                 if (rc != 0) {
2598                         kibnal_connreq_done(conn, 1, rc);
2599                         return;
2600                 }
2601                 
2602                 rc = kibnal_set_qp_state(conn, vv_qp_state_rts);
2603                 if (rc != 0) {
2604                         kibnal_connreq_done(conn, 1, rc);
2605                         return;
2606                 }
2607                 
2608                 kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_RTU);
2609                 kibnal_conn_addref(conn);       /* ++for CM callback */
2610                 
2611                 memset(&rtu, 0, sizeof(rtu));
2612                 cmrc = cm_accept(conn->ibc_cep, NULL, &rtu,
2613                                  kibnal_cm_callback, conn);
2614                 if (cmrc == cm_stat_success) {
2615                         /* Now I'm racing with disconnect signalled by
2616                          * kibnal_cm_callback */
2617                         kibnal_connreq_done(conn, 1, 0);
2618                         return;
2619                 }
2620
2621                 CERROR("cm_accept "LPX64" failed: %d\n", peer->ibp_nid, cmrc);
2622                 /* Back out of RTU: no callback coming */
2623                 kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_CHECK_REPLY);
2624                 kibnal_conn_decref(conn);
2625                 kibnal_connreq_done(conn, 1, -EIO);
2626                 return;
2627         }
2628
2629         if (cv->cv_conndata.status == cm_event_conn_reject) {
2630
2631                 if (cv->cv_conndata.data.reject.reason != cm_rej_code_stale_conn) {
2632                         CERROR("conn -> "LPX64" rejected: %d\n", peer->ibp_nid,
2633                                cv->cv_conndata.data.reject.reason);
2634                         kibnal_connreq_done(conn, 1, -ECONNREFUSED);
2635                         return;
2636                 }
2637
2638                 CWARN ("conn -> "LPX64" stale: retrying\n", peer->ibp_nid);
2639
2640                 cep = cm_create_cep(cm_cep_transp_rc);
2641                 if (cep == NULL) {
2642                         CERROR("Can't create new CEP\n");
2643                         kibnal_connreq_done(conn, 1, -ENOMEM);
2644                         return;
2645                 }
2646
2647                 cmrc = cm_cancel(conn->ibc_cep);
2648                 LASSERT (cmrc == cm_stat_success);
2649                 cmrc = cm_destroy_cep(conn->ibc_cep);
2650                 LASSERT (cmrc == cm_stat_success);
2651
2652                 conn->ibc_cep = cep;
2653
2654                 /* retry connect */
2655                 kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_ARP);
2656                 kibnal_connect_conn(conn);
2657                 return;
2658         }
2659
2660         CERROR("conn -> "LPX64" failed: %d\n", peer->ibp_nid,
2661                cv->cv_conndata.status);
2662         kibnal_connreq_done(conn, 1, -ECONNABORTED);
2663 }
2664
2665 void
2666 kibnal_send_connreq (kib_conn_t *conn)
2667 {
2668         kib_peer_t           *peer = conn->ibc_peer;
2669         kib_connvars_t       *cv = conn->ibc_connvars;
2670         ibat_arp_data_t      *arp = &cv->cv_arp;
2671         ib_path_record_v2_t  *path = &cv->cv_path;
2672         vv_return_t           vvrc;
2673         int                   rc;
2674
2675         /* Only called by connd => statics OK */
2676         LASSERT (!in_interrupt());
2677         LASSERT (current == kibnal_data.kib_connd);
2678         LASSERT (conn->ibc_state == IBNAL_CONN_ACTIVE_ARP);
2679         
2680         if (cv->cv_arprc != ibat_stat_ok) {
2681                 CERROR("Can't Arp "LPX64"@%u.%u.%u.%u: %d\n", peer->ibp_nid,
2682                        HIPQUAD(peer->ibp_ip), cv->cv_arprc);
2683                 kibnal_connreq_done(conn, 1, -ENETUNREACH);
2684                 return;
2685         }
2686
2687         if ((arp->mask & IBAT_PRI_PATH_VALID) != 0) {
2688                 CDEBUG(D_NET, "Got valid path for "LPX64"\n", peer->ibp_nid);
2689
2690                 *path = *arp->primary_path;
2691
2692                 vvrc = base_gid2port_num(kibnal_data.kib_hca, &path->sgid,
2693                                          &cv->cv_port);
2694                 LASSERT (vvrc == vv_return_ok);
2695
2696                 vvrc = gid2gid_index(kibnal_data.kib_hca, cv->cv_port,
2697                                      &path->sgid, &cv->cv_sgid_index);
2698                 LASSERT (vvrc == vv_return_ok);
2699
2700                 vvrc = pkey2pkey_index(kibnal_data.kib_hca, cv->cv_port,
2701                                        path->pkey, &cv->cv_pkey_index);
2702                 LASSERT (vvrc == vv_return_ok);
2703
2704                 path->mtu = IBNAL_IB_MTU;
2705
2706         } else if ((arp->mask & IBAT_LID_VALID) != 0) {
2707                 CWARN("Creating new path record for "LPX64"@%u.%u.%u.%u\n",
2708                       peer->ibp_nid, HIPQUAD(peer->ibp_ip));
2709
2710                 cv->cv_pkey_index = IBNAL_PKEY_IDX;
2711                 cv->cv_sgid_index = IBNAL_SGID_IDX;
2712                 cv->cv_port = arp->local_port_num;
2713
2714                 memset(path, 0, sizeof(*path));
2715
2716                 vvrc = port_num2base_gid(kibnal_data.kib_hca, cv->cv_port,
2717                                          &path->sgid);
2718                 LASSERT (vvrc == vv_return_ok);
2719
2720                 vvrc = port_num2base_lid(kibnal_data.kib_hca, cv->cv_port,
2721                                          &path->slid);
2722                 LASSERT (vvrc == vv_return_ok);
2723
2724                 path->dgid          = arp->gid;
2725                 path->sl            = IBNAL_SERVICE_LEVEL;
2726                 path->dlid          = arp->lid;
2727                 path->mtu           = IBNAL_IB_MTU;
2728                 path->rate          = IBNAL_STATIC_RATE;
2729                 path->pkt_life_time = IBNAL_PKT_LIFETIME;
2730                 path->pkey          = IBNAL_PKEY;
2731                 path->traffic_class = IBNAL_TRAFFIC_CLASS;
2732         } else {
2733                 CERROR("Can't Arp "LPX64"@%u.%u.%u.%u: no PATH or LID\n", 
2734                        peer->ibp_nid, HIPQUAD(peer->ibp_ip));
2735                 kibnal_connreq_done(conn, 1, -ENETUNREACH);
2736                 return;
2737         }
2738
2739         rc = kibnal_set_qp_state(conn, vv_qp_state_init);
2740         if (rc != 0) {
2741                 kibnal_connreq_done(conn, 1, rc);
2742         }
2743
2744         /* do the actual connection request */
2745         kibnal_connect_conn(conn);
2746 }
2747
2748 void
2749 kibnal_arp_callback (ibat_stat_t arprc, ibat_arp_data_t *arp_data, void *arg)
2750 {
2751         /* CAVEAT EMPTOR: tasklet context */
2752         kib_conn_t      *conn = (kib_conn_t *)arg;
2753         kib_peer_t      *peer = conn->ibc_peer;
2754         unsigned long    flags;
2755
2756         if (arprc != ibat_stat_ok)
2757                 CERROR("Arp "LPX64"@%u.%u.%u.%u failed: %d\n",
2758                        peer->ibp_nid, HIPQUAD(peer->ibp_ip), arprc);
2759         else
2760                 CDEBUG(D_NET, "Arp "LPX64"@%u.%u.%u.%u OK: LID %s PATH %s\n",
2761                        peer->ibp_nid, HIPQUAD(peer->ibp_ip), 
2762                        (arp_data->mask & IBAT_LID_VALID) == 0 ? "invalid" : "valid",
2763                        (arp_data->mask & IBAT_PRI_PATH_VALID) == 0 ? "invalid" : "valid");
2764
2765         LASSERT (conn != NULL);
2766         LASSERT (conn->ibc_state == IBNAL_CONN_ACTIVE_ARP);
2767
2768         conn->ibc_connvars->cv_arprc = arprc;
2769         if (arprc == ibat_stat_ok)
2770                 conn->ibc_connvars->cv_arp = *arp_data;
2771         
2772         /* connd takes over my ref on conn */
2773         spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
2774         
2775         list_add_tail(&conn->ibc_list, &kibnal_data.kib_connd_conns);
2776         wake_up(&kibnal_data.kib_connd_waitq);
2777         
2778         spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
2779 }
2780
2781 void
2782 kibnal_arp_peer (kib_peer_t *peer)
2783 {
2784         cm_cep_handle_t  cep;
2785         kib_conn_t      *conn;
2786         int              ibatrc;
2787
2788         /* Only the connd does this (i.e. single threaded) */
2789         LASSERT (current == kibnal_data.kib_connd);
2790         LASSERT (peer->ibp_connecting != 0);
2791
2792         cep = cm_create_cep(cm_cep_transp_rc);
2793         if (cep == NULL) {
2794                 CERROR ("Can't create cep for conn->"LPX64"\n",
2795                         peer->ibp_nid);
2796                 kibnal_peer_connect_failed(peer, 1);
2797                 return;
2798         }
2799
2800         conn = kibnal_create_conn(cep);
2801         if (conn == NULL) {
2802                 CERROR ("Can't allocate conn->"LPX64"\n",
2803                         peer->ibp_nid);
2804                 cm_destroy_cep(cep);
2805                 kibnal_peer_connect_failed(peer, 1);
2806                 return;
2807         }
2808
2809         conn->ibc_peer = peer;
2810         kibnal_peer_addref(peer);
2811
2812         kibnal_set_conn_state(conn, IBNAL_CONN_ACTIVE_ARP);
2813
2814         ibatrc = ibat_get_ib_data(htonl(peer->ibp_ip), INADDR_ANY, 
2815                                   ibat_paths_primary,
2816                                   &conn->ibc_connvars->cv_arp, 
2817                                   kibnal_arp_callback, conn, 0);
2818         CDEBUG(D_NET,"ibatrc %d\n", ibatrc);
2819         switch (ibatrc) {
2820         default:
2821                 LBUG();
2822                 
2823         case ibat_stat_pending:
2824                 /* NB callback has my ref on conn */
2825                 break;
2826                 
2827         case ibat_stat_ok:
2828                 /* Immediate return (ARP cache hit) == no callback. */
2829                 conn->ibc_connvars->cv_arprc = ibat_stat_ok;
2830                 kibnal_send_connreq(conn);
2831                 kibnal_conn_decref(conn);
2832                 break;
2833
2834         case ibat_stat_error:
2835         case ibat_stat_timeout:
2836         case ibat_stat_not_found:
2837                 CERROR("Arp "LPX64"@%u.%u.%u.%u failed: %d\n", peer->ibp_nid,
2838                        HIPQUAD(peer->ibp_ip), ibatrc);
2839                 kibnal_connreq_done(conn, 1, -ENETUNREACH);
2840                 kibnal_conn_decref(conn);
2841                 break;
2842         }
2843 }
2844
2845 int
2846 kibnal_conn_timed_out (kib_conn_t *conn)
2847 {
2848         kib_tx_t          *tx;
2849         struct list_head  *ttmp;
2850
2851         spin_lock(&conn->ibc_lock);
2852
2853         list_for_each (ttmp, &conn->ibc_tx_queue) {
2854                 tx = list_entry (ttmp, kib_tx_t, tx_list);
2855
2856                 LASSERT (tx->tx_queued);
2857
2858                 if (time_after_eq (jiffies, tx->tx_deadline)) {
2859                         spin_unlock(&conn->ibc_lock);
2860                         return 1;
2861                 }
2862         }
2863
2864         list_for_each (ttmp, &conn->ibc_active_txs) {
2865                 tx = list_entry (ttmp, kib_tx_t, tx_list);
2866
2867                 LASSERT (!tx->tx_queued);
2868                 LASSERT (tx->tx_waiting ||
2869                          tx->tx_sending != 0);
2870
2871                 if (time_after_eq (jiffies, tx->tx_deadline)) {
2872                         spin_unlock(&conn->ibc_lock);
2873                         return 1;
2874                 }
2875         }
2876
2877         spin_unlock(&conn->ibc_lock);
2878         return 0;
2879 }
2880
2881 void
2882 kibnal_check_conns (int idx)
2883 {
2884         struct list_head  *peers = &kibnal_data.kib_peers[idx];
2885         struct list_head  *ptmp;
2886         kib_peer_t        *peer;
2887         kib_conn_t        *conn;
2888         struct list_head  *ctmp;
2889         unsigned long      flags;
2890
2891  again:
2892         /* NB. We expect to have a look at all the peers and not find any
2893          * rdmas to time out, so we just use a shared lock while we
2894          * take a look... */
2895         read_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2896
2897         list_for_each (ptmp, peers) {
2898                 peer = list_entry (ptmp, kib_peer_t, ibp_list);
2899
2900                 list_for_each (ctmp, &peer->ibp_conns) {
2901                         conn = list_entry (ctmp, kib_conn_t, ibc_list);
2902
2903                         LASSERT (conn->ibc_state == IBNAL_CONN_ESTABLISHED);
2904
2905                         /* In case we have enough credits to return via a
2906                          * NOOP, but there were no non-blocking tx descs
2907                          * free to do it last time... */
2908                         kibnal_check_sends(conn);
2909
2910                         if (!kibnal_conn_timed_out(conn))
2911                                 continue;
2912
2913                         /* Handle timeout by closing the whole connection.  We
2914                          * can only be sure RDMA activity has ceased once the
2915                          * QP has been modified. */
2916                         
2917                         kibnal_conn_addref(conn); /* 1 ref for me... */
2918
2919                         read_unlock_irqrestore(&kibnal_data.kib_global_lock, 
2920                                                flags);
2921
2922                         CERROR("Timed out RDMA with "LPX64"\n",
2923                                peer->ibp_nid);
2924
2925                         kibnal_close_conn (conn, -ETIMEDOUT);
2926                         kibnal_conn_decref(conn); /* ...until here */
2927
2928                         /* start again now I've dropped the lock */
2929                         goto again;
2930                 }
2931         }
2932
2933         read_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2934 }
2935
2936 void
2937 kibnal_disconnect_conn (kib_conn_t *conn)
2938 {
2939         static cm_drequest_data_t dreq;         /* just for the space */
2940         
2941         cm_return_t    cmrc;
2942         unsigned long  flags;
2943
2944         LASSERT (!in_interrupt());
2945         LASSERT (current == kibnal_data.kib_connd);
2946         
2947         write_lock_irqsave(&kibnal_data.kib_global_lock, flags);
2948
2949         if (conn->ibc_disconnect) {
2950                 /* Had the CM callback already */
2951                 write_unlock_irqrestore(&kibnal_data.kib_global_lock,
2952                                         flags);
2953                 kibnal_conn_disconnected(conn);
2954                 return;
2955         }
2956                 
2957         LASSERT (conn->ibc_state == IBNAL_CONN_DISCONNECT1);
2958
2959         /* active disconnect */
2960         cmrc = cm_disconnect(conn->ibc_cep, &dreq, NULL);
2961         if (cmrc == cm_stat_success) {
2962                 /* waiting for CM */
2963                 conn->ibc_state = IBNAL_CONN_DISCONNECT2;
2964                 write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2965                 return;
2966         }
2967
2968         write_unlock_irqrestore(&kibnal_data.kib_global_lock, flags);
2969
2970         cm_cancel(conn->ibc_cep);
2971         kibnal_pause(HZ/10);
2972
2973         if (!conn->ibc_disconnect)              /* CM callback will never happen now */
2974                 kibnal_conn_decref(conn);
2975         
2976         LASSERT (atomic_read(&conn->ibc_refcount) > 0);
2977         LASSERT (conn->ibc_state == IBNAL_CONN_DISCONNECT1);
2978
2979         kibnal_conn_disconnected(conn);
2980 }
2981
2982 int
2983 kibnal_connd (void *arg)
2984 {
2985         wait_queue_t       wait;
2986         unsigned long      flags;
2987         kib_pcreq_t       *pcr;
2988         kib_conn_t        *conn;
2989         kib_peer_t        *peer;
2990         int                timeout;
2991         int                i;
2992         int                dropped_lock;
2993         int                peer_index = 0;
2994         unsigned long      deadline = jiffies;
2995         
2996         kportal_daemonize ("kibnal_connd");
2997         kportal_blockallsigs ();
2998
2999         init_waitqueue_entry (&wait, current);
3000         kibnal_data.kib_connd = current;
3001
3002         spin_lock_irqsave (&kibnal_data.kib_connd_lock, flags);
3003
3004         while (!kibnal_data.kib_shutdown) {
3005
3006                 dropped_lock = 0;
3007
3008                 if (!list_empty (&kibnal_data.kib_connd_zombies)) {
3009                         conn = list_entry (kibnal_data.kib_connd_zombies.next,
3010                                            kib_conn_t, ibc_list);
3011                         list_del (&conn->ibc_list);
3012                         
3013                         spin_unlock_irqrestore (&kibnal_data.kib_connd_lock, flags);
3014                         dropped_lock = 1;
3015
3016                         kibnal_destroy_conn(conn);
3017
3018                         spin_lock_irqsave (&kibnal_data.kib_connd_lock, flags);
3019                 }
3020
3021                 if (!list_empty (&kibnal_data.kib_connd_pcreqs)) {
3022                         pcr = list_entry(kibnal_data.kib_connd_pcreqs.next,
3023                                          kib_pcreq_t, pcr_list);
3024                         list_del(&pcr->pcr_list);
3025                         
3026                         spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
3027                         dropped_lock = 1;
3028
3029                         kibnal_recv_connreq(pcr->pcr_cep, &pcr->pcr_cmreq);
3030                         PORTAL_FREE(pcr, sizeof(*pcr));
3031
3032                         spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
3033                 }
3034                         
3035                 if (!list_empty (&kibnal_data.kib_connd_peers)) {
3036                         peer = list_entry (kibnal_data.kib_connd_peers.next,
3037                                            kib_peer_t, ibp_connd_list);
3038                         
3039                         list_del_init (&peer->ibp_connd_list);
3040                         spin_unlock_irqrestore (&kibnal_data.kib_connd_lock, flags);
3041                         dropped_lock = 1;
3042
3043                         kibnal_arp_peer (peer);
3044                         kibnal_peer_decref (peer);
3045
3046                         spin_lock_irqsave (&kibnal_data.kib_connd_lock, flags);
3047                 }
3048
3049                 if (!list_empty (&kibnal_data.kib_connd_conns)) {
3050                         conn = list_entry (kibnal_data.kib_connd_conns.next,
3051                                            kib_conn_t, ibc_list);
3052                         list_del (&conn->ibc_list);
3053                         
3054                         spin_unlock_irqrestore (&kibnal_data.kib_connd_lock, flags);
3055                         dropped_lock = 1;
3056
3057                         switch (conn->ibc_state) {
3058                         default:
3059                                 LBUG();
3060                                 
3061                         case IBNAL_CONN_ACTIVE_ARP:
3062                                 kibnal_send_connreq(conn);
3063                                 break;
3064
3065                         case IBNAL_CONN_ACTIVE_CONNECT:
3066                                 kibnal_check_connreply(conn);
3067                                 break;
3068
3069                         case IBNAL_CONN_PASSIVE_WAIT:
3070                                 kibnal_check_passive_wait(conn);
3071                                 break;
3072
3073                         case IBNAL_CONN_DISCONNECT1:
3074                         case IBNAL_CONN_DISCONNECT2:
3075                                 kibnal_disconnect_conn(conn);
3076                                 break;
3077                         }
3078                         kibnal_conn_decref(conn);
3079
3080                         spin_lock_irqsave (&kibnal_data.kib_connd_lock, flags);
3081                 }
3082
3083                 /* careful with the jiffy wrap... */
3084                 timeout = (int)(deadline - jiffies);
3085                 if (timeout <= 0) {
3086                         const int n = 4;
3087                         const int p = 1;
3088                         int       chunk = kibnal_data.kib_peer_hash_size;
3089                         
3090                         spin_unlock_irqrestore(&kibnal_data.kib_connd_lock, flags);
3091                         dropped_lock = 1;
3092
3093                         /* Time to check for RDMA timeouts on a few more
3094                          * peers: I do checks every 'p' seconds on a
3095                          * proportion of the peer table and I need to check
3096                          * every connection 'n' times within a timeout
3097                          * interval, to ensure I detect a timeout on any
3098                          * connection within (n+1)/n times the timeout
3099                          * interval. */
3100
3101                         if (kibnal_tunables.kib_io_timeout > n * p)
3102                                 chunk = (chunk * n * p) / 
3103                                         kibnal_tunables.kib_io_timeout;
3104                         if (chunk == 0)
3105                                 chunk = 1;
3106
3107                         for (i = 0; i < chunk; i++) {
3108                                 kibnal_check_conns (peer_index);
3109                                 peer_index = (peer_index + 1) % 
3110                                              kibnal_data.kib_peer_hash_size;
3111                         }
3112
3113                         deadline += p * HZ;
3114                         spin_lock_irqsave(&kibnal_data.kib_connd_lock, flags);
3115                 }
3116
3117                 if (dropped_lock)
3118                         continue;
3119                 
3120                 /* Nothing to do for 'timeout'  */
3121                 set_current_state (TASK_INTERRUPTIBLE);
3122                 add_wait_queue (&kibnal_data.kib_connd_waitq, &wait);
3123                 spin_unlock_irqrestore (&kibnal_data.kib_connd_lock, flags);
3124
3125                 schedule_timeout (timeout);
3126
3127                 set_current_state (TASK_RUNNING);
3128                 remove_wait_queue (&kibnal_data.kib_connd_waitq, &wait);
3129                 spin_lock_irqsave (&kibnal_data.kib_connd_lock, flags);
3130         }
3131
3132         spin_unlock_irqrestore (&kibnal_data.kib_connd_lock, flags);
3133
3134         kibnal_thread_fini ();
3135         return (0);
3136 }
3137
3138 void 
3139 kibnal_async_callback(vv_event_record_t ev)
3140 {
3141         CERROR("type: %d, port: %d, data: "LPX64"\n", 
3142                ev.event_type, ev.port_num, ev.type.data);
3143 }
3144
3145 void
3146 kibnal_cq_callback (unsigned long unused_context)
3147 {
3148         unsigned long    flags;
3149
3150         CDEBUG(D_NET, "!!\n");
3151
3152         spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3153         kibnal_data.kib_ready = 1;
3154         wake_up(&kibnal_data.kib_sched_waitq);
3155         spin_unlock_irqrestore(&kibnal_data.kib_sched_lock, flags);
3156 }
3157
3158 int
3159 kibnal_scheduler(void *arg)
3160 {
3161         long            id = (long)arg;
3162         wait_queue_t    wait;
3163         char            name[16];
3164         vv_wc_t         wc;
3165         vv_return_t     vvrc;
3166         vv_return_t     vvrc2;
3167         unsigned long   flags;
3168         kib_rx_t       *rx;
3169         __u64           rxseq = 0;
3170         int             busy_loops = 0;
3171
3172         snprintf(name, sizeof(name), "kibnal_sd_%02ld", id);
3173         kportal_daemonize(name);
3174         kportal_blockallsigs();
3175
3176         init_waitqueue_entry(&wait, current);
3177
3178         spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3179
3180         while (!kibnal_data.kib_shutdown) {
3181                 if (busy_loops++ >= IBNAL_RESCHED) {
3182                         spin_unlock_irqrestore(&kibnal_data.kib_sched_lock,
3183                                                flags);
3184
3185                         our_cond_resched();
3186                         busy_loops = 0;
3187                         
3188                         spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3189                 }
3190
3191                 if (kibnal_data.kib_ready &&
3192                     !kibnal_data.kib_checking_cq) {
3193                         /* take ownership of completion polling */
3194                         kibnal_data.kib_checking_cq = 1;
3195                         /* Assume I'll exhaust the CQ */
3196                         kibnal_data.kib_ready = 0;
3197                         spin_unlock_irqrestore(&kibnal_data.kib_sched_lock, 
3198                                                flags);
3199                         
3200                         vvrc = vv_poll_for_completion(kibnal_data.kib_hca, 
3201                                                       kibnal_data.kib_cq, &wc);
3202                         if (vvrc == vv_return_err_cq_empty) {
3203                                 vvrc2 = vv_request_completion_notification(
3204                                         kibnal_data.kib_hca, 
3205                                         kibnal_data.kib_cq, 
3206                                         vv_next_solicit_unsolicit_event);
3207                                 LASSERT (vvrc2 == vv_return_ok);
3208                         }
3209
3210                         if (vvrc == vv_return_ok &&
3211                             kibnal_wreqid2type(wc.wr_id) == IBNAL_WID_RX) {
3212                                 rx = (kib_rx_t *)kibnal_wreqid2ptr(wc.wr_id);
3213
3214                                 /* Grab the RX sequence number NOW before
3215                                  * anyone else can get an RX completion */
3216                                 rxseq = rx->rx_conn->ibc_rxseq++;
3217                         }
3218
3219                         spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3220                         /* give up ownership of completion polling */
3221                         kibnal_data.kib_checking_cq = 0;
3222
3223                         if (vvrc == vv_return_err_cq_empty)
3224                                 continue;
3225
3226                         LASSERT (vvrc == vv_return_ok);
3227                         /* Assume there's more: get another scheduler to check
3228                          * while I handle this completion... */
3229
3230                         kibnal_data.kib_ready = 1;
3231                         wake_up(&kibnal_data.kib_sched_waitq);
3232
3233                         spin_unlock_irqrestore(&kibnal_data.kib_sched_lock,
3234                                                flags);
3235
3236                         switch (kibnal_wreqid2type(wc.wr_id)) {
3237                         case IBNAL_WID_RX:
3238                                 kibnal_rx_complete(
3239                                         (kib_rx_t *)kibnal_wreqid2ptr(wc.wr_id),
3240                                         wc.completion_status,
3241                                         wc.num_bytes_transfered,
3242                                         rxseq);
3243                                 break;
3244
3245                         case IBNAL_WID_TX:
3246                                 kibnal_tx_complete(
3247                                         (kib_tx_t *)kibnal_wreqid2ptr(wc.wr_id),
3248                                         wc.completion_status);
3249                                 break;
3250
3251                         case IBNAL_WID_RDMA:
3252                                 /* We only get RDMA completion notification if
3253                                  * it fails.  So we just ignore them completely
3254                                  * because...
3255                                  *
3256                                  * 1) If an RDMA fails, all subsequent work
3257                                  * items, including the final SEND will fail
3258                                  * too, so I'm still guaranteed to notice that
3259                                  * this connection is hosed.
3260                                  *
3261                                  * 2) It's positively dangerous to look inside
3262                                  * the tx descriptor obtained from an RDMA work
3263                                  * item.  As soon as I drop the kib_sched_lock,
3264                                  * I give a scheduler on another CPU a chance
3265                                  * to get the final SEND completion, so the tx
3266                                  * descriptor can get freed as I inspect it. */
3267                                 CERROR ("RDMA failed: %d\n", 
3268                                         wc.completion_status);
3269                                 break;
3270
3271                         default:
3272                                 LBUG();
3273                         }
3274                         
3275                         spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3276                         continue;
3277                 }
3278
3279                 /* Nothing to do; sleep... */
3280
3281                 set_current_state(TASK_INTERRUPTIBLE);
3282                 add_wait_queue(&kibnal_data.kib_sched_waitq, &wait);
3283                 spin_unlock_irqrestore(&kibnal_data.kib_sched_lock,
3284                                        flags);
3285
3286                 schedule();
3287
3288                 remove_wait_queue(&kibnal_data.kib_sched_waitq, &wait);
3289                 set_current_state(TASK_RUNNING);
3290                 spin_lock_irqsave(&kibnal_data.kib_sched_lock, flags);
3291         }
3292
3293         spin_unlock_irqrestore(&kibnal_data.kib_sched_lock, flags);
3294
3295         kibnal_thread_fini();
3296         return (0);
3297 }
3298
3299
3300 lib_nal_t kibnal_lib = {
3301         .libnal_data = &kibnal_data,      /* NAL private data */
3302         .libnal_send = kibnal_send,
3303         .libnal_send_pages = kibnal_send_pages,
3304         .libnal_recv = kibnal_recv,
3305         .libnal_recv_pages = kibnal_recv_pages,
3306         .libnal_dist = kibnal_dist
3307 };