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