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