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