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