Whamcloud - gitweb
92a139c5dd7a6bca109bbb35b6be9bcd71ff30ef
[fs/lustre-release.git] / lnet / klnds / gnilnd / gnilnd.c
1 /*
2  * Copyright (C) 2012 Cray, Inc.
3  *
4  *   Author: Nic Henke <nic@cray.com>
5  *   Author: James Shimek <jshimek@cray.com>
6  *
7  *   This file is part of Lustre, http://www.lustre.org.
8  *
9  *   Lustre is free software; you can redistribute it and/or
10  *   modify it under the terms of version 2 of the GNU General Public
11  *   License as published by the Free Software Foundation.
12  *
13  *   Lustre is distributed in the hope that it will be useful,
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *   GNU General Public License for more details.
17  *
18  *   You should have received a copy of the GNU General Public License
19  *   along with Lustre; if not, write to the Free Software
20  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *
22  */
23 #include "gnilnd.h"
24
25 /* Primary entry points from LNET.  There are no guarantees against reentrance. */
26 lnd_t the_kgnilnd = {
27         .lnd_type       = GNILND,
28         .lnd_startup    = kgnilnd_startup,
29         .lnd_shutdown   = kgnilnd_shutdown,
30         .lnd_ctl        = kgnilnd_ctl,
31         .lnd_send       = kgnilnd_send,
32         .lnd_recv       = kgnilnd_recv,
33         .lnd_eager_recv = kgnilnd_eager_recv,
34         .lnd_query      = kgnilnd_query,
35 };
36
37 kgn_data_t      kgnilnd_data;
38
39 /* needs write_lock on kgn_peer_conn_lock */
40 int
41 kgnilnd_close_stale_conns_locked(kgn_peer_t *peer, kgn_conn_t *newconn)
42 {
43         kgn_conn_t         *conn;
44         struct list_head   *ctmp, *cnxt;
45         int                 loopback;
46         int                 count = 0;
47
48         loopback = peer->gnp_nid == peer->gnp_net->gnn_ni->ni_nid;
49
50         list_for_each_safe(ctmp, cnxt, &peer->gnp_conns) {
51                 conn = list_entry(ctmp, kgn_conn_t, gnc_list);
52
53                 if (conn->gnc_state != GNILND_CONN_ESTABLISHED)
54                         continue;
55
56                 if (conn == newconn)
57                         continue;
58
59                 if (conn->gnc_device != newconn->gnc_device)
60                         continue;
61
62                 /* This is a two connection loopback - one talking to the other */
63                 if (loopback &&
64                     newconn->gnc_my_connstamp == conn->gnc_peer_connstamp &&
65                     newconn->gnc_peer_connstamp == conn->gnc_my_connstamp) {
66                         CDEBUG(D_NET, "skipping prune of %p, "
67                                 "loopback and matching stamps"
68                                 " connstamp "LPU64"("LPU64")"
69                                 " peerstamp "LPU64"("LPU64")\n",
70                                 conn, newconn->gnc_my_connstamp,
71                                 conn->gnc_peer_connstamp,
72                                 newconn->gnc_peer_connstamp,
73                                 conn->gnc_my_connstamp);
74                         continue;
75                 }
76
77                 if (conn->gnc_peerstamp != newconn->gnc_peerstamp) {
78                         LASSERTF(conn->gnc_peerstamp < newconn->gnc_peerstamp,
79                                 "conn 0x%p peerstamp "LPU64" >= "
80                                 "newconn 0x%p peerstamp "LPU64"\n",
81                                 conn, conn->gnc_peerstamp,
82                                 newconn, newconn->gnc_peerstamp);
83
84                         CDEBUG(D_NET, "Closing stale conn nid: %s "
85                                " peerstamp:"LPX64"("LPX64")\n",
86                                libcfs_nid2str(peer->gnp_nid),
87                                conn->gnc_peerstamp, newconn->gnc_peerstamp);
88                 } else {
89
90                         LASSERTF(conn->gnc_peer_connstamp < newconn->gnc_peer_connstamp,
91                                 "conn 0x%p peer_connstamp "LPU64" >= "
92                                 "newconn 0x%p peer_connstamp "LPU64"\n",
93                                 conn, conn->gnc_peer_connstamp,
94                                 newconn, newconn->gnc_peer_connstamp);
95
96                         CDEBUG(D_NET, "Closing stale conn nid: %s"
97                                " connstamp:"LPU64"("LPU64")\n",
98                                libcfs_nid2str(peer->gnp_nid),
99                                conn->gnc_peer_connstamp, newconn->gnc_peer_connstamp);
100                 }
101
102                 count++;
103                 kgnilnd_close_conn_locked(conn, -ESTALE);
104         }
105
106         if (count != 0) {
107                 CWARN("Closed %d stale conns to %s\n", count, libcfs_nid2str(peer->gnp_nid));
108         }
109
110         RETURN(count);
111 }
112
113 int
114 kgnilnd_conn_isdup_locked(kgn_peer_t *peer, kgn_conn_t *newconn)
115 {
116         kgn_conn_t       *conn;
117         struct list_head *tmp;
118         int               loopback;
119         ENTRY;
120
121         loopback = peer->gnp_nid == peer->gnp_net->gnn_ni->ni_nid;
122
123         list_for_each(tmp, &peer->gnp_conns) {
124                 conn = list_entry(tmp, kgn_conn_t, gnc_list);
125                 CDEBUG(D_NET, "checking conn 0x%p for peer %s"
126                         " lo %d new "LPU64" existing "LPU64
127                         " new peer "LPU64" existing peer "LPU64
128                         " new dev %p existing dev %p\n",
129                         conn, libcfs_nid2str(peer->gnp_nid),
130                         loopback,
131                         newconn->gnc_peerstamp, conn->gnc_peerstamp,
132                         newconn->gnc_peer_connstamp, conn->gnc_peer_connstamp,
133                         newconn->gnc_device, conn->gnc_device);
134
135                 /* conn is in the process of closing */
136                 if (conn->gnc_state != GNILND_CONN_ESTABLISHED)
137                         continue;
138
139                 /* 'newconn' is from an earlier version of 'peer'!!! */
140                 if (newconn->gnc_peerstamp < conn->gnc_peerstamp)
141                         RETURN(1);
142
143                 /* 'conn' is from an earlier version of 'peer': it will be
144                  * removed when we cull stale conns later on... */
145                 if (newconn->gnc_peerstamp > conn->gnc_peerstamp)
146                         continue;
147
148                 /* Different devices are OK */
149                 if (conn->gnc_device != newconn->gnc_device)
150                         continue;
151
152                 /* It's me connecting to myself */
153                 if (loopback &&
154                     newconn->gnc_my_connstamp == conn->gnc_peer_connstamp &&
155                     newconn->gnc_peer_connstamp == conn->gnc_my_connstamp)
156                         continue;
157
158                 /* 'newconn' is an earlier connection from 'peer'!!! */
159                 if (newconn->gnc_peer_connstamp < conn->gnc_peer_connstamp)
160                         RETURN(2);
161
162                 /* 'conn' is an earlier connection from 'peer': it will be
163                  * removed when we cull stale conns later on... */
164                 if (newconn->gnc_peer_connstamp > conn->gnc_peer_connstamp)
165                         continue;
166
167                 /* 'newconn' has the SAME connection stamp; 'peer' isn't
168                  * playing the game... */
169                 RETURN(3);
170         }
171
172         RETURN(0);
173 }
174
175 int
176 kgnilnd_create_conn(kgn_conn_t **connp, kgn_device_t *dev)
177 {
178         kgn_conn_t      *conn;
179         gni_return_t    rrc;
180         int             rc = 0;
181
182         LASSERT (!in_interrupt());
183         atomic_inc(&kgnilnd_data.kgn_nconns);
184
185         /* divide by 2 to allow for complete reset and immediate reconnect */
186         if (atomic_read(&kgnilnd_data.kgn_nconns) >= GNILND_MAX_CQID/2) {
187                 CERROR("Too many conn are live: %d > %d\n",
188                         atomic_read(&kgnilnd_data.kgn_nconns), GNILND_MAX_CQID/2);
189                 atomic_dec(&kgnilnd_data.kgn_nconns);
190                 return -E2BIG;
191         }
192
193         LIBCFS_ALLOC(conn, sizeof(*conn));
194         if (conn == NULL) {
195                 atomic_dec(&kgnilnd_data.kgn_nconns);
196                 return -ENOMEM;
197         }
198
199         LIBCFS_ALLOC(conn->gnc_tx_ref_table, GNILND_MAX_MSG_ID * sizeof(void *));
200         if (conn->gnc_tx_ref_table == NULL) {
201                 CERROR("Can't allocate conn tx_ref_table\n");
202                 rc = -ENOMEM;
203                 GOTO(failed, rc);
204         }
205
206         atomic_set(&conn->gnc_refcount, 1);
207         atomic_set(&conn->gnc_reaper_noop, 0);
208         atomic_set(&conn->gnc_sched_noop, 0);
209         atomic_set(&conn->gnc_tx_in_use, 0);
210         INIT_LIST_HEAD(&conn->gnc_list);
211         INIT_LIST_HEAD(&conn->gnc_hashlist);
212         INIT_LIST_HEAD(&conn->gnc_schedlist);
213         INIT_LIST_HEAD(&conn->gnc_fmaq);
214         INIT_LIST_HEAD(&conn->gnc_mdd_list);
215         spin_lock_init(&conn->gnc_list_lock);
216         spin_lock_init(&conn->gnc_tx_lock);
217         conn->gnc_magic = GNILND_CONN_MAGIC;
218
219         /* set tx id to nearly the end to make sure we find wrapping
220          * issues soon */
221         conn->gnc_next_tx = (int) GNILND_MAX_MSG_ID - 10;
222
223         /* if this fails, we have conflicts and MAX_TX is too large */
224         CLASSERT(GNILND_MAX_MSG_ID < GNILND_MSGID_CLOSE);
225
226         /* get a new unique CQ id for this conn */
227         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
228         conn->gnc_my_connstamp = kgnilnd_data.kgn_connstamp++;
229         conn->gnc_cqid = kgnilnd_get_cqid_locked();
230         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
231
232         if (conn->gnc_cqid == 0) {
233                 CERROR("Could not allocate unique CQ ID for conn 0x%p\n", conn);
234                 rc = -E2BIG;
235                 GOTO(failed, rc);
236         }
237
238         CDEBUG(D_NET, "alloc cqid %u for conn 0x%p\n",
239                 conn->gnc_cqid, conn);
240
241         /* need to be set before gnc_ephandle to allow kgnilnd_destroy_conn_ep to
242          * check context */
243         conn->gnc_device = dev;
244
245         conn->gnc_timeout = MAX(*kgnilnd_tunables.kgn_timeout,
246                                 GNILND_MIN_TIMEOUT);
247         kgnilnd_update_reaper_timeout(conn->gnc_timeout);
248
249         /* this is the ep_handle for doing SMSG & BTE */
250         mutex_lock(&dev->gnd_cq_mutex);
251         rrc = kgnilnd_ep_create(dev->gnd_handle, dev->gnd_snd_fma_cqh,
252                                 &conn->gnc_ephandle);
253         mutex_unlock(&dev->gnd_cq_mutex);
254         if (rrc != GNI_RC_SUCCESS) {
255                 rc = -ENETDOWN;
256                 GOTO(failed, rc);
257         }
258
259         CDEBUG(D_NET, "created conn 0x%p ep_hndl 0x%p\n",
260                conn, conn->gnc_ephandle);
261
262         /* add ref for EP canceling */
263         kgnilnd_conn_addref(conn);
264         atomic_inc(&dev->gnd_neps);
265
266         *connp = conn;
267         return 0;
268
269 failed:
270         atomic_dec(&kgnilnd_data.kgn_nconns);
271         LIBCFS_FREE(conn->gnc_tx_ref_table, GNILND_MAX_MSG_ID * sizeof(void *));
272         LIBCFS_FREE(conn, sizeof(*conn));
273         return rc;
274 }
275
276 /* needs to be called with kgn_peer_conn_lock held (read or write) */
277 kgn_conn_t *
278 kgnilnd_find_conn_locked(kgn_peer_t *peer)
279 {
280         kgn_conn_t      *conn = NULL;
281
282         /* if we are in reset, this conn is going to die soon */
283         if (unlikely(kgnilnd_data.kgn_in_reset)) {
284                 RETURN(NULL);
285         }
286
287         /* just return the first ESTABLISHED connection */
288         list_for_each_entry(conn, &peer->gnp_conns, gnc_list) {
289                 /* kgnilnd_finish_connect doesn't put connections on the
290                  * peer list until they are actually established */
291                 LASSERTF(conn->gnc_state >= GNILND_CONN_ESTABLISHED,
292                         "found conn %p state %s on peer %p (%s)\n",
293                         conn, kgnilnd_conn_state2str(conn), peer,
294                         libcfs_nid2str(peer->gnp_nid));
295                 if (conn->gnc_state != GNILND_CONN_ESTABLISHED)
296                         continue;
297
298                 RETURN(conn);
299         }
300         RETURN(NULL);
301 }
302
303 /* needs write_lock on kgn_peer_conn_lock held */
304 kgn_conn_t *
305 kgnilnd_find_or_create_conn_locked(kgn_peer_t *peer) {
306
307         kgn_device_t    *dev = peer->gnp_net->gnn_dev;
308         kgn_conn_t      *conn;
309
310         conn = kgnilnd_find_conn_locked(peer);
311
312         if (conn != NULL) {
313                 return conn;
314         }
315
316         /* if the peer was previously connecting, check if we should
317          * trigger another connection attempt yet. */
318         if (time_before(jiffies, peer->gnp_reconnect_time)) {
319                 return NULL;
320         }
321
322         /* This check prevents us from creating a new connection to a peer while we are
323          * still in the process of closing an existing connection to the peer.
324          */
325         list_for_each_entry(conn, &peer->gnp_conns, gnc_list) {
326                 if (conn->gnc_ephandle != NULL) {
327                         CDEBUG(D_NET, "Not connecting non-null ephandle found peer 0x%p->%s\n", peer,
328                                 libcfs_nid2str(peer->gnp_nid));
329                         return NULL;
330                 }
331         }
332
333         if (peer->gnp_connecting != GNILND_PEER_IDLE) {
334                 /* if we are not connecting, fire up a new connection */
335                 /* or if we are anything but IDLE DONT start a new connection */
336                return NULL;
337         }
338
339         CDEBUG(D_NET, "starting connect to %s\n",
340                 libcfs_nid2str(peer->gnp_nid));
341         peer->gnp_connecting = GNILND_PEER_CONNECT;
342         kgnilnd_peer_addref(peer); /* extra ref for connd */
343
344         spin_lock(&dev->gnd_connd_lock);
345         list_add_tail(&peer->gnp_connd_list, &dev->gnd_connd_peers);
346         spin_unlock(&dev->gnd_connd_lock);
347
348         kgnilnd_schedule_dgram(dev);
349         CDEBUG(D_NETTRACE, "scheduling new connect\n");
350
351         return NULL;
352 }
353
354 /* Caller is responsible for deciding if/when to call this */
355 void
356 kgnilnd_destroy_conn_ep(kgn_conn_t *conn)
357 {
358         gni_return_t    rrc;
359         gni_ep_handle_t tmp_ep;
360
361         /* only if we actually initialized it,
362          *  then set NULL to tell kgnilnd_destroy_conn to leave it alone */
363
364         tmp_ep = xchg(&conn->gnc_ephandle, NULL);
365         if (tmp_ep != NULL) {
366                 /* we never re-use the EP, so unbind is not needed */
367                 mutex_lock(&conn->gnc_device->gnd_cq_mutex);
368                 rrc = kgnilnd_ep_destroy(tmp_ep);
369
370                 mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
371
372                 /* if this fails, it could hork up kgni smsg retransmit and others
373                  * since we could free the SMSG mbox memory, etc. */
374                 LASSERTF(rrc == GNI_RC_SUCCESS, "rrc %d conn 0x%p ep 0x%p\n",
375                          rrc, conn, conn->gnc_ephandle);
376
377                 atomic_dec(&conn->gnc_device->gnd_neps);
378
379                 /* clear out count added in kgnilnd_close_conn_locked
380                  * conn will have a peer once it hits finish_connect, where it
381                  * is the first spot we'll mark it ESTABLISHED as well */
382                 if (conn->gnc_peer) {
383                         kgnilnd_admin_decref(conn->gnc_peer->gnp_dirty_eps);
384                 }
385
386                 /* drop ref for EP */
387                 kgnilnd_conn_decref(conn);
388         }
389 }
390
391 void
392 kgnilnd_destroy_conn(kgn_conn_t *conn)
393 {
394         LASSERTF(!in_interrupt() &&
395                 !conn->gnc_scheduled &&
396                 !conn->gnc_in_purgatory &&
397                 conn->gnc_ephandle == NULL &&
398                 list_empty(&conn->gnc_list) &&
399                 list_empty(&conn->gnc_hashlist) &&
400                 list_empty(&conn->gnc_schedlist) &&
401                 list_empty(&conn->gnc_mdd_list) &&
402                 conn->gnc_magic == GNILND_CONN_MAGIC,
403                 "conn 0x%p->%s IRQ %d sched %d purg %d ep 0x%p Mg %d lists %d/%d/%d/%d\n",
404                 conn, conn->gnc_peer ? libcfs_nid2str(conn->gnc_peer->gnp_nid)
405                                      : "<?>",
406                 !!in_interrupt(), conn->gnc_scheduled,
407                 conn->gnc_in_purgatory,
408                 conn->gnc_ephandle,
409                 conn->gnc_magic,
410                 list_empty(&conn->gnc_list),
411                 list_empty(&conn->gnc_hashlist),
412                 list_empty(&conn->gnc_schedlist),
413                 list_empty(&conn->gnc_mdd_list));
414
415         /* Tripping these is especially bad, as it means we have items on the
416          *  lists that didn't keep their refcount on the connection - or
417          *  somebody evil released their own */
418         LASSERTF(list_empty(&conn->gnc_fmaq) &&
419                  atomic_read(&conn->gnc_nlive_fma) == 0 &&
420                  atomic_read(&conn->gnc_nlive_rdma) == 0,
421                  "conn 0x%p fmaq %d@0x%p nfma %d nrdma %d\n",
422                  conn, kgnilnd_count_list(&conn->gnc_fmaq), &conn->gnc_fmaq,
423                  atomic_read(&conn->gnc_nlive_fma), atomic_read(&conn->gnc_nlive_rdma));
424
425         CDEBUG(D_NET, "destroying conn %p ephandle %p error %d\n",
426                 conn, conn->gnc_ephandle, conn->gnc_error);
427
428         /* We are freeing this memory remove the magic value from the connection */
429         conn->gnc_magic = 0;
430
431         /* if there is an FMA blk left here, we'll tear it down */
432         if (conn->gnc_fma_blk) {
433                 if (conn->gnc_peer) {
434                         kgn_mbox_info_t *mbox;
435                         mbox = &conn->gnc_fma_blk->gnm_mbox_info[conn->gnc_mbox_id];
436                         mbox->mbx_prev_nid = conn->gnc_peer->gnp_nid;
437                 }
438                 kgnilnd_release_mbox(conn, 0);
439         }
440
441         if (conn->gnc_peer != NULL)
442                 kgnilnd_peer_decref(conn->gnc_peer);
443
444         if (conn->gnc_tx_ref_table != NULL) {
445                 LIBCFS_FREE(conn->gnc_tx_ref_table,
446                             GNILND_MAX_MSG_ID * sizeof(void *));
447         }
448
449         LIBCFS_FREE(conn, sizeof(*conn));
450         atomic_dec(&kgnilnd_data.kgn_nconns);
451 }
452
453 /* peer_alive and peer_notify done in the style of the o2iblnd */
454 void
455 kgnilnd_peer_alive(kgn_peer_t *peer)
456 {
457         set_mb(peer->gnp_last_alive, jiffies);
458 }
459
460 void
461 kgnilnd_peer_notify(kgn_peer_t *peer, int error)
462 {
463         int                     tell_lnet = 0;
464         int                     nnets = 0;
465         int                     rc;
466         int                     i, j;
467         kgn_conn_t             *conn;
468         kgn_net_t             **nets;
469         kgn_net_t              *net;
470
471
472         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DONT_NOTIFY))
473                 return;
474
475         /* Tell LNet we are giving ups on this peer - but only
476          * if it isn't already reconnected or trying to reconnect */
477         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
478
479         /* use kgnilnd_find_conn_locked to avoid any conns in the process of being nuked
480          *
481          * don't tell LNet if we are in reset - we assume that everyone will be able to
482          * reconnect just fine
483          */
484         conn = kgnilnd_find_conn_locked(peer);
485
486         CDEBUG(D_NETTRACE, "peer 0x%p->%s ting %d conn 0x%p, rst %d error %d\n",
487                peer, libcfs_nid2str(peer->gnp_nid), peer->gnp_connecting, conn,
488                kgnilnd_data.kgn_in_reset, error);
489
490         if ((peer->gnp_connecting == GNILND_PEER_IDLE) &&
491             (conn == NULL) &&
492             (!kgnilnd_data.kgn_in_reset) &&
493             (!kgnilnd_conn_clean_errno(error))) {
494                 tell_lnet = 1;
495         }
496
497         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
498
499         if (!tell_lnet) {
500                 /* short circuit if we dont need to notify Lnet */
501                 return;
502         }
503
504         rc = down_read_trylock(&kgnilnd_data.kgn_net_rw_sem);
505
506         if (rc) {
507             /* dont do this if this fails since LNET is in shutdown or something else
508              */
509
510                 for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++) {
511                         list_for_each_entry(net , &kgnilnd_data.kgn_nets[i], gnn_list) {
512                                 /* if gnn_shutdown set for any net shutdown is in progress just return */
513                                 if (net->gnn_shutdown) {
514                                         up_read(&kgnilnd_data.kgn_net_rw_sem);
515                                         return;
516                                 }
517                                 nnets++;
518                         }
519                 }
520
521                 if (nnets == 0) {
522                         /* shutdown in progress most likely */
523                         up_read(&kgnilnd_data.kgn_net_rw_sem);
524                         return;
525                 }
526
527                 LIBCFS_ALLOC(nets, nnets * sizeof(*nets));
528
529                 if (nets == NULL) {
530                         up_read(&kgnilnd_data.kgn_net_rw_sem);
531                         CERROR("Failed to allocate nets[%d]\n", nnets);
532                         return;
533                 }
534
535                 j = 0;
536                 for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++) {
537                         list_for_each_entry(net, &kgnilnd_data.kgn_nets[i], gnn_list) {
538                                 nets[j] = net;
539                                 kgnilnd_net_addref(net);
540                                 j++;
541                         }
542                 }
543                 up_read(&kgnilnd_data.kgn_net_rw_sem);
544
545                 for (i = 0; i < nnets; i++) {
546                         lnet_nid_t peer_nid;
547
548                         net = nets[i];
549
550                         peer_nid = kgnilnd_lnd2lnetnid(net->gnn_ni->ni_nid,
551                                                                  peer->gnp_nid);
552
553                         CDEBUG(D_NET, "peer 0x%p->%s last_alive %lu (%lus ago)\n",
554                                 peer, libcfs_nid2str(peer_nid), peer->gnp_last_alive,
555                                 cfs_duration_sec(jiffies - peer->gnp_last_alive));
556
557                         lnet_notify(net->gnn_ni, peer_nid, 0, peer->gnp_last_alive);
558
559
560                         kgnilnd_net_decref(net);
561                 }
562
563                 LIBCFS_FREE(nets, nnets * sizeof(*nets));
564         }
565 }
566
567 /* need write_lock on kgn_peer_conn_lock */
568 void
569 kgnilnd_close_conn_locked(kgn_conn_t *conn, int error)
570 {
571         kgn_peer_t        *peer = conn->gnc_peer;
572         ENTRY;
573
574         LASSERT(!in_interrupt());
575
576         /* store error for tx completion */
577         conn->gnc_error = error;
578         peer->gnp_last_errno = error;
579
580         /* use real error from peer if possible */
581         if (error == -ECONNRESET) {
582                 error = conn->gnc_peer_error;
583         }
584
585         /* if we NETERROR, make sure it is rate limited */
586         if (!kgnilnd_conn_clean_errno(error) &&
587             peer->gnp_down == GNILND_RCA_NODE_UP) {
588                 CNETERR("closing conn to %s: error %d\n",
589                        libcfs_nid2str(peer->gnp_nid), error);
590         } else {
591                 CDEBUG(D_NET, "closing conn to %s: error %d\n",
592                        libcfs_nid2str(peer->gnp_nid), error);
593         }
594
595         LASSERTF(conn->gnc_state == GNILND_CONN_ESTABLISHED,
596                 "conn %p to %s with bogus state %s\n", conn,
597                 libcfs_nid2str(conn->gnc_peer->gnp_nid),
598                 kgnilnd_conn_state2str(conn));
599         LASSERT(!list_empty(&conn->gnc_hashlist));
600         LASSERT(!list_empty(&conn->gnc_list));
601
602
603         /* mark peer count here so any place the EP gets destroyed will
604          * open up the peer count so that a new ESTABLISHED conn is then free
605          * to send new messages -- sending before the previous EPs are destroyed
606          * could end up with messages on the network for the old conn _after_
607          * the new conn and break the mbox safety protocol */
608         kgnilnd_admin_addref(conn->gnc_peer->gnp_dirty_eps);
609
610         /* Remove from conn hash table: no new callbacks */
611         list_del_init(&conn->gnc_hashlist);
612         kgnilnd_data.kgn_conn_version++;
613         kgnilnd_conn_decref(conn);
614
615         /* if we are in reset, go right to CLOSED as there is no scheduler
616          * thread to move from CLOSING to CLOSED */
617         if (unlikely(kgnilnd_data.kgn_in_reset)) {
618                 conn->gnc_state = GNILND_CONN_CLOSED;
619         } else {
620                 conn->gnc_state = GNILND_CONN_CLOSING;
621         }
622
623         /* leave on peer->gnp_conns to make sure we don't let the reaper
624          * or others try to unlink this peer until the conn is fully
625          * processed for closing */
626
627         if (kgnilnd_check_purgatory_conn(conn)) {
628                 kgnilnd_add_purgatory_locked(conn, conn->gnc_peer);
629         }
630
631         /* Reset RX timeout to ensure we wait for an incoming CLOSE
632          * for the full timeout.  If we get a CLOSE we know the
633          * peer has stopped all RDMA.  Otherwise if we wait for
634          * the full timeout we can also be sure all RDMA has stopped. */
635         conn->gnc_last_rx = conn->gnc_last_rx_cq = jiffies;
636         mb();
637
638         /* schedule sending CLOSE - if we are in quiesce, this adds to
639          * gnd_ready_conns and allows us to find it in quiesce processing */
640         kgnilnd_schedule_conn(conn);
641
642         EXIT;
643 }
644
645 void
646 kgnilnd_close_conn(kgn_conn_t *conn, int error)
647 {
648         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
649         /* need to check the state here - this call is racy and we don't
650          * know the state until after the lock is grabbed */
651         if (conn->gnc_state == GNILND_CONN_ESTABLISHED) {
652                 kgnilnd_close_conn_locked(conn, error);
653         }
654         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
655 }
656
657 void
658 kgnilnd_complete_closed_conn(kgn_conn_t *conn)
659 {
660         LIST_HEAD               (sinners);
661         kgn_tx_t               *tx, *txn;
662         int                     nlive = 0;
663         int                     nrdma = 0;
664         int                     nq_rdma = 0;
665         int                     logmsg;
666         ENTRY;
667
668         /* Dump log  on cksum error - wait until complete phase to let
669          * RX of error happen */
670         if (*kgnilnd_tunables.kgn_checksum_dump &&
671             (conn != NULL && conn->gnc_peer_error == -ENOKEY)) {
672                 libcfs_debug_dumplog();
673         }
674
675         /* _CLOSED set in kgnilnd_process_fmaq once we decide to
676          * send the CLOSE or not */
677         LASSERTF(conn->gnc_state == GNILND_CONN_CLOSED,
678                  "conn 0x%p->%s with bad state %s\n",
679                  conn, conn->gnc_peer ?
680                         libcfs_nid2str(conn->gnc_peer->gnp_nid) :
681                         "<?>",
682                  kgnilnd_conn_state2str(conn));
683
684         LASSERT(list_empty(&conn->gnc_hashlist));
685
686         /* we've sent the close, start nuking */
687         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_SCHEDULE_COMPLETE))
688                 kgnilnd_schedule_conn(conn);
689
690         if (conn->gnc_scheduled != GNILND_CONN_PROCESS) {
691                 CDEBUG(D_NETERROR, "Error someone scheduled us after we were "
692                                 "done, Attempting to recover conn 0x%p "
693                                 "scheduled %d function: %s line: %d\n", conn,
694                                 conn->gnc_scheduled, conn->gnc_sched_caller,
695                                 conn->gnc_sched_line);
696                 RETURN_EXIT;
697         }
698
699         /* we don't use lists to track things that we can get out of the
700          * tx_ref table... */
701
702         /* need to hold locks for tx_list_state, sampling it is too racy:
703          * - the lock actually protects tx != NULL, but we can't take the proper
704          *   lock until we check tx_list_state, which would be too late and
705          *   we could have the TX change under us.
706          * gnd_rdmaq_lock and gnd_lock and not used together, so taking both
707          * should be fine */
708         spin_lock(&conn->gnc_device->gnd_rdmaq_lock);
709         spin_lock(&conn->gnc_device->gnd_lock);
710
711         for (nrdma = 0; nrdma < GNILND_MAX_MSG_ID; nrdma++) {
712                 tx = conn->gnc_tx_ref_table[nrdma];
713
714                 if (tx != NULL) {
715                         /* only print the first error and if not CLOSE, we often don't see
716                          * CQ events for that by the time we get here... and really don't care */
717                         if (nlive || tx->tx_msg.gnm_type == GNILND_MSG_CLOSE)
718                                 tx->tx_state |= GNILND_TX_QUIET_ERROR;
719                         nlive++;
720                         GNIDBG_TX(D_NET, tx, "cleaning up on close, nlive %d", nlive);
721
722                         /* don't worry about gnc_lock here as nobody else should be
723                          * touching this conn */
724                         kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
725                         list_add_tail(&tx->tx_list, &sinners);
726                 }
727         }
728         spin_unlock(&conn->gnc_device->gnd_lock);
729         spin_unlock(&conn->gnc_device->gnd_rdmaq_lock);
730
731         /* nobody should have marked this as needing scheduling after
732          * we called close - so only ref should be us handling it */
733         if (conn->gnc_scheduled != GNILND_CONN_PROCESS) {
734                 CDEBUG(D_NETERROR, "Error someone scheduled us after we were "
735                                 "done, Attempting to recover conn 0x%p "
736                                 "scheduled %d function %s line: %d\n", conn,
737                                 conn->gnc_scheduled, conn->gnc_sched_caller,
738                                 conn->gnc_sched_line);
739         }
740         /* now reset a few to actual counters... */
741         nrdma = atomic_read(&conn->gnc_nlive_rdma);
742         nq_rdma = atomic_read(&conn->gnc_nq_rdma);
743
744         if (!list_empty(&sinners)) {
745                 list_for_each_entry_safe(tx, txn, &sinners, tx_list) {
746                         /* clear tx_list to make tx_add_list_locked happy */
747                         list_del_init(&tx->tx_list);
748                         /* The error codes determine if we hold onto the MDD */
749                         kgnilnd_tx_done(tx, conn->gnc_error);
750                 }
751         }
752
753         logmsg = (nlive + nrdma + nq_rdma);
754
755         if (logmsg) {
756                 if (conn->gnc_peer->gnp_down == GNILND_RCA_NODE_UP) {
757                         CNETERR("Closed conn 0x%p->%s (errno %d, peer errno %d): "
758                                 "canceled %d TX, %d/%d RDMA\n",
759                                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
760                                 conn->gnc_error, conn->gnc_peer_error,
761                                 nlive, nq_rdma, nrdma);
762                 } else {
763                         CDEBUG(D_NET, "Closed conn 0x%p->%s (errno %d,"
764                                 " peer errno %d): canceled %d TX, %d/%d RDMA\n",
765                                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
766                                 conn->gnc_error, conn->gnc_peer_error,
767                                 nlive, nq_rdma, nrdma);
768                 }
769         }
770
771         kgnilnd_destroy_conn_ep(conn);
772
773         /* Bug 765042 - race this with completing a new conn to same peer - we need
774          * finish_connect to detach purgatory before we can do it ourselves here */
775         CFS_RACE(CFS_FAIL_GNI_FINISH_PURG);
776
777         /* now it is safe to remove from peer list - anyone looking at
778          * gnp_conns now is free to unlink if not on purgatory */
779         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
780
781         conn->gnc_state = GNILND_CONN_DONE;
782
783         /* Decrement counter if we are marked by del_conn_or_peers for closing
784          */
785         if (conn->gnc_needs_closing)
786                 kgnilnd_admin_decref(kgnilnd_data.kgn_npending_conns);
787
788         /* Remove from peer's list of valid connections if its not in purgatory */
789         if (!conn->gnc_in_purgatory) {
790                 list_del_init(&conn->gnc_list);
791                 /* Lose peers reference on the conn */
792                 kgnilnd_conn_decref(conn);
793         }
794
795         /* NB - only unlinking if we set pending in del_peer_locked from admin or
796          * shutdown */
797         if (kgnilnd_peer_active(conn->gnc_peer) &&
798             conn->gnc_peer->gnp_pending_unlink &&
799             kgnilnd_can_unlink_peer_locked(conn->gnc_peer)) {
800                 kgnilnd_unlink_peer_locked(conn->gnc_peer);
801         }
802
803         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
804
805         /* I'm telling Mommy! - use peer_error if they initiated close */
806         kgnilnd_peer_notify(conn->gnc_peer,
807                             conn->gnc_error == -ECONNRESET ? conn->gnc_peer_error
808                                                            : conn->gnc_error);
809
810         EXIT;
811 }
812
813 int
814 kgnilnd_set_conn_params(kgn_dgram_t *dgram)
815 {
816         kgn_conn_t             *conn = dgram->gndg_conn;
817         kgn_connreq_t          *connreq = &dgram->gndg_conn_in;
818         kgn_gniparams_t        *rem_param = &connreq->gncr_gnparams;
819         gni_return_t            rrc;
820         int                     rc = 0;
821         gni_smsg_attr_t        *remote = &connreq->gncr_gnparams.gnpr_smsg_attr;
822
823         /* set timeout vals in conn early so we can use them for the NAK */
824
825         /* use max of the requested and our timeout, peer will do the same */
826         conn->gnc_timeout = MAX(conn->gnc_timeout, connreq->gncr_timeout);
827
828         /* only ep_bind really mucks around with the CQ */
829         /* only ep bind if we are not connecting to ourself and the dstnid is not a wildcard. this check
830          * is necessary as you can only bind an ep once and we must make sure we dont bind when already bound.
831          */
832         if (connreq->gncr_dstnid != LNET_NID_ANY && dgram->gndg_conn_out.gncr_dstnid != connreq->gncr_srcnid) {
833                 mutex_lock(&conn->gnc_device->gnd_cq_mutex);
834                 rrc = kgnilnd_ep_bind(conn->gnc_ephandle,
835                         connreq->gncr_gnparams.gnpr_host_id,
836                         conn->gnc_cqid);
837                 mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
838                 if (rrc != GNI_RC_SUCCESS) {
839                         rc = -ECONNABORTED;
840                         goto return_out;
841                 }
842         }
843
844         rrc = kgnilnd_ep_set_eventdata(conn->gnc_ephandle, conn->gnc_cqid,
845                          connreq->gncr_gnparams.gnpr_cqid);
846         if (rrc != GNI_RC_SUCCESS) {
847                 rc = -ECONNABORTED;
848                 goto cleanup_out;
849         }
850
851         /* Initialize SMSG */
852         rrc = kgnilnd_smsg_init(conn->gnc_ephandle, &conn->gnpr_smsg_attr,
853                         &connreq->gncr_gnparams.gnpr_smsg_attr);
854         if (unlikely(rrc == GNI_RC_INVALID_PARAM)) {
855                 gni_smsg_attr_t *local = &conn->gnpr_smsg_attr;
856                 /* help folks figure out if there is a tunable off, etc. */
857                 LCONSOLE_ERROR("SMSG attribute mismatch. Data from local/remote:"
858                                " type %d/%d msg_maxsize %u/%u"
859                                " mbox_maxcredit %u/%u. Please check kgni"
860                                " logs for further data\n",
861                                local->msg_type, remote->msg_type,
862                                local->msg_maxsize, remote->msg_maxsize,
863                                local->mbox_maxcredit, remote->mbox_maxcredit);
864         }
865         if (rrc != GNI_RC_SUCCESS) {
866                 rc = -ECONNABORTED;
867                 goto cleanup_out;
868         }
869
870         /* log this for help in debuggin SMSG buffer re-use */
871         CDEBUG(D_NET, "conn %p src %s dst %s smsg %p acquired"
872                 " local cqid %u SMSG %p->%u hndl "LPX64"."LPX64
873                 " remote cqid %u SMSG %p->%u hndl "LPX64"."LPX64"\n",
874                 conn, libcfs_nid2str(connreq->gncr_srcnid),
875                 libcfs_nid2str(connreq->gncr_dstnid),
876                 &conn->gnpr_smsg_attr,
877                 conn->gnc_cqid,
878                 conn->gnpr_smsg_attr.msg_buffer,
879                 conn->gnpr_smsg_attr.mbox_offset,
880                 conn->gnpr_smsg_attr.mem_hndl.qword1,
881                 conn->gnpr_smsg_attr.mem_hndl.qword2,
882                 rem_param->gnpr_cqid,
883                 rem_param->gnpr_smsg_attr.msg_buffer,
884                 rem_param->gnpr_smsg_attr.mbox_offset,
885                 rem_param->gnpr_smsg_attr.mem_hndl.qword1,
886                 rem_param->gnpr_smsg_attr.mem_hndl.qword2);
887
888         conn->gnc_peerstamp = connreq->gncr_peerstamp;
889         conn->gnc_peer_connstamp = connreq->gncr_connstamp;
890         conn->remote_mbox_addr = (void *)((char *)remote->msg_buffer + remote->mbox_offset);
891
892         /* We update the reaper timeout once we have a valid conn and timeout */
893         kgnilnd_update_reaper_timeout(GNILND_TO2KA(conn->gnc_timeout));
894
895         return 0;
896
897 cleanup_out:
898         rrc = kgnilnd_ep_unbind(conn->gnc_ephandle);
899         /* not sure I can just let this fly */
900         LASSERTF(rrc == GNI_RC_SUCCESS,
901                 "bad rc from gni_ep_unbind trying to cleanup: %d\n", rrc);
902
903 return_out:
904         LASSERTF(rc != 0, "SOFTWARE BUG: rc == 0\n");
905         CERROR("Error setting connection params from %s: %d\n",
906                libcfs_nid2str(connreq->gncr_srcnid), rc);
907         return rc;
908 }
909
910 /* needs down_read on kgn_net_rw_sem held from before this call until
911  * after the write_lock on kgn_peer_conn_lock - this ensures we stay sane
912  * with kgnilnd_shutdown - it'll get the sem and set shutdown, then get the
913  * kgn_peer_conn_lock to start del_peer'ing. If we hold the sem until after
914  * kgn_peer_conn_lock is held, we guarantee that nobody calls
915  * kgnilnd_add_peer_locked without checking gnn_shutdown */
916 int
917 kgnilnd_create_peer_safe(kgn_peer_t **peerp, lnet_nid_t nid, kgn_net_t *net)
918 {
919         kgn_peer_t      *peer;
920         int             rc;
921
922         LASSERT(nid != LNET_NID_ANY);
923
924         /* We dont pass the net around in the dgram anymore so here is where we find it
925          * this will work unless its in shutdown or the nid has a net that is invalid.
926          * Either way error code needs to be returned in that case.
927          *
928          * If the net passed in is not NULL then we can use it, this alleviates looking it
929          * when the calling function has access to the data.
930          */
931         if (net == NULL) {
932                 rc = kgnilnd_find_net(nid, &net);
933                 if (rc < 0)
934                         return rc;
935         } else {
936                 /* find net adds a reference on the net if we are not using
937                  * it we must do it manually so the net references are
938                  * correct when tearing down the net
939                  */
940                 kgnilnd_net_addref(net);
941         }
942
943         LIBCFS_ALLOC(peer, sizeof(*peer));
944         if (peer == NULL) {
945                 kgnilnd_net_decref(net);
946                 return -ENOMEM;
947         }
948         peer->gnp_nid = nid;
949         peer->gnp_down = GNILND_RCA_NODE_UP;
950
951         /* translate from nid to nic addr & store */
952         rc = kgnilnd_nid_to_nicaddrs(LNET_NIDADDR(nid), 1, &peer->gnp_host_id);
953         if (rc <= 0) {
954                 kgnilnd_net_decref(net);
955                 LIBCFS_FREE(peer, sizeof(*peer));
956                 return -ESRCH;
957         }
958         CDEBUG(D_NET, "peer 0x%p->%s -> NIC 0x%x\n", peer,
959                 libcfs_nid2str(nid), peer->gnp_host_id);
960
961         atomic_set(&peer->gnp_refcount, 1);     /* 1 ref for caller */
962         atomic_set(&peer->gnp_dirty_eps, 0);
963
964         INIT_LIST_HEAD(&peer->gnp_list);
965         INIT_LIST_HEAD(&peer->gnp_connd_list);
966         INIT_LIST_HEAD(&peer->gnp_conns);
967         INIT_LIST_HEAD(&peer->gnp_tx_queue);
968
969         /* the first reconnect should happen immediately, so we leave
970          * gnp_reconnect_interval set to 0 */
971
972         LASSERTF(net != NULL, "peer 0x%p->%s with NULL net\n",
973                  peer, libcfs_nid2str(nid));
974
975         /* must have kgn_net_rw_sem held for this...  */
976         if (net->gnn_shutdown) {
977                 /* shutdown has started already */
978                 kgnilnd_net_decref(net);
979                 LIBCFS_FREE(peer, sizeof(*peer));
980                 return -ESHUTDOWN;
981         }
982
983         peer->gnp_net = net;
984
985         atomic_inc(&kgnilnd_data.kgn_npeers);
986
987         *peerp = peer;
988         return 0;
989 }
990
991 void
992 kgnilnd_destroy_peer(kgn_peer_t *peer)
993 {
994         CDEBUG(D_NET, "peer %s %p deleted\n",
995                libcfs_nid2str(peer->gnp_nid), peer);
996         LASSERTF(atomic_read(&peer->gnp_refcount) == 0,
997                  "peer 0x%p->%s refs %d\n",
998                  peer, libcfs_nid2str(peer->gnp_nid),
999                  atomic_read(&peer->gnp_refcount));
1000         LASSERTF(atomic_read(&peer->gnp_dirty_eps) == 0,
1001                  "peer 0x%p->%s dirty eps %d\n",
1002                  peer, libcfs_nid2str(peer->gnp_nid),
1003                  atomic_read(&peer->gnp_dirty_eps));
1004         LASSERTF(peer->gnp_net != NULL, "peer %p (%s) with NULL net\n",
1005                  peer, libcfs_nid2str(peer->gnp_nid));
1006         LASSERTF(!kgnilnd_peer_active(peer),
1007                  "peer 0x%p->%s\n",
1008                 peer, libcfs_nid2str(peer->gnp_nid));
1009         LASSERTF(peer->gnp_connecting == GNILND_PEER_IDLE || peer->gnp_connecting == GNILND_PEER_KILL,
1010                  "peer 0x%p->%s, connecting %d\n",
1011                 peer, libcfs_nid2str(peer->gnp_nid), peer->gnp_connecting);
1012         LASSERTF(list_empty(&peer->gnp_conns),
1013                  "peer 0x%p->%s\n",
1014                 peer, libcfs_nid2str(peer->gnp_nid));
1015         LASSERTF(list_empty(&peer->gnp_tx_queue),
1016                  "peer 0x%p->%s\n",
1017                 peer, libcfs_nid2str(peer->gnp_nid));
1018         LASSERTF(list_empty(&peer->gnp_connd_list),
1019                  "peer 0x%p->%s\n",
1020                 peer, libcfs_nid2str(peer->gnp_nid));
1021
1022         /* NB a peer's connections keep a reference on their peer until
1023          * they are destroyed, so we can be assured that _all_ state to do
1024          * with this peer has been cleaned up when its refcount drops to
1025          * zero. */
1026
1027         atomic_dec(&kgnilnd_data.kgn_npeers);
1028         kgnilnd_net_decref(peer->gnp_net);
1029
1030         LIBCFS_FREE(peer, sizeof(*peer));
1031 }
1032
1033 /* the conn might not have made it all the way through to a connected
1034  * state - but we need to purgatory any conn that a remote peer might
1035  * have seen through a posted dgram as well */
1036 void
1037 kgnilnd_add_purgatory_locked(kgn_conn_t *conn, kgn_peer_t *peer)
1038 {
1039         kgn_mbox_info_t *mbox = NULL;
1040         ENTRY;
1041
1042         /* NB - the caller should own conn by removing him from the
1043          * scheduler thread when finishing the close */
1044
1045         LASSERTF(peer != NULL, "conn %p with NULL peer\n", conn);
1046
1047         /* If this is still true, need to add the calls to unlink back in and
1048          * figure out how to close the hole on loopback conns */
1049         LASSERTF(kgnilnd_peer_active(peer), "can't use inactive peer %s (%p)"
1050                 " we'll never recover the resources\n",
1051                 libcfs_nid2str(peer->gnp_nid), peer);
1052
1053         CDEBUG(D_NET, "conn %p peer %p dev %p\n", conn, peer,
1054                 conn->gnc_device);
1055
1056         conn->gnc_in_purgatory = 1;
1057
1058         mbox = &conn->gnc_fma_blk->gnm_mbox_info[conn->gnc_mbox_id];
1059         mbox->mbx_prev_purg_nid = peer->gnp_nid;
1060         mbox->mbx_add_purgatory = jiffies;
1061         kgnilnd_release_mbox(conn, 1);
1062
1063         LASSERTF(list_empty(&conn->gnc_mdd_list),
1064                 "conn 0x%p->%s with active purgatory hold MDD %d\n",
1065                 conn, libcfs_nid2str(peer->gnp_nid),
1066                 kgnilnd_count_list(&conn->gnc_mdd_list));
1067
1068         EXIT;
1069 }
1070
1071 /* Instead of detaching everything from purgatory here we just mark the conn as needing
1072  * detach, when the reaper checks the conn the next time it will detach it.
1073  * Calling function requires write_lock held on kgn_peer_conn_lock
1074  */
1075 void
1076 kgnilnd_mark_for_detach_purgatory_all_locked(kgn_peer_t *peer) {
1077         kgn_conn_t       *conn;
1078
1079         list_for_each_entry(conn, &peer->gnp_conns, gnc_list) {
1080                 if (conn->gnc_in_purgatory && !conn->gnc_needs_detach) {
1081                         conn->gnc_needs_detach = 1;
1082                         kgnilnd_admin_addref(kgnilnd_data.kgn_npending_detach);
1083                 }
1084         }
1085 }
1086
1087 /* Calling function needs a write_lock held on kgn_peer_conn_lock */
1088 void
1089 kgnilnd_detach_purgatory_locked(kgn_conn_t *conn, struct list_head *conn_list)
1090 {
1091         kgn_mbox_info_t *mbox = NULL;
1092
1093         /* if needed, add the conn purgatory data to the list passed in */
1094         if (conn->gnc_in_purgatory) {
1095                 CDEBUG(D_NET, "peer %p->%s purg_conn %p@%s mdd_list #tx %d\n",
1096                         conn->gnc_peer, libcfs_nid2str(conn->gnc_peer->gnp_nid),
1097                         conn, kgnilnd_conn_state2str(conn),
1098                         kgnilnd_count_list(&conn->gnc_mdd_list));
1099
1100                 mbox = &conn->gnc_fma_blk->gnm_mbox_info[conn->gnc_mbox_id];
1101                 mbox->mbx_detach_of_purgatory = jiffies;
1102
1103                 /* conn->gnc_list is the entry point on peer->gnp_conns, so detaching it
1104                  * here removes it from the list of 'valid' peer connections.
1105                  * We put the current conn onto a list of conns to call kgnilnd_release_purgatory_locked()
1106                  * and as such the caller of kgnilnd_detach_purgatory_locked() now owns that conn, since its not
1107                  * on the peer's conn_list anymore.
1108                  */
1109
1110                 list_del_init(&conn->gnc_list);
1111
1112                 /* NB - only unlinking if we set pending in del_peer_locked from admin or
1113                  * shutdown */
1114                 if (kgnilnd_peer_active(conn->gnc_peer) &&
1115                     conn->gnc_peer->gnp_pending_unlink &&
1116                     kgnilnd_can_unlink_peer_locked(conn->gnc_peer)) {
1117                         kgnilnd_unlink_peer_locked(conn->gnc_peer);
1118                 }
1119                 /* The reaper will not call detach unless the conn is fully through kgnilnd_complete_closed_conn.
1120                  * If the conn is not in a DONE state somehow we are attempting to detach even though
1121                  * the conn has not been fully cleaned up. If we detach while the conn is still closing
1122                  * we will end up with an orphaned connection that has valid ep_handle, that is not on a
1123                  * peer.
1124                  */
1125
1126                 LASSERTF(conn->gnc_state == GNILND_CONN_DONE, "Conn in invalid state  %p@%s \n",
1127                                 conn, kgnilnd_conn_state2str(conn));
1128
1129                 /* move from peer to the delayed release list */
1130                 list_add_tail(&conn->gnc_list, conn_list);
1131         }
1132 }
1133
1134 void
1135 kgnilnd_release_purgatory_list(struct list_head *conn_list)
1136 {
1137         kgn_device_t            *dev;
1138         kgn_conn_t              *conn, *connN;
1139         kgn_mdd_purgatory_t     *gmp, *gmpN;
1140
1141         list_for_each_entry_safe(conn, connN, conn_list, gnc_list) {
1142                 dev = conn->gnc_device;
1143
1144                 kgnilnd_release_mbox(conn, -1);
1145                 conn->gnc_in_purgatory = 0;
1146
1147                 list_del_init(&conn->gnc_list);
1148
1149                 /* gnc_needs_detach is set in kgnilnd_del_conn_or_peer. It is used to keep track
1150                  * of conns that have been marked for detach by kgnilnd_del_conn_or_peer.
1151                  * The function uses kgn_npending_detach to verify the conn has
1152                  * actually been detached.
1153                  */
1154
1155                 if (conn->gnc_needs_detach)
1156                         kgnilnd_admin_decref(kgnilnd_data.kgn_npending_detach);
1157
1158                 /* if this guy is really dead (we are doing release from reaper),
1159                  * make sure we tell LNet - if this is from other context,
1160                  * the checks in the function will prevent an errant
1161                  * notification */
1162                 kgnilnd_peer_notify(conn->gnc_peer, conn->gnc_error);
1163
1164                 list_for_each_entry_safe(gmp, gmpN, &conn->gnc_mdd_list,
1165                                          gmp_list) {
1166                         CDEBUG(D_NET,
1167                                "dev %p releasing held mdd "LPX64"."LPX64"\n",
1168                                conn->gnc_device, gmp->gmp_map_key.qword1,
1169                                gmp->gmp_map_key.qword2);
1170
1171                         atomic_dec(&dev->gnd_n_mdd_held);
1172                         kgnilnd_mem_mdd_release(conn->gnc_device->gnd_handle,
1173                                                 &gmp->gmp_map_key);
1174                         /* ignoring the return code - if kgni/ghal can't find it
1175                          * it must be released already */
1176
1177                         list_del_init(&gmp->gmp_list);
1178                         LIBCFS_FREE(gmp, sizeof(*gmp));
1179                 }
1180                 /* lose conn ref for purgatory */
1181                 kgnilnd_conn_decref(conn);
1182         }
1183 }
1184
1185 /* needs write_lock on kgnilnd_data.kgn_peer_conn_lock held */
1186 void
1187 kgnilnd_peer_increase_reconnect_locked(kgn_peer_t *peer)
1188 {
1189         int current_to;
1190
1191         current_to = peer->gnp_reconnect_interval;
1192
1193         /* we'll try to reconnect fast the first time, then back-off */
1194         if (current_to == 0) {
1195                 peer->gnp_reconnect_time = jiffies - 1;
1196                 current_to = *kgnilnd_tunables.kgn_min_reconnect_interval;
1197         } else {
1198                 peer->gnp_reconnect_time = jiffies + cfs_time_seconds(current_to);
1199                 /* add 50% of min timeout & retry */
1200                 current_to += *kgnilnd_tunables.kgn_min_reconnect_interval / 2;
1201         }
1202
1203         current_to = MIN(current_to,
1204                                 *kgnilnd_tunables.kgn_max_reconnect_interval);
1205
1206         peer->gnp_reconnect_interval = current_to;
1207         CDEBUG(D_NET, "peer %s can reconnect at %lu interval %lu\n",
1208                libcfs_nid2str(peer->gnp_nid), peer->gnp_reconnect_time,
1209                peer->gnp_reconnect_interval);
1210 }
1211
1212 /* needs kgnilnd_data.kgn_peer_conn_lock held */
1213 kgn_peer_t *
1214 kgnilnd_find_peer_locked(lnet_nid_t nid)
1215 {
1216         struct list_head *peer_list = kgnilnd_nid2peerlist(nid);
1217         kgn_peer_t       *peer;
1218
1219         /* Chopping nid down to only NIDADDR using LNET_NIDADDR so we only
1220          * have a single peer per device instead of a peer per nid/net combo.
1221          */
1222
1223         list_for_each_entry(peer, peer_list, gnp_list) {
1224                 if (LNET_NIDADDR(nid) != LNET_NIDADDR(peer->gnp_nid))
1225                         continue;
1226
1227                 CDEBUG(D_NET, "got peer [%p] -> %s c %d (%d)\n",
1228                        peer, libcfs_nid2str(nid),
1229                        peer->gnp_connecting,
1230                        atomic_read(&peer->gnp_refcount));
1231                 return peer;
1232         }
1233         return NULL;
1234 }
1235
1236 /* need write_lock on kgn_peer_conn_lock */
1237 void
1238 kgnilnd_unlink_peer_locked(kgn_peer_t *peer)
1239 {
1240         LASSERTF(list_empty(&peer->gnp_conns),
1241                 "peer 0x%p->%s\n",
1242                  peer, libcfs_nid2str(peer->gnp_nid));
1243         LASSERTF(list_empty(&peer->gnp_tx_queue),
1244                 "peer 0x%p->%s\n",
1245                  peer, libcfs_nid2str(peer->gnp_nid));
1246         LASSERTF(kgnilnd_peer_active(peer),
1247                 "peer 0x%p->%s\n",
1248                  peer, libcfs_nid2str(peer->gnp_nid));
1249         CDEBUG(D_NET, "unlinking peer 0x%p->%s\n",
1250                 peer, libcfs_nid2str(peer->gnp_nid));
1251
1252         list_del_init(&peer->gnp_list);
1253         kgnilnd_data.kgn_peer_version++;
1254         kgnilnd_admin_decref(kgnilnd_data.kgn_npending_unlink);
1255         /* lose peerlist's ref */
1256         kgnilnd_peer_decref(peer);
1257 }
1258
1259 int
1260 kgnilnd_get_peer_info(int index,
1261                       kgn_peer_t **found_peer,
1262                       lnet_nid_t *id, __u32 *nic_addr,
1263                       int *refcount, int *connecting)
1264 {
1265         struct list_head  *ptmp;
1266         kgn_peer_t        *peer;
1267         int               i;
1268         int               rc = -ENOENT;
1269
1270         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1271
1272         for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++) {
1273
1274                 list_for_each(ptmp, &kgnilnd_data.kgn_peers[i]) {
1275                         peer = list_entry(ptmp, kgn_peer_t, gnp_list);
1276
1277                         if (index-- > 0)
1278                                 continue;
1279
1280                         CDEBUG(D_NET, "found peer %p (%s) at index %d\n",
1281                                peer, libcfs_nid2str(peer->gnp_nid), index);
1282
1283                         *found_peer  = peer;
1284                         *id          = peer->gnp_nid;
1285                         *nic_addr    = peer->gnp_host_id;
1286                         *refcount    = atomic_read(&peer->gnp_refcount);
1287                         *connecting  = peer->gnp_connecting;
1288
1289                         rc = 0;
1290                         goto out;
1291                 }
1292         }
1293 out:
1294         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1295         if (rc)
1296                 CDEBUG(D_NET, "no gni peer at index %d\n", index);
1297         return rc;
1298 }
1299
1300 /* requires write_lock on kgn_peer_conn_lock held */
1301 void
1302 kgnilnd_add_peer_locked(lnet_nid_t nid, kgn_peer_t *new_stub_peer, kgn_peer_t **peerp)
1303 {
1304         kgn_peer_t        *peer, *peer2;
1305
1306         LASSERTF(new_stub_peer != NULL, "bad stub peer for nid %s\n",
1307                  libcfs_nid2str(nid));
1308
1309         peer2 = kgnilnd_find_peer_locked(nid);
1310         if (peer2 != NULL) {
1311                 /* A peer was created during the lock transition, so drop
1312                  * the new one we created */
1313                 kgnilnd_peer_decref(new_stub_peer);
1314                 peer = peer2;
1315         } else {
1316                 peer = new_stub_peer;
1317                 /* peer table takes existing ref on peer */
1318
1319                 LASSERTF(!kgnilnd_peer_active(peer),
1320                         "peer 0x%p->%s already in peer table\n",
1321                         peer, libcfs_nid2str(peer->gnp_nid));
1322                 list_add_tail(&peer->gnp_list,
1323                               kgnilnd_nid2peerlist(nid));
1324                 kgnilnd_data.kgn_peer_version++;
1325         }
1326
1327         LASSERTF(peer->gnp_net != NULL, "peer 0x%p->%s with NULL net\n",
1328                  peer, libcfs_nid2str(peer->gnp_nid));
1329         *peerp = peer;
1330 }
1331
1332 int
1333 kgnilnd_add_peer(kgn_net_t *net, lnet_nid_t nid, kgn_peer_t **peerp)
1334 {
1335         kgn_peer_t        *peer;
1336         int                rc;
1337         ENTRY;
1338
1339         if (nid == LNET_NID_ANY)
1340                 return -EINVAL;
1341
1342         /* NB - this will not block during normal operations -
1343          * the only writer of this is in the startup/shutdown path. */
1344         rc = down_read_trylock(&kgnilnd_data.kgn_net_rw_sem);
1345         if (!rc) {
1346                 rc = -ESHUTDOWN;
1347                 RETURN(rc);
1348         }
1349         rc = kgnilnd_create_peer_safe(&peer, nid, net);
1350         if (rc != 0) {
1351                 up_read(&kgnilnd_data.kgn_net_rw_sem);
1352                 RETURN(rc);
1353         }
1354
1355         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
1356         up_read(&kgnilnd_data.kgn_net_rw_sem);
1357
1358         kgnilnd_add_peer_locked(nid, peer, peerp);
1359
1360         CDEBUG(D_NET, "peer 0x%p->%s connecting %d\n",
1361                peerp, libcfs_nid2str((*peerp)->gnp_nid),
1362                (*peerp)->gnp_connecting);
1363
1364         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1365         RETURN(0);
1366 }
1367
1368 /* needs write_lock on kgn_peer_conn_lock */
1369 void
1370 kgnilnd_cancel_peer_connect_locked(kgn_peer_t *peer, struct list_head *zombies)
1371 {
1372         kgn_tx_t        *tx, *txn;
1373
1374         /* we do care about state of gnp_connecting - we could be between
1375          * reconnect attempts, so try to find the dgram and cancel the TX
1376          * anyways. If we are in the process of posting DONT do anything;
1377          * once it fails or succeeds we can nuke the connect attempt.
1378          * We have no idea where in kgnilnd_post_dgram we are so we cant
1379          * attempt to cancel until the function is done.
1380          */
1381
1382         /* make sure peer isn't in process of connecting or waiting for connect*/
1383         spin_lock(&peer->gnp_net->gnn_dev->gnd_connd_lock);
1384         if (!(list_empty(&peer->gnp_connd_list))) {
1385                 list_del_init(&peer->gnp_connd_list);
1386                 /* remove connd ref */
1387                 kgnilnd_peer_decref(peer);
1388         }
1389         spin_unlock(&peer->gnp_net->gnn_dev->gnd_connd_lock);
1390
1391         if (peer->gnp_connecting == GNILND_PEER_POSTING || peer->gnp_connecting == GNILND_PEER_NEEDS_DEATH) {
1392                 peer->gnp_connecting = GNILND_PEER_NEEDS_DEATH;
1393                 /* We are in process of posting right now the xchg set it up for us to
1394                  * cancel the connect so we are finished for now */
1395         } else {
1396                 /* no need for exchange we have the peer lock and its ready for us to nuke */
1397                 LASSERTF(peer->gnp_connecting != GNILND_PEER_POSTING,
1398                         "Peer in invalid state 0x%p->%s, connecting %d\n",
1399                         peer, libcfs_nid2str(peer->gnp_nid), peer->gnp_connecting);
1400                 peer->gnp_connecting = GNILND_PEER_IDLE;
1401                 set_mb(peer->gnp_last_dgram_errno, -ETIMEDOUT);
1402                 kgnilnd_find_and_cancel_dgram(peer->gnp_net->gnn_dev,
1403                                                       peer->gnp_nid);
1404         }
1405
1406         /* The least we can do is nuke the tx's no matter what.... */
1407         list_for_each_entry_safe(tx, txn, &peer->gnp_tx_queue, tx_list) {
1408                 kgnilnd_tx_del_state_locked(tx, peer, NULL,
1409                                            GNILND_TX_ALLOCD);
1410                 list_add_tail(&tx->tx_list, zombies);
1411         }
1412 }
1413
1414 /* needs write_lock on kgn_peer_conn_lock */
1415 void
1416 kgnilnd_del_peer_locked(kgn_peer_t *peer, int error)
1417 {
1418         /* this peer could be passive and only held for purgatory,
1419          * take a ref to ensure it doesn't disappear in this function */
1420         kgnilnd_peer_addref(peer);
1421
1422         CFS_RACE(CFS_FAIL_GNI_FIND_TARGET);
1423
1424         /* if purgatory release cleared it out, don't try again */
1425         if (kgnilnd_peer_active(peer)) {
1426                 /* always do this to allow kgnilnd_start_connect and
1427                  * kgnilnd_finish_connect to catch this before they
1428                  * wrap up their operations */
1429                 if (kgnilnd_can_unlink_peer_locked(peer)) {
1430                         /* already released purgatory, so only active
1431                          * conns hold it */
1432                         kgnilnd_unlink_peer_locked(peer);
1433                 } else {
1434                         kgnilnd_close_peer_conns_locked(peer, error);
1435                         /* peer unlinks itself when last conn is closed */
1436                 }
1437         }
1438
1439         /* we are done, release back to the wild */
1440         kgnilnd_peer_decref(peer);
1441 }
1442
1443 int
1444 kgnilnd_del_conn_or_peer(kgn_net_t *net, lnet_nid_t nid, int command,
1445                           int error)
1446 {
1447         LIST_HEAD               (souls);
1448         LIST_HEAD               (zombies);
1449         struct list_head        *ptmp, *pnxt;
1450         kgn_peer_t              *peer;
1451         int                     lo;
1452         int                     hi;
1453         int                     i;
1454         int                     rc = -ENOENT;
1455
1456         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
1457
1458         if (nid != LNET_NID_ANY)
1459                 lo = hi = kgnilnd_nid2peerlist(nid) - kgnilnd_data.kgn_peers;
1460         else {
1461                 lo = 0;
1462                 hi = *kgnilnd_tunables.kgn_peer_hash_size - 1;
1463                 /* wildcards always succeed */
1464                 rc = 0;
1465         }
1466
1467         for (i = lo; i <= hi; i++) {
1468                 list_for_each_safe(ptmp, pnxt, &kgnilnd_data.kgn_peers[i]) {
1469                         peer = list_entry(ptmp, kgn_peer_t, gnp_list);
1470
1471                         LASSERTF(peer->gnp_net != NULL,
1472                                 "peer %p (%s) with NULL net\n",
1473                                  peer, libcfs_nid2str(peer->gnp_nid));
1474
1475                         if (net != NULL && peer->gnp_net != net)
1476                                 continue;
1477
1478                         if (!(nid == LNET_NID_ANY || LNET_NIDADDR(peer->gnp_nid) == LNET_NIDADDR(nid)))
1479                                 continue;
1480
1481                         /* In both cases, we want to stop any in-flight
1482                          * connect attempts */
1483                         kgnilnd_cancel_peer_connect_locked(peer, &zombies);
1484
1485                         switch (command) {
1486                         case GNILND_DEL_CONN:
1487                                 kgnilnd_close_peer_conns_locked(peer, error);
1488                                 break;
1489                         case GNILND_DEL_PEER:
1490                                 peer->gnp_pending_unlink = 1;
1491                                 kgnilnd_admin_addref(kgnilnd_data.kgn_npending_unlink);
1492                                 kgnilnd_mark_for_detach_purgatory_all_locked(peer);
1493                                 kgnilnd_del_peer_locked(peer, error);
1494                                 break;
1495                         case GNILND_CLEAR_PURGATORY:
1496                                 /* Mark everything ready for detach reaper will cleanup
1497                                  * once we release the kgn_peer_conn_lock
1498                                  */
1499                                 kgnilnd_mark_for_detach_purgatory_all_locked(peer);
1500                                 peer->gnp_last_errno = -EISCONN;
1501                                 /* clear reconnect so he can reconnect soon */
1502                                 peer->gnp_reconnect_time = 0;
1503                                 peer->gnp_reconnect_interval = 0;
1504                                 break;
1505                         default:
1506                                 CERROR("bad command %d\n", command);
1507                                 LBUG();
1508                         }
1509                         /* we matched something */
1510                         rc = 0;
1511                 }
1512         }
1513
1514         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1515
1516         /* release all of the souls found held in purgatory */
1517         kgnilnd_release_purgatory_list(&souls);
1518
1519         /* nuke peer TX */
1520         kgnilnd_txlist_done(&zombies, error);
1521
1522         /* This function does not return until the commands it initiated have completed,
1523          * since they have to work there way through the other threads. In the case of shutdown
1524          * threads are not woken up until after this call is initiated so we cannot wait, we just
1525          * need to return. The same applies for stack reset we shouldnt wait as the reset thread
1526          * handles closing.
1527          */
1528
1529         CFS_RACE(CFS_FAIL_GNI_RACE_RESET);
1530
1531         if (error == -ENOTRECOVERABLE || error == -ESHUTDOWN) {
1532                 return rc;
1533         }
1534
1535         i = 4;
1536         while (atomic_read(&kgnilnd_data.kgn_npending_conns)   ||
1537                atomic_read(&kgnilnd_data.kgn_npending_detach)  ||
1538                atomic_read(&kgnilnd_data.kgn_npending_unlink)) {
1539
1540                 cfs_pause(cfs_time_seconds(1));
1541                 i++;
1542
1543                 CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET, "Waiting on %d peers %d closes %d detaches\n",
1544                                 atomic_read(&kgnilnd_data.kgn_npending_unlink),
1545                                 atomic_read(&kgnilnd_data.kgn_npending_conns),
1546                                 atomic_read(&kgnilnd_data.kgn_npending_detach));
1547         }
1548
1549         return rc;
1550 }
1551
1552 kgn_conn_t *
1553 kgnilnd_get_conn_by_idx(int index)
1554 {
1555         kgn_peer_t        *peer;
1556         struct list_head  *ptmp;
1557         kgn_conn_t        *conn;
1558         struct list_head  *ctmp;
1559         int                i;
1560
1561
1562         for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++) {
1563                 read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1564                 list_for_each(ptmp, &kgnilnd_data.kgn_peers[i]) {
1565
1566                         peer = list_entry(ptmp, kgn_peer_t, gnp_list);
1567
1568                         list_for_each(ctmp, &peer->gnp_conns) {
1569                                 conn = list_entry(ctmp, kgn_conn_t, gnc_list);
1570
1571                                 if (conn->gnc_state != GNILND_CONN_ESTABLISHED)
1572                                         continue;
1573
1574                                 if (index-- > 0)
1575                                         continue;
1576
1577                                 CDEBUG(D_NET, "++conn[%p] -> %s (%d)\n", conn,
1578                                        libcfs_nid2str(conn->gnc_peer->gnp_nid),
1579                                        atomic_read(&conn->gnc_refcount));
1580                                 kgnilnd_conn_addref(conn);
1581                                 read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1582                                 return conn;
1583                         }
1584                 }
1585                 read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1586         }
1587
1588         return NULL;
1589 }
1590
1591 int
1592 kgnilnd_get_conn_info(kgn_peer_t *peer,
1593                       int *device_id, __u64 *peerstamp,
1594                       int *tx_seq, int *rx_seq,
1595                       int *fmaq_len, int *nfma, int *nrdma)
1596 {
1597         kgn_conn_t        *conn;
1598         int               rc = 0;
1599
1600         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1601
1602         conn = kgnilnd_find_conn_locked(peer);
1603         if (conn == NULL) {
1604                 rc = -ENOENT;
1605                 goto out;
1606         }
1607
1608         *device_id = conn->gnc_device->gnd_host_id;
1609         *peerstamp = conn->gnc_peerstamp;
1610         *tx_seq = conn->gnc_tx_seq;
1611         *rx_seq = conn->gnc_rx_seq;
1612         *fmaq_len = kgnilnd_count_list(&conn->gnc_fmaq);
1613         *nfma = atomic_read(&conn->gnc_nlive_fma);
1614         *nrdma = atomic_read(&conn->gnc_nlive_rdma);
1615 out:
1616         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1617         return rc;
1618 }
1619
1620 /* needs write_lock on kgn_peer_conn_lock */
1621 int
1622 kgnilnd_close_peer_conns_locked(kgn_peer_t *peer, int why)
1623 {
1624         kgn_conn_t         *conn;
1625         struct list_head   *ctmp, *cnxt;
1626         int                 count = 0;
1627
1628         list_for_each_safe(ctmp, cnxt, &peer->gnp_conns) {
1629                 conn = list_entry(ctmp, kgn_conn_t, gnc_list);
1630
1631                 if (conn->gnc_state != GNILND_CONN_ESTABLISHED)
1632                         continue;
1633
1634                 count++;
1635                 /* we mark gnc_needs closing and increment kgn_npending_conns so that
1636                  * kgnilnd_del_conn_or_peer can wait on the other threads closing
1637                  * and cleaning up the connection.
1638                  */
1639                 if (!conn->gnc_needs_closing) {
1640                         conn->gnc_needs_closing = 1;
1641                         kgnilnd_admin_addref(kgnilnd_data.kgn_npending_conns);
1642                 }
1643                 kgnilnd_close_conn_locked(conn, why);
1644         }
1645         return count;
1646 }
1647
1648 int
1649 kgnilnd_report_node_state(lnet_nid_t nid, int down)
1650 {
1651         int         rc;
1652         kgn_peer_t  *peer, *new_peer;
1653         LIST_HEAD(zombies);
1654
1655         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
1656         peer = kgnilnd_find_peer_locked(nid);
1657
1658         if (peer == NULL) {
1659                 int       i;
1660                 int       found_net = 0;
1661                 kgn_net_t *net;
1662
1663                 write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1664
1665                 /* Don't add a peer for node up events */
1666                 if (down == GNILND_RCA_NODE_UP) {
1667                         return 0;
1668                 }
1669
1670                 /* find any valid net - we don't care which one... */
1671                 down_read(&kgnilnd_data.kgn_net_rw_sem);
1672                 for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++) {
1673                         list_for_each_entry(net, &kgnilnd_data.kgn_nets[i],
1674                                             gnn_list) {
1675                                 found_net = 1;
1676                                 break;
1677                         }
1678
1679                         if (found_net) {
1680                                 break;
1681                         }
1682                 }
1683                 up_read(&kgnilnd_data.kgn_net_rw_sem);
1684
1685                 if (!found_net) {
1686                         CNETERR("Could not find a net for nid %lld\n", nid);
1687                         return 1;
1688                 }
1689
1690                 /* The nid passed in does not yet contain the net portion.
1691                  * Let's build it up now
1692                  */
1693                 nid = LNET_MKNID(LNET_NIDNET(net->gnn_ni->ni_nid), nid);
1694                 rc = kgnilnd_add_peer(net, nid, &new_peer);
1695
1696                 if (rc) {
1697                         CNETERR("Could not add peer for nid %lld, rc %d\n",
1698                                 nid, rc);
1699                         return 1;
1700                 }
1701
1702                 write_lock(&kgnilnd_data.kgn_peer_conn_lock);
1703                 peer = kgnilnd_find_peer_locked(nid);
1704
1705                 if (peer == NULL) {
1706                         CNETERR("Could not find peer for nid %lld\n", nid);
1707                         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1708                         return 1;
1709                 }
1710         }
1711
1712         peer->gnp_down = down;
1713
1714         if (down == GNILND_RCA_NODE_DOWN) {
1715                 kgn_conn_t *conn;
1716
1717                 peer->gnp_down_event_time = jiffies;
1718                 kgnilnd_cancel_peer_connect_locked(peer, &zombies);
1719                 conn = kgnilnd_find_conn_locked(peer);
1720
1721                 if (conn != NULL) {
1722                         kgnilnd_close_conn_locked(conn, -ENETRESET);
1723                 }
1724         } else {
1725                 peer->gnp_up_event_time = jiffies;
1726         }
1727
1728         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1729
1730         if (down == GNILND_RCA_NODE_DOWN) {
1731                 /* using ENETRESET so we don't get messages from
1732                  * kgnilnd_tx_done
1733                  */
1734                 kgnilnd_txlist_done(&zombies, -ENETRESET);
1735
1736                 if (*kgnilnd_tunables.kgn_peer_health) {
1737                         kgnilnd_peer_notify(peer, -ECONNRESET);
1738                 }
1739         }
1740
1741         CDEBUG(D_INFO, "marking nid %lld %s\n", nid, down ? "down" : "up");
1742         return 0;
1743 }
1744
1745 int
1746 kgnilnd_ctl(lnet_ni_t *ni, unsigned int cmd, void *arg)
1747 {
1748         struct libcfs_ioctl_data *data = arg;
1749         kgn_net_t                *net = ni->ni_data;
1750         int                       rc = -EINVAL;
1751
1752         LASSERT(ni == net->gnn_ni);
1753
1754         switch (cmd) {
1755         case IOC_LIBCFS_GET_PEER: {
1756                 lnet_nid_t   nid = 0;
1757                 kgn_peer_t  *peer = NULL;
1758                 __u32 nic_addr = 0;
1759                 __u64 peerstamp = 0;
1760                 int peer_refcount = 0, peer_connecting = 0;
1761                 int device_id = 0;
1762                 int tx_seq = 0, rx_seq = 0;
1763                 int fmaq_len = 0, nfma = 0, nrdma = 0;
1764
1765                 rc = kgnilnd_get_peer_info(data->ioc_count, &peer,
1766                                            &nid, &nic_addr, &peer_refcount,
1767                                            &peer_connecting);
1768                 if (rc)
1769                         break;
1770
1771                 /* Barf */
1772                 /* LNET_MKNID is used to mask from lnet the multiplexing/demultiplexing of connections and peers
1773                  * LNET assumes a conn and peer per net, the LNET_MKNID/LNET_NIDADDR allows us to let Lnet see what it
1774                  * wants to see instead of the underlying network that is being used to send the data
1775                  */
1776                 data->ioc_nid    = LNET_MKNID(LNET_NIDNET(ni->ni_nid), LNET_NIDADDR(nid));
1777                 data->ioc_flags  = peer_connecting;
1778                 data->ioc_count  = peer_refcount;
1779
1780                 rc = kgnilnd_get_conn_info(peer, &device_id, &peerstamp,
1781                                            &tx_seq, &rx_seq, &fmaq_len,
1782                                            &nfma, &nrdma);
1783
1784                 /* This is allowable - a persistent peer could not
1785                  * have a connection */
1786                 if (rc) {
1787                         /* flag to indicate we are not connected -
1788                          * need to print as such */
1789                         data->ioc_flags |= (1<<16);
1790                         rc = 0;
1791                 } else {
1792                         /* still barf */
1793                         data->ioc_net = device_id;
1794                         data->ioc_u64[0] = peerstamp;
1795                         data->ioc_u32[0] = fmaq_len;
1796                         data->ioc_u32[1] = nfma;
1797                         data->ioc_u32[2] = tx_seq;
1798                         data->ioc_u32[3] = rx_seq;
1799                         data->ioc_u32[4] = nrdma;
1800                 }
1801                 break;
1802         }
1803         case IOC_LIBCFS_ADD_PEER: {
1804                 /* just dummy value to allow using common interface */
1805                 kgn_peer_t      *peer;
1806                 rc = kgnilnd_add_peer(net, data->ioc_nid, &peer);
1807                 break;
1808         }
1809         case IOC_LIBCFS_DEL_PEER: {
1810                 /* NULL is passed in so it affects all peers in existence without regard to network
1811                  * as the peer may not exist on the network LNET believes it to be on.
1812                  */
1813                 rc = kgnilnd_del_conn_or_peer(NULL, data->ioc_nid,
1814                                               GNILND_DEL_PEER, -EUCLEAN);
1815                 break;
1816         }
1817         case IOC_LIBCFS_GET_CONN: {
1818                 kgn_conn_t *conn = kgnilnd_get_conn_by_idx(data->ioc_count);
1819
1820                 if (conn == NULL)
1821                         rc = -ENOENT;
1822                 else {
1823                         rc = 0;
1824                         /* LNET_MKNID is used to build the correct address based on what LNET wants to see instead of
1825                          * the generic connection that is used to send the data
1826                          */
1827                         data->ioc_nid    = LNET_MKNID(LNET_NIDNET(ni->ni_nid), LNET_NIDADDR(conn->gnc_peer->gnp_nid));
1828                         data->ioc_u32[0] = conn->gnc_device->gnd_id;
1829                         kgnilnd_conn_decref(conn);
1830                 }
1831                 break;
1832         }
1833         case IOC_LIBCFS_CLOSE_CONNECTION: {
1834                 /* use error = -ENETRESET to indicate it was lctl disconnect */
1835                 /* NULL is passed in so it affects all the nets as the connection is virtual
1836                  * and may not exist on the network LNET believes it to be on.
1837                  */
1838                 rc = kgnilnd_del_conn_or_peer(NULL, data->ioc_nid,
1839                                               GNILND_DEL_CONN, -ENETRESET);
1840                 break;
1841         }
1842         case IOC_LIBCFS_PUSH_CONNECTION: {
1843                 /* we use this to flush purgatory */
1844                 rc = kgnilnd_del_conn_or_peer(NULL, data->ioc_nid,
1845                                               GNILND_CLEAR_PURGATORY, -EUCLEAN);
1846                 break;
1847         }
1848         case IOC_LIBCFS_REGISTER_MYNID: {
1849                 /* Ignore if this is a noop */
1850                 if (data->ioc_nid == ni->ni_nid) {
1851                         rc = 0;
1852                 } else {
1853                         CERROR("obsolete IOC_LIBCFS_REGISTER_MYNID: %s(%s)\n",
1854                                libcfs_nid2str(data->ioc_nid),
1855                                libcfs_nid2str(ni->ni_nid));
1856                         rc = -EINVAL;
1857                 }
1858                 break;
1859         }
1860         }
1861
1862         return rc;
1863 }
1864
1865 void
1866 kgnilnd_query(lnet_ni_t *ni, lnet_nid_t nid, cfs_time_t *when)
1867 {
1868         kgn_net_t               *net = ni->ni_data;
1869         kgn_tx_t                *tx;
1870         kgn_peer_t              *peer = NULL;
1871         kgn_conn_t              *conn = NULL;
1872         lnet_process_id_t       id = {.nid = nid, .pid = LUSTRE_SRV_LNET_PID};
1873         ENTRY;
1874
1875         /* I expect to find him, so only take a read lock */
1876         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1877         peer = kgnilnd_find_peer_locked(nid);
1878         if (peer != NULL) {
1879                 /* LIE if in a quiesce - we will update the timeouts after,
1880                  * but we don't want sends failing during it */
1881                 if (kgnilnd_data.kgn_quiesce_trigger) {
1882                         *when = jiffies;
1883                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1884                         GOTO(out, 0);
1885                 }
1886
1887                 /* Update to best guess, might refine on later checks */
1888                 *when = peer->gnp_last_alive;
1889
1890                 /* we have a peer, how about a conn? */
1891                 conn = kgnilnd_find_conn_locked(peer);
1892
1893                 if (conn == NULL)  {
1894                         /* if there is no conn, check peer last errno to see if clean disconnect
1895                          * - if it was, we lie to LNet because we believe a TX would complete
1896                          * on reconnect */
1897                         if (kgnilnd_conn_clean_errno(peer->gnp_last_errno)) {
1898                                 *when = jiffies;
1899                         }
1900                         /* we still want to fire a TX and new conn in this case */
1901                 } else {
1902                         /* gnp_last_alive is valid, run for the hills */
1903                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1904                         GOTO(out, 0);
1905                 }
1906         }
1907         /* if we get here, either we have no peer or no conn for him, so fire off
1908          * new TX to trigger conn setup */
1909         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1910
1911         /* if we couldn't find him, we'll fire up a TX and get connected -
1912          * if we don't do this, after ni_peer_timeout, LNet will declare him dead.
1913          * So really we treat kgnilnd_query as a bit of a 'connect now' type
1914          * event because it'll only do this when it wants to send
1915          *
1916          * Use a real TX for this to get the proper gnp_tx_queue behavior, etc
1917          * normally we'd use kgnilnd_send_ctlmsg for this, but we don't really
1918          * care that this goes out quickly since we already know we need a new conn
1919          * formed */
1920         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_NOOP_SEND))
1921                 return;
1922
1923         tx = kgnilnd_new_tx_msg(GNILND_MSG_NOOP, ni->ni_nid);
1924         if (tx != NULL) {
1925                 kgnilnd_launch_tx(tx, net, &id);
1926         }
1927 out:
1928         CDEBUG(D_NETTRACE, "peer 0x%p->%s when %lu\n", peer,
1929                libcfs_nid2str(nid), *when);
1930         EXIT;
1931 }
1932
1933 int
1934 kgnilnd_dev_init(kgn_device_t *dev)
1935 {
1936         gni_return_t      rrc;
1937         int               rc = 0;
1938         unsigned int      cq_size;
1939         ENTRY;
1940
1941         /* size of these CQs should be able to accommodate the outgoing
1942          * RDMA and SMSG transactions.  Since we really don't know what we
1943          * really need here, we'll take credits * 2 * 3 to allow a bunch.
1944          * We need to dig into this more with the performance work. */
1945         cq_size = *kgnilnd_tunables.kgn_credits * 2 * 3;
1946
1947         rrc = kgnilnd_cdm_create(dev->gnd_id, *kgnilnd_tunables.kgn_ptag,
1948                                  GNILND_COOKIE, 0,
1949                                  &dev->gnd_domain);
1950         if (rrc != GNI_RC_SUCCESS) {
1951                 CERROR("Can't create CDM %d (%d)\n", dev->gnd_id, rrc);
1952                 rc = -ENODEV;
1953                 GOTO(failed, rc);
1954         }
1955
1956         rrc = kgnilnd_cdm_attach(dev->gnd_domain, dev->gnd_id,
1957                                  &dev->gnd_host_id, &dev->gnd_handle);
1958         if (rrc != GNI_RC_SUCCESS) {
1959                 CERROR("Can't attach CDM to device %d (%d)\n",
1960                         dev->gnd_id, rrc);
1961                 rc = -ENODEV;
1962                 GOTO(failed, rc);
1963         }
1964
1965         /* a bit gross, but not much we can do - Aries Sim doesn't have
1966          * hardcoded NIC/NID that we can use */
1967         rc = kgnilnd_setup_nic_translation(dev->gnd_host_id);
1968         if (rc != 0) {
1969                 rc = -ENODEV;
1970                 GOTO(failed, rc);
1971         }
1972
1973         /* only dev 0 gets the errors - no need to reset the stack twice
1974          * - this works because we have a single PTAG, if we had more
1975          * then we'd need to have multiple handlers */
1976         if (dev->gnd_id == 0) {
1977                 rrc = kgnilnd_subscribe_errors(dev->gnd_handle,
1978                                                 GNI_ERRMASK_CRITICAL |
1979                                                 GNI_ERRMASK_UNKNOWN_TRANSACTION,
1980                                               0, NULL, kgnilnd_critical_error,
1981                                               &dev->gnd_err_handle);
1982                 if (rrc != GNI_RC_SUCCESS) {
1983                         CERROR("Can't subscribe for errors on device %d: rc %d\n",
1984                                 dev->gnd_id, rrc);
1985                         rc = -ENODEV;
1986                         GOTO(failed, rc);
1987                 }
1988
1989                 rc = kgnilnd_set_quiesce_callback(dev->gnd_handle,
1990                                                   kgnilnd_quiesce_end_callback);
1991                 if (rc != GNI_RC_SUCCESS) {
1992                         CERROR("Can't subscribe for quiesce callback on device %d: rc %d\n",
1993                                 dev->gnd_id, rrc);
1994                         rc = -ENODEV;
1995                         GOTO(failed, rc);
1996                 }
1997         }
1998
1999         rc = kgnilnd_nicaddr_to_nid(dev->gnd_host_id, &dev->gnd_nid);
2000         if (rc < 0) {
2001                 /* log messages during startup */
2002                 if (kgnilnd_data.kgn_init < GNILND_INIT_ALL) {
2003                         CERROR("couldn't translate host_id 0x%x to nid. rc %d\n",
2004                                 dev->gnd_host_id, rc);
2005                 }
2006                 rc = -ESRCH;
2007                 GOTO(failed, rc);
2008         }
2009         CDEBUG(D_NET, "NIC %x -> NID %d\n", dev->gnd_host_id, dev->gnd_nid);
2010
2011         rrc = kgnilnd_cq_create(dev->gnd_handle, cq_size,
2012                                 0, kgnilnd_device_callback,
2013                                 dev->gnd_id, &dev->gnd_snd_rdma_cqh);
2014         if (rrc != GNI_RC_SUCCESS) {
2015                 CERROR("Can't create rdma send cq size %u for device "
2016                        "%d (%d)\n", cq_size, dev->gnd_id, rrc);
2017                 rc = -EINVAL;
2018                 GOTO(failed, rc);
2019         }
2020
2021         rrc = kgnilnd_cq_create(dev->gnd_handle, cq_size,
2022                         0, kgnilnd_device_callback, dev->gnd_id,
2023                         &dev->gnd_snd_fma_cqh);
2024         if (rrc != GNI_RC_SUCCESS) {
2025                 CERROR("Can't create fma send cq size %u for device %d (%d)\n",
2026                        cq_size, dev->gnd_id, rrc);
2027                 rc = -EINVAL;
2028                 GOTO(failed, rc);
2029         }
2030
2031         /* This one we size differently - overflows are possible and it needs to be
2032          * sized based on machine size */
2033         rrc = kgnilnd_cq_create(dev->gnd_handle,
2034                         *kgnilnd_tunables.kgn_fma_cq_size,
2035                         0, kgnilnd_device_callback, dev->gnd_id,
2036                         &dev->gnd_rcv_fma_cqh);
2037         if (rrc != GNI_RC_SUCCESS) {
2038                 CERROR("Can't create fma cq size %d for device %d (%d)\n",
2039                        *kgnilnd_tunables.kgn_fma_cq_size, dev->gnd_id, rrc);
2040                 rc = -EINVAL;
2041                 GOTO(failed, rc);
2042         }
2043
2044         RETURN(0);
2045
2046 failed:
2047         kgnilnd_dev_fini(dev);
2048         RETURN(rc);
2049 }
2050
2051 void
2052 kgnilnd_dev_fini(kgn_device_t *dev)
2053 {
2054         gni_return_t rrc;
2055         ENTRY;
2056
2057         /* At quiesce or rest time, need to loop through and clear gnd_ready_conns ?*/
2058         LASSERTF(list_empty(&dev->gnd_ready_conns) &&
2059                  list_empty(&dev->gnd_map_tx) &&
2060                  list_empty(&dev->gnd_rdmaq),
2061                  "dev 0x%p ready_conns %d@0x%p map_tx %d@0x%p rdmaq %d@0x%p\n",
2062                  dev, kgnilnd_count_list(&dev->gnd_ready_conns), &dev->gnd_ready_conns,
2063                  kgnilnd_count_list(&dev->gnd_map_tx), &dev->gnd_map_tx,
2064                  kgnilnd_count_list(&dev->gnd_rdmaq), &dev->gnd_rdmaq);
2065
2066         /* These should follow from tearing down all connections */
2067         LASSERTF(dev->gnd_map_nphys == 0 && dev->gnd_map_physnop == 0,
2068                 "%d physical mappings of %d pages still mapped\n",
2069                  dev->gnd_map_nphys, dev->gnd_map_physnop);
2070
2071         LASSERTF(dev->gnd_map_nvirt == 0 && dev->gnd_map_virtnob == 0,
2072                 "%d virtual mappings of "LPU64" bytes still mapped\n",
2073                  dev->gnd_map_nvirt, dev->gnd_map_virtnob);
2074
2075         LASSERTF(atomic_read(&dev->gnd_n_mdd) == 0 &&
2076                  atomic_read(&dev->gnd_n_mdd_held) == 0 &&
2077                  atomic64_read(&dev->gnd_nbytes_map) == 0,
2078                 "%d SMSG mappings of %ld bytes still mapped or held %d\n",
2079                  atomic_read(&dev->gnd_n_mdd),
2080                  atomic64_read(&dev->gnd_nbytes_map), atomic_read(&dev->gnd_n_mdd_held));
2081
2082         LASSERT(list_empty(&dev->gnd_map_list));
2083
2084         /* What other assertions needed to ensure all connections torn down ? */
2085
2086         /* check all counters == 0 (EP, MDD, etc) */
2087
2088         /* if we are resetting due to quiese (stack reset), don't check
2089          * thread states */
2090         LASSERTF(kgnilnd_data.kgn_quiesce_trigger ||
2091                 atomic_read(&kgnilnd_data.kgn_nthreads) == 0,
2092                 "tried to shutdown with threads active\n");
2093
2094         if (dev->gnd_rcv_fma_cqh) {
2095                 rrc = kgnilnd_cq_destroy(dev->gnd_rcv_fma_cqh);
2096                 LASSERTF(rrc == GNI_RC_SUCCESS,
2097                         "bad rc from gni_cq_destroy on rcv_fma_cqh: %d\n", rrc);
2098                 dev->gnd_rcv_fma_cqh = NULL;
2099         }
2100
2101         if (dev->gnd_snd_rdma_cqh) {
2102                 rrc = kgnilnd_cq_destroy(dev->gnd_snd_rdma_cqh);
2103                 LASSERTF(rrc == GNI_RC_SUCCESS,
2104                         "bad rc from gni_cq_destroy on send_rdma_cqh: %d\n", rrc);
2105                 dev->gnd_snd_rdma_cqh = NULL;
2106         }
2107
2108         if (dev->gnd_snd_fma_cqh) {
2109                 rrc = kgnilnd_cq_destroy(dev->gnd_snd_fma_cqh);
2110                 LASSERTF(rrc == GNI_RC_SUCCESS,
2111                         "bad rc from gni_cq_destroy on snd_fma_cqh: %d\n", rrc);
2112                 dev->gnd_snd_fma_cqh = NULL;
2113         }
2114
2115         if (dev->gnd_err_handle) {
2116                 rrc = kgnilnd_release_errors(dev->gnd_err_handle);
2117                 LASSERTF(rrc == GNI_RC_SUCCESS,
2118                         "bad rc from gni_release_errors: %d\n", rrc);
2119                 dev->gnd_err_handle = NULL;
2120         }
2121
2122         if (dev->gnd_domain) {
2123                 rrc = kgnilnd_cdm_destroy(dev->gnd_domain);
2124                 LASSERTF(rrc == GNI_RC_SUCCESS,
2125                         "bad rc from gni_cdm_destroy: %d\n", rrc);
2126                 dev->gnd_domain = NULL;
2127         }
2128
2129         EXIT;
2130 }
2131
2132
2133 int kgnilnd_base_startup(void)
2134 {
2135         struct timeval       tv;
2136         int                  pkmem = atomic_read(&libcfs_kmemory);
2137         int                  rc;
2138         int                  i;
2139         kgn_device_t        *dev;
2140         struct task_struct  *thrd;
2141         ENTRY;
2142
2143         LASSERTF(kgnilnd_data.kgn_init == GNILND_INIT_NOTHING,
2144                 "init %d\n", kgnilnd_data.kgn_init);
2145
2146         /* zero pointers, flags etc */
2147         memset(&kgnilnd_data, 0, sizeof(kgnilnd_data));
2148
2149         /* CAVEAT EMPTOR: Every 'Fma' message includes the sender's NID and
2150          * a unique (for all time) connstamp so we can uniquely identify
2151          * the sender.  The connstamp is an incrementing counter
2152          * initialised with seconds + microseconds at startup time.  So we
2153          * rely on NOT creating connections more frequently on average than
2154          * 1MHz to ensure we don't use old connstamps when we reboot. */
2155         do_gettimeofday(&tv);
2156         kgnilnd_data.kgn_connstamp =
2157                  kgnilnd_data.kgn_peerstamp =
2158                         (((__u64)tv.tv_sec) * 1000000) + tv.tv_usec;
2159
2160         init_rwsem(&kgnilnd_data.kgn_net_rw_sem);
2161
2162         for (i = 0; i < GNILND_MAXDEVS; i++) {
2163                 kgn_device_t  *dev = &kgnilnd_data.kgn_devices[i];
2164
2165                 dev->gnd_id = i;
2166                 INIT_LIST_HEAD(&dev->gnd_ready_conns);
2167                 INIT_LIST_HEAD(&dev->gnd_map_tx);
2168                 INIT_LIST_HEAD(&dev->gnd_fma_buffs);
2169                 mutex_init(&dev->gnd_cq_mutex);
2170                 sema_init(&dev->gnd_fmablk_sem, 1);
2171                 spin_lock_init(&dev->gnd_fmablk_lock);
2172                 init_waitqueue_head(&dev->gnd_waitq);
2173                 init_waitqueue_head(&dev->gnd_dgram_waitq);
2174                 init_waitqueue_head(&dev->gnd_dgping_waitq);
2175                 spin_lock_init(&dev->gnd_lock);
2176                 INIT_LIST_HEAD(&dev->gnd_map_list);
2177                 spin_lock_init(&dev->gnd_map_lock);
2178                 atomic_set(&dev->gnd_nfmablk, 0);
2179                 atomic_set(&dev->gnd_fmablk_vers, 1);
2180                 atomic_set(&dev->gnd_neps, 0);
2181                 atomic_set(&dev->gnd_canceled_dgrams, 0);
2182                 INIT_LIST_HEAD(&dev->gnd_connd_peers);
2183                 spin_lock_init(&dev->gnd_connd_lock);
2184                 spin_lock_init(&dev->gnd_dgram_lock);
2185                 spin_lock_init(&dev->gnd_rdmaq_lock);
2186                 INIT_LIST_HEAD(&dev->gnd_rdmaq);
2187                 init_rwsem(&dev->gnd_conn_sem);
2188
2189                 /* alloc & setup nid based dgram table */
2190                 LIBCFS_ALLOC(dev->gnd_dgrams,
2191                             sizeof(struct list_head) * *kgnilnd_tunables.kgn_peer_hash_size);
2192
2193                 if (dev->gnd_dgrams == NULL) {
2194                         rc = -ENOMEM;
2195                         GOTO(failed, rc);
2196                 }
2197
2198                 for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++) {
2199                         INIT_LIST_HEAD(&dev->gnd_dgrams[i]);
2200                 }
2201                 atomic_set(&dev->gnd_ndgrams, 0);
2202                 atomic_set(&dev->gnd_nwcdgrams, 0);
2203                 /* setup timer for RDMAQ processing */
2204                 setup_timer(&dev->gnd_rdmaq_timer, kgnilnd_schedule_device_timer,
2205                             (unsigned long)dev);
2206
2207                 /* setup timer for mapping processing */
2208                 setup_timer(&dev->gnd_map_timer, kgnilnd_schedule_device_timer,
2209                             (unsigned long)dev);
2210
2211         }
2212
2213         /* CQID 0 isn't allowed, set to MAX_MSG_ID - 1 to check for conflicts early */
2214         kgnilnd_data.kgn_next_cqid = GNILND_MAX_MSG_ID - 1;
2215         kgnilnd_data.kgn_new_min_timeout = *kgnilnd_tunables.kgn_timeout;
2216         init_waitqueue_head(&kgnilnd_data.kgn_reaper_waitq);
2217         init_waitqueue_head(&kgnilnd_data.kgn_ruhroh_waitq);
2218         spin_lock_init(&kgnilnd_data.kgn_reaper_lock);
2219
2220         sema_init(&kgnilnd_data.kgn_quiesce_sem, 1);
2221         atomic_set(&kgnilnd_data.kgn_nquiesce, 0);
2222         atomic_set(&kgnilnd_data.kgn_npending_conns, 0);
2223         atomic_set(&kgnilnd_data.kgn_npending_unlink, 0);
2224         atomic_set(&kgnilnd_data.kgn_npending_detach, 0);
2225         atomic_set(&kgnilnd_data.kgn_rev_offset, 0);
2226         atomic_set(&kgnilnd_data.kgn_rev_length, 0);
2227         atomic_set(&kgnilnd_data.kgn_rev_copy_buff, 0);
2228
2229         /* OK to call kgnilnd_api_shutdown() to cleanup now */
2230         kgnilnd_data.kgn_init = GNILND_INIT_DATA;
2231         try_module_get(THIS_MODULE);
2232
2233         rwlock_init(&kgnilnd_data.kgn_peer_conn_lock);
2234
2235         LIBCFS_ALLOC(kgnilnd_data.kgn_peers,
2236                     sizeof(struct list_head) * *kgnilnd_tunables.kgn_peer_hash_size);
2237
2238         if (kgnilnd_data.kgn_peers == NULL) {
2239                 rc = -ENOMEM;
2240                 GOTO(failed, rc);
2241         }
2242
2243         for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++) {
2244                 INIT_LIST_HEAD(&kgnilnd_data.kgn_peers[i]);
2245         }
2246
2247         LIBCFS_ALLOC(kgnilnd_data.kgn_conns,
2248                     sizeof(struct list_head) * *kgnilnd_tunables.kgn_peer_hash_size);
2249
2250         if (kgnilnd_data.kgn_conns == NULL) {
2251                 rc = -ENOMEM;
2252                 GOTO(failed, rc);
2253         }
2254
2255         for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++) {
2256                 INIT_LIST_HEAD(&kgnilnd_data.kgn_conns[i]);
2257         }
2258
2259         LIBCFS_ALLOC(kgnilnd_data.kgn_nets,
2260                     sizeof(struct list_head) * *kgnilnd_tunables.kgn_net_hash_size);
2261
2262         if (kgnilnd_data.kgn_nets == NULL) {
2263                 rc = -ENOMEM;
2264                 GOTO(failed, rc);
2265         }
2266
2267         for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++) {
2268                 INIT_LIST_HEAD(&kgnilnd_data.kgn_nets[i]);
2269         }
2270
2271         kgnilnd_data.kgn_mbox_cache =
2272                 kmem_cache_create("kgn_mbox_block", KMALLOC_MAX_SIZE, 0,
2273                                   SLAB_HWCACHE_ALIGN, NULL);
2274         if (kgnilnd_data.kgn_mbox_cache == NULL) {
2275                 CERROR("Can't create slab for physical mbox blocks\n");
2276                 rc = -ENOMEM;
2277                 GOTO(failed, rc);
2278         }
2279
2280         kgnilnd_data.kgn_rx_cache =
2281                 kmem_cache_create("kgn_rx_t", sizeof(kgn_rx_t), 0, 0, NULL);
2282         if (kgnilnd_data.kgn_rx_cache == NULL) {
2283                 CERROR("Can't create slab for kgn_rx_t descriptors\n");
2284                 rc = -ENOMEM;
2285                 GOTO(failed, rc);
2286         }
2287
2288         kgnilnd_data.kgn_tx_cache =
2289                 kmem_cache_create("kgn_tx_t", sizeof(kgn_tx_t), 0, 0, NULL);
2290         if (kgnilnd_data.kgn_tx_cache == NULL) {
2291                 CERROR("Can't create slab for kgn_tx_t\n");
2292                 rc = -ENOMEM;
2293                 GOTO(failed, rc);
2294         }
2295
2296         kgnilnd_data.kgn_tx_phys_cache =
2297                 kmem_cache_create("kgn_tx_phys",
2298                                    LNET_MAX_IOV * sizeof(gni_mem_segment_t),
2299                                    0, 0, NULL);
2300         if (kgnilnd_data.kgn_tx_phys_cache == NULL) {
2301                 CERROR("Can't create slab for kgn_tx_phys\n");
2302                 rc = -ENOMEM;
2303                 GOTO(failed, rc);
2304         }
2305
2306         kgnilnd_data.kgn_dgram_cache =
2307                 kmem_cache_create("kgn_dgram_t", sizeof(kgn_dgram_t), 0, 0, NULL);
2308         if (kgnilnd_data.kgn_dgram_cache == NULL) {
2309                 CERROR("Can't create slab for outgoing datagrams\n");
2310                 rc = -ENOMEM;
2311                 GOTO(failed, rc);
2312         }
2313
2314         /* allocate a MAX_IOV array of page pointers for each cpu */
2315         kgnilnd_data.kgn_cksum_map_pages = kmalloc(num_possible_cpus() * sizeof (struct page *),
2316                                                    GFP_KERNEL);
2317         if (kgnilnd_data.kgn_cksum_map_pages == NULL) {
2318                 CERROR("Can't allocate vmap cksum pages\n");
2319                 rc = -ENOMEM;
2320                 GOTO(failed, rc);
2321         }
2322         kgnilnd_data.kgn_cksum_npages = num_possible_cpus();
2323         memset(kgnilnd_data.kgn_cksum_map_pages, 0,
2324                 kgnilnd_data.kgn_cksum_npages * sizeof (struct page *));
2325
2326         for (i = 0; i < kgnilnd_data.kgn_cksum_npages; i++) {
2327                 kgnilnd_data.kgn_cksum_map_pages[i] = kmalloc(LNET_MAX_IOV * sizeof (struct page *),
2328                                                               GFP_KERNEL);
2329                 if (kgnilnd_data.kgn_cksum_map_pages[i] == NULL) {
2330                         CERROR("Can't allocate vmap cksum pages for cpu %d\n", i);
2331                         rc = -ENOMEM;
2332                         GOTO(failed, rc);
2333                 }
2334         }
2335
2336         LASSERT(kgnilnd_data.kgn_ndevs == 0);
2337
2338         /* Use all available GNI devices */
2339         for (i = 0; i < GNILND_MAXDEVS; i++) {
2340                 dev = &kgnilnd_data.kgn_devices[kgnilnd_data.kgn_ndevs];
2341
2342                 rc = kgnilnd_dev_init(dev);
2343                 if (rc == 0) {
2344                         /* Increment here so base_shutdown cleans it up */
2345                         kgnilnd_data.kgn_ndevs++;
2346
2347                         rc = kgnilnd_allocate_phys_fmablk(dev);
2348                         if (rc) {
2349                                 GOTO(failed, rc);
2350                         }
2351                 }
2352         }
2353
2354         if (kgnilnd_data.kgn_ndevs == 0) {
2355                 CERROR("Can't initialise any GNI devices\n");
2356                 rc = -ENODEV;
2357                 GOTO(failed, rc);
2358         }
2359
2360         rc = kgnilnd_thread_start(kgnilnd_reaper, NULL, "kgnilnd_rpr", 0);
2361         if (rc != 0) {
2362                 CERROR("Can't spawn gnilnd reaper: %d\n", rc);
2363                 GOTO(failed, rc);
2364         }
2365
2366         rc = kgnilnd_start_rca_thread();
2367         if (rc != 0) {
2368                 CERROR("Can't spawn gnilnd rca: %d\n", rc);
2369                 GOTO(failed, rc);
2370         }
2371
2372         /*
2373          * Start ruhroh thread.  We can't use kgnilnd_thread_start() because
2374          * we don't want this thread included in kgnilnd_data.kgn_nthreads
2375          * count.  This thread controls quiesce, so it mustn't
2376          * quiesce itself.
2377          */
2378         thrd = kthread_run(kgnilnd_ruhroh_thread, NULL, "%s_%02d", "kgnilnd_rr", 0);
2379         if (IS_ERR(thrd)) {
2380                 rc = PTR_ERR(thrd);
2381                 CERROR("Can't spawn gnilnd ruhroh thread: %d\n", rc);
2382                 GOTO(failed, rc);
2383         }
2384
2385         /* threads will load balance across devs as they are available */
2386         for (i = 0; i < *kgnilnd_tunables.kgn_sched_threads; i++) {
2387                 rc = kgnilnd_thread_start(kgnilnd_scheduler, (void *)((long)i),
2388                                           "kgnilnd_sd", i);
2389                 if (rc != 0) {
2390                         CERROR("Can't spawn gnilnd scheduler[%d]: %d\n",
2391                                i, rc);
2392                         GOTO(failed, rc);
2393                 }
2394         }
2395
2396         for (i = 0; i < kgnilnd_data.kgn_ndevs; i++) {
2397                 dev = &kgnilnd_data.kgn_devices[i];
2398                 rc = kgnilnd_thread_start(kgnilnd_dgram_mover, dev,
2399                                           "kgnilnd_dg", dev->gnd_id);
2400                 if (rc != 0) {
2401                         CERROR("Can't spawn gnilnd dgram_mover[%d]: %d\n",
2402                                dev->gnd_id, rc);
2403                         GOTO(failed, rc);
2404                 }
2405
2406                 rc = kgnilnd_thread_start(kgnilnd_dgram_waitq, dev,
2407                                           "kgnilnd_dgn", dev->gnd_id);
2408                 if (rc != 0) {
2409                         CERROR("Can't spawn gnilnd dgram_waitq[%d]: %d\n",
2410                                 dev->gnd_id, rc);
2411                         GOTO(failed, rc);
2412                 }
2413
2414                 rc = kgnilnd_setup_wildcard_dgram(dev);
2415
2416                 if (rc != 0) {
2417                         CERROR("Can't create wildcard dgrams[%d]: %d\n",
2418                                 dev->gnd_id, rc);
2419                         GOTO(failed, rc);
2420                 }
2421         }
2422
2423
2424
2425         /* flag everything initialised */
2426         kgnilnd_data.kgn_init = GNILND_INIT_ALL;
2427         /*****************************************************/
2428
2429         CDEBUG(D_MALLOC, "initial kmem %d\n", pkmem);
2430         RETURN(0);
2431
2432 failed:
2433         kgnilnd_base_shutdown();
2434         kgnilnd_data.kgn_init = GNILND_INIT_NOTHING;
2435         RETURN(rc);
2436 }
2437
2438 void
2439 kgnilnd_base_shutdown(void)
2440 {
2441         int                     i;
2442         ENTRY;
2443
2444         while (CFS_FAIL_TIMEOUT(CFS_FAIL_GNI_PAUSE_SHUTDOWN, 1)) {};
2445
2446         kgnilnd_data.kgn_wc_kill = 1;
2447
2448         for (i = 0; i < kgnilnd_data.kgn_ndevs; i++) {
2449                 kgn_device_t *dev = &kgnilnd_data.kgn_devices[i];
2450                 kgnilnd_cancel_wc_dgrams(dev);
2451                 kgnilnd_del_conn_or_peer(NULL, LNET_NID_ANY, GNILND_DEL_PEER, -ESHUTDOWN);
2452                 kgnilnd_wait_for_canceled_dgrams(dev);
2453         }
2454
2455         /* Peer state all cleaned up BEFORE setting shutdown, so threads don't
2456          * have to worry about shutdown races.  NB connections may be created
2457          * while there are still active connds, but these will be temporary
2458          * since peer creation always fails after the listener has started to
2459          * shut down.
2460          * all peers should have been cleared out on the nets */
2461         LASSERTF(atomic_read(&kgnilnd_data.kgn_npeers) == 0,
2462                 "peers left %d\n", atomic_read(&kgnilnd_data.kgn_npeers));
2463
2464         /* Wait for the ruhroh thread to shut down. */
2465         kgnilnd_data.kgn_ruhroh_shutdown = 1;
2466         wake_up(&kgnilnd_data.kgn_ruhroh_waitq);
2467         i = 2;
2468         while (kgnilnd_data.kgn_ruhroh_running != 0) {
2469                 i++;
2470                 CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
2471                        "Waiting for ruhroh thread to terminate\n");
2472                 cfs_pause(cfs_time_seconds(1));
2473         }
2474
2475        /* Flag threads to terminate */
2476         kgnilnd_data.kgn_shutdown = 1;
2477
2478         for (i = 0; i < kgnilnd_data.kgn_ndevs; i++) {
2479                 kgn_device_t *dev = &kgnilnd_data.kgn_devices[i];
2480
2481                 /* should clear all the MDDs */
2482                 kgnilnd_unmap_phys_fmablk(dev);
2483
2484                 kgnilnd_schedule_device(dev);
2485                 wake_up_all(&dev->gnd_dgram_waitq);
2486                 wake_up_all(&dev->gnd_dgping_waitq);
2487                 LASSERT(list_empty(&dev->gnd_connd_peers));
2488         }
2489
2490         spin_lock(&kgnilnd_data.kgn_reaper_lock);
2491         wake_up_all(&kgnilnd_data.kgn_reaper_waitq);
2492         spin_unlock(&kgnilnd_data.kgn_reaper_lock);
2493
2494         kgnilnd_wakeup_rca_thread();
2495
2496         /* Wait for threads to exit */
2497         i = 2;
2498         while (atomic_read(&kgnilnd_data.kgn_nthreads) != 0) {
2499                 i++;
2500                 CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET, /* power of 2? */
2501                        "Waiting for %d threads to terminate\n",
2502                        atomic_read(&kgnilnd_data.kgn_nthreads));
2503                 cfs_pause(cfs_time_seconds(1));
2504         }
2505
2506         LASSERTF(atomic_read(&kgnilnd_data.kgn_npeers) == 0,
2507                 "peers left %d\n", atomic_read(&kgnilnd_data.kgn_npeers));
2508
2509         if (kgnilnd_data.kgn_peers != NULL) {
2510                 for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++)
2511                         LASSERT(list_empty(&kgnilnd_data.kgn_peers[i]));
2512
2513                 LIBCFS_FREE(kgnilnd_data.kgn_peers,
2514                             sizeof (struct list_head) *
2515                             *kgnilnd_tunables.kgn_peer_hash_size);
2516         }
2517
2518         down_write(&kgnilnd_data.kgn_net_rw_sem);
2519         if (kgnilnd_data.kgn_nets != NULL) {
2520                 for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++)
2521                         LASSERT(list_empty(&kgnilnd_data.kgn_nets[i]));
2522
2523                 LIBCFS_FREE(kgnilnd_data.kgn_nets,
2524                             sizeof (struct list_head) *
2525                             *kgnilnd_tunables.kgn_net_hash_size);
2526         }
2527         up_write(&kgnilnd_data.kgn_net_rw_sem);
2528
2529         LASSERTF(atomic_read(&kgnilnd_data.kgn_nconns) == 0,
2530                 "conns left %d\n", atomic_read(&kgnilnd_data.kgn_nconns));
2531
2532         if (kgnilnd_data.kgn_conns != NULL) {
2533                 for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++)
2534                         LASSERT(list_empty(&kgnilnd_data.kgn_conns[i]));
2535
2536                 LIBCFS_FREE(kgnilnd_data.kgn_conns,
2537                             sizeof (struct list_head) *
2538                             *kgnilnd_tunables.kgn_peer_hash_size);
2539         }
2540
2541         for (i = 0; i < kgnilnd_data.kgn_ndevs; i++) {
2542                 kgn_device_t *dev = &kgnilnd_data.kgn_devices[i];
2543                 kgnilnd_dev_fini(dev);
2544
2545                 LASSERTF(atomic_read(&dev->gnd_ndgrams) == 0,
2546                         "dgrams left %d\n", atomic_read(&dev->gnd_ndgrams));
2547
2548                 if (dev->gnd_dgrams != NULL) {
2549                         for (i = 0; i < *kgnilnd_tunables.kgn_peer_hash_size; i++)
2550                                 LASSERT(list_empty(&dev->gnd_dgrams[i]));
2551
2552                         LIBCFS_FREE(dev->gnd_dgrams,
2553                                     sizeof (struct list_head) *
2554                                     *kgnilnd_tunables.kgn_peer_hash_size);
2555                 }
2556
2557                 kgnilnd_free_phys_fmablk(dev);
2558         }
2559
2560         if (kgnilnd_data.kgn_mbox_cache != NULL)
2561                 kmem_cache_destroy(kgnilnd_data.kgn_mbox_cache);
2562
2563         if (kgnilnd_data.kgn_rx_cache != NULL)
2564                 kmem_cache_destroy(kgnilnd_data.kgn_rx_cache);
2565
2566         if (kgnilnd_data.kgn_tx_cache != NULL)
2567                 kmem_cache_destroy(kgnilnd_data.kgn_tx_cache);
2568
2569         if (kgnilnd_data.kgn_tx_phys_cache != NULL)
2570                 kmem_cache_destroy(kgnilnd_data.kgn_tx_phys_cache);
2571
2572         if (kgnilnd_data.kgn_dgram_cache != NULL)
2573                 kmem_cache_destroy(kgnilnd_data.kgn_dgram_cache);
2574
2575         if (kgnilnd_data.kgn_cksum_map_pages != NULL) {
2576                 for (i = 0; i < kgnilnd_data.kgn_cksum_npages; i++) {
2577                         if (kgnilnd_data.kgn_cksum_map_pages[i] != NULL) {
2578                                 kfree(kgnilnd_data.kgn_cksum_map_pages[i]);
2579                         }
2580                 }
2581                 kfree(kgnilnd_data.kgn_cksum_map_pages);
2582         }
2583
2584         CDEBUG(D_MALLOC, "after NAL cleanup: kmem %d\n",
2585                atomic_read(&libcfs_kmemory));
2586
2587         kgnilnd_data.kgn_init = GNILND_INIT_NOTHING;
2588         module_put(THIS_MODULE);
2589
2590         EXIT;
2591 }
2592
2593 int
2594 kgnilnd_startup(lnet_ni_t *ni)
2595 {
2596         int               rc, devno;
2597         kgn_net_t        *net;
2598         ENTRY;
2599
2600         LASSERTF(ni->ni_lnd == &the_kgnilnd,
2601                 "bad LND 0x%p != the_kgnilnd @ 0x%p\n",
2602                 ni->ni_lnd, &the_kgnilnd);
2603
2604         if (kgnilnd_data.kgn_init == GNILND_INIT_NOTHING) {
2605                 rc = kgnilnd_base_startup();
2606                 if (rc != 0)
2607                         RETURN(rc);
2608         }
2609
2610         /* Serialize with shutdown. */
2611         down(&kgnilnd_data.kgn_quiesce_sem);
2612
2613         LIBCFS_ALLOC(net, sizeof(*net));
2614         if (net == NULL) {
2615                 CERROR("could not allocate net for new interface instance\n");
2616                 rc = -ENOMEM;
2617                 /* no need to cleanup the CDM... */
2618                 GOTO(failed, rc);
2619         }
2620         INIT_LIST_HEAD(&net->gnn_list);
2621         ni->ni_data = net;
2622         net->gnn_ni = ni;
2623         ni->ni_maxtxcredits = *kgnilnd_tunables.kgn_credits;
2624         ni->ni_peertxcredits = *kgnilnd_tunables.kgn_peer_credits;
2625
2626         if (*kgnilnd_tunables.kgn_peer_health) {
2627                 int     fudge;
2628                 int     timeout;
2629                 /* give this a bit of leeway - we don't have a hard timeout
2630                  * as we only check timeouts periodically - see comment in kgnilnd_reaper */
2631                 fudge = (GNILND_TO2KA(*kgnilnd_tunables.kgn_timeout) / GNILND_REAPER_NCHECKS);
2632                 timeout = *kgnilnd_tunables.kgn_timeout + fudge;
2633
2634                 if (*kgnilnd_tunables.kgn_peer_timeout >= timeout)
2635                         ni->ni_peertimeout = *kgnilnd_tunables.kgn_peer_timeout;
2636                 else if (*kgnilnd_tunables.kgn_peer_timeout > -1) {
2637                         LCONSOLE_ERROR("Peer_timeout is set to %d but needs to be >= %d\n",
2638                                         *kgnilnd_tunables.kgn_peer_timeout,
2639                                         timeout);
2640                         ni->ni_data = NULL;
2641                         LIBCFS_FREE(net, sizeof(*net));
2642                         rc = -EINVAL;
2643                         GOTO(failed, rc);
2644                 } else
2645                         ni->ni_peertimeout = timeout;
2646
2647                 LCONSOLE_INFO("Enabling LNet peer health for gnilnd, timeout %ds\n",
2648                               ni->ni_peertimeout);
2649         }
2650
2651         atomic_set(&net->gnn_refcount, 1);
2652
2653         /* if we have multiple devices, spread the nets around */
2654         net->gnn_netnum = LNET_NETNUM(LNET_NIDNET(ni->ni_nid));
2655
2656         devno = LNET_NIDNET(ni->ni_nid) % GNILND_MAXDEVS;
2657         net->gnn_dev = &kgnilnd_data.kgn_devices[devno];
2658
2659         /* allocate a 'dummy' cdm for datagram use. We can only have a single
2660          * datagram between a nid:inst_id and nid2:inst_id. The fake cdm
2661          * give us additional inst_id to use, allowing the datagrams to flow
2662          * like rivers of honey and beer */
2663
2664         /* the instance id for the cdm is the NETNUM offset by MAXDEVS -
2665          * ensuring we'll have a unique id */
2666
2667
2668         ni->ni_nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), net->gnn_dev->gnd_nid);
2669         CDEBUG(D_NET, "adding net %p nid=%s on dev %d \n",
2670                 net, libcfs_nid2str(ni->ni_nid), net->gnn_dev->gnd_id);
2671         /* until the gnn_list is set, we need to cleanup ourselves as
2672          * kgnilnd_shutdown is just gonna get confused */
2673
2674         down_write(&kgnilnd_data.kgn_net_rw_sem);
2675         list_add_tail(&net->gnn_list, kgnilnd_netnum2netlist(net->gnn_netnum));
2676         up_write(&kgnilnd_data.kgn_net_rw_sem);
2677
2678         /* we need a separate thread to call probe_wait_by_id until
2679          * we get a function callback notifier from kgni */
2680         up(&kgnilnd_data.kgn_quiesce_sem);
2681         RETURN(0);
2682  failed:
2683         up(&kgnilnd_data.kgn_quiesce_sem);
2684         kgnilnd_shutdown(ni);
2685         RETURN(rc);
2686 }
2687
2688 void
2689 kgnilnd_shutdown(lnet_ni_t *ni)
2690 {
2691         kgn_net_t     *net = ni->ni_data;
2692         int           i;
2693         int           rc;
2694         ENTRY;
2695
2696         CFS_RACE(CFS_FAIL_GNI_SR_DOWN_RACE);
2697
2698         LASSERTF(kgnilnd_data.kgn_init == GNILND_INIT_ALL,
2699                 "init %d\n", kgnilnd_data.kgn_init);
2700
2701         /* Serialize with startup. */
2702         down(&kgnilnd_data.kgn_quiesce_sem);
2703         CDEBUG(D_MALLOC, "before NAL cleanup: kmem %d\n",
2704                atomic_read(&libcfs_kmemory));
2705
2706         if (net == NULL) {
2707                 CERROR("got NULL net for ni %p\n", ni);
2708                 rc = -EINVAL;
2709                 GOTO(out, rc);
2710         }
2711
2712         LASSERTF(ni == net->gnn_ni,
2713                 "ni %p gnn_ni %p\n", net, net->gnn_ni);
2714
2715         ni->ni_data = NULL;
2716
2717         LASSERT(!net->gnn_shutdown);
2718         LASSERTF(atomic_read(&net->gnn_refcount) != 0,
2719                 "net %p refcount %d\n",
2720                  net, atomic_read(&net->gnn_refcount));
2721
2722         if (!list_empty(&net->gnn_list)) {
2723                 /* serialize with peer creation */
2724                 down_write(&kgnilnd_data.kgn_net_rw_sem);
2725                 net->gnn_shutdown = 1;
2726                 up_write(&kgnilnd_data.kgn_net_rw_sem);
2727
2728                 kgnilnd_cancel_net_dgrams(net);
2729
2730                 kgnilnd_del_conn_or_peer(net, LNET_NID_ANY, GNILND_DEL_PEER, -ESHUTDOWN);
2731
2732                 /* if we are quiesced, need to wake up - we need those threads
2733                  * alive to release peers, etc */
2734                 if (GNILND_IS_QUIESCED) {
2735                         set_mb(kgnilnd_data.kgn_quiesce_trigger, GNILND_QUIESCE_IDLE);
2736                         kgnilnd_quiesce_wait("shutdown");
2737                 }
2738
2739                 kgnilnd_wait_for_canceled_dgrams(net->gnn_dev);
2740
2741                 /* We wait until the nets ref's are 1, we will release final ref which is ours
2742                  * this allows us to make sure everything else is done before we free the
2743                  * net.
2744                  */
2745                 i = 4;
2746                 while (atomic_read(&net->gnn_refcount) != 1) {
2747                         i++;
2748                         CDEBUG(((i & (-i)) == i) ? D_WARNING : D_NET,
2749                                 "Waiting for %d references to clear on net %d\n",
2750                                 atomic_read(&net->gnn_refcount),
2751                                 net->gnn_netnum);
2752                         cfs_pause(cfs_time_seconds(1));
2753                 }
2754
2755                 /* release ref from kgnilnd_startup */
2756                 kgnilnd_net_decref(net);
2757                 /* serialize with reaper and conn_task looping */
2758                 down_write(&kgnilnd_data.kgn_net_rw_sem);
2759                 list_del_init(&net->gnn_list);
2760                 up_write(&kgnilnd_data.kgn_net_rw_sem);
2761
2762         }
2763
2764         /* not locking, this can't race with writers */
2765         LASSERTF(atomic_read(&net->gnn_refcount) == 0,
2766                 "net %p refcount %d\n",
2767                  net, atomic_read(&net->gnn_refcount));
2768         LIBCFS_FREE(net, sizeof(*net));
2769
2770 out:
2771         down_read(&kgnilnd_data.kgn_net_rw_sem);
2772         for (i = 0; i < *kgnilnd_tunables.kgn_net_hash_size; i++) {
2773                 if (!list_empty(&kgnilnd_data.kgn_nets[i])) {
2774                         up_read(&kgnilnd_data.kgn_net_rw_sem);
2775                         break;
2776                 }
2777
2778                 if (i == *kgnilnd_tunables.kgn_net_hash_size - 1) {
2779                         up_read(&kgnilnd_data.kgn_net_rw_sem);
2780                         kgnilnd_base_shutdown();
2781                 }
2782         }
2783         CDEBUG(D_MALLOC, "after NAL cleanup: kmem %d\n",
2784                atomic_read(&libcfs_kmemory));
2785
2786         up(&kgnilnd_data.kgn_quiesce_sem);
2787         EXIT;
2788         return;
2789 }
2790
2791 void __exit
2792 kgnilnd_module_fini(void)
2793 {
2794         lnet_unregister_lnd(&the_kgnilnd);
2795         kgnilnd_proc_fini();
2796         kgnilnd_remove_sysctl();
2797         kgnilnd_tunables_fini();
2798 }
2799
2800 int __init
2801 kgnilnd_module_init(void)
2802 {
2803         int    rc;
2804
2805         rc = kgnilnd_tunables_init();
2806         if (rc != 0)
2807                 return rc;
2808
2809         printk(KERN_INFO "Lustre: kgnilnd build version: "KGNILND_BUILD_REV"\n");
2810
2811         kgnilnd_insert_sysctl();
2812         kgnilnd_proc_init();
2813
2814         lnet_register_lnd(&the_kgnilnd);
2815
2816         return 0;
2817 }
2818
2819 MODULE_AUTHOR("Cray, Inc. <nic@cray.com>");
2820 MODULE_DESCRIPTION("Kernel Gemini LND v"KGNILND_BUILD_REV);
2821 MODULE_LICENSE("GPL");
2822
2823 module_init(kgnilnd_module_init);
2824 module_exit(kgnilnd_module_fini);