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