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