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