Whamcloud - gitweb
8d318cd0d6aeca3e0a9db168b166326f9d9e16dd
[fs/lustre-release.git] / lnet / lnet / api-ni.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #define DEBUG_SUBSYSTEM S_LNET
34 #include <linux/log2.h>
35 #include <linux/ktime.h>
36
37 #include <lnet/lib-lnet.h>
38
39 #define D_LNI D_CONSOLE
40
41 lnet_t      the_lnet;                           /* THE state of the network */
42 EXPORT_SYMBOL(the_lnet);
43
44 static char *ip2nets = "";
45 module_param(ip2nets, charp, 0444);
46 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
47
48 static char *networks = "";
49 module_param(networks, charp, 0444);
50 MODULE_PARM_DESC(networks, "local networks");
51
52 static char *routes = "";
53 module_param(routes, charp, 0444);
54 MODULE_PARM_DESC(routes, "routes to non-local networks");
55
56 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
57 module_param(rnet_htable_size, int, 0444);
58 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
59
60 static int use_tcp_bonding = false;
61 module_param(use_tcp_bonding, int, 0444);
62 MODULE_PARM_DESC(use_tcp_bonding,
63                  "Set to 1 to use socklnd bonding. 0 to use Multi-Rail");
64
65 static __u32 lnet_numa_range = 0;
66 module_param(lnet_numa_range, int, 0444);
67 MODULE_PARM_DESC(lnet_numa_range,
68                 "NUMA range to consider during Multi-Rail selection");
69
70 /*
71  * This sequence number keeps track of how many times DLC was used to
72  * update the configuration. It is incremented on any DLC update and
73  * checked when sending a message to determine if there is a need to
74  * re-run the selection algorithm to handle configuration change.
75  * Look at lnet_select_pathway() for more details on its usage.
76  */
77 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
78
79 static int lnet_ping(lnet_process_id_t id, signed long timeout,
80                      lnet_process_id_t __user *ids, int n_ids);
81
82 static char *
83 lnet_get_routes(void)
84 {
85         return routes;
86 }
87
88 static char *
89 lnet_get_networks(void)
90 {
91         char   *nets;
92         int     rc;
93
94         if (*networks != 0 && *ip2nets != 0) {
95                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
96                                    "'ip2nets' but not both at once\n");
97                 return NULL;
98         }
99
100         if (*ip2nets != 0) {
101                 rc = lnet_parse_ip2nets(&nets, ip2nets);
102                 return (rc == 0) ? nets : NULL;
103         }
104
105         if (*networks != 0)
106                 return networks;
107
108         return "tcp";
109 }
110
111 static void
112 lnet_init_locks(void)
113 {
114         spin_lock_init(&the_lnet.ln_eq_wait_lock);
115         init_waitqueue_head(&the_lnet.ln_eq_waitq);
116         init_waitqueue_head(&the_lnet.ln_rc_waitq);
117         mutex_init(&the_lnet.ln_lnd_mutex);
118         mutex_init(&the_lnet.ln_api_mutex);
119 }
120
121 static void
122 lnet_fini_locks(void)
123 {
124 }
125
126 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
127 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
128                                             *  MDs kmem_cache */
129
130 static int
131 lnet_descriptor_setup(void)
132 {
133         /* create specific kmem_cache for MEs and small MDs (i.e., originally
134          * allocated in <size-xxx> kmem_cache).
135          */
136         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(lnet_me_t),
137                                             0, 0, NULL);
138         if (!lnet_mes_cachep)
139                 return -ENOMEM;
140
141         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
142                                                   LNET_SMALL_MD_SIZE, 0, 0,
143                                                   NULL);
144         if (!lnet_small_mds_cachep)
145                 return -ENOMEM;
146
147         return 0;
148 }
149
150 static void
151 lnet_descriptor_cleanup(void)
152 {
153
154         if (lnet_small_mds_cachep) {
155                 kmem_cache_destroy(lnet_small_mds_cachep);
156                 lnet_small_mds_cachep = NULL;
157         }
158
159         if (lnet_mes_cachep) {
160                 kmem_cache_destroy(lnet_mes_cachep);
161                 lnet_mes_cachep = NULL;
162         }
163 }
164
165 static int
166 lnet_create_remote_nets_table(void)
167 {
168         int               i;
169         struct list_head *hash;
170
171         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
172         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
173         LIBCFS_ALLOC(hash, LNET_REMOTE_NETS_HASH_SIZE * sizeof(*hash));
174         if (hash == NULL) {
175                 CERROR("Failed to create remote nets hash table\n");
176                 return -ENOMEM;
177         }
178
179         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
180                 INIT_LIST_HEAD(&hash[i]);
181         the_lnet.ln_remote_nets_hash = hash;
182         return 0;
183 }
184
185 static void
186 lnet_destroy_remote_nets_table(void)
187 {
188         int i;
189
190         if (the_lnet.ln_remote_nets_hash == NULL)
191                 return;
192
193         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
194                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
195
196         LIBCFS_FREE(the_lnet.ln_remote_nets_hash,
197                     LNET_REMOTE_NETS_HASH_SIZE *
198                     sizeof(the_lnet.ln_remote_nets_hash[0]));
199         the_lnet.ln_remote_nets_hash = NULL;
200 }
201
202 static void
203 lnet_destroy_locks(void)
204 {
205         if (the_lnet.ln_res_lock != NULL) {
206                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
207                 the_lnet.ln_res_lock = NULL;
208         }
209
210         if (the_lnet.ln_net_lock != NULL) {
211                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
212                 the_lnet.ln_net_lock = NULL;
213         }
214
215         lnet_fini_locks();
216 }
217
218 static int
219 lnet_create_locks(void)
220 {
221         lnet_init_locks();
222
223         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
224         if (the_lnet.ln_res_lock == NULL)
225                 goto failed;
226
227         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
228         if (the_lnet.ln_net_lock == NULL)
229                 goto failed;
230
231         return 0;
232
233  failed:
234         lnet_destroy_locks();
235         return -ENOMEM;
236 }
237
238 static void lnet_assert_wire_constants(void)
239 {
240         /* Wire protocol assertions generated by 'wirecheck'
241          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
242          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
243          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
244
245         /* Constants... */
246         CLASSERT(LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
247         CLASSERT(LNET_PROTO_TCP_VERSION_MAJOR == 1);
248         CLASSERT(LNET_PROTO_TCP_VERSION_MINOR == 0);
249         CLASSERT(LNET_MSG_ACK == 0);
250         CLASSERT(LNET_MSG_PUT == 1);
251         CLASSERT(LNET_MSG_GET == 2);
252         CLASSERT(LNET_MSG_REPLY == 3);
253         CLASSERT(LNET_MSG_HELLO == 4);
254
255         /* Checks for struct lnet_handle_wire */
256         CLASSERT((int)sizeof(struct lnet_handle_wire) == 16);
257         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_interface_cookie) == 0);
258         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) == 8);
259         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_object_cookie) == 8);
260         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) == 8);
261
262         /* Checks for struct lnet_magicversion_t */
263         CLASSERT((int)sizeof(lnet_magicversion_t) == 8);
264         CLASSERT((int)offsetof(lnet_magicversion_t, magic) == 0);
265         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->magic) == 4);
266         CLASSERT((int)offsetof(lnet_magicversion_t, version_major) == 4);
267         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->version_major) == 2);
268         CLASSERT((int)offsetof(lnet_magicversion_t, version_minor) == 6);
269         CLASSERT((int)sizeof(((lnet_magicversion_t *)0)->version_minor) == 2);
270
271         /* Checks for struct lnet_hdr_t */
272         CLASSERT((int)sizeof(lnet_hdr_t) == 72);
273         CLASSERT((int)offsetof(lnet_hdr_t, dest_nid) == 0);
274         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->dest_nid) == 8);
275         CLASSERT((int)offsetof(lnet_hdr_t, src_nid) == 8);
276         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->src_nid) == 8);
277         CLASSERT((int)offsetof(lnet_hdr_t, dest_pid) == 16);
278         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->dest_pid) == 4);
279         CLASSERT((int)offsetof(lnet_hdr_t, src_pid) == 20);
280         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->src_pid) == 4);
281         CLASSERT((int)offsetof(lnet_hdr_t, type) == 24);
282         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->type) == 4);
283         CLASSERT((int)offsetof(lnet_hdr_t, payload_length) == 28);
284         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->payload_length) == 4);
285         CLASSERT((int)offsetof(lnet_hdr_t, msg) == 32);
286         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg) == 40);
287
288         /* Ack */
289         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.dst_wmd) == 32);
290         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.dst_wmd) == 16);
291         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.match_bits) == 48);
292         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.match_bits) == 8);
293         CLASSERT((int)offsetof(lnet_hdr_t, msg.ack.mlength) == 56);
294         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.ack.mlength) == 4);
295
296         /* Put */
297         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.ack_wmd) == 32);
298         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.ack_wmd) == 16);
299         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.match_bits) == 48);
300         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.match_bits) == 8);
301         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.hdr_data) == 56);
302         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.hdr_data) == 8);
303         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.ptl_index) == 64);
304         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.ptl_index) == 4);
305         CLASSERT((int)offsetof(lnet_hdr_t, msg.put.offset) == 68);
306         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.put.offset) == 4);
307
308         /* Get */
309         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.return_wmd) == 32);
310         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.return_wmd) == 16);
311         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.match_bits) == 48);
312         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.match_bits) == 8);
313         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.ptl_index) == 56);
314         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.ptl_index) == 4);
315         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.src_offset) == 60);
316         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.src_offset) == 4);
317         CLASSERT((int)offsetof(lnet_hdr_t, msg.get.sink_length) == 64);
318         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.get.sink_length) == 4);
319
320         /* Reply */
321         CLASSERT((int)offsetof(lnet_hdr_t, msg.reply.dst_wmd) == 32);
322         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.reply.dst_wmd) == 16);
323
324         /* Hello */
325         CLASSERT((int)offsetof(lnet_hdr_t, msg.hello.incarnation) == 32);
326         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.hello.incarnation) == 8);
327         CLASSERT((int)offsetof(lnet_hdr_t, msg.hello.type) == 40);
328         CLASSERT((int)sizeof(((lnet_hdr_t *)0)->msg.hello.type) == 4);
329 }
330
331 static lnd_t *lnet_find_lnd_by_type(__u32 type)
332 {
333         lnd_t            *lnd;
334         struct list_head *tmp;
335
336         /* holding lnd mutex */
337         list_for_each(tmp, &the_lnet.ln_lnds) {
338                 lnd = list_entry(tmp, lnd_t, lnd_list);
339
340                 if (lnd->lnd_type == type)
341                         return lnd;
342         }
343         return NULL;
344 }
345
346 void
347 lnet_register_lnd (lnd_t *lnd)
348 {
349         mutex_lock(&the_lnet.ln_lnd_mutex);
350
351         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
352         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
353
354         list_add_tail(&lnd->lnd_list, &the_lnet.ln_lnds);
355         lnd->lnd_refcount = 0;
356
357         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
358
359         mutex_unlock(&the_lnet.ln_lnd_mutex);
360 }
361 EXPORT_SYMBOL(lnet_register_lnd);
362
363 void
364 lnet_unregister_lnd (lnd_t *lnd)
365 {
366         mutex_lock(&the_lnet.ln_lnd_mutex);
367
368         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
369         LASSERT(lnd->lnd_refcount == 0);
370
371         list_del(&lnd->lnd_list);
372         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
373
374         mutex_unlock(&the_lnet.ln_lnd_mutex);
375 }
376 EXPORT_SYMBOL(lnet_unregister_lnd);
377
378 void
379 lnet_counters_get(lnet_counters_t *counters)
380 {
381         lnet_counters_t *ctr;
382         int             i;
383
384         memset(counters, 0, sizeof(*counters));
385
386         lnet_net_lock(LNET_LOCK_EX);
387
388         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
389                 counters->msgs_max     += ctr->msgs_max;
390                 counters->msgs_alloc   += ctr->msgs_alloc;
391                 counters->errors       += ctr->errors;
392                 counters->send_count   += ctr->send_count;
393                 counters->recv_count   += ctr->recv_count;
394                 counters->route_count  += ctr->route_count;
395                 counters->drop_count   += ctr->drop_count;
396                 counters->send_length  += ctr->send_length;
397                 counters->recv_length  += ctr->recv_length;
398                 counters->route_length += ctr->route_length;
399                 counters->drop_length  += ctr->drop_length;
400
401         }
402         lnet_net_unlock(LNET_LOCK_EX);
403 }
404 EXPORT_SYMBOL(lnet_counters_get);
405
406 void
407 lnet_counters_reset(void)
408 {
409         lnet_counters_t *counters;
410         int             i;
411
412         lnet_net_lock(LNET_LOCK_EX);
413
414         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
415                 memset(counters, 0, sizeof(lnet_counters_t));
416
417         lnet_net_unlock(LNET_LOCK_EX);
418 }
419
420 static char *
421 lnet_res_type2str(int type)
422 {
423         switch (type) {
424         default:
425                 LBUG();
426         case LNET_COOKIE_TYPE_MD:
427                 return "MD";
428         case LNET_COOKIE_TYPE_ME:
429                 return "ME";
430         case LNET_COOKIE_TYPE_EQ:
431                 return "EQ";
432         }
433 }
434
435 static void
436 lnet_res_container_cleanup(struct lnet_res_container *rec)
437 {
438         int     count = 0;
439
440         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
441                 return;
442
443         while (!list_empty(&rec->rec_active)) {
444                 struct list_head *e = rec->rec_active.next;
445
446                 list_del_init(e);
447                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
448                         lnet_eq_free(list_entry(e, lnet_eq_t, eq_list));
449
450                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
451                         lnet_md_free(list_entry(e, lnet_libmd_t, md_list));
452
453                 } else { /* NB: Active MEs should be attached on portals */
454                         LBUG();
455                 }
456                 count++;
457         }
458
459         if (count > 0) {
460                 /* Found alive MD/ME/EQ, user really should unlink/free
461                  * all of them before finalize LNet, but if someone didn't,
462                  * we have to recycle garbage for him */
463                 CERROR("%d active elements on exit of %s container\n",
464                        count, lnet_res_type2str(rec->rec_type));
465         }
466
467         if (rec->rec_lh_hash != NULL) {
468                 LIBCFS_FREE(rec->rec_lh_hash,
469                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
470                 rec->rec_lh_hash = NULL;
471         }
472
473         rec->rec_type = 0; /* mark it as finalized */
474 }
475
476 static int
477 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
478 {
479         int     rc = 0;
480         int     i;
481
482         LASSERT(rec->rec_type == 0);
483
484         rec->rec_type = type;
485         INIT_LIST_HEAD(&rec->rec_active);
486
487         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
488
489         /* Arbitrary choice of hash table size */
490         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
491                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
492         if (rec->rec_lh_hash == NULL) {
493                 rc = -ENOMEM;
494                 goto out;
495         }
496
497         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
498                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
499
500         return 0;
501
502 out:
503         CERROR("Failed to setup %s resource container\n",
504                lnet_res_type2str(type));
505         lnet_res_container_cleanup(rec);
506         return rc;
507 }
508
509 static void
510 lnet_res_containers_destroy(struct lnet_res_container **recs)
511 {
512         struct lnet_res_container       *rec;
513         int                             i;
514
515         cfs_percpt_for_each(rec, i, recs)
516                 lnet_res_container_cleanup(rec);
517
518         cfs_percpt_free(recs);
519 }
520
521 static struct lnet_res_container **
522 lnet_res_containers_create(int type)
523 {
524         struct lnet_res_container       **recs;
525         struct lnet_res_container       *rec;
526         int                             rc;
527         int                             i;
528
529         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
530         if (recs == NULL) {
531                 CERROR("Failed to allocate %s resource containers\n",
532                        lnet_res_type2str(type));
533                 return NULL;
534         }
535
536         cfs_percpt_for_each(rec, i, recs) {
537                 rc = lnet_res_container_setup(rec, i, type);
538                 if (rc != 0) {
539                         lnet_res_containers_destroy(recs);
540                         return NULL;
541                 }
542         }
543
544         return recs;
545 }
546
547 lnet_libhandle_t *
548 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
549 {
550         /* ALWAYS called with lnet_res_lock held */
551         struct list_head        *head;
552         lnet_libhandle_t        *lh;
553         unsigned int            hash;
554
555         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
556                 return NULL;
557
558         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
559         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
560
561         list_for_each_entry(lh, head, lh_hash_chain) {
562                 if (lh->lh_cookie == cookie)
563                         return lh;
564         }
565
566         return NULL;
567 }
568
569 void
570 lnet_res_lh_initialize(struct lnet_res_container *rec, lnet_libhandle_t *lh)
571 {
572         /* ALWAYS called with lnet_res_lock held */
573         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
574         unsigned int    hash;
575
576         lh->lh_cookie = rec->rec_lh_cookie;
577         rec->rec_lh_cookie += 1 << ibits;
578
579         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
580
581         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
582 }
583
584 static int lnet_unprepare(void);
585
586 static int
587 lnet_prepare(lnet_pid_t requested_pid)
588 {
589         /* Prepare to bring up the network */
590         struct lnet_res_container **recs;
591         int                       rc = 0;
592
593         if (requested_pid == LNET_PID_ANY) {
594                 /* Don't instantiate LNET just for me */
595                 return -ENETDOWN;
596         }
597
598         LASSERT(the_lnet.ln_refcount == 0);
599
600         the_lnet.ln_routing = 0;
601
602         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
603         the_lnet.ln_pid = requested_pid;
604
605         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
606         INIT_LIST_HEAD(&the_lnet.ln_peers);
607         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
608         INIT_LIST_HEAD(&the_lnet.ln_nets);
609         INIT_LIST_HEAD(&the_lnet.ln_routers);
610         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
611         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
612
613         rc = lnet_descriptor_setup();
614         if (rc != 0)
615                 goto failed;
616
617         rc = lnet_create_remote_nets_table();
618         if (rc != 0)
619                 goto failed;
620
621         /*
622          * NB the interface cookie in wire handles guards against delayed
623          * replies and ACKs appearing valid after reboot.
624          */
625         the_lnet.ln_interface_cookie = ktime_get_real_ns();
626
627         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
628                                                 sizeof(lnet_counters_t));
629         if (the_lnet.ln_counters == NULL) {
630                 CERROR("Failed to allocate counters for LNet\n");
631                 rc = -ENOMEM;
632                 goto failed;
633         }
634
635         rc = lnet_peer_tables_create();
636         if (rc != 0)
637                 goto failed;
638
639         rc = lnet_msg_containers_create();
640         if (rc != 0)
641                 goto failed;
642
643         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
644                                       LNET_COOKIE_TYPE_EQ);
645         if (rc != 0)
646                 goto failed;
647
648         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
649         if (recs == NULL) {
650                 rc = -ENOMEM;
651                 goto failed;
652         }
653
654         the_lnet.ln_me_containers = recs;
655
656         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
657         if (recs == NULL) {
658                 rc = -ENOMEM;
659                 goto failed;
660         }
661
662         the_lnet.ln_md_containers = recs;
663
664         rc = lnet_portals_create();
665         if (rc != 0) {
666                 CERROR("Failed to create portals for LNet: %d\n", rc);
667                 goto failed;
668         }
669
670         return 0;
671
672  failed:
673         lnet_unprepare();
674         return rc;
675 }
676
677 static int
678 lnet_unprepare (void)
679 {
680         /* NB no LNET_LOCK since this is the last reference.  All LND instances
681          * have shut down already, so it is safe to unlink and free all
682          * descriptors, even those that appear committed to a network op (eg MD
683          * with non-zero pending count) */
684
685         lnet_fail_nid(LNET_NID_ANY, 0);
686
687         LASSERT(the_lnet.ln_refcount == 0);
688         LASSERT(list_empty(&the_lnet.ln_test_peers));
689         LASSERT(list_empty(&the_lnet.ln_nets));
690
691         lnet_portals_destroy();
692
693         if (the_lnet.ln_md_containers != NULL) {
694                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
695                 the_lnet.ln_md_containers = NULL;
696         }
697
698         if (the_lnet.ln_me_containers != NULL) {
699                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
700                 the_lnet.ln_me_containers = NULL;
701         }
702
703         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
704
705         lnet_msg_containers_destroy();
706         lnet_peer_uninit();
707         lnet_rtrpools_free(0);
708
709         if (the_lnet.ln_counters != NULL) {
710                 cfs_percpt_free(the_lnet.ln_counters);
711                 the_lnet.ln_counters = NULL;
712         }
713         lnet_destroy_remote_nets_table();
714         lnet_descriptor_cleanup();
715
716         return 0;
717 }
718
719 lnet_ni_t  *
720 lnet_net2ni_locked(__u32 net_id, int cpt)
721 {
722         struct lnet_ni   *ni;
723         struct lnet_net  *net;
724
725         LASSERT(cpt != LNET_LOCK_EX);
726
727         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
728                 if (net->net_id == net_id) {
729                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
730                                         ni_netlist);
731                         return ni;
732                 }
733         }
734
735         return NULL;
736 }
737
738 lnet_ni_t *
739 lnet_net2ni_addref(__u32 net)
740 {
741         lnet_ni_t *ni;
742
743         lnet_net_lock(0);
744         ni = lnet_net2ni_locked(net, 0);
745         if (ni)
746                 lnet_ni_addref_locked(ni, 0);
747         lnet_net_unlock(0);
748
749         return ni;
750 }
751 EXPORT_SYMBOL(lnet_net2ni_addref);
752
753 struct lnet_net *
754 lnet_get_net_locked(__u32 net_id)
755 {
756         struct lnet_net  *net;
757
758         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
759                 if (net->net_id == net_id)
760                         return net;
761         }
762
763         return NULL;
764 }
765
766 unsigned int
767 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
768 {
769         __u64           key = nid;
770         unsigned int    val;
771
772         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
773
774         if (number == 1)
775                 return 0;
776
777         val = hash_long(key, LNET_CPT_BITS);
778         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
779         if (val < number)
780                 return val;
781
782         return (unsigned int)(key + val + (val >> 1)) % number;
783 }
784
785 int
786 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
787 {
788         struct lnet_net *net;
789
790         /* must called with hold of lnet_net_lock */
791         if (LNET_CPT_NUMBER == 1)
792                 return 0; /* the only one */
793
794         /*
795          * If NI is provided then use the CPT identified in the NI cpt
796          * list if one exists. If one doesn't exist, then that NI is
797          * associated with all CPTs and it follows that the net it belongs
798          * to is implicitly associated with all CPTs, so just hash the nid
799          * and return that.
800          */
801         if (ni != NULL) {
802                 if (ni->ni_cpts != NULL)
803                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
804                                                              ni->ni_ncpts)];
805                 else
806                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
807         }
808
809         /* no NI provided so look at the net */
810         net = lnet_get_net_locked(LNET_NIDNET(nid));
811
812         if (net != NULL && net->net_cpts != NULL) {
813                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
814         }
815
816         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
817 }
818
819 int
820 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
821 {
822         int     cpt;
823         int     cpt2;
824
825         if (LNET_CPT_NUMBER == 1)
826                 return 0; /* the only one */
827
828         cpt = lnet_net_lock_current();
829
830         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
831
832         lnet_net_unlock(cpt);
833
834         return cpt2;
835 }
836 EXPORT_SYMBOL(lnet_cpt_of_nid);
837
838 int
839 lnet_islocalnet(__u32 net_id)
840 {
841         struct lnet_net *net;
842         int             cpt;
843         bool            local;
844
845         cpt = lnet_net_lock_current();
846
847         net = lnet_get_net_locked(net_id);
848
849         local = net != NULL;
850
851         lnet_net_unlock(cpt);
852
853         return local;
854 }
855
856 bool
857 lnet_is_ni_healthy_locked(struct lnet_ni *ni)
858 {
859         if (ni->ni_state == LNET_NI_STATE_ACTIVE ||
860             ni->ni_state == LNET_NI_STATE_DEGRADED)
861                 return true;
862
863         return false;
864 }
865
866 lnet_ni_t  *
867 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
868 {
869         struct lnet_net  *net;
870         struct lnet_ni   *ni;
871
872         LASSERT(cpt != LNET_LOCK_EX);
873
874         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
875                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
876                         if (ni->ni_nid == nid)
877                                 return ni;
878                 }
879         }
880
881         return NULL;
882 }
883
884 lnet_ni_t *
885 lnet_nid2ni_addref(lnet_nid_t nid)
886 {
887         lnet_ni_t *ni;
888
889         lnet_net_lock(0);
890         ni = lnet_nid2ni_locked(nid, 0);
891         if (ni)
892                 lnet_ni_addref_locked(ni, 0);
893         lnet_net_unlock(0);
894
895         return ni;
896 }
897 EXPORT_SYMBOL(lnet_nid2ni_addref);
898
899 int
900 lnet_islocalnid(lnet_nid_t nid)
901 {
902         struct lnet_ni  *ni;
903         int             cpt;
904
905         cpt = lnet_net_lock_current();
906         ni = lnet_nid2ni_locked(nid, cpt);
907         lnet_net_unlock(cpt);
908
909         return ni != NULL;
910 }
911
912 int
913 lnet_count_acceptor_nets(void)
914 {
915         /* Return the # of NIs that need the acceptor. */
916         int              count = 0;
917         struct lnet_net  *net;
918         int              cpt;
919
920         cpt = lnet_net_lock_current();
921         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
922                 /* all socklnd type networks should have the acceptor
923                  * thread started */
924                 if (net->net_lnd->lnd_accept != NULL)
925                         count++;
926         }
927
928         lnet_net_unlock(cpt);
929
930         return count;
931 }
932
933 static struct lnet_ping_info *
934 lnet_ping_info_create(int num_ni)
935 {
936         struct lnet_ping_info *ping_info;
937         unsigned int     infosz;
938
939         infosz = offsetof(struct lnet_ping_info, pi_ni[num_ni]);
940         LIBCFS_ALLOC(ping_info, infosz);
941         if (ping_info == NULL) {
942                 CERROR("Can't allocate ping info[%d]\n", num_ni);
943                 return NULL;
944         }
945
946         ping_info->pi_nnis = num_ni;
947         ping_info->pi_pid = the_lnet.ln_pid;
948         ping_info->pi_magic = LNET_PROTO_PING_MAGIC;
949         ping_info->pi_features = LNET_PING_FEAT_NI_STATUS;
950
951         return ping_info;
952 }
953
954 static inline int
955 lnet_get_net_ni_count_locked(struct lnet_net *net)
956 {
957         struct lnet_ni  *ni;
958         int             count = 0;
959
960         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
961                 count++;
962
963         return count;
964 }
965
966 static inline int
967 lnet_get_net_ni_count_pre(struct lnet_net *net)
968 {
969         struct lnet_ni  *ni;
970         int             count = 0;
971
972         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
973                 count++;
974
975         return count;
976 }
977
978 static inline int
979 lnet_get_ni_count(void)
980 {
981         struct lnet_ni  *ni;
982         struct lnet_net *net;
983         int             count = 0;
984
985         lnet_net_lock(0);
986
987         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
988                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
989                         count++;
990         }
991
992         lnet_net_unlock(0);
993
994         return count;
995 }
996
997 static inline void
998 lnet_ping_info_free(struct lnet_ping_info *pinfo)
999 {
1000         LIBCFS_FREE(pinfo,
1001                     offsetof(struct lnet_ping_info,
1002                              pi_ni[pinfo->pi_nnis]));
1003 }
1004
1005 static void
1006 lnet_ping_info_destroy(void)
1007 {
1008         struct lnet_net *net;
1009         struct lnet_ni  *ni;
1010
1011         lnet_net_lock(LNET_LOCK_EX);
1012
1013         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1014                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1015                         lnet_ni_lock(ni);
1016                         ni->ni_status = NULL;
1017                         lnet_ni_unlock(ni);
1018                 }
1019         }
1020
1021         lnet_ping_info_free(the_lnet.ln_ping_info);
1022         the_lnet.ln_ping_info = NULL;
1023
1024         lnet_net_unlock(LNET_LOCK_EX);
1025 }
1026
1027 static void
1028 lnet_ping_event_handler(lnet_event_t *event)
1029 {
1030         struct lnet_ping_info *pinfo = event->md.user_ptr;
1031
1032         if (event->unlinked)
1033                 pinfo->pi_features = LNET_PING_FEAT_INVAL;
1034 }
1035
1036 static int
1037 lnet_ping_info_setup(struct lnet_ping_info **ppinfo, lnet_handle_md_t *md_handle,
1038                      int ni_count, bool set_eq)
1039 {
1040         lnet_handle_me_t  me_handle;
1041         lnet_process_id_t id = {LNET_NID_ANY, LNET_PID_ANY};
1042         lnet_md_t         md = {NULL};
1043         int               rc, rc2;
1044
1045         if (set_eq) {
1046                 rc = LNetEQAlloc(0, lnet_ping_event_handler,
1047                                  &the_lnet.ln_ping_target_eq);
1048                 if (rc != 0) {
1049                         CERROR("Can't allocate ping EQ: %d\n", rc);
1050                         return rc;
1051                 }
1052         }
1053
1054         *ppinfo = lnet_ping_info_create(ni_count);
1055         if (*ppinfo == NULL) {
1056                 rc = -ENOMEM;
1057                 goto failed_0;
1058         }
1059
1060         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1061                           LNET_PROTO_PING_MATCHBITS, 0,
1062                           LNET_UNLINK, LNET_INS_AFTER,
1063                           &me_handle);
1064         if (rc != 0) {
1065                 CERROR("Can't create ping ME: %d\n", rc);
1066                 goto failed_1;
1067         }
1068
1069         /* initialize md content */
1070         md.start     = *ppinfo;
1071         md.length    = offsetof(struct lnet_ping_info,
1072                                 pi_ni[(*ppinfo)->pi_nnis]);
1073         md.threshold = LNET_MD_THRESH_INF;
1074         md.max_size  = 0;
1075         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1076                        LNET_MD_MANAGE_REMOTE;
1077         md.user_ptr  = NULL;
1078         md.eq_handle = the_lnet.ln_ping_target_eq;
1079         md.user_ptr = *ppinfo;
1080
1081         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, md_handle);
1082         if (rc != 0) {
1083                 CERROR("Can't attach ping MD: %d\n", rc);
1084                 goto failed_2;
1085         }
1086
1087         return 0;
1088
1089 failed_2:
1090         rc2 = LNetMEUnlink(me_handle);
1091         LASSERT(rc2 == 0);
1092 failed_1:
1093         lnet_ping_info_free(*ppinfo);
1094         *ppinfo = NULL;
1095 failed_0:
1096         if (set_eq)
1097                 LNetEQFree(the_lnet.ln_ping_target_eq);
1098         return rc;
1099 }
1100
1101 static void
1102 lnet_ping_md_unlink(struct lnet_ping_info *pinfo, lnet_handle_md_t *md_handle)
1103 {
1104         sigset_t        blocked = cfs_block_allsigs();
1105
1106         LNetMDUnlink(*md_handle);
1107         LNetInvalidateHandle(md_handle);
1108
1109         /* NB md could be busy; this just starts the unlink */
1110         while (pinfo->pi_features != LNET_PING_FEAT_INVAL) {
1111                 CDEBUG(D_NET, "Still waiting for ping MD to unlink\n");
1112                 set_current_state(TASK_UNINTERRUPTIBLE);
1113                 schedule_timeout(cfs_time_seconds(1));
1114         }
1115
1116         cfs_restore_sigs(blocked);
1117 }
1118
1119 static void
1120 lnet_ping_info_install_locked(struct lnet_ping_info *ping_info)
1121 {
1122         int                     i;
1123         struct lnet_ni          *ni;
1124         struct lnet_net         *net;
1125         struct lnet_ni_status *ns;
1126
1127         i = 0;
1128         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1129                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1130                         LASSERT(i < ping_info->pi_nnis);
1131
1132                         ns = &ping_info->pi_ni[i];
1133
1134                         ns->ns_nid = ni->ni_nid;
1135
1136                         lnet_ni_lock(ni);
1137                         ns->ns_status = (ni->ni_status != NULL) ?
1138                                         ni->ni_status->ns_status :
1139                                                 LNET_NI_STATUS_UP;
1140                         ni->ni_status = ns;
1141                         lnet_ni_unlock(ni);
1142
1143                         i++;
1144                 }
1145
1146         }
1147 }
1148
1149 static void
1150 lnet_ping_target_update(struct lnet_ping_info *pinfo, lnet_handle_md_t md_handle)
1151 {
1152         struct lnet_ping_info *old_pinfo = NULL;
1153         lnet_handle_md_t old_md;
1154
1155         /* switch the NIs to point to the new ping info created */
1156         lnet_net_lock(LNET_LOCK_EX);
1157
1158         if (!the_lnet.ln_routing)
1159                 pinfo->pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1160         lnet_ping_info_install_locked(pinfo);
1161
1162         if (the_lnet.ln_ping_info != NULL) {
1163                 old_pinfo = the_lnet.ln_ping_info;
1164                 old_md = the_lnet.ln_ping_target_md;
1165         }
1166         the_lnet.ln_ping_target_md = md_handle;
1167         the_lnet.ln_ping_info = pinfo;
1168
1169         lnet_net_unlock(LNET_LOCK_EX);
1170
1171         if (old_pinfo != NULL) {
1172                 /* unlink the old ping info */
1173                 lnet_ping_md_unlink(old_pinfo, &old_md);
1174                 lnet_ping_info_free(old_pinfo);
1175         }
1176 }
1177
1178 static void
1179 lnet_ping_target_fini(void)
1180 {
1181         int             rc;
1182
1183         lnet_ping_md_unlink(the_lnet.ln_ping_info,
1184                             &the_lnet.ln_ping_target_md);
1185
1186         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1187         LASSERT(rc == 0);
1188
1189         lnet_ping_info_destroy();
1190 }
1191
1192 static int
1193 lnet_ni_tq_credits(lnet_ni_t *ni)
1194 {
1195         int     credits;
1196
1197         LASSERT(ni->ni_ncpts >= 1);
1198
1199         if (ni->ni_ncpts == 1)
1200                 return ni->ni_net->net_tunables.lct_max_tx_credits;
1201
1202         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
1203         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
1204         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
1205
1206         return credits;
1207 }
1208
1209 static void
1210 lnet_ni_unlink_locked(lnet_ni_t *ni)
1211 {
1212         if (!list_empty(&ni->ni_cptlist)) {
1213                 list_del_init(&ni->ni_cptlist);
1214                 lnet_ni_decref_locked(ni, 0);
1215         }
1216
1217         /* move it to zombie list and nobody can find it anymore */
1218         LASSERT(!list_empty(&ni->ni_netlist));
1219         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
1220         lnet_ni_decref_locked(ni, 0);
1221 }
1222
1223 static void
1224 lnet_clear_zombies_nis_locked(struct lnet_net *net)
1225 {
1226         int             i;
1227         int             islo;
1228         lnet_ni_t       *ni;
1229         struct list_head *zombie_list = &net->net_ni_zombie;
1230
1231         /*
1232          * Now wait for the NIs I just nuked to show up on the zombie
1233          * list and shut them down in guaranteed thread context
1234          */
1235         i = 2;
1236         while (!list_empty(zombie_list)) {
1237                 int     *ref;
1238                 int     j;
1239
1240                 ni = list_entry(zombie_list->next,
1241                                 lnet_ni_t, ni_netlist);
1242                 list_del_init(&ni->ni_netlist);
1243                 /* the ni should be in deleting state. If it's not it's
1244                  * a bug */
1245                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
1246                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1247                         if (*ref == 0)
1248                                 continue;
1249                         /* still busy, add it back to zombie list */
1250                         list_add(&ni->ni_netlist, zombie_list);
1251                         break;
1252                 }
1253
1254                 if (!list_empty(&ni->ni_netlist)) {
1255                         lnet_net_unlock(LNET_LOCK_EX);
1256                         ++i;
1257                         if ((i & (-i)) == i) {
1258                                 CDEBUG(D_WARNING,
1259                                        "Waiting for zombie LNI %s\n",
1260                                        libcfs_nid2str(ni->ni_nid));
1261                         }
1262                         set_current_state(TASK_UNINTERRUPTIBLE);
1263                         schedule_timeout(cfs_time_seconds(1));
1264                         lnet_net_lock(LNET_LOCK_EX);
1265                         continue;
1266                 }
1267
1268                 lnet_net_unlock(LNET_LOCK_EX);
1269
1270                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
1271
1272                 LASSERT(!in_interrupt());
1273                 (net->net_lnd->lnd_shutdown)(ni);
1274
1275                 if (!islo)
1276                         CDEBUG(D_LNI, "Removed LNI %s\n",
1277                               libcfs_nid2str(ni->ni_nid));
1278
1279                 lnet_ni_free(ni);
1280                 i = 2;
1281                 lnet_net_lock(LNET_LOCK_EX);
1282         }
1283 }
1284
1285 /* shutdown down the NI and release refcount */
1286 static void
1287 lnet_shutdown_lndni(struct lnet_ni *ni)
1288 {
1289         int i;
1290         struct lnet_net *net = ni->ni_net;
1291
1292         lnet_net_lock(LNET_LOCK_EX);
1293         ni->ni_state = LNET_NI_STATE_DELETING;
1294         lnet_ni_unlink_locked(ni);
1295         lnet_net_unlock(LNET_LOCK_EX);
1296
1297         /* clear messages for this NI on the lazy portal */
1298         for (i = 0; i < the_lnet.ln_nportals; i++)
1299                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
1300
1301         lnet_net_lock(LNET_LOCK_EX);
1302         lnet_clear_zombies_nis_locked(net);
1303         lnet_net_unlock(LNET_LOCK_EX);
1304 }
1305
1306 static void
1307 lnet_shutdown_lndnet(struct lnet_net *net)
1308 {
1309         struct lnet_ni *ni;
1310
1311         lnet_net_lock(LNET_LOCK_EX);
1312
1313         net->net_state = LNET_NET_STATE_DELETING;
1314
1315         list_del_init(&net->net_list);
1316
1317         while (!list_empty(&net->net_ni_list)) {
1318                 ni = list_entry(net->net_ni_list.next,
1319                                 lnet_ni_t, ni_netlist);
1320                 lnet_net_unlock(LNET_LOCK_EX);
1321                 lnet_shutdown_lndni(ni);
1322                 lnet_net_lock(LNET_LOCK_EX);
1323         }
1324
1325         lnet_net_unlock(LNET_LOCK_EX);
1326
1327         /* Do peer table cleanup for this net */
1328         lnet_peer_tables_cleanup(net);
1329
1330         lnet_net_lock(LNET_LOCK_EX);
1331         /*
1332          * decrement ref count on lnd only when the entire network goes
1333          * away
1334          */
1335         net->net_lnd->lnd_refcount--;
1336
1337         lnet_net_unlock(LNET_LOCK_EX);
1338
1339         lnet_net_free(net);
1340 }
1341
1342 static void
1343 lnet_shutdown_lndnets(void)
1344 {
1345         struct lnet_net *net;
1346
1347         /* NB called holding the global mutex */
1348
1349         /* All quiet on the API front */
1350         LASSERT(!the_lnet.ln_shutdown);
1351         LASSERT(the_lnet.ln_refcount == 0);
1352
1353         lnet_net_lock(LNET_LOCK_EX);
1354         the_lnet.ln_shutdown = 1;       /* flag shutdown */
1355
1356         while (!list_empty(&the_lnet.ln_nets)) {
1357                 /*
1358                  * move the nets to the zombie list to avoid them being
1359                  * picked up for new work. LONET is also included in the
1360                  * Nets that will be moved to the zombie list
1361                  */
1362                 net = list_entry(the_lnet.ln_nets.next,
1363                                  struct lnet_net, net_list);
1364                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
1365         }
1366
1367         /* Drop the cached loopback Net. */
1368         if (the_lnet.ln_loni != NULL) {
1369                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
1370                 the_lnet.ln_loni = NULL;
1371         }
1372         lnet_net_unlock(LNET_LOCK_EX);
1373
1374         /* iterate through the net zombie list and delete each net */
1375         while (!list_empty(&the_lnet.ln_net_zombie)) {
1376                 net = list_entry(the_lnet.ln_net_zombie.next,
1377                                  struct lnet_net, net_list);
1378                 lnet_shutdown_lndnet(net);
1379         }
1380
1381         lnet_net_lock(LNET_LOCK_EX);
1382         the_lnet.ln_shutdown = 0;
1383         lnet_net_unlock(LNET_LOCK_EX);
1384 }
1385
1386 static int
1387 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
1388 {
1389         int                     rc = -EINVAL;
1390         struct lnet_tx_queue    *tq;
1391         int                     i;
1392         struct lnet_net         *net = ni->ni_net;
1393
1394         mutex_lock(&the_lnet.ln_lnd_mutex);
1395
1396         if (tun) {
1397                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
1398                 ni->ni_lnd_tunables_set = true;
1399         }
1400
1401         rc = (net->net_lnd->lnd_startup)(ni);
1402
1403         mutex_unlock(&the_lnet.ln_lnd_mutex);
1404
1405         if (rc != 0) {
1406                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
1407                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
1408                 lnet_net_lock(LNET_LOCK_EX);
1409                 net->net_lnd->lnd_refcount--;
1410                 lnet_net_unlock(LNET_LOCK_EX);
1411                 goto failed0;
1412         }
1413
1414         ni->ni_state = LNET_NI_STATE_ACTIVE;
1415
1416         /* We keep a reference on the loopback net through the loopback NI */
1417         if (net->net_lnd->lnd_type == LOLND) {
1418                 lnet_ni_addref(ni);
1419                 LASSERT(the_lnet.ln_loni == NULL);
1420                 the_lnet.ln_loni = ni;
1421                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
1422                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
1423                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
1424                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
1425                 return 0;
1426         }
1427
1428         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
1429             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
1430                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1431                                    libcfs_lnd2str(net->net_lnd->lnd_type),
1432                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
1433                                         "" : "per-peer ");
1434                 /* shutdown the NI since if we get here then it must've already
1435                  * been started
1436                  */
1437                 lnet_shutdown_lndni(ni);
1438                 return -EINVAL;
1439         }
1440
1441         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
1442                 tq->tq_credits_min =
1443                 tq->tq_credits_max =
1444                 tq->tq_credits = lnet_ni_tq_credits(ni);
1445         }
1446
1447         atomic_set(&ni->ni_tx_credits,
1448                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
1449
1450         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1451                 libcfs_nid2str(ni->ni_nid),
1452                 ni->ni_net->net_tunables.lct_peer_tx_credits,
1453                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
1454                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
1455                 ni->ni_net->net_tunables.lct_peer_timeout);
1456
1457         return 0;
1458 failed0:
1459         lnet_ni_free(ni);
1460         return rc;
1461 }
1462
1463 static int
1464 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
1465 {
1466         struct lnet_ni          *ni;
1467         struct lnet_net         *net_l = NULL;
1468         struct list_head        local_ni_list;
1469         int                     rc;
1470         int                     ni_count = 0;
1471         __u32                   lnd_type;
1472         lnd_t                   *lnd;
1473         int                     peer_timeout =
1474                 net->net_tunables.lct_peer_timeout;
1475         int                     maxtxcredits =
1476                 net->net_tunables.lct_max_tx_credits;
1477         int                     peerrtrcredits =
1478                 net->net_tunables.lct_peer_rtr_credits;
1479
1480         INIT_LIST_HEAD(&local_ni_list);
1481
1482         /*
1483          * make sure that this net is unique. If it isn't then
1484          * we are adding interfaces to an already existing network, and
1485          * 'net' is just a convenient way to pass in the list.
1486          * if it is unique we need to find the LND and load it if
1487          * necessary.
1488          */
1489         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
1490                 lnd_type = LNET_NETTYP(net->net_id);
1491
1492                 LASSERT(libcfs_isknown_lnd(lnd_type));
1493
1494                 if (lnd_type == CIBLND || lnd_type == OPENIBLND ||
1495                     lnd_type == IIBLND || lnd_type == VIBLND) {
1496                         CERROR("LND %s obsoleted\n", libcfs_lnd2str(lnd_type));
1497                         rc = -EINVAL;
1498                         goto failed0;
1499                 }
1500
1501                 mutex_lock(&the_lnet.ln_lnd_mutex);
1502                 lnd = lnet_find_lnd_by_type(lnd_type);
1503
1504                 if (lnd == NULL) {
1505                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1506                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
1507                         mutex_lock(&the_lnet.ln_lnd_mutex);
1508
1509                         lnd = lnet_find_lnd_by_type(lnd_type);
1510                         if (lnd == NULL) {
1511                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1512                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1513                                 libcfs_lnd2str(lnd_type),
1514                                 libcfs_lnd2modname(lnd_type), rc);
1515 #ifndef HAVE_MODULE_LOADING_SUPPORT
1516                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1517                                                 "compiled with kernel module "
1518                                                 "loading support.");
1519 #endif
1520                                 rc = -EINVAL;
1521                                 goto failed0;
1522                         }
1523                 }
1524
1525                 lnet_net_lock(LNET_LOCK_EX);
1526                 lnd->lnd_refcount++;
1527                 lnet_net_unlock(LNET_LOCK_EX);
1528
1529                 net->net_lnd = lnd;
1530
1531                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1532
1533                 net_l = net;
1534         }
1535
1536         /*
1537          * net_l: if the network being added is unique then net_l
1538          *        will point to that network
1539          *        if the network being added is not unique then
1540          *        net_l points to the existing network.
1541          *
1542          * When we enter the loop below, we'll pick NIs off he
1543          * network beign added and start them up, then add them to
1544          * a local ni list. Once we've successfully started all
1545          * the NIs then we join the local NI list (of started up
1546          * networks) with the net_l->net_ni_list, which should
1547          * point to the correct network to add the new ni list to
1548          *
1549          * If any of the new NIs fail to start up, then we want to
1550          * iterate through the local ni list, which should include
1551          * any NIs which were successfully started up, and shut
1552          * them down.
1553          *
1554          * After than we want to delete the network being added,
1555          * to avoid a memory leak.
1556          */
1557
1558         /*
1559          * When a network uses TCP bonding then all its interfaces
1560          * must be specified when the network is first defined: the
1561          * TCP bonding code doesn't allow for interfaces to be added
1562          * or removed.
1563          */
1564         if (net_l != net && net_l != NULL && use_tcp_bonding &&
1565             LNET_NETTYP(net_l->net_id) == SOCKLND) {
1566                 rc = -EINVAL;
1567                 goto failed0;
1568         }
1569
1570         while (!list_empty(&net->net_ni_added)) {
1571                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
1572                                 ni_netlist);
1573                 list_del_init(&ni->ni_netlist);
1574
1575                 /* make sure that the the NI we're about to start
1576                  * up is actually unique. if it's not fail. */
1577                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
1578                                         ni->ni_interfaces[0])) {
1579                         rc = -EINVAL;
1580                         goto failed1;
1581                 }
1582
1583                 /* adjust the pointer the parent network, just in case it
1584                  * the net is a duplicate */
1585                 ni->ni_net = net_l;
1586
1587                 rc = lnet_startup_lndni(ni, tun);
1588
1589                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
1590                         ni->ni_net->net_lnd->lnd_query != NULL);
1591
1592                 if (rc < 0)
1593                         goto failed1;
1594
1595                 lnet_ni_addref(ni);
1596                 list_add_tail(&ni->ni_netlist, &local_ni_list);
1597
1598                 ni_count++;
1599         }
1600
1601         lnet_net_lock(LNET_LOCK_EX);
1602         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
1603         lnet_incr_dlc_seq();
1604         lnet_net_unlock(LNET_LOCK_EX);
1605
1606         /* if the network is not unique then we don't want to keep
1607          * it around after we're done. Free it. Otherwise add that
1608          * net to the global the_lnet.ln_nets */
1609         if (net_l != net && net_l != NULL) {
1610                 /*
1611                  * TODO - note. currently the tunables can not be updated
1612                  * once added
1613                  */
1614                 lnet_net_free(net);
1615         } else {
1616                 net->net_state = LNET_NET_STATE_ACTIVE;
1617                 /*
1618                  * restore tunables after it has been overwitten by the
1619                  * lnd
1620                  */
1621                 if (peer_timeout != -1)
1622                         net->net_tunables.lct_peer_timeout = peer_timeout;
1623                 if (maxtxcredits != -1)
1624                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
1625                 if (peerrtrcredits != -1)
1626                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
1627
1628                 lnet_net_lock(LNET_LOCK_EX);
1629                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
1630                 lnet_net_unlock(LNET_LOCK_EX);
1631         }
1632
1633         return ni_count;
1634
1635 failed1:
1636         /*
1637          * shutdown the new NIs that are being started up
1638          * free the NET being started
1639          */
1640         while (!list_empty(&local_ni_list)) {
1641                 ni = list_entry(local_ni_list.next, struct lnet_ni,
1642                                 ni_netlist);
1643
1644                 lnet_shutdown_lndni(ni);
1645         }
1646
1647 failed0:
1648         lnet_net_free(net);
1649
1650         return rc;
1651 }
1652
1653 static int
1654 lnet_startup_lndnets(struct list_head *netlist)
1655 {
1656         struct lnet_net         *net;
1657         int                     rc;
1658         int                     ni_count = 0;
1659
1660         while (!list_empty(netlist)) {
1661                 net = list_entry(netlist->next, struct lnet_net, net_list);
1662                 list_del_init(&net->net_list);
1663
1664                 rc = lnet_startup_lndnet(net, NULL);
1665
1666                 if (rc < 0)
1667                         goto failed;
1668
1669                 ni_count += rc;
1670         }
1671
1672         return ni_count;
1673 failed:
1674         lnet_shutdown_lndnets();
1675
1676         return rc;
1677 }
1678
1679 /**
1680  * Initialize LNet library.
1681  *
1682  * Automatically called at module loading time. Caller has to call
1683  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
1684  * latter returned 0. It must be called exactly once.
1685  *
1686  * \retval 0 on success
1687  * \retval -ve on failures.
1688  */
1689 int lnet_lib_init(void)
1690 {
1691         int rc;
1692
1693         lnet_assert_wire_constants();
1694
1695         memset(&the_lnet, 0, sizeof(the_lnet));
1696
1697         /* refer to global cfs_cpt_table for now */
1698         the_lnet.ln_cpt_table   = cfs_cpt_table;
1699         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
1700
1701         LASSERT(the_lnet.ln_cpt_number > 0);
1702         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
1703                 /* we are under risk of consuming all lh_cookie */
1704                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
1705                        "please change setting of CPT-table and retry\n",
1706                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
1707                 return -E2BIG;
1708         }
1709
1710         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
1711                 the_lnet.ln_cpt_bits++;
1712
1713         rc = lnet_create_locks();
1714         if (rc != 0) {
1715                 CERROR("Can't create LNet global locks: %d\n", rc);
1716                 return rc;
1717         }
1718
1719         the_lnet.ln_refcount = 0;
1720         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1721         INIT_LIST_HEAD(&the_lnet.ln_lnds);
1722         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
1723         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
1724         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
1725
1726         /* The hash table size is the number of bits it takes to express the set
1727          * ln_num_routes, minus 1 (better to under estimate than over so we
1728          * don't waste memory). */
1729         if (rnet_htable_size <= 0)
1730                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
1731         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
1732                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
1733         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
1734                                            order_base_2(rnet_htable_size) - 1);
1735
1736         /* All LNDs apart from the LOLND are in separate modules.  They
1737          * register themselves when their module loads, and unregister
1738          * themselves when their module is unloaded. */
1739         lnet_register_lnd(&the_lolnd);
1740         return 0;
1741 }
1742
1743 /**
1744  * Finalize LNet library.
1745  *
1746  * \pre lnet_lib_init() called with success.
1747  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1748  */
1749 void lnet_lib_exit(void)
1750 {
1751         LASSERT(the_lnet.ln_refcount == 0);
1752
1753         while (!list_empty(&the_lnet.ln_lnds))
1754                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
1755                                                lnd_t, lnd_list));
1756         lnet_destroy_locks();
1757 }
1758
1759 /**
1760  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1761  *
1762  * Users must call this function at least once before any other functions.
1763  * For each successful call there must be a corresponding call to
1764  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1765  * ignored.
1766  *
1767  * The PID used by LNet may be different from the one requested.
1768  * See LNetGetId().
1769  *
1770  * \param requested_pid PID requested by the caller.
1771  *
1772  * \return >= 0 on success, and < 0 error code on failures.
1773  */
1774 int
1775 LNetNIInit(lnet_pid_t requested_pid)
1776 {
1777         int                     im_a_router = 0;
1778         int                     rc;
1779         int                     ni_count;
1780         struct lnet_ping_info   *pinfo;
1781         lnet_handle_md_t        md_handle;
1782         struct list_head        net_head;
1783         struct lnet_net         *net;
1784
1785         INIT_LIST_HEAD(&net_head);
1786
1787         mutex_lock(&the_lnet.ln_api_mutex);
1788
1789         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1790
1791         if (the_lnet.ln_refcount > 0) {
1792                 rc = the_lnet.ln_refcount++;
1793                 mutex_unlock(&the_lnet.ln_api_mutex);
1794                 return rc;
1795         }
1796
1797         rc = lnet_prepare(requested_pid);
1798         if (rc != 0) {
1799                 mutex_unlock(&the_lnet.ln_api_mutex);
1800                 return rc;
1801         }
1802
1803         /* create a network for Loopback network */
1804         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
1805         if (net == NULL) {
1806                 rc = -ENOMEM;
1807                 goto err_empty_list;
1808         }
1809
1810         /* Add in the loopback NI */
1811         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
1812                 rc = -ENOMEM;
1813                 goto err_empty_list;
1814         }
1815
1816         /* If LNet is being initialized via DLC it is possible
1817          * that the user requests not to load module parameters (ones which
1818          * are supported by DLC) on initialization.  Therefore, make sure not
1819          * to load networks, routes and forwarding from module parameters
1820          * in this case.  On cleanup in case of failure only clean up
1821          * routes if it has been loaded */
1822         if (!the_lnet.ln_nis_from_mod_params) {
1823                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
1824                                          use_tcp_bonding);
1825                 if (rc < 0)
1826                         goto err_empty_list;
1827         }
1828
1829         ni_count = lnet_startup_lndnets(&net_head);
1830         if (ni_count < 0) {
1831                 rc = ni_count;
1832                 goto err_empty_list;
1833         }
1834
1835         if (!the_lnet.ln_nis_from_mod_params) {
1836                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1837                 if (rc != 0)
1838                         goto err_shutdown_lndnis;
1839
1840                 rc = lnet_check_routes();
1841                 if (rc != 0)
1842                         goto err_destroy_routes;
1843
1844                 rc = lnet_rtrpools_alloc(im_a_router);
1845                 if (rc != 0)
1846                         goto err_destroy_routes;
1847         }
1848
1849         rc = lnet_acceptor_start();
1850         if (rc != 0)
1851                 goto err_destroy_routes;
1852
1853         the_lnet.ln_refcount = 1;
1854         /* Now I may use my own API functions... */
1855
1856         rc = lnet_ping_info_setup(&pinfo, &md_handle, ni_count, true);
1857         if (rc != 0)
1858                 goto err_acceptor_stop;
1859
1860         lnet_ping_target_update(pinfo, md_handle);
1861
1862         rc = lnet_router_checker_start();
1863         if (rc != 0)
1864                 goto err_stop_ping;
1865
1866         lnet_fault_init();
1867         lnet_proc_init();
1868
1869         mutex_unlock(&the_lnet.ln_api_mutex);
1870
1871         return 0;
1872
1873 err_stop_ping:
1874         lnet_ping_target_fini();
1875 err_acceptor_stop:
1876         the_lnet.ln_refcount = 0;
1877         lnet_acceptor_stop();
1878 err_destroy_routes:
1879         if (!the_lnet.ln_nis_from_mod_params)
1880                 lnet_destroy_routes();
1881 err_shutdown_lndnis:
1882         lnet_shutdown_lndnets();
1883 err_empty_list:
1884         lnet_unprepare();
1885         LASSERT(rc < 0);
1886         mutex_unlock(&the_lnet.ln_api_mutex);
1887         while (!list_empty(&net_head)) {
1888                 struct lnet_net *net;
1889
1890                 net = list_entry(net_head.next, struct lnet_net, net_list);
1891                 list_del_init(&net->net_list);
1892                 lnet_net_free(net);
1893         }
1894         return rc;
1895 }
1896 EXPORT_SYMBOL(LNetNIInit);
1897
1898 /**
1899  * Stop LNet interfaces, routing, and forwarding.
1900  *
1901  * Users must call this function once for each successful call to LNetNIInit().
1902  * Once the LNetNIFini() operation has been started, the results of pending
1903  * API operations are undefined.
1904  *
1905  * \return always 0 for current implementation.
1906  */
1907 int
1908 LNetNIFini()
1909 {
1910         mutex_lock(&the_lnet.ln_api_mutex);
1911
1912         LASSERT(the_lnet.ln_refcount > 0);
1913
1914         if (the_lnet.ln_refcount != 1) {
1915                 the_lnet.ln_refcount--;
1916         } else {
1917                 LASSERT(!the_lnet.ln_niinit_self);
1918
1919                 lnet_fault_fini();
1920
1921                 lnet_proc_fini();
1922                 lnet_router_checker_stop();
1923                 lnet_ping_target_fini();
1924
1925                 /* Teardown fns that use my own API functions BEFORE here */
1926                 the_lnet.ln_refcount = 0;
1927
1928                 lnet_acceptor_stop();
1929                 lnet_destroy_routes();
1930                 lnet_shutdown_lndnets();
1931                 lnet_unprepare();
1932         }
1933
1934         mutex_unlock(&the_lnet.ln_api_mutex);
1935         return 0;
1936 }
1937 EXPORT_SYMBOL(LNetNIFini);
1938
1939
1940 static int lnet_handle_dbg_task(struct lnet_ioctl_dbg *dbg,
1941                                 struct lnet_dbg_task_info *dbg_info)
1942 {
1943         switch (dbg->dbg_task) {
1944         case LNET_DBG_INCR_DLC_SEQ:
1945                 lnet_incr_dlc_seq();
1946         }
1947
1948         return 0;
1949 }
1950 /**
1951  * Grabs the ni data from the ni structure and fills the out
1952  * parameters
1953  *
1954  * \param[in] ni network        interface structure
1955  * \param[out] cfg_ni           NI config information
1956  * \param[out] tun              network and LND tunables
1957  */
1958 static void
1959 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
1960                    struct lnet_ioctl_config_lnd_tunables *tun,
1961                    struct lnet_ioctl_element_stats *stats,
1962                    __u32 tun_size)
1963 {
1964         size_t min_size = 0;
1965         int i;
1966
1967         if (!ni || !cfg_ni || !tun)
1968                 return;
1969
1970         if (ni->ni_interfaces[0] != NULL) {
1971                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
1972                         if (ni->ni_interfaces[i] != NULL) {
1973                                 strncpy(cfg_ni->lic_ni_intf[i],
1974                                         ni->ni_interfaces[i],
1975                                         sizeof(cfg_ni->lic_ni_intf[i]));
1976                         }
1977                 }
1978         }
1979
1980         cfg_ni->lic_nid = ni->ni_nid;
1981         cfg_ni->lic_status = ni->ni_status->ns_status;
1982         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
1983         cfg_ni->lic_dev_cpt = ni->dev_cpt;
1984
1985         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
1986
1987         if (stats) {
1988                 stats->send_count = atomic_read(&ni->ni_stats.send_count);
1989                 stats->recv_count = atomic_read(&ni->ni_stats.recv_count);
1990         }
1991
1992         /*
1993          * tun->lt_tun will always be present, but in order to be
1994          * backwards compatible, we need to deal with the cases when
1995          * tun->lt_tun is smaller than what the kernel has, because it
1996          * comes from an older version of a userspace program, then we'll
1997          * need to copy as much information as we have available space.
1998          */
1999         min_size = tun_size - sizeof(tun->lt_cmn);
2000         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2001
2002         /* copy over the cpts */
2003         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2004             ni->ni_cpts == NULL)  {
2005                 for (i = 0; i < ni->ni_ncpts; i++)
2006                         cfg_ni->lic_cpts[i] = i;
2007         } else {
2008                 for (i = 0;
2009                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2010                      i < LNET_MAX_SHOW_NUM_CPT;
2011                      i++)
2012                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2013         }
2014         cfg_ni->lic_ncpts = ni->ni_ncpts;
2015 }
2016
2017 /**
2018  * NOTE: This is a legacy function left in the code to be backwards
2019  * compatible with older userspace programs. It should eventually be
2020  * removed.
2021  *
2022  * Grabs the ni data from the ni structure and fills the out
2023  * parameters
2024  *
2025  * \param[in] ni network        interface structure
2026  * \param[out] config           config information
2027  */
2028 static void
2029 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2030                          struct lnet_ioctl_config_data *config)
2031 {
2032         struct lnet_ioctl_net_config *net_config;
2033         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2034         size_t min_size, tunable_size = 0;
2035         int i;
2036
2037         if (!ni || !config)
2038                 return;
2039
2040         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2041         if (!net_config)
2042                 return;
2043
2044         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2045                      ARRAY_SIZE(net_config->ni_interfaces));
2046
2047         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2048                 if (!ni->ni_interfaces[i])
2049                         break;
2050
2051                 strncpy(net_config->ni_interfaces[i],
2052                         ni->ni_interfaces[i],
2053                         sizeof(net_config->ni_interfaces[i]));
2054         }
2055
2056         config->cfg_nid = ni->ni_nid;
2057         config->cfg_config_u.cfg_net.net_peer_timeout =
2058                 ni->ni_net->net_tunables.lct_peer_timeout;
2059         config->cfg_config_u.cfg_net.net_max_tx_credits =
2060                 ni->ni_net->net_tunables.lct_max_tx_credits;
2061         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2062                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2063         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2064                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2065
2066         net_config->ni_status = ni->ni_status->ns_status;
2067
2068         if (ni->ni_cpts) {
2069                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2070
2071                 for (i = 0; i < num_cpts; i++)
2072                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2073
2074                 config->cfg_ncpts = num_cpts;
2075         }
2076
2077         /*
2078          * See if user land tools sent in a newer and larger version
2079          * of struct lnet_tunables than what the kernel uses.
2080          */
2081         min_size = sizeof(*config) + sizeof(*net_config);
2082
2083         if (config->cfg_hdr.ioc_len > min_size)
2084                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2085
2086         /* Don't copy too much data to user space */
2087         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2088         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2089
2090         if (lnd_cfg && min_size) {
2091                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2092                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2093
2094                 /* Tell user land that kernel side has less data */
2095                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2096                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2097                         config->cfg_hdr.ioc_len -= min_size;
2098                 }
2099         }
2100 }
2101
2102 struct lnet_ni *
2103 lnet_get_ni_idx_locked(int idx)
2104 {
2105         struct lnet_ni          *ni;
2106         struct lnet_net         *net;
2107
2108         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2109                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2110                         if (idx-- == 0)
2111                                 return ni;
2112                 }
2113         }
2114
2115         return NULL;
2116 }
2117
2118 struct lnet_ni *
2119 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2120 {
2121         struct lnet_ni          *ni;
2122         struct lnet_net         *net = mynet;
2123
2124         if (prev == NULL) {
2125                 if (net == NULL)
2126                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2127                                         net_list);
2128                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2129                                 ni_netlist);
2130
2131                 return ni;
2132         }
2133
2134         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2135                 /* if you reached the end of the ni list and the net is
2136                  * specified, then there are no more nis in that net */
2137                 if (net != NULL)
2138                         return NULL;
2139
2140                 /* we reached the end of this net ni list. move to the
2141                  * next net */
2142                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2143                         /* no more nets and no more NIs. */
2144                         return NULL;
2145
2146                 /* get the next net */
2147                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2148                                  net_list);
2149                 /* get the ni on it */
2150                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2151                                 ni_netlist);
2152
2153                 return ni;
2154         }
2155
2156         /* there are more nis left */
2157         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2158
2159         return ni;
2160 }
2161
2162 int
2163 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2164 {
2165         struct lnet_ni *ni;
2166         int cpt;
2167         int rc = -ENOENT;
2168         int idx = config->cfg_count;
2169
2170         cpt = lnet_net_lock_current();
2171
2172         ni = lnet_get_ni_idx_locked(idx);
2173
2174         if (ni != NULL) {
2175                 rc = 0;
2176                 lnet_ni_lock(ni);
2177                 lnet_fill_ni_info_legacy(ni, config);
2178                 lnet_ni_unlock(ni);
2179         }
2180
2181         lnet_net_unlock(cpt);
2182         return rc;
2183 }
2184
2185 int
2186 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2187                    struct lnet_ioctl_config_lnd_tunables *tun,
2188                    struct lnet_ioctl_element_stats *stats,
2189                    __u32 tun_size)
2190 {
2191         struct lnet_ni          *ni;
2192         int                     cpt;
2193         int                     rc = -ENOENT;
2194
2195         if (!cfg_ni || !tun || !stats)
2196                 return -EINVAL;
2197
2198         cpt = lnet_net_lock_current();
2199
2200         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2201
2202         if (ni) {
2203                 rc = 0;
2204                 lnet_ni_lock(ni);
2205                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2206                 lnet_ni_unlock(ni);
2207         }
2208
2209         lnet_net_unlock(cpt);
2210         return rc;
2211 }
2212
2213 static int lnet_add_net_common(struct lnet_net *net,
2214                                struct lnet_ioctl_config_lnd_tunables *tun)
2215 {
2216         struct lnet_net         *netl = NULL;
2217         __u32                   net_id;
2218         lnet_ping_info_t        *pinfo;
2219         lnet_handle_md_t        md_handle;
2220         int                     rc;
2221         lnet_remotenet_t        *rnet;
2222         int                     net_ni_count;
2223         int                     num_acceptor_nets;
2224
2225         lnet_net_lock(LNET_LOCK_EX);
2226         rnet = lnet_find_rnet_locked(net->net_id);
2227         lnet_net_unlock(LNET_LOCK_EX);
2228         /*
2229          * make sure that the net added doesn't invalidate the current
2230          * configuration LNet is keeping
2231          */
2232         if (rnet) {
2233                 CERROR("Adding net %s will invalidate routing configuration\n",
2234                        libcfs_net2str(net->net_id));
2235                 rc = -EUSERS;
2236                 goto failed1;
2237         }
2238
2239         /*
2240          * make sure you calculate the correct number of slots in the ping
2241          * info. Since the ping info is a flattened list of all the NIs,
2242          * we should allocate enough slots to accomodate the number of NIs
2243          * which will be added.
2244          *
2245          * since ni hasn't been configured yet, use
2246          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
2247          */
2248         net_ni_count = lnet_get_net_ni_count_pre(net);
2249
2250         rc = lnet_ping_info_setup(&pinfo, &md_handle,
2251                                   net_ni_count + lnet_get_ni_count(),
2252                                   false);
2253         if (rc < 0)
2254                 goto failed1;
2255
2256         if (tun)
2257                 memcpy(&net->net_tunables,
2258                        &tun->lt_cmn, sizeof(net->net_tunables));
2259         else
2260                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
2261
2262         /*
2263          * before starting this network get a count of the current TCP
2264          * networks which require the acceptor thread running. If that
2265          * count is == 0 before we start up this network, then we'd want to
2266          * start up the acceptor thread after starting up this network
2267          */
2268         num_acceptor_nets = lnet_count_acceptor_nets();
2269
2270         net_id = net->net_id;
2271
2272         rc = lnet_startup_lndnet(net,
2273                                  (tun) ? &tun->lt_tun : NULL);
2274         if (rc < 0)
2275                 goto failed;
2276
2277         lnet_net_lock(LNET_LOCK_EX);
2278         netl = lnet_get_net_locked(net_id);
2279         lnet_net_unlock(LNET_LOCK_EX);
2280
2281         LASSERT(netl);
2282
2283         /*
2284          * Start the acceptor thread if this is the first network
2285          * being added that requires the thread.
2286          */
2287         if (netl->net_lnd->lnd_accept &&
2288             num_acceptor_nets == 0)
2289         {
2290                 rc = lnet_acceptor_start();
2291                 if (rc < 0) {
2292                         /* shutdown the net that we just started */
2293                         CERROR("Failed to start up acceptor thread\n");
2294                         lnet_shutdown_lndnet(net);
2295                         goto failed;
2296                 }
2297         }
2298
2299         lnet_net_lock(LNET_LOCK_EX);
2300         lnet_peer_net_added(netl);
2301         lnet_net_unlock(LNET_LOCK_EX);
2302
2303         lnet_ping_target_update(pinfo, md_handle);
2304
2305         return 0;
2306
2307 failed:
2308         lnet_ping_md_unlink(pinfo, &md_handle);
2309         lnet_ping_info_free(pinfo);
2310 failed1:
2311         lnet_net_free(net);
2312         return rc;
2313 }
2314
2315 static int lnet_handle_legacy_ip2nets(char *ip2nets,
2316                                       struct lnet_ioctl_config_lnd_tunables *tun)
2317 {
2318         struct lnet_net *net;
2319         char *nets;
2320         int rc;
2321         struct list_head net_head;
2322
2323         INIT_LIST_HEAD(&net_head);
2324
2325         rc = lnet_parse_ip2nets(&nets, ip2nets);
2326         if (rc < 0)
2327                 return rc;
2328
2329         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2330         if (rc < 0)
2331                 return rc;
2332
2333         mutex_lock(&the_lnet.ln_api_mutex);
2334         while (!list_empty(&net_head)) {
2335                 net = list_entry(net_head.next, struct lnet_net, net_list);
2336                 list_del_init(&net->net_list);
2337                 rc = lnet_add_net_common(net, tun);
2338                 if (rc < 0)
2339                         goto out;
2340         }
2341
2342 out:
2343         mutex_unlock(&the_lnet.ln_api_mutex);
2344
2345         while (!list_empty(&net_head)) {
2346                 net = list_entry(net_head.next, struct lnet_net, net_list);
2347                 list_del_init(&net->net_list);
2348                 lnet_net_free(net);
2349         }
2350         return rc;
2351 }
2352
2353 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
2354 {
2355         struct lnet_net *net;
2356         struct lnet_ni *ni;
2357         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
2358         int rc;
2359         __u32 net_id;
2360
2361         /* get the tunables if they are available */
2362         if (conf->lic_cfg_hdr.ioc_len >=
2363             sizeof(*conf) + sizeof(*tun))
2364                 tun = (struct lnet_ioctl_config_lnd_tunables *)
2365                         conf->lic_bulk;
2366
2367         /* handle legacy ip2nets from DLC */
2368         if (conf->lic_legacy_ip2nets[0] != '\0')
2369                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
2370                                                   tun);
2371
2372         net_id = LNET_NIDNET(conf->lic_nid);
2373
2374         net = lnet_net_alloc(net_id, NULL);
2375         if (!net)
2376                 return -ENOMEM;
2377
2378         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
2379                                        conf->lic_ni_intf[0]);
2380         if (!ni)
2381                 return -ENOMEM;
2382
2383         mutex_lock(&the_lnet.ln_api_mutex);
2384
2385         rc = lnet_add_net_common(net, tun);
2386
2387         mutex_unlock(&the_lnet.ln_api_mutex);
2388
2389         return rc;
2390 }
2391
2392 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
2393 {
2394         struct lnet_net  *net;
2395         struct lnet_ni *ni;
2396         __u32 net_id = LNET_NIDNET(conf->lic_nid);
2397         lnet_ping_info_t *pinfo;
2398         lnet_handle_md_t  md_handle;
2399         int               rc;
2400         int               net_count;
2401         __u32             addr;
2402
2403         /* don't allow userspace to shutdown the LOLND */
2404         if (LNET_NETTYP(net_id) == LOLND)
2405                 return -EINVAL;
2406
2407         mutex_lock(&the_lnet.ln_api_mutex);
2408
2409         lnet_net_lock(0);
2410
2411         net = lnet_get_net_locked(net_id);
2412         if (!net) {
2413                 CERROR("net %s not found\n",
2414                        libcfs_net2str(net_id));
2415                 rc = -ENOENT;
2416                 goto net_unlock;
2417         }
2418
2419         addr = LNET_NIDADDR(conf->lic_nid);
2420         if (addr == 0) {
2421                 /* remove the entire net */
2422                 net_count = lnet_get_net_ni_count_locked(net);
2423
2424                 lnet_net_unlock(0);
2425
2426                 /* create and link a new ping info, before removing the old one */
2427                 rc = lnet_ping_info_setup(&pinfo, &md_handle,
2428                                         lnet_get_ni_count() - net_count,
2429                                         false);
2430                 if (rc != 0)
2431                         goto out;
2432
2433                 lnet_shutdown_lndnet(net);
2434
2435                 if (lnet_count_acceptor_nets() == 0)
2436                         lnet_acceptor_stop();
2437
2438                 lnet_ping_target_update(pinfo, md_handle);
2439
2440                 goto out;
2441         }
2442
2443         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
2444         if (!ni) {
2445                 CERROR("nid %s not found \n",
2446                        libcfs_nid2str(conf->lic_nid));
2447                 rc = -ENOENT;
2448                 goto net_unlock;
2449         }
2450
2451         net_count = lnet_get_net_ni_count_locked(net);
2452
2453         lnet_net_unlock(0);
2454
2455         /* create and link a new ping info, before removing the old one */
2456         rc = lnet_ping_info_setup(&pinfo, &md_handle,
2457                                   lnet_get_ni_count() - 1, false);
2458         if (rc != 0)
2459                 goto out;
2460
2461         lnet_shutdown_lndni(ni);
2462
2463         if (lnet_count_acceptor_nets() == 0)
2464                 lnet_acceptor_stop();
2465
2466         lnet_ping_target_update(pinfo, md_handle);
2467
2468         /* check if the net is empty and remove it if it is */
2469         if (net_count == 1)
2470                 lnet_shutdown_lndnet(net);
2471
2472         goto out;
2473
2474 net_unlock:
2475         lnet_net_unlock(0);
2476 out:
2477         mutex_unlock(&the_lnet.ln_api_mutex);
2478
2479         return rc;
2480 }
2481
2482 /*
2483  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
2484  * They are only expected to be called for unique networks.
2485  * That can be as a result of older DLC library
2486  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
2487  */
2488 int
2489 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
2490 {
2491         struct lnet_net         *net;
2492         struct list_head        net_head;
2493         int                     rc;
2494         struct lnet_ioctl_config_lnd_tunables tun;
2495         char *nets = conf->cfg_config_u.cfg_net.net_intf;
2496
2497         INIT_LIST_HEAD(&net_head);
2498
2499         /* Create a net/ni structures for the network string */
2500         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2501         if (rc <= 0)
2502                 return rc == 0 ? -EINVAL : rc;
2503
2504         mutex_lock(&the_lnet.ln_api_mutex);
2505
2506         if (rc > 1) {
2507                 rc = -EINVAL; /* only add one network per call */
2508                 goto failed;
2509         }
2510
2511         net = list_entry(net_head.next, struct lnet_net, net_list);
2512         list_del_init(&net->net_list);
2513
2514         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
2515
2516         memset(&tun, sizeof(tun), 0);
2517
2518         tun.lt_cmn.lct_peer_timeout =
2519           conf->cfg_config_u.cfg_net.net_peer_timeout;
2520         tun.lt_cmn.lct_peer_tx_credits =
2521           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
2522         tun.lt_cmn.lct_peer_rtr_credits =
2523           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
2524         tun.lt_cmn.lct_max_tx_credits =
2525           conf->cfg_config_u.cfg_net.net_max_tx_credits;
2526
2527         rc = lnet_add_net_common(net, &tun);
2528         if (rc != 0)
2529                 goto failed;
2530
2531         return 0;
2532
2533 failed:
2534         mutex_unlock(&the_lnet.ln_api_mutex);
2535         while (!list_empty(&net_head)) {
2536                 net = list_entry(net_head.next, struct lnet_net, net_list);
2537                 list_del_init(&net->net_list);
2538                 lnet_net_free(net);
2539         }
2540         return rc;
2541 }
2542
2543 int
2544 lnet_dyn_del_net(__u32 net_id)
2545 {
2546         struct lnet_net  *net;
2547         struct lnet_ping_info *pinfo;
2548         lnet_handle_md_t  md_handle;
2549         int               rc;
2550         int               net_ni_count;
2551
2552         /* don't allow userspace to shutdown the LOLND */
2553         if (LNET_NETTYP(net_id) == LOLND)
2554                 return -EINVAL;
2555
2556         mutex_lock(&the_lnet.ln_api_mutex);
2557
2558         lnet_net_lock(0);
2559
2560         net = lnet_get_net_locked(net_id);
2561         if (net == NULL) {
2562                 rc = -EINVAL;
2563                 goto out;
2564         }
2565
2566         net_ni_count = lnet_get_net_ni_count_locked(net);
2567
2568         lnet_net_unlock(0);
2569
2570         /* create and link a new ping info, before removing the old one */
2571         rc = lnet_ping_info_setup(&pinfo, &md_handle,
2572                                   lnet_get_ni_count() - net_ni_count, false);
2573         if (rc != 0)
2574                 goto out;
2575
2576         lnet_shutdown_lndnet(net);
2577
2578         if (lnet_count_acceptor_nets() == 0)
2579                 lnet_acceptor_stop();
2580
2581         lnet_ping_target_update(pinfo, md_handle);
2582
2583 out:
2584         mutex_unlock(&the_lnet.ln_api_mutex);
2585
2586         return rc;
2587 }
2588
2589 void lnet_incr_dlc_seq(void)
2590 {
2591         atomic_inc(&lnet_dlc_seq_no);
2592 }
2593
2594 __u32 lnet_get_dlc_seq_locked(void)
2595 {
2596         return atomic_read(&lnet_dlc_seq_no);
2597 }
2598
2599 inline __u32 lnet_get_numa_range(void)
2600 {
2601         return lnet_numa_range;
2602 }
2603
2604 /**
2605  * LNet ioctl handler.
2606  *
2607  */
2608 int
2609 LNetCtl(unsigned int cmd, void *arg)
2610 {
2611         struct libcfs_ioctl_data *data = arg;
2612         struct lnet_ioctl_config_data *config;
2613         lnet_process_id_t         id = {0};
2614         lnet_ni_t                *ni;
2615         int                       rc;
2616
2617         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
2618                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
2619
2620         switch (cmd) {
2621         case IOC_LIBCFS_GET_NI:
2622                 rc = LNetGetId(data->ioc_count, &id);
2623                 data->ioc_nid = id.nid;
2624                 return rc;
2625
2626         case IOC_LIBCFS_FAIL_NID:
2627                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
2628
2629         case IOC_LIBCFS_ADD_ROUTE:
2630                 config = arg;
2631
2632                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2633                         return -EINVAL;
2634
2635                 mutex_lock(&the_lnet.ln_api_mutex);
2636                 rc = lnet_add_route(config->cfg_net,
2637                                     config->cfg_config_u.cfg_route.rtr_hop,
2638                                     config->cfg_nid,
2639                                     config->cfg_config_u.cfg_route.
2640                                         rtr_priority);
2641                 if (rc == 0) {
2642                         rc = lnet_check_routes();
2643                         if (rc != 0)
2644                                 lnet_del_route(config->cfg_net,
2645                                                config->cfg_nid);
2646                 }
2647                 mutex_unlock(&the_lnet.ln_api_mutex);
2648                 return rc;
2649
2650         case IOC_LIBCFS_DEL_ROUTE:
2651                 config = arg;
2652
2653                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2654                         return -EINVAL;
2655
2656                 mutex_lock(&the_lnet.ln_api_mutex);
2657                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
2658                 mutex_unlock(&the_lnet.ln_api_mutex);
2659                 return rc;
2660
2661         case IOC_LIBCFS_GET_ROUTE:
2662                 config = arg;
2663
2664                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2665                         return -EINVAL;
2666
2667                 mutex_lock(&the_lnet.ln_api_mutex);
2668                 rc = lnet_get_route(config->cfg_count,
2669                                     &config->cfg_net,
2670                                     &config->cfg_config_u.cfg_route.rtr_hop,
2671                                     &config->cfg_nid,
2672                                     &config->cfg_config_u.cfg_route.rtr_flags,
2673                                     &config->cfg_config_u.cfg_route.
2674                                         rtr_priority);
2675                 mutex_unlock(&the_lnet.ln_api_mutex);
2676                 return rc;
2677
2678         case IOC_LIBCFS_GET_LOCAL_NI: {
2679                 struct lnet_ioctl_config_ni *cfg_ni;
2680                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
2681                 struct lnet_ioctl_element_stats *stats;
2682                 __u32 tun_size;
2683
2684                 cfg_ni = arg;
2685                 /* get the tunables if they are available */
2686                 if (cfg_ni->lic_cfg_hdr.ioc_len <
2687                     sizeof(*cfg_ni) + sizeof(*stats)+ sizeof(*tun))
2688                         return -EINVAL;
2689
2690                 stats = (struct lnet_ioctl_element_stats *)
2691                         cfg_ni->lic_bulk;
2692                 tun = (struct lnet_ioctl_config_lnd_tunables *)
2693                                 (cfg_ni->lic_bulk + sizeof(*stats));
2694
2695                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
2696                         sizeof(*stats);
2697
2698                 mutex_lock(&the_lnet.ln_api_mutex);
2699                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
2700                 mutex_unlock(&the_lnet.ln_api_mutex);
2701                 return rc;
2702         }
2703
2704         case IOC_LIBCFS_GET_NET: {
2705                 size_t total = sizeof(*config) +
2706                                sizeof(struct lnet_ioctl_net_config);
2707                 config = arg;
2708
2709                 if (config->cfg_hdr.ioc_len < total)
2710                         return -EINVAL;
2711
2712                 mutex_lock(&the_lnet.ln_api_mutex);
2713                 rc = lnet_get_net_config(config);
2714                 mutex_unlock(&the_lnet.ln_api_mutex);
2715                 return rc;
2716         }
2717
2718         case IOC_LIBCFS_GET_LNET_STATS:
2719         {
2720                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
2721
2722                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
2723                         return -EINVAL;
2724
2725                 mutex_lock(&the_lnet.ln_api_mutex);
2726                 lnet_counters_get(&lnet_stats->st_cntrs);
2727                 mutex_unlock(&the_lnet.ln_api_mutex);
2728                 return 0;
2729         }
2730
2731         case IOC_LIBCFS_CONFIG_RTR:
2732                 config = arg;
2733
2734                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2735                         return -EINVAL;
2736
2737                 mutex_lock(&the_lnet.ln_api_mutex);
2738                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
2739                         rc = lnet_rtrpools_enable();
2740                         mutex_unlock(&the_lnet.ln_api_mutex);
2741                         return rc;
2742                 }
2743                 lnet_rtrpools_disable();
2744                 mutex_unlock(&the_lnet.ln_api_mutex);
2745                 return 0;
2746
2747         case IOC_LIBCFS_ADD_BUF:
2748                 config = arg;
2749
2750                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2751                         return -EINVAL;
2752
2753                 mutex_lock(&the_lnet.ln_api_mutex);
2754                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
2755                                                 buf_tiny,
2756                                           config->cfg_config_u.cfg_buffers.
2757                                                 buf_small,
2758                                           config->cfg_config_u.cfg_buffers.
2759                                                 buf_large);
2760                 mutex_unlock(&the_lnet.ln_api_mutex);
2761                 return rc;
2762
2763         case IOC_LIBCFS_SET_NUMA_RANGE: {
2764                 struct lnet_ioctl_numa_range *numa;
2765                 numa = arg;
2766                 if (numa->nr_hdr.ioc_len != sizeof(*numa))
2767                         return -EINVAL;
2768                 mutex_lock(&the_lnet.ln_api_mutex);
2769                 lnet_numa_range = numa->nr_range;
2770                 mutex_unlock(&the_lnet.ln_api_mutex);
2771                 return 0;
2772         }
2773
2774         case IOC_LIBCFS_GET_NUMA_RANGE: {
2775                 struct lnet_ioctl_numa_range *numa;
2776                 numa = arg;
2777                 if (numa->nr_hdr.ioc_len != sizeof(*numa))
2778                         return -EINVAL;
2779                 numa->nr_range = lnet_numa_range;
2780                 return 0;
2781         }
2782
2783         case IOC_LIBCFS_GET_BUF: {
2784                 struct lnet_ioctl_pool_cfg *pool_cfg;
2785                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
2786
2787                 config = arg;
2788
2789                 if (config->cfg_hdr.ioc_len < total)
2790                         return -EINVAL;
2791
2792                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
2793
2794                 mutex_lock(&the_lnet.ln_api_mutex);
2795                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
2796                 mutex_unlock(&the_lnet.ln_api_mutex);
2797                 return rc;
2798         }
2799
2800         case IOC_LIBCFS_ADD_PEER_NI: {
2801                 struct lnet_ioctl_peer_cfg *cfg = arg;
2802
2803                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
2804                         return -EINVAL;
2805
2806                 mutex_lock(&the_lnet.ln_api_mutex);
2807                 lnet_incr_dlc_seq();
2808                 rc = lnet_add_peer_ni_to_peer(cfg->prcfg_key_nid,
2809                                               cfg->prcfg_cfg_nid,
2810                                               cfg->prcfg_mr);
2811                 mutex_unlock(&the_lnet.ln_api_mutex);
2812                 return rc;
2813         }
2814
2815         case IOC_LIBCFS_DEL_PEER_NI: {
2816                 struct lnet_ioctl_peer_cfg *cfg = arg;
2817
2818                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
2819                         return -EINVAL;
2820
2821                 mutex_lock(&the_lnet.ln_api_mutex);
2822                 lnet_incr_dlc_seq();
2823                 rc = lnet_del_peer_ni_from_peer(cfg->prcfg_key_nid,
2824                                                 cfg->prcfg_cfg_nid);
2825                 mutex_unlock(&the_lnet.ln_api_mutex);
2826                 return rc;
2827         }
2828
2829         case IOC_LIBCFS_GET_PEER_INFO: {
2830                 struct lnet_ioctl_peer *peer_info = arg;
2831
2832                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
2833                         return -EINVAL;
2834
2835                 mutex_lock(&the_lnet.ln_api_mutex);
2836                 rc = lnet_get_peer_ni_info(
2837                    peer_info->pr_count,
2838                    &peer_info->pr_nid,
2839                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
2840                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
2841                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
2842                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
2843                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
2844                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
2845                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_rtr_credits,
2846                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
2847                 mutex_unlock(&the_lnet.ln_api_mutex);
2848                 return rc;
2849         }
2850
2851         case IOC_LIBCFS_GET_PEER_NI: {
2852                 struct lnet_ioctl_peer_cfg *cfg = arg;
2853                 struct lnet_peer_ni_credit_info *lpni_cri;
2854                 struct lnet_ioctl_element_stats *lpni_stats;
2855                 size_t total = sizeof(*cfg) + sizeof(*lpni_cri) +
2856                                sizeof(*lpni_stats);
2857
2858                 if (cfg->prcfg_hdr.ioc_len < total)
2859                         return -EINVAL;
2860
2861                 lpni_cri = (struct lnet_peer_ni_credit_info*) cfg->prcfg_bulk;
2862                 lpni_stats = (struct lnet_ioctl_element_stats *)
2863                              (cfg->prcfg_bulk + sizeof(*lpni_cri));
2864
2865                 mutex_lock(&the_lnet.ln_api_mutex);
2866                 rc = lnet_get_peer_info(cfg->prcfg_idx, &cfg->prcfg_key_nid,
2867                                         &cfg->prcfg_cfg_nid, &cfg->prcfg_mr,
2868                                         lpni_cri, lpni_stats);
2869                 mutex_unlock(&the_lnet.ln_api_mutex);
2870                 return rc;
2871         }
2872
2873         case IOC_LIBCFS_NOTIFY_ROUTER: {
2874                 unsigned long jiffies_passed;
2875
2876                 jiffies_passed = ktime_get_real_seconds() - data->ioc_u64[0];
2877                 jiffies_passed = cfs_time_seconds(jiffies_passed);
2878
2879                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
2880                                    jiffies - jiffies_passed);
2881         }
2882
2883         case IOC_LIBCFS_LNET_DIST:
2884                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
2885                 if (rc < 0 && rc != -EHOSTUNREACH)
2886                         return rc;
2887
2888                 data->ioc_u32[0] = rc;
2889                 return 0;
2890
2891         case IOC_LIBCFS_TESTPROTOCOMPAT:
2892                 lnet_net_lock(LNET_LOCK_EX);
2893                 the_lnet.ln_testprotocompat = data->ioc_flags;
2894                 lnet_net_unlock(LNET_LOCK_EX);
2895                 return 0;
2896
2897         case IOC_LIBCFS_LNET_FAULT:
2898                 return lnet_fault_ctl(data->ioc_flags, data);
2899
2900         case IOC_LIBCFS_PING: {
2901                 signed long timeout;
2902
2903                 id.nid = data->ioc_nid;
2904                 id.pid = data->ioc_u32[0];
2905
2906                 /* Don't block longer than 2 minutes */
2907                 if (data->ioc_u32[1] > 120 * MSEC_PER_SEC)
2908                         return -EINVAL;
2909
2910                 /* If timestamp is negative then disable timeout */
2911                 if ((s32)data->ioc_u32[1] < 0)
2912                         timeout = MAX_SCHEDULE_TIMEOUT;
2913                 else
2914                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
2915
2916                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
2917                                data->ioc_plen1 / sizeof(lnet_process_id_t));
2918                 if (rc < 0)
2919                         return rc;
2920                 data->ioc_count = rc;
2921                 return 0;
2922         }
2923
2924         case IOC_LIBCFS_DBG: {
2925                 struct lnet_ioctl_dbg *dbg = arg;
2926                 struct lnet_dbg_task_info *dbg_info;
2927                 size_t total = sizeof(*dbg) + sizeof(*dbg_info);
2928
2929                 if (dbg->dbg_hdr.ioc_len < total)
2930                         return -EINVAL;
2931
2932                 dbg_info = (struct lnet_dbg_task_info*) dbg->dbg_bulk;
2933
2934                 return lnet_handle_dbg_task(dbg, dbg_info);
2935         }
2936
2937         default:
2938                 ni = lnet_net2ni_addref(data->ioc_net);
2939                 if (ni == NULL)
2940                         return -EINVAL;
2941
2942                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
2943                         rc = -EINVAL;
2944                 else
2945                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
2946
2947                 lnet_ni_decref(ni);
2948                 return rc;
2949         }
2950         /* not reached */
2951 }
2952 EXPORT_SYMBOL(LNetCtl);
2953
2954 void LNetDebugPeer(lnet_process_id_t id)
2955 {
2956         lnet_debug_peer(id.nid);
2957 }
2958 EXPORT_SYMBOL(LNetDebugPeer);
2959
2960 /**
2961  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
2962  * all interfaces share a same PID, as requested by LNetNIInit().
2963  *
2964  * \param index Index of the interface to look up.
2965  * \param id On successful return, this location will hold the
2966  * lnet_process_id_t ID of the interface.
2967  *
2968  * \retval 0 If an interface exists at \a index.
2969  * \retval -ENOENT If no interface has been found.
2970  */
2971 int
2972 LNetGetId(unsigned int index, lnet_process_id_t *id)
2973 {
2974         struct lnet_ni   *ni;
2975         struct lnet_net  *net;
2976         int               cpt;
2977         int               rc = -ENOENT;
2978
2979         LASSERT(the_lnet.ln_refcount > 0);
2980
2981         cpt = lnet_net_lock_current();
2982
2983         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2984                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2985                         if (index-- != 0)
2986                                 continue;
2987
2988                         id->nid = ni->ni_nid;
2989                         id->pid = the_lnet.ln_pid;
2990                         rc = 0;
2991                         break;
2992                 }
2993         }
2994
2995         lnet_net_unlock(cpt);
2996         return rc;
2997 }
2998 EXPORT_SYMBOL(LNetGetId);
2999
3000 /**
3001  * Print a string representation of handle \a h into buffer \a str of
3002  * \a len bytes.
3003  */
3004 void
3005 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
3006 {
3007         snprintf(str, len, "%#llx", h.cookie);
3008 }
3009 EXPORT_SYMBOL(LNetSnprintHandle);
3010
3011 static int lnet_ping(lnet_process_id_t id, signed long timeout,
3012                      lnet_process_id_t __user *ids, int n_ids)
3013 {
3014         lnet_handle_eq_t     eqh;
3015         lnet_handle_md_t     mdh;
3016         lnet_event_t         event;
3017         lnet_md_t            md = { NULL };
3018         int                  which;
3019         int                  unlinked = 0;
3020         int                  replied = 0;
3021         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
3022         int                  infosz;
3023         struct lnet_ping_info    *info;
3024         lnet_process_id_t    tmpid;
3025         int                  i;
3026         int                  nob;
3027         int                  rc;
3028         int                  rc2;
3029         sigset_t         blocked;
3030
3031         infosz = offsetof(struct lnet_ping_info, pi_ni[n_ids]);
3032
3033         /* n_ids limit is arbitrary */
3034         if (n_ids <= 0 || n_ids > 20 || id.nid == LNET_NID_ANY)
3035                 return -EINVAL;
3036
3037         if (id.pid == LNET_PID_ANY)
3038                 id.pid = LNET_PID_LUSTRE;
3039
3040         LIBCFS_ALLOC(info, infosz);
3041         if (info == NULL)
3042                 return -ENOMEM;
3043
3044         /* NB 2 events max (including any unlink event) */
3045         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
3046         if (rc != 0) {
3047                 CERROR("Can't allocate EQ: %d\n", rc);
3048                 goto out_0;
3049         }
3050
3051         /* initialize md content */
3052         md.start     = info;
3053         md.length    = infosz;
3054         md.threshold = 2; /*GET/REPLY*/
3055         md.max_size  = 0;
3056         md.options   = LNET_MD_TRUNCATE;
3057         md.user_ptr  = NULL;
3058         md.eq_handle = eqh;
3059
3060         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
3061         if (rc != 0) {
3062                 CERROR("Can't bind MD: %d\n", rc);
3063                 goto out_1;
3064         }
3065
3066         rc = LNetGet(LNET_NID_ANY, mdh, id,
3067                      LNET_RESERVED_PORTAL,
3068                      LNET_PROTO_PING_MATCHBITS, 0);
3069
3070         if (rc != 0) {
3071                 /* Don't CERROR; this could be deliberate! */
3072
3073                 rc2 = LNetMDUnlink(mdh);
3074                 LASSERT(rc2 == 0);
3075
3076                 /* NB must wait for the UNLINK event below... */
3077                 unlinked = 1;
3078                 timeout = a_long_time;
3079         }
3080
3081         do {
3082                 /* MUST block for unlink to complete */
3083                 if (unlinked)
3084                         blocked = cfs_block_allsigs();
3085
3086                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
3087
3088                 if (unlinked)
3089                         cfs_restore_sigs(blocked);
3090
3091                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
3092                        (rc2 <= 0) ? -1 : event.type,
3093                        (rc2 <= 0) ? -1 : event.status,
3094                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
3095
3096                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
3097
3098                 if (rc2 <= 0 || event.status != 0) {
3099                         /* timeout or error */
3100                         if (!replied && rc == 0)
3101                                 rc = (rc2 < 0) ? rc2 :
3102                                      (rc2 == 0) ? -ETIMEDOUT :
3103                                      event.status;
3104
3105                         if (!unlinked) {
3106                                 /* Ensure completion in finite time... */
3107                                 LNetMDUnlink(mdh);
3108                                 /* No assertion (racing with network) */
3109                                 unlinked = 1;
3110                                 timeout = a_long_time;
3111                         } else if (rc2 == 0) {
3112                                 /* timed out waiting for unlink */
3113                                 CWARN("ping %s: late network completion\n",
3114                                       libcfs_id2str(id));
3115                         }
3116                 } else if (event.type == LNET_EVENT_REPLY) {
3117                         replied = 1;
3118                         rc = event.mlength;
3119                 }
3120
3121         } while (rc2 <= 0 || !event.unlinked);
3122
3123         if (!replied) {
3124                 if (rc >= 0)
3125                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
3126                               libcfs_id2str(id));
3127                 rc = -EIO;
3128                 goto out_1;
3129         }
3130
3131         nob = rc;
3132         LASSERT(nob >= 0 && nob <= infosz);
3133
3134         rc = -EPROTO;                           /* if I can't parse... */
3135
3136         if (nob < 8) {
3137                 /* can't check magic/version */
3138                 CERROR("%s: ping info too short %d\n",
3139                        libcfs_id2str(id), nob);
3140                 goto out_1;
3141         }
3142
3143         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
3144                 lnet_swap_pinginfo(info);
3145         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
3146                 CERROR("%s: Unexpected magic %08x\n",
3147                        libcfs_id2str(id), info->pi_magic);
3148                 goto out_1;
3149         }
3150
3151         if ((info->pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
3152                 CERROR("%s: ping w/o NI status: 0x%x\n",
3153                        libcfs_id2str(id), info->pi_features);
3154                 goto out_1;
3155         }
3156
3157         if (nob < offsetof(struct lnet_ping_info, pi_ni[0])) {
3158                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
3159                        nob, (int)offsetof(struct lnet_ping_info, pi_ni[0]));
3160                 goto out_1;
3161         }
3162
3163         if (info->pi_nnis < n_ids)
3164                 n_ids = info->pi_nnis;
3165
3166         if (nob < offsetof(struct lnet_ping_info, pi_ni[n_ids])) {
3167                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
3168                        nob, (int)offsetof(struct lnet_ping_info, pi_ni[n_ids]));
3169                 goto out_1;
3170         }
3171
3172         rc = -EFAULT;                           /* If I SEGV... */
3173
3174         memset(&tmpid, 0, sizeof(tmpid));
3175         for (i = 0; i < n_ids; i++) {
3176                 tmpid.pid = info->pi_pid;
3177                 tmpid.nid = info->pi_ni[i].ns_nid;
3178                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
3179                         goto out_1;
3180         }
3181         rc = info->pi_nnis;
3182
3183  out_1:
3184         rc2 = LNetEQFree(eqh);
3185         if (rc2 != 0)
3186                 CERROR("rc2 %d\n", rc2);
3187         LASSERT(rc2 == 0);
3188
3189  out_0:
3190         LIBCFS_FREE(info, infosz);
3191         return rc;
3192 }