Whamcloud - gitweb
LU-10391 lnet: migrate full LNet NI information collection
[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  */
31
32 #define DEBUG_SUBSYSTEM S_LNET
33
34 #include <linux/ctype.h>
35 #include <linux/generic-radix-tree.h>
36 #include <linux/log2.h>
37 #include <linux/ktime.h>
38 #include <linux/moduleparam.h>
39 #include <linux/uaccess.h>
40 #ifdef HAVE_SCHED_HEADERS
41 #include <linux/sched/signal.h>
42 #endif
43 #include <net/genetlink.h>
44
45 #include <libcfs/linux/linux-net.h>
46 #include <lnet/udsp.h>
47 #include <lnet/lib-lnet.h>
48
49 #define D_LNI D_CONSOLE
50
51 /*
52  * initialize ln_api_mutex statically, since it needs to be used in
53  * discovery_set callback. That module parameter callback can be called
54  * before module init completes. The mutex needs to be ready for use then.
55  */
56 struct lnet the_lnet = {
57         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
58 };              /* THE state of the network */
59 EXPORT_SYMBOL(the_lnet);
60
61 static char *ip2nets = "";
62 module_param(ip2nets, charp, 0444);
63 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
64
65 static char *networks = "";
66 module_param(networks, charp, 0444);
67 MODULE_PARM_DESC(networks, "local networks");
68
69 static char *routes = "";
70 module_param(routes, charp, 0444);
71 MODULE_PARM_DESC(routes, "routes to non-local networks");
72
73 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
74 module_param(rnet_htable_size, int, 0444);
75 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
76
77 static int use_tcp_bonding;
78 module_param(use_tcp_bonding, int, 0444);
79 MODULE_PARM_DESC(use_tcp_bonding,
80                  "use_tcp_bonding parameter has been removed");
81
82 unsigned int lnet_numa_range = 0;
83 module_param(lnet_numa_range, uint, 0444);
84 MODULE_PARM_DESC(lnet_numa_range,
85                 "NUMA range to consider during Multi-Rail selection");
86
87 /*
88  * lnet_health_sensitivity determines by how much we decrement the health
89  * value on sending error. The value defaults to 100, which means health
90  * interface health is decremented by 100 points every failure.
91  */
92 unsigned int lnet_health_sensitivity = 100;
93 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
94 #ifdef HAVE_KERNEL_PARAM_OPS
95 static struct kernel_param_ops param_ops_health_sensitivity = {
96         .set = sensitivity_set,
97         .get = param_get_int,
98 };
99 #define param_check_health_sensitivity(name, p) \
100                 __param_check(name, p, int)
101 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
102 #else
103 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
104                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
105 #endif
106 MODULE_PARM_DESC(lnet_health_sensitivity,
107                 "Value to decrement the health value by on error");
108
109 /*
110  * lnet_recovery_interval determines how often we should perform recovery
111  * on unhealthy interfaces.
112  */
113 unsigned int lnet_recovery_interval = 1;
114 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
115 #ifdef HAVE_KERNEL_PARAM_OPS
116 static struct kernel_param_ops param_ops_recovery_interval = {
117         .set = recovery_interval_set,
118         .get = param_get_int,
119 };
120 #define param_check_recovery_interval(name, p) \
121                 __param_check(name, p, int)
122 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
123 #else
124 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
125                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
126 #endif
127 MODULE_PARM_DESC(lnet_recovery_interval,
128                 "DEPRECATED - Interval to recover unhealthy interfaces in seconds");
129
130 unsigned int lnet_recovery_limit;
131 module_param(lnet_recovery_limit, uint, 0644);
132 MODULE_PARM_DESC(lnet_recovery_limit,
133                  "How long to attempt recovery of unhealthy peer interfaces in seconds. Set to 0 to allow indefinite recovery");
134
135 unsigned int lnet_max_recovery_ping_interval = 900;
136 unsigned int lnet_max_recovery_ping_count = 9;
137 static int max_recovery_ping_interval_set(const char *val,
138                                           cfs_kernel_param_arg_t *kp);
139
140 #define param_check_max_recovery_ping_interval(name, p) \
141                 __param_check(name, p, int)
142
143 #ifdef HAVE_KERNEL_PARAM_OPS
144 static struct kernel_param_ops param_ops_max_recovery_ping_interval = {
145         .set = max_recovery_ping_interval_set,
146         .get = param_get_int,
147 };
148 module_param(lnet_max_recovery_ping_interval, max_recovery_ping_interval, 0644);
149 #else
150 module_param_call(lnet_max_recovery_ping_interval, max_recovery_ping_interval,
151                   param_get_int, &lnet_max_recovery_ping_interval, 0644);
152 #endif
153 MODULE_PARM_DESC(lnet_max_recovery_ping_interval,
154                  "The max interval between LNet recovery pings, in seconds");
155
156 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
157 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
158
159 static struct kernel_param_ops param_ops_interfaces_max = {
160         .set = intf_max_set,
161         .get = param_get_int,
162 };
163
164 #define param_check_interfaces_max(name, p) \
165                 __param_check(name, p, int)
166
167 #ifdef HAVE_KERNEL_PARAM_OPS
168 module_param(lnet_interfaces_max, interfaces_max, 0644);
169 #else
170 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
171                   &param_ops_interfaces_max, 0644);
172 #endif
173 MODULE_PARM_DESC(lnet_interfaces_max,
174                 "Maximum number of interfaces in a node.");
175
176 unsigned lnet_peer_discovery_disabled = 0;
177 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
178
179 static struct kernel_param_ops param_ops_discovery_disabled = {
180         .set = discovery_set,
181         .get = param_get_int,
182 };
183
184 #define param_check_discovery_disabled(name, p) \
185                 __param_check(name, p, int)
186 #ifdef HAVE_KERNEL_PARAM_OPS
187 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
188 #else
189 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
190                   &param_ops_discovery_disabled, 0644);
191 #endif
192 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
193                 "Set to 1 to disable peer discovery on this node.");
194
195 unsigned int lnet_drop_asym_route;
196 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
197
198 static struct kernel_param_ops param_ops_drop_asym_route = {
199         .set = drop_asym_route_set,
200         .get = param_get_int,
201 };
202
203 #define param_check_drop_asym_route(name, p)    \
204         __param_check(name, p, int)
205 #ifdef HAVE_KERNEL_PARAM_OPS
206 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
207 #else
208 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
209                   &param_ops_drop_asym_route, 0644);
210 #endif
211 MODULE_PARM_DESC(lnet_drop_asym_route,
212                  "Set to 1 to drop asymmetrical route messages.");
213
214 #define LNET_TRANSACTION_TIMEOUT_DEFAULT 150
215 unsigned int lnet_transaction_timeout = LNET_TRANSACTION_TIMEOUT_DEFAULT;
216 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
217 #ifdef HAVE_KERNEL_PARAM_OPS
218 static struct kernel_param_ops param_ops_transaction_timeout = {
219         .set = transaction_to_set,
220         .get = param_get_int,
221 };
222
223 #define param_check_transaction_timeout(name, p) \
224                 __param_check(name, p, int)
225 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
226 #else
227 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
228                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
229 #endif
230 MODULE_PARM_DESC(lnet_transaction_timeout,
231                 "Maximum number of seconds to wait for a peer response.");
232
233 #define LNET_RETRY_COUNT_DEFAULT 2
234 unsigned int lnet_retry_count = LNET_RETRY_COUNT_DEFAULT;
235 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
236 #ifdef HAVE_KERNEL_PARAM_OPS
237 static struct kernel_param_ops param_ops_retry_count = {
238         .set = retry_count_set,
239         .get = param_get_int,
240 };
241
242 #define param_check_retry_count(name, p) \
243                 __param_check(name, p, int)
244 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
245 #else
246 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
247                   &lnet_retry_count, S_IRUGO|S_IWUSR);
248 #endif
249 MODULE_PARM_DESC(lnet_retry_count,
250                  "Maximum number of times to retry transmitting a message");
251
252 unsigned int lnet_response_tracking = 3;
253 static int response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp);
254
255 #ifdef HAVE_KERNEL_PARAM_OPS
256 static struct kernel_param_ops param_ops_response_tracking = {
257         .set = response_tracking_set,
258         .get = param_get_int,
259 };
260
261 #define param_check_response_tracking(name, p)  \
262         __param_check(name, p, int)
263 module_param(lnet_response_tracking, response_tracking, 0644);
264 #else
265 module_param_call(lnet_response_tracking, response_tracking_set, param_get_int,
266                   &lnet_response_tracking, 0644);
267 #endif
268 MODULE_PARM_DESC(lnet_response_tracking,
269                  "(0|1|2|3) LNet Internal Only|GET Reply only|PUT ACK only|Full Tracking (default)");
270
271 int lock_prim_nid = 1;
272 module_param(lock_prim_nid, int, 0444);
273 MODULE_PARM_DESC(lock_prim_nid,
274                  "Whether nid passed down by Lustre is locked as primary");
275
276 #define LNET_LND_TIMEOUT_DEFAULT ((LNET_TRANSACTION_TIMEOUT_DEFAULT - 1) / \
277                                   (LNET_RETRY_COUNT_DEFAULT + 1))
278 unsigned int lnet_lnd_timeout = LNET_LND_TIMEOUT_DEFAULT;
279 static void lnet_set_lnd_timeout(void)
280 {
281         lnet_lnd_timeout = max((lnet_transaction_timeout - 1) /
282                                (lnet_retry_count + 1), 1U);
283 }
284
285 /*
286  * This sequence number keeps track of how many times DLC was used to
287  * update the local NIs. It is incremented when a NI is added or
288  * removed and checked when sending a message to determine if there is
289  * a need to re-run the selection algorithm. See lnet_select_pathway()
290  * for more details on its usage.
291  */
292 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
293
294 struct lnet_fail_ping {
295         struct lnet_processid           lfp_id;
296         int                             lfp_errno;
297 };
298
299 struct lnet_genl_ping_list {
300         unsigned int                    lgpl_index;
301         unsigned int                    lgpl_list_count;
302         unsigned int                    lgpl_failed_count;
303         signed long                     lgpl_timeout;
304         struct lnet_nid                 lgpl_src_nid;
305         GENRADIX(struct lnet_fail_ping) lgpl_failed;
306         GENRADIX(struct lnet_processid) lgpl_list;
307 };
308
309 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
310                      signed long timeout, struct lnet_genl_ping_list *plist,
311                      int n_ids);
312
313 static int lnet_discover(struct lnet_process_id id, __u32 force,
314                          struct lnet_process_id __user *ids, int n_ids);
315
316 static int
317 sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
318 {
319         int rc;
320         unsigned *sensitivity = (unsigned *)kp->arg;
321         unsigned long value;
322
323         rc = kstrtoul(val, 0, &value);
324         if (rc) {
325                 CERROR("Invalid module parameter value for 'lnet_health_sensitivity'\n");
326                 return rc;
327         }
328
329         /*
330          * The purpose of locking the api_mutex here is to ensure that
331          * the correct value ends up stored properly.
332          */
333         mutex_lock(&the_lnet.ln_api_mutex);
334
335         if (value > LNET_MAX_HEALTH_VALUE) {
336                 mutex_unlock(&the_lnet.ln_api_mutex);
337                 CERROR("Invalid health value. Maximum: %d value = %lu\n",
338                        LNET_MAX_HEALTH_VALUE, value);
339                 return -EINVAL;
340         }
341
342         if (*sensitivity != 0 && value == 0 && lnet_retry_count != 0) {
343                 lnet_retry_count = 0;
344                 lnet_set_lnd_timeout();
345         }
346
347         *sensitivity = value;
348
349         mutex_unlock(&the_lnet.ln_api_mutex);
350
351         return 0;
352 }
353
354 static int
355 recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
356 {
357         CWARN("'lnet_recovery_interval' has been deprecated\n");
358
359         return 0;
360 }
361
362 static int
363 max_recovery_ping_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
364 {
365         int rc;
366         unsigned long value;
367
368         rc = kstrtoul(val, 0, &value);
369         if (rc) {
370                 CERROR("Invalid module parameter value for 'lnet_max_recovery_ping_interval'\n");
371                 return rc;
372         }
373
374         if (!value) {
375                 CERROR("Invalid max ping timeout. Must be strictly positive\n");
376                 return -EINVAL;
377         }
378
379         /* The purpose of locking the api_mutex here is to ensure that
380          * the correct value ends up stored properly.
381          */
382         mutex_lock(&the_lnet.ln_api_mutex);
383         lnet_max_recovery_ping_interval = value;
384         lnet_max_recovery_ping_count = 0;
385         value >>= 1;
386         while (value) {
387                 lnet_max_recovery_ping_count++;
388                 value >>= 1;
389         }
390         mutex_unlock(&the_lnet.ln_api_mutex);
391
392         return 0;
393 }
394
395 static int
396 discovery_set(const char *val, cfs_kernel_param_arg_t *kp)
397 {
398         int rc;
399         unsigned *discovery_off = (unsigned *)kp->arg;
400         unsigned long value;
401         struct lnet_ping_buffer *pbuf;
402
403         rc = kstrtoul(val, 0, &value);
404         if (rc) {
405                 CERROR("Invalid module parameter value for 'lnet_peer_discovery_disabled'\n");
406                 return rc;
407         }
408
409         value = (value) ? 1 : 0;
410
411         /*
412          * The purpose of locking the api_mutex here is to ensure that
413          * the correct value ends up stored properly.
414          */
415         mutex_lock(&the_lnet.ln_api_mutex);
416
417         if (value == *discovery_off) {
418                 mutex_unlock(&the_lnet.ln_api_mutex);
419                 return 0;
420         }
421
422         /*
423          * We still want to set the discovery value even when LNet is not
424          * running. This is the case when LNet is being loaded and we want
425          * the module parameters to take effect. Otherwise if we're
426          * changing the value dynamically, we want to set it after
427          * updating the peers
428          */
429         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
430                 *discovery_off = value;
431                 mutex_unlock(&the_lnet.ln_api_mutex);
432                 return 0;
433         }
434
435         /* tell peers that discovery setting has changed */
436         lnet_net_lock(LNET_LOCK_EX);
437         pbuf = the_lnet.ln_ping_target;
438         if (value)
439                 pbuf->pb_info.pi_features &= ~LNET_PING_FEAT_DISCOVERY;
440         else
441                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
442         lnet_net_unlock(LNET_LOCK_EX);
443
444         /* only send a push when we're turning off discovery */
445         if (*discovery_off <= 0 && value > 0)
446                 lnet_push_update_to_peers(1);
447         *discovery_off = value;
448
449         mutex_unlock(&the_lnet.ln_api_mutex);
450
451         return 0;
452 }
453
454 static int
455 drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp)
456 {
457         int rc;
458         unsigned int *drop_asym_route = (unsigned int *)kp->arg;
459         unsigned long value;
460
461         rc = kstrtoul(val, 0, &value);
462         if (rc) {
463                 CERROR("Invalid module parameter value for "
464                        "'lnet_drop_asym_route'\n");
465                 return rc;
466         }
467
468         /*
469          * The purpose of locking the api_mutex here is to ensure that
470          * the correct value ends up stored properly.
471          */
472         mutex_lock(&the_lnet.ln_api_mutex);
473
474         if (value == *drop_asym_route) {
475                 mutex_unlock(&the_lnet.ln_api_mutex);
476                 return 0;
477         }
478
479         *drop_asym_route = value;
480
481         mutex_unlock(&the_lnet.ln_api_mutex);
482
483         return 0;
484 }
485
486 static int
487 transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp)
488 {
489         int rc;
490         unsigned *transaction_to = (unsigned *)kp->arg;
491         unsigned long value;
492
493         rc = kstrtoul(val, 0, &value);
494         if (rc) {
495                 CERROR("Invalid module parameter value for 'lnet_transaction_timeout'\n");
496                 return rc;
497         }
498
499         /*
500          * The purpose of locking the api_mutex here is to ensure that
501          * the correct value ends up stored properly.
502          */
503         mutex_lock(&the_lnet.ln_api_mutex);
504
505         if (value <= lnet_retry_count || value == 0) {
506                 mutex_unlock(&the_lnet.ln_api_mutex);
507                 CERROR("Invalid value for lnet_transaction_timeout (%lu). "
508                        "Has to be greater than lnet_retry_count (%u)\n",
509                        value, lnet_retry_count);
510                 return -EINVAL;
511         }
512
513         if (value == *transaction_to) {
514                 mutex_unlock(&the_lnet.ln_api_mutex);
515                 return 0;
516         }
517
518         *transaction_to = value;
519         /* Update the lnet_lnd_timeout now that we've modified the
520          * transaction timeout
521          */
522         lnet_set_lnd_timeout();
523
524         mutex_unlock(&the_lnet.ln_api_mutex);
525
526         return 0;
527 }
528
529 static int
530 retry_count_set(const char *val, cfs_kernel_param_arg_t *kp)
531 {
532         int rc;
533         unsigned *retry_count = (unsigned *)kp->arg;
534         unsigned long value;
535
536         rc = kstrtoul(val, 0, &value);
537         if (rc) {
538                 CERROR("Invalid module parameter value for 'lnet_retry_count'\n");
539                 return rc;
540         }
541
542         /*
543          * The purpose of locking the api_mutex here is to ensure that
544          * the correct value ends up stored properly.
545          */
546         mutex_lock(&the_lnet.ln_api_mutex);
547
548         if (lnet_health_sensitivity == 0 && value > 0) {
549                 mutex_unlock(&the_lnet.ln_api_mutex);
550                 CERROR("Can not set lnet_retry_count when health feature is turned off\n");
551                 return -EINVAL;
552         }
553
554         if (value > lnet_transaction_timeout) {
555                 mutex_unlock(&the_lnet.ln_api_mutex);
556                 CERROR("Invalid value for lnet_retry_count (%lu). "
557                        "Has to be smaller than lnet_transaction_timeout (%u)\n",
558                        value, lnet_transaction_timeout);
559                 return -EINVAL;
560         }
561
562         *retry_count = value;
563
564         /* Update the lnet_lnd_timeout now that we've modified the
565          * retry count
566          */
567         lnet_set_lnd_timeout();
568
569         mutex_unlock(&the_lnet.ln_api_mutex);
570
571         return 0;
572 }
573
574 static int
575 intf_max_set(const char *val, cfs_kernel_param_arg_t *kp)
576 {
577         int value, rc;
578
579         rc = kstrtoint(val, 0, &value);
580         if (rc) {
581                 CERROR("Invalid module parameter value for 'lnet_interfaces_max'\n");
582                 return rc;
583         }
584
585         if (value < LNET_INTERFACES_MIN) {
586                 CWARN("max interfaces provided are too small, setting to %d\n",
587                       LNET_INTERFACES_MAX_DEFAULT);
588                 value = LNET_INTERFACES_MAX_DEFAULT;
589         }
590
591         *(int *)kp->arg = value;
592
593         return 0;
594 }
595
596 static int
597 response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp)
598 {
599         int rc;
600         unsigned long new_value;
601
602         rc = kstrtoul(val, 0, &new_value);
603         if (rc) {
604                 CERROR("Invalid value for 'lnet_response_tracking'\n");
605                 return -EINVAL;
606         }
607
608         if (new_value < 0 || new_value > 3) {
609                 CWARN("Invalid value (%lu) for 'lnet_response_tracking'\n",
610                       new_value);
611                 return -EINVAL;
612         }
613
614         lnet_response_tracking = new_value;
615
616         return 0;
617 }
618
619 static const char *
620 lnet_get_routes(void)
621 {
622         return routes;
623 }
624
625 static const char *
626 lnet_get_networks(void)
627 {
628         const char *nets;
629         int rc;
630
631         if (*networks != 0 && *ip2nets != 0) {
632                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
633                                    "'ip2nets' but not both at once\n");
634                 return NULL;
635         }
636
637         if (*ip2nets != 0) {
638                 rc = lnet_parse_ip2nets(&nets, ip2nets);
639                 return (rc == 0) ? nets : NULL;
640         }
641
642         if (*networks != 0)
643                 return networks;
644
645         return "tcp";
646 }
647
648 static void
649 lnet_init_locks(void)
650 {
651         spin_lock_init(&the_lnet.ln_eq_wait_lock);
652         spin_lock_init(&the_lnet.ln_msg_resend_lock);
653         init_completion(&the_lnet.ln_mt_wait_complete);
654         mutex_init(&the_lnet.ln_lnd_mutex);
655 }
656
657 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
658 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
659                                             *  MDs kmem_cache */
660 struct kmem_cache *lnet_udsp_cachep;       /* udsp cache */
661 struct kmem_cache *lnet_rspt_cachep;       /* response tracker cache */
662 struct kmem_cache *lnet_msg_cachep;
663
664 static int
665 lnet_slab_setup(void)
666 {
667         /* create specific kmem_cache for MEs and small MDs (i.e., originally
668          * allocated in <size-xxx> kmem_cache).
669          */
670         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(struct lnet_me),
671                                             0, 0, NULL);
672         if (!lnet_mes_cachep)
673                 return -ENOMEM;
674
675         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
676                                                   LNET_SMALL_MD_SIZE, 0, 0,
677                                                   NULL);
678         if (!lnet_small_mds_cachep)
679                 return -ENOMEM;
680
681         lnet_udsp_cachep = kmem_cache_create("lnet_udsp",
682                                              sizeof(struct lnet_udsp),
683                                              0, 0, NULL);
684         if (!lnet_udsp_cachep)
685                 return -ENOMEM;
686
687         lnet_rspt_cachep = kmem_cache_create("lnet_rspt", sizeof(struct lnet_rsp_tracker),
688                                             0, 0, NULL);
689         if (!lnet_rspt_cachep)
690                 return -ENOMEM;
691
692         lnet_msg_cachep = kmem_cache_create("lnet_msg", sizeof(struct lnet_msg),
693                                             0, 0, NULL);
694         if (!lnet_msg_cachep)
695                 return -ENOMEM;
696
697         return 0;
698 }
699
700 static void
701 lnet_slab_cleanup(void)
702 {
703         if (lnet_msg_cachep) {
704                 kmem_cache_destroy(lnet_msg_cachep);
705                 lnet_msg_cachep = NULL;
706         }
707
708         if (lnet_rspt_cachep) {
709                 kmem_cache_destroy(lnet_rspt_cachep);
710                 lnet_rspt_cachep = NULL;
711         }
712
713         if (lnet_udsp_cachep) {
714                 kmem_cache_destroy(lnet_udsp_cachep);
715                 lnet_udsp_cachep = NULL;
716         }
717
718         if (lnet_small_mds_cachep) {
719                 kmem_cache_destroy(lnet_small_mds_cachep);
720                 lnet_small_mds_cachep = NULL;
721         }
722
723         if (lnet_mes_cachep) {
724                 kmem_cache_destroy(lnet_mes_cachep);
725                 lnet_mes_cachep = NULL;
726         }
727 }
728
729 static int
730 lnet_create_remote_nets_table(void)
731 {
732         int               i;
733         struct list_head *hash;
734
735         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
736         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
737         CFS_ALLOC_PTR_ARRAY(hash, LNET_REMOTE_NETS_HASH_SIZE);
738         if (hash == NULL) {
739                 CERROR("Failed to create remote nets hash table\n");
740                 return -ENOMEM;
741         }
742
743         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
744                 INIT_LIST_HEAD(&hash[i]);
745         the_lnet.ln_remote_nets_hash = hash;
746         return 0;
747 }
748
749 static void
750 lnet_destroy_remote_nets_table(void)
751 {
752         int i;
753
754         if (the_lnet.ln_remote_nets_hash == NULL)
755                 return;
756
757         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
758                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
759
760         CFS_FREE_PTR_ARRAY(the_lnet.ln_remote_nets_hash,
761                            LNET_REMOTE_NETS_HASH_SIZE);
762         the_lnet.ln_remote_nets_hash = NULL;
763 }
764
765 static void
766 lnet_destroy_locks(void)
767 {
768         if (the_lnet.ln_res_lock != NULL) {
769                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
770                 the_lnet.ln_res_lock = NULL;
771         }
772
773         if (the_lnet.ln_net_lock != NULL) {
774                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
775                 the_lnet.ln_net_lock = NULL;
776         }
777 }
778
779 static int
780 lnet_create_locks(void)
781 {
782         lnet_init_locks();
783
784         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
785         if (the_lnet.ln_res_lock == NULL)
786                 goto failed;
787
788         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
789         if (the_lnet.ln_net_lock == NULL)
790                 goto failed;
791
792         return 0;
793
794  failed:
795         lnet_destroy_locks();
796         return -ENOMEM;
797 }
798
799 static void lnet_assert_wire_constants(void)
800 {
801         /* Wire protocol assertions generated by 'wirecheck'
802          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
803          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
804          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7)
805          */
806
807         /* Constants... */
808         BUILD_BUG_ON(LNET_PROTO_TCP_MAGIC != 0xeebc0ded);
809         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MAJOR != 1);
810         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MINOR != 0);
811         BUILD_BUG_ON(LNET_MSG_ACK != 0);
812         BUILD_BUG_ON(LNET_MSG_PUT != 1);
813         BUILD_BUG_ON(LNET_MSG_GET != 2);
814         BUILD_BUG_ON(LNET_MSG_REPLY != 3);
815         BUILD_BUG_ON(LNET_MSG_HELLO != 4);
816
817         BUILD_BUG_ON((int)sizeof(lnet_nid_t) != 8);
818         BUILD_BUG_ON((int)sizeof(lnet_pid_t) != 4);
819
820         /* Checks for struct lnet_nid */
821         BUILD_BUG_ON((int)sizeof(struct lnet_nid) != 20);
822         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_size) != 0);
823         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_size) != 1);
824         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_type) != 1);
825         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_type) != 1);
826         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_num) != 2);
827         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_num) != 2);
828         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_addr) != 4);
829         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_addr) != 16);
830
831         /* Checks for struct lnet_process_id_packed */
832         BUILD_BUG_ON((int)sizeof(struct lnet_process_id_packed) != 12);
833         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, nid) != 0);
834         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->nid) != 8);
835         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, pid) != 8);
836         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->pid) != 4);
837
838         /* Checks for struct lnet_handle_wire */
839         BUILD_BUG_ON((int)sizeof(struct lnet_handle_wire) != 16);
840         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
841                                    wh_interface_cookie) != 0);
842         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) != 8);
843         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
844                                    wh_object_cookie) != 8);
845         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) != 8);
846
847         /* Checks for struct struct lnet_magicversion */
848         BUILD_BUG_ON((int)sizeof(struct lnet_magicversion) != 8);
849         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, magic) != 0);
850         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->magic) != 4);
851         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, version_major) != 4);
852         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_major) != 2);
853         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion,
854                                    version_minor) != 6);
855         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_minor) != 2);
856
857         /* Checks for struct _lnet_hdr_nid4 */
858         BUILD_BUG_ON((int)sizeof(struct _lnet_hdr_nid4) != 72);
859         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, dest_nid) != 0);
860         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->dest_nid) != 8);
861         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, src_nid) != 8);
862         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->src_nid) != 8);
863         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, dest_pid) != 16);
864         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->dest_pid) != 4);
865         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, src_pid) != 20);
866         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->src_pid) != 4);
867         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, type) != 24);
868         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->type) != 4);
869         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, payload_length) != 28);
870         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->payload_length) != 4);
871         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg) != 32);
872         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg) != 40);
873
874         /* Ack */
875         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.dst_wmd) != 32);
876         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.dst_wmd) != 16);
877         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.match_bits) != 48);
878         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.match_bits) != 8);
879         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.mlength) != 56);
880         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.mlength) != 4);
881
882         /* Put */
883         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.ack_wmd) != 32);
884         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.ack_wmd) != 16);
885         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.match_bits) != 48);
886         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.match_bits) != 8);
887         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.hdr_data) != 56);
888         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.hdr_data) != 8);
889         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.ptl_index) != 64);
890         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.ptl_index) != 4);
891         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.offset) != 68);
892         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.offset) != 4);
893
894         /* Get */
895         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.return_wmd) != 32);
896         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.return_wmd) != 16);
897         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.match_bits) != 48);
898         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.match_bits) != 8);
899         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.ptl_index) != 56);
900         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.ptl_index) != 4);
901         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.src_offset) != 60);
902         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.src_offset) != 4);
903         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.sink_length) != 64);
904         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.sink_length) != 4);
905
906         /* Reply */
907         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.reply.dst_wmd) != 32);
908         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.reply.dst_wmd) != 16);
909
910         /* Hello */
911         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.hello.incarnation) != 32);
912         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.hello.incarnation) != 8);
913         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.hello.type) != 40);
914         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.hello.type) != 4);
915
916         /* Checks for struct lnet_ni_status and related constants */
917         BUILD_BUG_ON(LNET_NI_STATUS_INVALID != 0x00000000);
918         BUILD_BUG_ON(LNET_NI_STATUS_UP != 0x15aac0de);
919         BUILD_BUG_ON(LNET_NI_STATUS_DOWN != 0xdeadface);
920
921         /* Checks for struct lnet_ni_status */
922         BUILD_BUG_ON((int)sizeof(struct lnet_ni_status) != 16);
923         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_nid) != 0);
924         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_nid) != 8);
925         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_status) != 8);
926         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_status) != 4);
927         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_msg_size) != 12);
928         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_msg_size) != 4);
929
930         /* Checks for struct lnet_ni_large_status */
931         BUILD_BUG_ON((int)sizeof(struct lnet_ni_large_status) != 24);
932         BUILD_BUG_ON((int)offsetof(struct lnet_ni_large_status, ns_status) != 0);
933         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_large_status *)0)->ns_status) != 4);
934         BUILD_BUG_ON((int)offsetof(struct lnet_ni_large_status, ns_nid) != 4);
935         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_large_status *)0)->ns_nid) != 20);
936
937         /* Checks for struct lnet_ping_info and related constants */
938         BUILD_BUG_ON(LNET_PROTO_PING_MAGIC != 0x70696E67);
939         BUILD_BUG_ON(LNET_PING_FEAT_INVAL != 0);
940         BUILD_BUG_ON(LNET_PING_FEAT_BASE != 1);
941         BUILD_BUG_ON(LNET_PING_FEAT_NI_STATUS != 2);
942         BUILD_BUG_ON(LNET_PING_FEAT_RTE_DISABLED != 4);
943         BUILD_BUG_ON(LNET_PING_FEAT_MULTI_RAIL != 8);
944         BUILD_BUG_ON(LNET_PING_FEAT_DISCOVERY != 16);
945         BUILD_BUG_ON(LNET_PING_FEAT_LARGE_ADDR != 32);
946         BUILD_BUG_ON(LNET_PING_FEAT_PRIMARY_LARGE != 64);
947         BUILD_BUG_ON(LNET_PING_FEAT_BITS != 127);
948
949         /* Checks for struct lnet_ping_info */
950         BUILD_BUG_ON((int)sizeof(struct lnet_ping_info) != 16);
951         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_magic) != 0);
952         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_magic) != 4);
953         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_features) != 4);
954         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_features) != 4);
955         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_pid) != 8);
956         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_pid) != 4);
957         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_nnis) != 12);
958         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_nnis) != 4);
959         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_ni) != 16);
960         BUILD_BUG_ON(offsetof(struct lnet_ping_info, pi_ni) != sizeof(struct lnet_ping_info));
961
962         /* Acceptor connection request */
963         BUILD_BUG_ON(LNET_PROTO_ACCEPTOR_VERSION != 1);
964
965         /* Checks for struct lnet_acceptor_connreq */
966         BUILD_BUG_ON((int)sizeof(struct lnet_acceptor_connreq) != 16);
967         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_magic) != 0);
968         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_magic) != 4);
969         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_version) != 4);
970         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_version) != 4);
971         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_nid) != 8);
972         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_nid) != 8);
973
974         /* Checks for struct lnet_acceptor_connreq_v2 */
975         BUILD_BUG_ON((int)sizeof(struct lnet_acceptor_connreq_v2) != 28);
976         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_magic) != 0);
977         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_magic) != 4);
978         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_version) != 4);
979         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_version) != 4);
980         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_nid) != 8);
981         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_nid) != 20);
982
983         /* Checks for struct lnet_counters_common */
984         BUILD_BUG_ON((int)sizeof(struct lnet_counters_common) != 60);
985         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_alloc) != 0);
986         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_alloc) != 4);
987         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_max) != 4);
988         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_max) != 4);
989         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_errors) != 8);
990         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_errors) != 4);
991         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_count) != 12);
992         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_count) != 4);
993         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_count) != 16);
994         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_count) != 4);
995         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_count) != 20);
996         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_count) != 4);
997         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_count) != 24);
998         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_count) != 4);
999         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_length) != 28);
1000         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_length) != 8);
1001         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_length) != 36);
1002         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_length) != 8);
1003         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_length) != 44);
1004         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_length) != 8);
1005         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_length) != 52);
1006         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_length) != 8);
1007 }
1008
1009 static const struct lnet_lnd *lnet_find_lnd_by_type(__u32 type)
1010 {
1011         const struct lnet_lnd *lnd;
1012
1013         /* holding lnd mutex */
1014         if (type >= NUM_LNDS)
1015                 return NULL;
1016         lnd = the_lnet.ln_lnds[type];
1017         LASSERT(!lnd || lnd->lnd_type == type);
1018
1019         return lnd;
1020 }
1021
1022 unsigned int
1023 lnet_get_lnd_timeout(void)
1024 {
1025         return lnet_lnd_timeout;
1026 }
1027 EXPORT_SYMBOL(lnet_get_lnd_timeout);
1028
1029 void
1030 lnet_register_lnd(const struct lnet_lnd *lnd)
1031 {
1032         mutex_lock(&the_lnet.ln_lnd_mutex);
1033
1034         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
1035         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
1036
1037         the_lnet.ln_lnds[lnd->lnd_type] = lnd;
1038
1039         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
1040
1041         mutex_unlock(&the_lnet.ln_lnd_mutex);
1042 }
1043 EXPORT_SYMBOL(lnet_register_lnd);
1044
1045 void
1046 lnet_unregister_lnd(const struct lnet_lnd *lnd)
1047 {
1048         mutex_lock(&the_lnet.ln_lnd_mutex);
1049
1050         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
1051
1052         the_lnet.ln_lnds[lnd->lnd_type] = NULL;
1053         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
1054
1055         mutex_unlock(&the_lnet.ln_lnd_mutex);
1056 }
1057 EXPORT_SYMBOL(lnet_unregister_lnd);
1058
1059 static void
1060 lnet_counters_get_common_locked(struct lnet_counters_common *common)
1061 {
1062         struct lnet_counters *ctr;
1063         int i;
1064
1065         /* FIXME !!! Their is no assert_lnet_net_locked() to ensure this
1066          * actually called under the protection of the lnet_net_lock.
1067          */
1068         memset(common, 0, sizeof(*common));
1069
1070         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
1071                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
1072                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
1073                 common->lcc_errors       += ctr->lct_common.lcc_errors;
1074                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
1075                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
1076                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
1077                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
1078                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
1079                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
1080                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
1081                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
1082         }
1083 }
1084
1085 void
1086 lnet_counters_get_common(struct lnet_counters_common *common)
1087 {
1088         lnet_net_lock(LNET_LOCK_EX);
1089         lnet_counters_get_common_locked(common);
1090         lnet_net_unlock(LNET_LOCK_EX);
1091 }
1092 EXPORT_SYMBOL(lnet_counters_get_common);
1093
1094 int
1095 lnet_counters_get(struct lnet_counters *counters)
1096 {
1097         struct lnet_counters *ctr;
1098         struct lnet_counters_health *health = &counters->lct_health;
1099         int i, rc = 0;
1100
1101         memset(counters, 0, sizeof(*counters));
1102
1103         lnet_net_lock(LNET_LOCK_EX);
1104
1105         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1106                 GOTO(out_unlock, rc = -ENODEV);
1107
1108         lnet_counters_get_common_locked(&counters->lct_common);
1109
1110         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
1111                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
1112                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
1113                 health->lch_response_timeout_count +=
1114                                 ctr->lct_health.lch_response_timeout_count;
1115                 health->lch_local_interrupt_count +=
1116                                 ctr->lct_health.lch_local_interrupt_count;
1117                 health->lch_local_dropped_count +=
1118                                 ctr->lct_health.lch_local_dropped_count;
1119                 health->lch_local_aborted_count +=
1120                                 ctr->lct_health.lch_local_aborted_count;
1121                 health->lch_local_no_route_count +=
1122                                 ctr->lct_health.lch_local_no_route_count;
1123                 health->lch_local_timeout_count +=
1124                                 ctr->lct_health.lch_local_timeout_count;
1125                 health->lch_local_error_count +=
1126                                 ctr->lct_health.lch_local_error_count;
1127                 health->lch_remote_dropped_count +=
1128                                 ctr->lct_health.lch_remote_dropped_count;
1129                 health->lch_remote_error_count +=
1130                                 ctr->lct_health.lch_remote_error_count;
1131                 health->lch_remote_timeout_count +=
1132                                 ctr->lct_health.lch_remote_timeout_count;
1133                 health->lch_network_timeout_count +=
1134                                 ctr->lct_health.lch_network_timeout_count;
1135         }
1136 out_unlock:
1137         lnet_net_unlock(LNET_LOCK_EX);
1138         return rc;
1139 }
1140 EXPORT_SYMBOL(lnet_counters_get);
1141
1142 void
1143 lnet_counters_reset(void)
1144 {
1145         struct lnet_counters *counters;
1146         int             i;
1147
1148         lnet_net_lock(LNET_LOCK_EX);
1149
1150         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1151                 goto avoid_reset;
1152
1153         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
1154                 memset(counters, 0, sizeof(struct lnet_counters));
1155 avoid_reset:
1156         lnet_net_unlock(LNET_LOCK_EX);
1157 }
1158
1159 static char *
1160 lnet_res_type2str(int type)
1161 {
1162         switch (type) {
1163         default:
1164                 LBUG();
1165         case LNET_COOKIE_TYPE_MD:
1166                 return "MD";
1167         case LNET_COOKIE_TYPE_ME:
1168                 return "ME";
1169         case LNET_COOKIE_TYPE_EQ:
1170                 return "EQ";
1171         }
1172 }
1173
1174 static void
1175 lnet_res_container_cleanup(struct lnet_res_container *rec)
1176 {
1177         int     count = 0;
1178
1179         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
1180                 return;
1181
1182         while (!list_empty(&rec->rec_active)) {
1183                 struct list_head *e = rec->rec_active.next;
1184
1185                 list_del_init(e);
1186                 if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
1187                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
1188
1189                 } else { /* NB: Active MEs should be attached on portals */
1190                         LBUG();
1191                 }
1192                 count++;
1193         }
1194
1195         if (count > 0) {
1196                 /* Found alive MD/ME/EQ, user really should unlink/free
1197                  * all of them before finalize LNet, but if someone didn't,
1198                  * we have to recycle garbage for him */
1199                 CERROR("%d active elements on exit of %s container\n",
1200                        count, lnet_res_type2str(rec->rec_type));
1201         }
1202
1203         if (rec->rec_lh_hash != NULL) {
1204                 CFS_FREE_PTR_ARRAY(rec->rec_lh_hash, LNET_LH_HASH_SIZE);
1205                 rec->rec_lh_hash = NULL;
1206         }
1207
1208         rec->rec_type = 0; /* mark it as finalized */
1209 }
1210
1211 static int
1212 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
1213 {
1214         int     rc = 0;
1215         int     i;
1216
1217         LASSERT(rec->rec_type == 0);
1218
1219         rec->rec_type = type;
1220         INIT_LIST_HEAD(&rec->rec_active);
1221
1222         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1223
1224         /* Arbitrary choice of hash table size */
1225         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1226                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1227         if (rec->rec_lh_hash == NULL) {
1228                 rc = -ENOMEM;
1229                 goto out;
1230         }
1231
1232         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1233                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1234
1235         return 0;
1236
1237 out:
1238         CERROR("Failed to setup %s resource container\n",
1239                lnet_res_type2str(type));
1240         lnet_res_container_cleanup(rec);
1241         return rc;
1242 }
1243
1244 static void
1245 lnet_res_containers_destroy(struct lnet_res_container **recs)
1246 {
1247         struct lnet_res_container       *rec;
1248         int                             i;
1249
1250         cfs_percpt_for_each(rec, i, recs)
1251                 lnet_res_container_cleanup(rec);
1252
1253         cfs_percpt_free(recs);
1254 }
1255
1256 static struct lnet_res_container **
1257 lnet_res_containers_create(int type)
1258 {
1259         struct lnet_res_container       **recs;
1260         struct lnet_res_container       *rec;
1261         int                             rc;
1262         int                             i;
1263
1264         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1265         if (recs == NULL) {
1266                 CERROR("Failed to allocate %s resource containers\n",
1267                        lnet_res_type2str(type));
1268                 return NULL;
1269         }
1270
1271         cfs_percpt_for_each(rec, i, recs) {
1272                 rc = lnet_res_container_setup(rec, i, type);
1273                 if (rc != 0) {
1274                         lnet_res_containers_destroy(recs);
1275                         return NULL;
1276                 }
1277         }
1278
1279         return recs;
1280 }
1281
1282 struct lnet_libhandle *
1283 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1284 {
1285         /* ALWAYS called with lnet_res_lock held */
1286         struct list_head        *head;
1287         struct lnet_libhandle   *lh;
1288         unsigned int            hash;
1289
1290         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1291                 return NULL;
1292
1293         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1294         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1295
1296         list_for_each_entry(lh, head, lh_hash_chain) {
1297                 if (lh->lh_cookie == cookie)
1298                         return lh;
1299         }
1300
1301         return NULL;
1302 }
1303
1304 void
1305 lnet_res_lh_initialize(struct lnet_res_container *rec,
1306                        struct lnet_libhandle *lh)
1307 {
1308         /* ALWAYS called with lnet_res_lock held */
1309         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1310         unsigned int    hash;
1311
1312         lh->lh_cookie = rec->rec_lh_cookie;
1313         rec->rec_lh_cookie += 1 << ibits;
1314
1315         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1316
1317         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1318 }
1319
1320 struct list_head **
1321 lnet_create_array_of_queues(void)
1322 {
1323         struct list_head **qs;
1324         struct list_head *q;
1325         int i;
1326
1327         qs = cfs_percpt_alloc(lnet_cpt_table(),
1328                               sizeof(struct list_head));
1329         if (!qs) {
1330                 CERROR("Failed to allocate queues\n");
1331                 return NULL;
1332         }
1333
1334         cfs_percpt_for_each(q, i, qs)
1335                 INIT_LIST_HEAD(q);
1336
1337         return qs;
1338 }
1339
1340 static int lnet_unprepare(void);
1341
1342 static int
1343 lnet_prepare(lnet_pid_t requested_pid)
1344 {
1345         /* Prepare to bring up the network */
1346         struct lnet_res_container **recs;
1347         int                       rc = 0;
1348
1349         if (requested_pid == LNET_PID_ANY) {
1350                 /* Don't instantiate LNET just for me */
1351                 return -ENETDOWN;
1352         }
1353
1354         LASSERT(the_lnet.ln_refcount == 0);
1355
1356         the_lnet.ln_routing = 0;
1357
1358         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1359         the_lnet.ln_pid = requested_pid;
1360
1361         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1362         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1363         INIT_LIST_HEAD(&the_lnet.ln_nets);
1364         INIT_LIST_HEAD(&the_lnet.ln_routers);
1365         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1366         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1367         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1368         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1369         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1370         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1371         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1372         INIT_LIST_HEAD(&the_lnet.ln_udsp_list);
1373         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1374         the_lnet.ln_mt_handler = NULL;
1375         init_completion(&the_lnet.ln_started);
1376         atomic_set(&the_lnet.ln_late_msg_count, 0);
1377         atomic64_set(&the_lnet.ln_late_msg_nsecs, 0);
1378
1379         rc = lnet_slab_setup();
1380         if (rc != 0)
1381                 goto failed;
1382
1383         rc = lnet_create_remote_nets_table();
1384         if (rc != 0)
1385                 goto failed;
1386
1387         /*
1388          * NB the interface cookie in wire handles guards against delayed
1389          * replies and ACKs appearing valid after reboot.
1390          */
1391         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1392
1393         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1394                                                 sizeof(struct lnet_counters));
1395         if (the_lnet.ln_counters == NULL) {
1396                 CERROR("Failed to allocate counters for LNet\n");
1397                 rc = -ENOMEM;
1398                 goto failed;
1399         }
1400
1401         rc = lnet_peer_tables_create();
1402         if (rc != 0)
1403                 goto failed;
1404
1405         rc = lnet_msg_containers_create();
1406         if (rc != 0)
1407                 goto failed;
1408
1409         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1410                                       LNET_COOKIE_TYPE_EQ);
1411         if (rc != 0)
1412                 goto failed;
1413
1414         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1415         if (recs == NULL) {
1416                 rc = -ENOMEM;
1417                 goto failed;
1418         }
1419
1420         the_lnet.ln_md_containers = recs;
1421
1422         rc = lnet_portals_create();
1423         if (rc != 0) {
1424                 CERROR("Failed to create portals for LNet: %d\n", rc);
1425                 goto failed;
1426         }
1427
1428         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1429         if (!the_lnet.ln_mt_zombie_rstqs) {
1430                 rc = -ENOMEM;
1431                 goto failed;
1432         }
1433
1434         return 0;
1435
1436  failed:
1437         lnet_unprepare();
1438         return rc;
1439 }
1440
1441 static int
1442 lnet_unprepare(void)
1443 {
1444         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1445          * have shut down already, so it is safe to unlink and free all
1446          * descriptors, even those that appear committed to a network op (eg MD
1447          * with non-zero pending count) */
1448
1449         lnet_fail_nid(LNET_NID_ANY, 0);
1450
1451         LASSERT(the_lnet.ln_refcount == 0);
1452         LASSERT(list_empty(&the_lnet.ln_test_peers));
1453         LASSERT(list_empty(&the_lnet.ln_nets));
1454
1455         if (the_lnet.ln_mt_zombie_rstqs) {
1456                 lnet_clean_zombie_rstqs();
1457                 the_lnet.ln_mt_zombie_rstqs = NULL;
1458         }
1459
1460         lnet_assert_handler_unused(the_lnet.ln_mt_handler);
1461         the_lnet.ln_mt_handler = NULL;
1462
1463         lnet_portals_destroy();
1464
1465         if (the_lnet.ln_md_containers != NULL) {
1466                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1467                 the_lnet.ln_md_containers = NULL;
1468         }
1469
1470         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1471
1472         lnet_msg_containers_destroy();
1473         lnet_peer_uninit();
1474         lnet_rtrpools_free(0);
1475
1476         if (the_lnet.ln_counters != NULL) {
1477                 cfs_percpt_free(the_lnet.ln_counters);
1478                 the_lnet.ln_counters = NULL;
1479         }
1480         lnet_destroy_remote_nets_table();
1481         lnet_udsp_destroy(true);
1482         lnet_slab_cleanup();
1483
1484         return 0;
1485 }
1486
1487 struct lnet_ni  *
1488 lnet_net2ni_locked(__u32 net_id, int cpt)
1489 {
1490         struct lnet_ni   *ni;
1491         struct lnet_net  *net;
1492
1493         LASSERT(cpt != LNET_LOCK_EX);
1494
1495         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1496                 if (net->net_id == net_id) {
1497                         ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
1498                                               ni_netlist);
1499                         return ni;
1500                 }
1501         }
1502
1503         return NULL;
1504 }
1505
1506 struct lnet_ni *
1507 lnet_net2ni_addref(__u32 net)
1508 {
1509         struct lnet_ni *ni;
1510
1511         lnet_net_lock(0);
1512         ni = lnet_net2ni_locked(net, 0);
1513         if (ni)
1514                 lnet_ni_addref_locked(ni, 0);
1515         lnet_net_unlock(0);
1516
1517         return ni;
1518 }
1519 EXPORT_SYMBOL(lnet_net2ni_addref);
1520
1521 struct lnet_net *
1522 lnet_get_net_locked(__u32 net_id)
1523 {
1524         struct lnet_net  *net;
1525
1526         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1527                 if (net->net_id == net_id)
1528                         return net;
1529         }
1530
1531         return NULL;
1532 }
1533
1534 void
1535 lnet_net_clr_pref_rtrs(struct lnet_net *net)
1536 {
1537         struct list_head zombies;
1538         struct lnet_nid_list *ne;
1539         struct lnet_nid_list *tmp;
1540
1541         INIT_LIST_HEAD(&zombies);
1542
1543         lnet_net_lock(LNET_LOCK_EX);
1544         list_splice_init(&net->net_rtr_pref_nids, &zombies);
1545         lnet_net_unlock(LNET_LOCK_EX);
1546
1547         list_for_each_entry_safe(ne, tmp, &zombies, nl_list) {
1548                 list_del_init(&ne->nl_list);
1549                 LIBCFS_FREE(ne, sizeof(*ne));
1550         }
1551 }
1552
1553 int
1554 lnet_net_add_pref_rtr(struct lnet_net *net,
1555                       struct lnet_nid *gw_nid)
1556 __must_hold(&the_lnet.ln_api_mutex)
1557 {
1558         struct lnet_nid_list *ne;
1559
1560         /* This function is called with api_mutex held. When the api_mutex
1561          * is held the list can not be modified, as it is only modified as
1562          * a result of applying a UDSP and that happens under api_mutex
1563          * lock.
1564          */
1565         list_for_each_entry(ne, &net->net_rtr_pref_nids, nl_list) {
1566                 if (nid_same(&ne->nl_nid, gw_nid))
1567                         return -EEXIST;
1568         }
1569
1570         LIBCFS_ALLOC(ne, sizeof(*ne));
1571         if (!ne)
1572                 return -ENOMEM;
1573
1574         ne->nl_nid = *gw_nid;
1575
1576         /* Lock the cpt to protect against addition and checks in the
1577          * selection algorithm
1578          */
1579         lnet_net_lock(LNET_LOCK_EX);
1580         list_add(&ne->nl_list, &net->net_rtr_pref_nids);
1581         lnet_net_unlock(LNET_LOCK_EX);
1582
1583         return 0;
1584 }
1585
1586 static unsigned int
1587 lnet_nid4_cpt_hash(lnet_nid_t nid, unsigned int number)
1588 {
1589         __u64 key = nid;
1590         __u16 lnd = LNET_NETTYP(LNET_NIDNET(nid));
1591         unsigned int cpt;
1592
1593         if (lnd == KFILND || lnd == GNILND) {
1594                 cpt = hash_long(key, LNET_CPT_BITS);
1595
1596                 /* NB: The number of CPTs needn't be a power of 2 */
1597                 if (cpt >= number)
1598                         cpt = (key + cpt + (cpt >> 1)) % number;
1599         } else {
1600                 __u64 pair_bits = 0x0001000100010001LLU;
1601                 __u64 mask = pair_bits * 0xFF;
1602                 __u64 pair_sum;
1603                 /* For ipv4 NIDs, use (sum-by-multiplication of nid bytes) mod
1604                  * (number of CPTs) to match nid to a CPT.
1605                  */
1606                 pair_sum = (key & mask) + ((key >> 8) & mask);
1607                 pair_sum = (pair_sum * pair_bits) >> 48;
1608                 cpt = (unsigned int)(pair_sum) % number;
1609         }
1610
1611         CDEBUG(D_NET, "Match nid %s to cpt %u\n",
1612                libcfs_nid2str(nid), cpt);
1613
1614         return cpt;
1615 }
1616
1617 unsigned int
1618 lnet_nid_cpt_hash(struct lnet_nid *nid, unsigned int number)
1619 {
1620         unsigned int val;
1621         u32 h = 0;
1622         int i;
1623
1624         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1625
1626         if (number == 1)
1627                 return 0;
1628
1629         if (nid_is_nid4(nid))
1630                 return lnet_nid4_cpt_hash(lnet_nid_to_nid4(nid), number);
1631
1632         for (i = 0; i < 4; i++)
1633                 h = cfs_hash_32(nid->nid_addr[i]^h, 32);
1634         val = cfs_hash_32(LNET_NID_NET(nid) ^ h, LNET_CPT_BITS);
1635         if (val < number)
1636                 return val;
1637         return (unsigned int)(h + val + (val >> 1)) % number;
1638 }
1639
1640 int
1641 lnet_cpt_of_nid_locked(struct lnet_nid *nid, struct lnet_ni *ni)
1642 {
1643         struct lnet_net *net;
1644
1645         /* must called with hold of lnet_net_lock */
1646         if (LNET_CPT_NUMBER == 1)
1647                 return 0; /* the only one */
1648
1649         /*
1650          * If NI is provided then use the CPT identified in the NI cpt
1651          * list if one exists. If one doesn't exist, then that NI is
1652          * associated with all CPTs and it follows that the net it belongs
1653          * to is implicitly associated with all CPTs, so just hash the nid
1654          * and return that.
1655          */
1656         if (ni != NULL) {
1657                 if (ni->ni_cpts != NULL)
1658                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1659                                                              ni->ni_ncpts)];
1660                 else
1661                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1662         }
1663
1664         /* no NI provided so look at the net */
1665         net = lnet_get_net_locked(LNET_NID_NET(nid));
1666
1667         if (net != NULL && net->net_cpts != NULL) {
1668                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1669         }
1670
1671         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1672 }
1673
1674 int
1675 lnet_nid2cpt(struct lnet_nid *nid, struct lnet_ni *ni)
1676 {
1677         int     cpt;
1678         int     cpt2;
1679
1680         if (LNET_CPT_NUMBER == 1)
1681                 return 0; /* the only one */
1682
1683         cpt = lnet_net_lock_current();
1684
1685         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1686
1687         lnet_net_unlock(cpt);
1688
1689         return cpt2;
1690 }
1691 EXPORT_SYMBOL(lnet_nid2cpt);
1692
1693 int
1694 lnet_cpt_of_nid(lnet_nid_t nid4, struct lnet_ni *ni)
1695 {
1696         struct lnet_nid nid;
1697
1698         if (LNET_CPT_NUMBER == 1)
1699                 return 0; /* the only one */
1700
1701         lnet_nid4_to_nid(nid4, &nid);
1702         return lnet_nid2cpt(&nid, ni);
1703 }
1704 EXPORT_SYMBOL(lnet_cpt_of_nid);
1705
1706 int
1707 lnet_islocalnet_locked(__u32 net_id)
1708 {
1709         struct lnet_net *net;
1710         bool local;
1711
1712         net = lnet_get_net_locked(net_id);
1713
1714         local = net != NULL;
1715
1716         return local;
1717 }
1718
1719 int
1720 lnet_islocalnet(__u32 net_id)
1721 {
1722         int cpt;
1723         bool local;
1724
1725         cpt = lnet_net_lock_current();
1726
1727         local = lnet_islocalnet_locked(net_id);
1728
1729         lnet_net_unlock(cpt);
1730
1731         return local;
1732 }
1733
1734 struct lnet_ni  *
1735 lnet_nid_to_ni_locked(struct lnet_nid *nid, int cpt)
1736 {
1737         struct lnet_net  *net;
1738         struct lnet_ni *ni;
1739
1740         LASSERT(cpt != LNET_LOCK_EX);
1741
1742         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1743                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1744                         if (nid_same(&ni->ni_nid, nid))
1745                                 return ni;
1746                 }
1747         }
1748
1749         return NULL;
1750 }
1751
1752 struct lnet_ni *
1753 lnet_nid_to_ni_addref(struct lnet_nid *nid)
1754 {
1755         struct lnet_ni *ni;
1756
1757         lnet_net_lock(0);
1758         ni = lnet_nid_to_ni_locked(nid, 0);
1759         if (ni)
1760                 lnet_ni_addref_locked(ni, 0);
1761         lnet_net_unlock(0);
1762
1763         return ni;
1764 }
1765 EXPORT_SYMBOL(lnet_nid_to_ni_addref);
1766
1767 int
1768 lnet_islocalnid(struct lnet_nid *nid)
1769 {
1770         struct lnet_ni  *ni;
1771         int             cpt;
1772
1773         cpt = lnet_net_lock_current();
1774         ni = lnet_nid_to_ni_locked(nid, cpt);
1775         lnet_net_unlock(cpt);
1776
1777         return ni != NULL;
1778 }
1779
1780 int
1781 lnet_count_acceptor_nets(void)
1782 {
1783         /* Return the # of NIs that need the acceptor. */
1784         int              count = 0;
1785         struct lnet_net  *net;
1786         int              cpt;
1787
1788         cpt = lnet_net_lock_current();
1789         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1790                 /* all socklnd type networks should have the acceptor
1791                  * thread started */
1792                 if (net->net_lnd->lnd_accept != NULL)
1793                         count++;
1794         }
1795
1796         lnet_net_unlock(cpt);
1797
1798         return count;
1799 }
1800
1801 struct lnet_ping_buffer *
1802 lnet_ping_buffer_alloc(int nbytes, gfp_t gfp)
1803 {
1804         struct lnet_ping_buffer *pbuf;
1805
1806         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nbytes), gfp);
1807         if (pbuf) {
1808                 pbuf->pb_nbytes = nbytes;       /* sizeof of pb_info */
1809                 pbuf->pb_needs_post = false;
1810                 atomic_set(&pbuf->pb_refcnt, 1);
1811         }
1812
1813         return pbuf;
1814 }
1815
1816 void
1817 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1818 {
1819         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1820         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nbytes));
1821 }
1822
1823 static struct lnet_ping_buffer *
1824 lnet_ping_target_create(int nbytes)
1825 {
1826         struct lnet_ping_buffer *pbuf;
1827
1828         pbuf = lnet_ping_buffer_alloc(nbytes, GFP_NOFS);
1829         if (pbuf == NULL) {
1830                 CERROR("Can't allocate ping source [%d]\n", nbytes);
1831                 return NULL;
1832         }
1833
1834         pbuf->pb_info.pi_nnis = 0;
1835         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1836         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1837         pbuf->pb_info.pi_features =
1838                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1839
1840         return pbuf;
1841 }
1842
1843 static inline int
1844 lnet_get_net_ni_bytes_locked(struct lnet_net *net)
1845 {
1846         struct lnet_ni *ni;
1847         int bytes = 0;
1848
1849         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1850                 bytes += lnet_ping_sts_size(&ni->ni_nid);
1851
1852         return bytes;
1853 }
1854
1855 static inline int
1856 lnet_get_ni_bytes(void)
1857 {
1858         struct lnet_ni *ni;
1859         struct lnet_net *net;
1860         int bytes = 0;
1861
1862         lnet_net_lock(0);
1863
1864         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1865                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1866                         bytes += lnet_ping_sts_size(&ni->ni_nid);
1867         }
1868
1869         lnet_net_unlock(0);
1870
1871         return bytes;
1872 }
1873
1874 void
1875 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1876 {
1877         struct lnet_ni_large_status *lstat, *lend;
1878         struct lnet_ni_status *stat, *end;
1879         int nnis;
1880         int i;
1881
1882         __swab32s(&pbuf->pb_info.pi_magic);
1883         __swab32s(&pbuf->pb_info.pi_features);
1884         __swab32s(&pbuf->pb_info.pi_pid);
1885         __swab32s(&pbuf->pb_info.pi_nnis);
1886         nnis = pbuf->pb_info.pi_nnis;
1887         stat = &pbuf->pb_info.pi_ni[0];
1888         end = (void *)&pbuf->pb_info + pbuf->pb_nbytes;
1889         for (i = 0; i < nnis && stat + 1 <= end; i++, stat++) {
1890                 __swab64s(&stat->ns_nid);
1891                 __swab32s(&stat->ns_status);
1892                 if (i == 0)
1893                         /* Might be total size */
1894                         __swab32s(&stat->ns_msg_size);
1895         }
1896         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_LARGE_ADDR))
1897                 return;
1898
1899         lstat = (struct lnet_ni_large_status *)stat;
1900         lend = (void *)end;
1901         while (lstat + 1 <= lend) {
1902                 __swab32s(&lstat->ns_status);
1903                 /* struct lnet_nid never needs to be swabed */
1904                 lstat = lnet_ping_sts_next(lstat);
1905         }
1906 }
1907
1908 int
1909 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1910 {
1911         if (!pinfo)
1912                 return -EINVAL;
1913         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1914                 return -EPROTO;
1915         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1916                 return -EPROTO;
1917         /* Loopback is guaranteed to be present */
1918         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1919                 return -ERANGE;
1920         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1921                 return -EPROTO;
1922         return 0;
1923 }
1924
1925 static void
1926 lnet_ping_target_destroy(void)
1927 {
1928         struct lnet_net *net;
1929         struct lnet_ni  *ni;
1930
1931         lnet_net_lock(LNET_LOCK_EX);
1932
1933         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1934                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1935                         lnet_ni_lock(ni);
1936                         ni->ni_status = NULL;
1937                         lnet_ni_unlock(ni);
1938                 }
1939         }
1940
1941         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1942         the_lnet.ln_ping_target = NULL;
1943
1944         lnet_net_unlock(LNET_LOCK_EX);
1945 }
1946
1947 static void
1948 lnet_ping_target_event_handler(struct lnet_event *event)
1949 {
1950         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1951
1952         if (event->unlinked)
1953                 lnet_ping_buffer_decref(pbuf);
1954 }
1955
1956 static int
1957 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1958                        struct lnet_handle_md *ping_mdh,
1959                        int ni_bytes, bool set_eq)
1960 {
1961         struct lnet_processid id = {
1962                 .nid = LNET_ANY_NID,
1963                 .pid = LNET_PID_ANY
1964         };
1965         struct lnet_me *me;
1966         struct lnet_md md = { NULL };
1967         int rc;
1968
1969         if (set_eq)
1970                 the_lnet.ln_ping_target_handler =
1971                         lnet_ping_target_event_handler;
1972
1973         *ppbuf = lnet_ping_target_create(ni_bytes);
1974         if (*ppbuf == NULL) {
1975                 rc = -ENOMEM;
1976                 goto fail_free_eq;
1977         }
1978
1979         /* Ping target ME/MD */
1980         me = LNetMEAttach(LNET_RESERVED_PORTAL, &id,
1981                           LNET_PROTO_PING_MATCHBITS, 0,
1982                           LNET_UNLINK, LNET_INS_AFTER);
1983         if (IS_ERR(me)) {
1984                 rc = PTR_ERR(me);
1985                 CERROR("Can't create ping target ME: %d\n", rc);
1986                 goto fail_decref_ping_buffer;
1987         }
1988
1989         /* initialize md content */
1990         md.start     = &(*ppbuf)->pb_info;
1991         md.length    = (*ppbuf)->pb_nbytes;
1992         md.threshold = LNET_MD_THRESH_INF;
1993         md.max_size  = 0;
1994         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1995                        LNET_MD_MANAGE_REMOTE;
1996         md.handler   = the_lnet.ln_ping_target_handler;
1997         md.user_ptr  = *ppbuf;
1998
1999         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
2000         if (rc != 0) {
2001                 CERROR("Can't attach ping target MD: %d\n", rc);
2002                 goto fail_decref_ping_buffer;
2003         }
2004         lnet_ping_buffer_addref(*ppbuf);
2005
2006         return 0;
2007
2008 fail_decref_ping_buffer:
2009         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
2010         lnet_ping_buffer_decref(*ppbuf);
2011         *ppbuf = NULL;
2012 fail_free_eq:
2013         return rc;
2014 }
2015
2016 static void
2017 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
2018                     struct lnet_handle_md *ping_mdh)
2019 {
2020         LNetMDUnlink(*ping_mdh);
2021         LNetInvalidateMDHandle(ping_mdh);
2022
2023         /* NB the MD could be busy; this just starts the unlink */
2024         wait_var_event_warning(&pbuf->pb_refcnt,
2025                                atomic_read(&pbuf->pb_refcnt) <= 1,
2026                                "Still waiting for ping data MD to unlink\n");
2027 }
2028
2029 static void
2030 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
2031 {
2032         struct lnet_ni *ni;
2033         struct lnet_net *net;
2034         struct lnet_ni_status *ns, *end;
2035         struct lnet_ni_large_status *lns, *lend;
2036         int rc;
2037
2038         pbuf->pb_info.pi_nnis = 0;
2039         ns = &pbuf->pb_info.pi_ni[0];
2040         end = (void *)&pbuf->pb_info + pbuf->pb_nbytes;
2041         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2042                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2043                         if (!nid_is_nid4(&ni->ni_nid)) {
2044                                 if (ns == &pbuf->pb_info.pi_ni[1]) {
2045                                         /* This is primary, and it is long */
2046                                         pbuf->pb_info.pi_features |=
2047                                                 LNET_PING_FEAT_PRIMARY_LARGE;
2048                                 }
2049                                 continue;
2050                         }
2051                         LASSERT(ns + 1 <= end);
2052                         ns->ns_nid = lnet_nid_to_nid4(&ni->ni_nid);
2053
2054                         lnet_ni_lock(ni);
2055                         ns->ns_status = lnet_ni_get_status_locked(ni);
2056                         ni->ni_status = &ns->ns_status;
2057                         lnet_ni_unlock(ni);
2058
2059                         pbuf->pb_info.pi_nnis++;
2060                         ns++;
2061                 }
2062         }
2063
2064         lns = (void *)ns;
2065         lend = (void *)end;
2066         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2067                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2068                         if (nid_is_nid4(&ni->ni_nid))
2069                                 continue;
2070                         LASSERT(lns + 1 <= lend);
2071
2072                         lns->ns_nid = ni->ni_nid;
2073
2074                         lnet_ni_lock(ni);
2075                         ns->ns_status = lnet_ni_get_status_locked(ni);
2076                         ni->ni_status = &lns->ns_status;
2077                         lnet_ni_unlock(ni);
2078
2079                         lns = lnet_ping_sts_next(lns);
2080                 }
2081         }
2082         if ((void *)lns > (void *)ns) {
2083                 /* Record total info size */
2084                 pbuf->pb_info.pi_ni[0].ns_msg_size =
2085                         (void *)lns - (void *)&pbuf->pb_info;
2086                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_LARGE_ADDR;
2087         }
2088
2089         /* We (ab)use the ns_status of the loopback interface to
2090          * transmit the sequence number. The first interface listed
2091          * must be the loopback interface.
2092          */
2093         rc = lnet_ping_info_validate(&pbuf->pb_info);
2094         if (rc) {
2095                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
2096                 LBUG();
2097         }
2098         LNET_PING_BUFFER_SEQNO(pbuf) =
2099                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
2100 }
2101
2102 static void
2103 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
2104                         struct lnet_handle_md ping_mdh)
2105 {
2106         struct lnet_ping_buffer *old_pbuf = NULL;
2107         struct lnet_handle_md old_ping_md;
2108
2109         /* switch the NIs to point to the new ping info created */
2110         lnet_net_lock(LNET_LOCK_EX);
2111
2112         if (!the_lnet.ln_routing)
2113                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
2114         if (!lnet_peer_discovery_disabled)
2115                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
2116
2117         /* Ensure only known feature bits have been set. */
2118         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
2119         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
2120
2121         lnet_ping_target_install_locked(pbuf);
2122
2123         if (the_lnet.ln_ping_target) {
2124                 old_pbuf = the_lnet.ln_ping_target;
2125                 old_ping_md = the_lnet.ln_ping_target_md;
2126         }
2127         the_lnet.ln_ping_target_md = ping_mdh;
2128         the_lnet.ln_ping_target = pbuf;
2129
2130         lnet_net_unlock(LNET_LOCK_EX);
2131
2132         if (old_pbuf) {
2133                 /* unlink and free the old ping info */
2134                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
2135                 lnet_ping_buffer_decref(old_pbuf);
2136         }
2137
2138         lnet_push_update_to_peers(0);
2139 }
2140
2141 static void
2142 lnet_ping_target_fini(void)
2143 {
2144         lnet_ping_md_unlink(the_lnet.ln_ping_target,
2145                             &the_lnet.ln_ping_target_md);
2146
2147         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
2148         lnet_ping_target_destroy();
2149 }
2150
2151 /* Resize the push target. */
2152 int lnet_push_target_resize(void)
2153 {
2154         struct lnet_handle_md mdh;
2155         struct lnet_handle_md old_mdh;
2156         struct lnet_ping_buffer *pbuf;
2157         struct lnet_ping_buffer *old_pbuf;
2158         int nbytes;
2159         int rc;
2160
2161 again:
2162         nbytes = the_lnet.ln_push_target_nbytes;
2163         if (nbytes <= 0) {
2164                 CDEBUG(D_NET, "Invalid nbytes %d\n", nbytes);
2165                 return -EINVAL;
2166         }
2167
2168         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
2169          * dropped when we need to resize again (see "old_pbuf" below) or when
2170          * LNet is shutdown (see lnet_push_target_fini())
2171          */
2172         pbuf = lnet_ping_buffer_alloc(nbytes, GFP_NOFS);
2173         if (!pbuf) {
2174                 CDEBUG(D_NET, "Can't allocate pbuf for nbytes %d\n", nbytes);
2175                 return -ENOMEM;
2176         }
2177
2178         rc = lnet_push_target_post(pbuf, &mdh);
2179         if (rc) {
2180                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
2181                 lnet_ping_buffer_decref(pbuf);
2182                 return rc;
2183         }
2184
2185         lnet_net_lock(LNET_LOCK_EX);
2186         old_pbuf = the_lnet.ln_push_target;
2187         old_mdh = the_lnet.ln_push_target_md;
2188         the_lnet.ln_push_target = pbuf;
2189         the_lnet.ln_push_target_md = mdh;
2190         lnet_net_unlock(LNET_LOCK_EX);
2191
2192         if (old_pbuf) {
2193                 LNetMDUnlink(old_mdh);
2194                 /* Drop ref set by lnet_ping_buffer_alloc() */
2195                 lnet_ping_buffer_decref(old_pbuf);
2196         }
2197
2198         /* Received another push or reply that requires a larger buffer */
2199         if (nbytes < the_lnet.ln_push_target_nbytes)
2200                 goto again;
2201
2202         CDEBUG(D_NET, "nbytes %d success\n", nbytes);
2203         return 0;
2204 }
2205
2206 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
2207                           struct lnet_handle_md *mdhp)
2208 {
2209         struct lnet_processid id = { LNET_ANY_NID, LNET_PID_ANY };
2210         struct lnet_md md = { NULL };
2211         struct lnet_me *me;
2212         int rc;
2213
2214         me = LNetMEAttach(LNET_RESERVED_PORTAL, &id,
2215                           LNET_PROTO_PING_MATCHBITS, 0,
2216                           LNET_UNLINK, LNET_INS_AFTER);
2217         if (IS_ERR(me)) {
2218                 rc = PTR_ERR(me);
2219                 CERROR("Can't create push target ME: %d\n", rc);
2220                 return rc;
2221         }
2222
2223         pbuf->pb_needs_post = false;
2224
2225         /* This reference is dropped by lnet_push_target_event_handler() */
2226         lnet_ping_buffer_addref(pbuf);
2227
2228         /* initialize md content */
2229         md.start     = &pbuf->pb_info;
2230         md.length    = pbuf->pb_nbytes;
2231         md.threshold = 1;
2232         md.max_size  = 0;
2233         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
2234         md.user_ptr  = pbuf;
2235         md.handler   = the_lnet.ln_push_target_handler;
2236
2237         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
2238         if (rc) {
2239                 CERROR("Can't attach push MD: %d\n", rc);
2240                 lnet_ping_buffer_decref(pbuf);
2241                 pbuf->pb_needs_post = true;
2242                 return rc;
2243         }
2244
2245         CDEBUG(D_NET, "posted push target %p\n", pbuf);
2246
2247         return 0;
2248 }
2249
2250 static void lnet_push_target_event_handler(struct lnet_event *ev)
2251 {
2252         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
2253
2254         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
2255                ev->unlinked);
2256
2257         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2258                 lnet_swap_pinginfo(pbuf);
2259
2260         if (ev->type == LNET_EVENT_UNLINK) {
2261                 /* Drop ref added by lnet_push_target_post() */
2262                 lnet_ping_buffer_decref(pbuf);
2263                 return;
2264         }
2265
2266         lnet_peer_push_event(ev);
2267         if (ev->unlinked)
2268                 /* Drop ref added by lnet_push_target_post */
2269                 lnet_ping_buffer_decref(pbuf);
2270 }
2271
2272 /* Initialize the push target. */
2273 static int lnet_push_target_init(void)
2274 {
2275         int rc;
2276
2277         if (the_lnet.ln_push_target)
2278                 return -EALREADY;
2279
2280         the_lnet.ln_push_target_handler =
2281                 lnet_push_target_event_handler;
2282
2283         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2284         LASSERT(rc == 0);
2285
2286         /* Start at the required minimum, we'll enlarge if required. */
2287         the_lnet.ln_push_target_nbytes = LNET_PING_INFO_MIN_SIZE;
2288
2289         rc = lnet_push_target_resize();
2290         if (rc) {
2291                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2292                 the_lnet.ln_push_target_handler = NULL;
2293         }
2294
2295         return rc;
2296 }
2297
2298 /* Clean up the push target. */
2299 static void lnet_push_target_fini(void)
2300 {
2301         if (!the_lnet.ln_push_target)
2302                 return;
2303
2304         /* Unlink and invalidate to prevent new references. */
2305         LNetMDUnlink(the_lnet.ln_push_target_md);
2306         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2307
2308         /* Wait for the unlink to complete. */
2309         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2310                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2311                                "Still waiting for ping data MD to unlink\n");
2312
2313         /* Drop ref set by lnet_ping_buffer_alloc() */
2314         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2315         the_lnet.ln_push_target = NULL;
2316         the_lnet.ln_push_target_nbytes = 0;
2317
2318         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2319         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2320         the_lnet.ln_push_target_handler = NULL;
2321 }
2322
2323 static int
2324 lnet_ni_tq_credits(struct lnet_ni *ni)
2325 {
2326         int     credits;
2327
2328         LASSERT(ni->ni_ncpts >= 1);
2329
2330         if (ni->ni_ncpts == 1)
2331                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2332
2333         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2334         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2335         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2336
2337         return credits;
2338 }
2339
2340 static void
2341 lnet_ni_unlink_locked(struct lnet_ni *ni)
2342 {
2343         /* move it to zombie list and nobody can find it anymore */
2344         LASSERT(!list_empty(&ni->ni_netlist));
2345         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2346         lnet_ni_decref_locked(ni, 0);
2347 }
2348
2349 static void
2350 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2351 {
2352         int             i;
2353         int             islo;
2354         struct lnet_ni  *ni;
2355         struct list_head *zombie_list = &net->net_ni_zombie;
2356
2357         /*
2358          * Now wait for the NIs I just nuked to show up on the zombie
2359          * list and shut them down in guaranteed thread context
2360          */
2361         i = 2;
2362         while ((ni = list_first_entry_or_null(zombie_list,
2363                                               struct lnet_ni,
2364                                               ni_netlist)) != NULL) {
2365                 int *ref;
2366                 int j;
2367
2368                 list_del_init(&ni->ni_netlist);
2369                 /* the ni should be in deleting state. If it's not it's
2370                  * a bug */
2371                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2372                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2373                         if (*ref == 0)
2374                                 continue;
2375                         /* still busy, add it back to zombie list */
2376                         list_add(&ni->ni_netlist, zombie_list);
2377                         break;
2378                 }
2379
2380                 if (!list_empty(&ni->ni_netlist)) {
2381                         /* Unlock mutex while waiting to allow other
2382                          * threads to read the LNet state and fall through
2383                          * to avoid deadlock
2384                          */
2385                         lnet_net_unlock(LNET_LOCK_EX);
2386                         mutex_unlock(&the_lnet.ln_api_mutex);
2387
2388                         ++i;
2389                         if ((i & (-i)) == i) {
2390                                 CDEBUG(D_WARNING,
2391                                        "Waiting for zombie LNI %s\n",
2392                                        libcfs_nidstr(&ni->ni_nid));
2393                         }
2394                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2395
2396                         mutex_lock(&the_lnet.ln_api_mutex);
2397                         lnet_net_lock(LNET_LOCK_EX);
2398                         continue;
2399                 }
2400
2401                 lnet_net_unlock(LNET_LOCK_EX);
2402
2403                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2404
2405                 LASSERT(!in_interrupt());
2406                 /* Holding the LND mutex makes it safe for lnd_shutdown
2407                  * to call module_put(). Module unload cannot finish
2408                  * until lnet_unregister_lnd() completes, and that
2409                  * requires the LND mutex.
2410                  */
2411                 mutex_unlock(&the_lnet.ln_api_mutex);
2412                 mutex_lock(&the_lnet.ln_lnd_mutex);
2413                 (net->net_lnd->lnd_shutdown)(ni);
2414                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2415                 mutex_lock(&the_lnet.ln_api_mutex);
2416
2417                 if (!islo)
2418                         CDEBUG(D_LNI, "Removed LNI %s\n",
2419                               libcfs_nidstr(&ni->ni_nid));
2420
2421                 lnet_ni_free(ni);
2422                 i = 2;
2423                 lnet_net_lock(LNET_LOCK_EX);
2424         }
2425 }
2426
2427 /* shutdown down the NI and release refcount */
2428 static void
2429 lnet_shutdown_lndni(struct lnet_ni *ni)
2430 {
2431         int i;
2432         struct lnet_net *net = ni->ni_net;
2433
2434         lnet_net_lock(LNET_LOCK_EX);
2435         lnet_ni_lock(ni);
2436         ni->ni_state = LNET_NI_STATE_DELETING;
2437         lnet_ni_unlock(ni);
2438         lnet_ni_unlink_locked(ni);
2439         lnet_incr_dlc_seq();
2440         lnet_net_unlock(LNET_LOCK_EX);
2441
2442         /* clear messages for this NI on the lazy portal */
2443         for (i = 0; i < the_lnet.ln_nportals; i++)
2444                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2445
2446         lnet_net_lock(LNET_LOCK_EX);
2447         lnet_clear_zombies_nis_locked(net);
2448         lnet_net_unlock(LNET_LOCK_EX);
2449 }
2450
2451 static void
2452 lnet_shutdown_lndnet(struct lnet_net *net)
2453 {
2454         struct lnet_ni *ni;
2455
2456         lnet_net_lock(LNET_LOCK_EX);
2457
2458         list_del_init(&net->net_list);
2459
2460         while ((ni = list_first_entry_or_null(&net->net_ni_list,
2461                                               struct lnet_ni,
2462                                               ni_netlist)) != NULL) {
2463                 lnet_net_unlock(LNET_LOCK_EX);
2464                 lnet_shutdown_lndni(ni);
2465                 lnet_net_lock(LNET_LOCK_EX);
2466         }
2467
2468         lnet_net_unlock(LNET_LOCK_EX);
2469
2470         /* Do peer table cleanup for this net */
2471         lnet_peer_tables_cleanup(net);
2472
2473         lnet_net_free(net);
2474 }
2475
2476 static void
2477 lnet_shutdown_lndnets(void)
2478 {
2479         struct lnet_net *net;
2480         LIST_HEAD(resend);
2481         struct lnet_msg *msg, *tmp;
2482
2483         /* NB called holding the global mutex */
2484
2485         /* All quiet on the API front */
2486         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING ||
2487                 the_lnet.ln_state == LNET_STATE_STOPPING);
2488         LASSERT(the_lnet.ln_refcount == 0);
2489
2490         lnet_net_lock(LNET_LOCK_EX);
2491         the_lnet.ln_state = LNET_STATE_STOPPING;
2492
2493         /*
2494          * move the nets to the zombie list to avoid them being
2495          * picked up for new work. LONET is also included in the
2496          * Nets that will be moved to the zombie list
2497          */
2498         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2499
2500         /* Drop the cached loopback Net. */
2501         if (the_lnet.ln_loni != NULL) {
2502                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2503                 the_lnet.ln_loni = NULL;
2504         }
2505         lnet_net_unlock(LNET_LOCK_EX);
2506
2507         /* iterate through the net zombie list and delete each net */
2508         while ((net = list_first_entry_or_null(&the_lnet.ln_net_zombie,
2509                                                struct lnet_net,
2510                                                net_list)) != NULL)
2511                 lnet_shutdown_lndnet(net);
2512
2513         spin_lock(&the_lnet.ln_msg_resend_lock);
2514         list_splice(&the_lnet.ln_msg_resend, &resend);
2515         spin_unlock(&the_lnet.ln_msg_resend_lock);
2516
2517         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2518                 list_del_init(&msg->msg_list);
2519                 msg->msg_no_resend = true;
2520                 lnet_finalize(msg, -ECANCELED);
2521         }
2522
2523         lnet_net_lock(LNET_LOCK_EX);
2524         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2525         lnet_net_unlock(LNET_LOCK_EX);
2526 }
2527
2528 static int
2529 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2530 {
2531         int                     rc = -EINVAL;
2532         struct lnet_tx_queue    *tq;
2533         int                     i;
2534         struct lnet_net         *net = ni->ni_net;
2535
2536         mutex_lock(&the_lnet.ln_lnd_mutex);
2537
2538         if (tun) {
2539                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2540                 ni->ni_lnd_tunables_set = true;
2541         }
2542
2543         rc = (net->net_lnd->lnd_startup)(ni);
2544
2545         mutex_unlock(&the_lnet.ln_lnd_mutex);
2546
2547         if (rc != 0) {
2548                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2549                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2550                 goto failed0;
2551         }
2552
2553         /* We keep a reference on the loopback net through the loopback NI */
2554         if (net->net_lnd->lnd_type == LOLND) {
2555                 lnet_ni_addref(ni);
2556                 LASSERT(the_lnet.ln_loni == NULL);
2557                 the_lnet.ln_loni = ni;
2558                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2559                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2560                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2561                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2562                 return 0;
2563         }
2564
2565         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2566             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2567                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2568                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2569                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2570                                         "" : "per-peer ");
2571                 /* shutdown the NI since if we get here then it must've already
2572                  * been started
2573                  */
2574                 lnet_shutdown_lndni(ni);
2575                 return -EINVAL;
2576         }
2577
2578         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2579                 tq->tq_credits_min =
2580                 tq->tq_credits_max =
2581                 tq->tq_credits = lnet_ni_tq_credits(ni);
2582         }
2583
2584         atomic_set(&ni->ni_tx_credits,
2585                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2586         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2587
2588         /* Nodes with small feet have little entropy. The NID for this
2589          * node gives the most entropy in the low bits.
2590          */
2591         add_device_randomness(&ni->ni_nid, sizeof(ni->ni_nid));
2592
2593         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2594                 libcfs_nidstr(&ni->ni_nid),
2595                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2596                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2597                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2598                 ni->ni_net->net_tunables.lct_peer_timeout);
2599
2600         return 0;
2601 failed0:
2602         lnet_ni_free(ni);
2603         return rc;
2604 }
2605
2606 static const struct lnet_lnd *lnet_load_lnd(u32 lnd_type)
2607 {
2608         const struct lnet_lnd *lnd;
2609         int rc = 0;
2610
2611         mutex_lock(&the_lnet.ln_lnd_mutex);
2612         lnd = lnet_find_lnd_by_type(lnd_type);
2613         if (!lnd) {
2614                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2615                 rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2616                 mutex_lock(&the_lnet.ln_lnd_mutex);
2617
2618                 lnd = lnet_find_lnd_by_type(lnd_type);
2619                 if (!lnd) {
2620                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2621                         CERROR("Can't load LND %s, module %s, rc=%d\n",
2622                         libcfs_lnd2str(lnd_type),
2623                         libcfs_lnd2modname(lnd_type), rc);
2624 #ifndef HAVE_MODULE_LOADING_SUPPORT
2625                         LCONSOLE_ERROR_MSG(0x104,
2626                                            "Your kernel must be compiled with kernel module loading support.");
2627 #endif
2628                         return ERR_PTR(-EINVAL);
2629                 }
2630         }
2631         mutex_unlock(&the_lnet.ln_lnd_mutex);
2632
2633         return lnd;
2634 }
2635
2636 static int
2637 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2638 {
2639         struct lnet_ni *ni;
2640         struct lnet_net *net_l = NULL;
2641         LIST_HEAD(local_ni_list);
2642         int rc;
2643         int ni_count = 0;
2644         __u32 lnd_type;
2645         const struct lnet_lnd  *lnd;
2646         int peer_timeout =
2647                 net->net_tunables.lct_peer_timeout;
2648         int maxtxcredits =
2649                 net->net_tunables.lct_max_tx_credits;
2650         int peerrtrcredits =
2651                 net->net_tunables.lct_peer_rtr_credits;
2652
2653         /*
2654          * make sure that this net is unique. If it isn't then
2655          * we are adding interfaces to an already existing network, and
2656          * 'net' is just a convenient way to pass in the list.
2657          * if it is unique we need to find the LND and load it if
2658          * necessary.
2659          */
2660         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2661                 lnd_type = LNET_NETTYP(net->net_id);
2662
2663                 lnd = lnet_load_lnd(lnd_type);
2664                 if (IS_ERR(lnd)) {
2665                         rc = PTR_ERR(lnd);
2666                         goto failed0;
2667                 }
2668
2669                 mutex_lock(&the_lnet.ln_lnd_mutex);
2670                 net->net_lnd = lnd;
2671                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2672
2673                 net_l = net;
2674         }
2675
2676         /*
2677          * net_l: if the network being added is unique then net_l
2678          *        will point to that network
2679          *        if the network being added is not unique then
2680          *        net_l points to the existing network.
2681          *
2682          * When we enter the loop below, we'll pick NIs off he
2683          * network beign added and start them up, then add them to
2684          * a local ni list. Once we've successfully started all
2685          * the NIs then we join the local NI list (of started up
2686          * networks) with the net_l->net_ni_list, which should
2687          * point to the correct network to add the new ni list to
2688          *
2689          * If any of the new NIs fail to start up, then we want to
2690          * iterate through the local ni list, which should include
2691          * any NIs which were successfully started up, and shut
2692          * them down.
2693          *
2694          * After than we want to delete the network being added,
2695          * to avoid a memory leak.
2696          */
2697         while ((ni = list_first_entry_or_null(&net->net_ni_added,
2698                                               struct lnet_ni,
2699                                               ni_netlist)) != NULL) {
2700                 list_del_init(&ni->ni_netlist);
2701
2702                 /* make sure that the the NI we're about to start
2703                  * up is actually unique. if it's not fail. */
2704                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2705                                         ni->ni_interface)) {
2706                         rc = -EEXIST;
2707                         goto failed1;
2708                 }
2709
2710                 /* adjust the pointer the parent network, just in case it
2711                  * the net is a duplicate */
2712                 ni->ni_net = net_l;
2713
2714                 rc = lnet_startup_lndni(ni, tun);
2715
2716                 if (rc != 0)
2717                         goto failed1;
2718
2719                 lnet_ni_addref(ni);
2720                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2721
2722                 ni_count++;
2723         }
2724
2725         lnet_net_lock(LNET_LOCK_EX);
2726         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2727         lnet_incr_dlc_seq();
2728
2729         list_for_each_entry(ni, &net_l->net_ni_list, ni_netlist) {
2730                 if (!ni)
2731                         break;
2732                 lnet_ni_lock(ni);
2733                 ni->ni_state = LNET_NI_STATE_ACTIVE;
2734                 lnet_ni_unlock(ni);
2735         }
2736         lnet_net_unlock(LNET_LOCK_EX);
2737
2738         /* if the network is not unique then we don't want to keep
2739          * it around after we're done. Free it. Otherwise add that
2740          * net to the global the_lnet.ln_nets */
2741         if (net_l != net && net_l != NULL) {
2742                 /*
2743                  * TODO - note. currently the tunables can not be updated
2744                  * once added
2745                  */
2746                 lnet_net_free(net);
2747         } else {
2748                 /*
2749                  * restore tunables after it has been overwitten by the
2750                  * lnd
2751                  */
2752                 if (peer_timeout != -1)
2753                         net->net_tunables.lct_peer_timeout = peer_timeout;
2754                 if (maxtxcredits != -1)
2755                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2756                 if (peerrtrcredits != -1)
2757                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2758
2759                 lnet_net_lock(LNET_LOCK_EX);
2760                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2761                 lnet_net_unlock(LNET_LOCK_EX);
2762         }
2763
2764         return ni_count;
2765
2766 failed1:
2767         /*
2768          * shutdown the new NIs that are being started up
2769          * free the NET being started
2770          */
2771         while ((ni = list_first_entry_or_null(&local_ni_list,
2772                                               struct lnet_ni,
2773                                               ni_netlist)) != NULL)
2774                 lnet_shutdown_lndni(ni);
2775
2776 failed0:
2777         lnet_net_free(net);
2778
2779         return rc;
2780 }
2781
2782 static int
2783 lnet_startup_lndnets(struct list_head *netlist)
2784 {
2785         struct lnet_net         *net;
2786         int                     rc;
2787         int                     ni_count = 0;
2788
2789         /*
2790          * Change to running state before bringing up the LNDs. This
2791          * allows lnet_shutdown_lndnets() to assert that we've passed
2792          * through here.
2793          */
2794         lnet_net_lock(LNET_LOCK_EX);
2795         the_lnet.ln_state = LNET_STATE_RUNNING;
2796         lnet_net_unlock(LNET_LOCK_EX);
2797
2798         while ((net = list_first_entry_or_null(netlist,
2799                                                struct lnet_net,
2800                                                net_list)) != NULL) {
2801                 list_del_init(&net->net_list);
2802
2803                 rc = lnet_startup_lndnet(net, NULL);
2804
2805                 if (rc < 0)
2806                         goto failed;
2807
2808                 ni_count += rc;
2809         }
2810
2811         return ni_count;
2812 failed:
2813         lnet_shutdown_lndnets();
2814
2815         return rc;
2816 }
2817
2818 static int lnet_genl_parse_list(struct sk_buff *msg,
2819                                 const struct ln_key_list *data[], u16 idx)
2820 {
2821         const struct ln_key_list *list = data[idx];
2822         const struct ln_key_props *props;
2823         struct nlattr *node;
2824         u16 count;
2825
2826         if (!list)
2827                 return 0;
2828
2829         if (!list->lkl_maxattr)
2830                 return -ERANGE;
2831
2832         props = list->lkl_list;
2833         if (!props)
2834                 return -EINVAL;
2835
2836         node = nla_nest_start(msg, LN_SCALAR_ATTR_LIST);
2837         if (!node)
2838                 return -ENOBUFS;
2839
2840         for (count = 1; count <= list->lkl_maxattr; count++) {
2841                 struct nlattr *key = nla_nest_start(msg, count);
2842
2843                 if (count == 1)
2844                         nla_put_u16(msg, LN_SCALAR_ATTR_LIST_SIZE,
2845                                     list->lkl_maxattr);
2846
2847                 nla_put_u16(msg, LN_SCALAR_ATTR_INDEX, count);
2848                 if (props[count].lkp_value)
2849                         nla_put_string(msg, LN_SCALAR_ATTR_VALUE,
2850                                        props[count].lkp_value);
2851                 if (props[count].lkp_key_format)
2852                         nla_put_u16(msg, LN_SCALAR_ATTR_KEY_FORMAT,
2853                                     props[count].lkp_key_format);
2854                 nla_put_u16(msg, LN_SCALAR_ATTR_NLA_TYPE,
2855                             props[count].lkp_data_type);
2856                 if (props[count].lkp_data_type == NLA_NESTED) {
2857                         int rc;
2858
2859                         rc = lnet_genl_parse_list(msg, data, ++idx);
2860                         if (rc < 0)
2861                                 return rc;
2862                         idx = rc;
2863                 }
2864
2865                 nla_nest_end(msg, key);
2866         }
2867
2868         nla_nest_end(msg, node);
2869         return idx;
2870 }
2871
2872 int lnet_genl_send_scalar_list(struct sk_buff *msg, u32 portid, u32 seq,
2873                                const struct genl_family *family, int flags,
2874                                u8 cmd, const struct ln_key_list *data[])
2875 {
2876         int rc = 0;
2877         void *hdr;
2878
2879         if (!data[0])
2880                 return -EINVAL;
2881
2882         hdr = genlmsg_put(msg, portid, seq, family, flags, cmd);
2883         if (!hdr)
2884                 GOTO(canceled, rc = -EMSGSIZE);
2885
2886         rc = lnet_genl_parse_list(msg, data, 0);
2887         if (rc < 0)
2888                 GOTO(canceled, rc);
2889
2890         genlmsg_end(msg, hdr);
2891 canceled:
2892         if (rc < 0)
2893                 genlmsg_cancel(msg, hdr);
2894         return rc > 0 ? 0 : rc;
2895 }
2896 EXPORT_SYMBOL(lnet_genl_send_scalar_list);
2897
2898 static struct genl_family lnet_family;
2899
2900 /**
2901  * Initialize LNet library.
2902  *
2903  * Automatically called at module loading time. Caller has to call
2904  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2905  * latter returned 0. It must be called exactly once.
2906  *
2907  * \retval 0 on success
2908  * \retval -ve on failures.
2909  */
2910 int lnet_lib_init(void)
2911 {
2912         int rc;
2913
2914         lnet_assert_wire_constants();
2915
2916         /* refer to global cfs_cpt_table for now */
2917         the_lnet.ln_cpt_table = cfs_cpt_tab;
2918         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2919
2920         LASSERT(the_lnet.ln_cpt_number > 0);
2921         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2922                 /* we are under risk of consuming all lh_cookie */
2923                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2924                        "please change setting of CPT-table and retry\n",
2925                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2926                 return -E2BIG;
2927         }
2928
2929         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2930                 the_lnet.ln_cpt_bits++;
2931
2932         rc = lnet_create_locks();
2933         if (rc != 0) {
2934                 CERROR("Can't create LNet global locks: %d\n", rc);
2935                 return rc;
2936         }
2937
2938         rc = genl_register_family(&lnet_family);
2939         if (rc != 0) {
2940                 lnet_destroy_locks();
2941                 CERROR("Can't register LNet netlink family: %d\n", rc);
2942                 return rc;
2943         }
2944
2945         the_lnet.ln_refcount = 0;
2946         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2947         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2948
2949         /* The hash table size is the number of bits it takes to express the set
2950          * ln_num_routes, minus 1 (better to under estimate than over so we
2951          * don't waste memory). */
2952         if (rnet_htable_size <= 0)
2953                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2954         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2955                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2956         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2957                                            order_base_2(rnet_htable_size) - 1);
2958
2959         /* All LNDs apart from the LOLND are in separate modules.  They
2960          * register themselves when their module loads, and unregister
2961          * themselves when their module is unloaded. */
2962         lnet_register_lnd(&the_lolnd);
2963         return 0;
2964 }
2965
2966 /**
2967  * Finalize LNet library.
2968  *
2969  * \pre lnet_lib_init() called with success.
2970  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2971  *
2972  * As this happens at module-unload, all lnds must already be unloaded,
2973  * so they must already be unregistered.
2974  */
2975 void lnet_lib_exit(void)
2976 {
2977         int i;
2978
2979         LASSERT(the_lnet.ln_refcount == 0);
2980         lnet_unregister_lnd(&the_lolnd);
2981         for (i = 0; i < NUM_LNDS; i++)
2982                 LASSERT(!the_lnet.ln_lnds[i]);
2983         lnet_destroy_locks();
2984         genl_unregister_family(&lnet_family);
2985 }
2986
2987 /**
2988  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2989  *
2990  * Users must call this function at least once before any other functions.
2991  * For each successful call there must be a corresponding call to
2992  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2993  * ignored.
2994  *
2995  * The PID used by LNet may be different from the one requested.
2996  * See LNetGetId().
2997  *
2998  * \param requested_pid PID requested by the caller.
2999  *
3000  * \return >= 0 on success, and < 0 error code on failures.
3001  */
3002 int
3003 LNetNIInit(lnet_pid_t requested_pid)
3004 {
3005         int im_a_router = 0;
3006         int rc;
3007         int ni_bytes;
3008         struct lnet_ping_buffer *pbuf;
3009         struct lnet_handle_md ping_mdh;
3010         LIST_HEAD(net_head);
3011         struct lnet_net *net;
3012
3013         mutex_lock(&the_lnet.ln_api_mutex);
3014
3015         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
3016
3017         if (the_lnet.ln_state == LNET_STATE_STOPPING) {
3018                 mutex_unlock(&the_lnet.ln_api_mutex);
3019                 return -ESHUTDOWN;
3020         }
3021
3022         if (the_lnet.ln_refcount > 0) {
3023                 rc = the_lnet.ln_refcount++;
3024                 mutex_unlock(&the_lnet.ln_api_mutex);
3025                 return rc;
3026         }
3027
3028         rc = lnet_prepare(requested_pid);
3029         if (rc != 0) {
3030                 mutex_unlock(&the_lnet.ln_api_mutex);
3031                 return rc;
3032         }
3033
3034         /* create a network for Loopback network */
3035         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
3036         if (net == NULL) {
3037                 rc = -ENOMEM;
3038                 goto err_empty_list;
3039         }
3040
3041         /* Add in the loopback NI */
3042         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
3043                 rc = -ENOMEM;
3044                 goto err_empty_list;
3045         }
3046
3047         if (use_tcp_bonding)
3048                 CWARN("use_tcp_bonding has been removed. Use Multi-Rail and Dynamic Discovery instead, see LU-13641\n");
3049
3050         /* If LNet is being initialized via DLC it is possible
3051          * that the user requests not to load module parameters (ones which
3052          * are supported by DLC) on initialization.  Therefore, make sure not
3053          * to load networks, routes and forwarding from module parameters
3054          * in this case.  On cleanup in case of failure only clean up
3055          * routes if it has been loaded */
3056         if (!the_lnet.ln_nis_from_mod_params) {
3057                 rc = lnet_parse_networks(&net_head, lnet_get_networks());
3058                 if (rc < 0)
3059                         goto err_empty_list;
3060         }
3061
3062         rc = lnet_startup_lndnets(&net_head);
3063         if (rc < 0)
3064                 goto err_empty_list;
3065
3066         if (!the_lnet.ln_nis_from_mod_params) {
3067                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
3068                 if (rc != 0)
3069                         goto err_shutdown_lndnis;
3070
3071                 rc = lnet_rtrpools_alloc(im_a_router);
3072                 if (rc != 0)
3073                         goto err_destroy_routes;
3074         }
3075
3076         rc = lnet_acceptor_start();
3077         if (rc != 0)
3078                 goto err_destroy_routes;
3079
3080         the_lnet.ln_refcount = 1;
3081         /* Now I may use my own API functions... */
3082
3083         ni_bytes = LNET_PING_INFO_HDR_SIZE;
3084         list_for_each_entry(net, &the_lnet.ln_nets, net_list)
3085                 ni_bytes += lnet_get_net_ni_bytes_locked(net);
3086
3087         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_bytes, true);
3088         if (rc != 0)
3089                 goto err_acceptor_stop;
3090
3091         lnet_ping_target_update(pbuf, ping_mdh);
3092
3093         the_lnet.ln_mt_handler = lnet_mt_event_handler;
3094
3095         rc = lnet_push_target_init();
3096         if (rc != 0)
3097                 goto err_stop_ping;
3098
3099         rc = lnet_peer_discovery_start();
3100         if (rc != 0)
3101                 goto err_destroy_push_target;
3102
3103         rc = lnet_monitor_thr_start();
3104         if (rc != 0)
3105                 goto err_stop_discovery_thr;
3106
3107         lnet_fault_init();
3108         lnet_router_debugfs_init();
3109
3110         mutex_unlock(&the_lnet.ln_api_mutex);
3111
3112         complete_all(&the_lnet.ln_started);
3113
3114         /* wait for all routers to start */
3115         lnet_wait_router_start();
3116
3117         return 0;
3118
3119 err_stop_discovery_thr:
3120         lnet_peer_discovery_stop();
3121 err_destroy_push_target:
3122         lnet_push_target_fini();
3123 err_stop_ping:
3124         lnet_ping_target_fini();
3125 err_acceptor_stop:
3126         the_lnet.ln_refcount = 0;
3127         lnet_acceptor_stop();
3128 err_destroy_routes:
3129         if (!the_lnet.ln_nis_from_mod_params)
3130                 lnet_destroy_routes();
3131 err_shutdown_lndnis:
3132         lnet_shutdown_lndnets();
3133 err_empty_list:
3134         lnet_unprepare();
3135         LASSERT(rc < 0);
3136         mutex_unlock(&the_lnet.ln_api_mutex);
3137         while ((net = list_first_entry_or_null(&net_head,
3138                                                struct lnet_net,
3139                                                net_list)) != NULL) {
3140                 list_del_init(&net->net_list);
3141                 lnet_net_free(net);
3142         }
3143         return rc;
3144 }
3145 EXPORT_SYMBOL(LNetNIInit);
3146
3147 /**
3148  * Stop LNet interfaces, routing, and forwarding.
3149  *
3150  * Users must call this function once for each successful call to LNetNIInit().
3151  * Once the LNetNIFini() operation has been started, the results of pending
3152  * API operations are undefined.
3153  *
3154  * \return always 0 for current implementation.
3155  */
3156 int
3157 LNetNIFini(void)
3158 {
3159         mutex_lock(&the_lnet.ln_api_mutex);
3160
3161         LASSERT(the_lnet.ln_refcount > 0);
3162
3163         if (the_lnet.ln_refcount != 1) {
3164                 the_lnet.ln_refcount--;
3165         } else {
3166                 LASSERT(!the_lnet.ln_niinit_self);
3167
3168                 lnet_net_lock(LNET_LOCK_EX);
3169                 the_lnet.ln_state = LNET_STATE_STOPPING;
3170                 lnet_net_unlock(LNET_LOCK_EX);
3171
3172                 lnet_fault_fini();
3173
3174                 lnet_router_debugfs_fini();
3175                 lnet_monitor_thr_stop();
3176                 lnet_peer_discovery_stop();
3177                 lnet_push_target_fini();
3178                 lnet_ping_target_fini();
3179
3180                 /* Teardown fns that use my own API functions BEFORE here */
3181                 the_lnet.ln_refcount = 0;
3182
3183                 lnet_acceptor_stop();
3184                 lnet_destroy_routes();
3185                 lnet_shutdown_lndnets();
3186                 lnet_unprepare();
3187         }
3188
3189         mutex_unlock(&the_lnet.ln_api_mutex);
3190         return 0;
3191 }
3192 EXPORT_SYMBOL(LNetNIFini);
3193
3194 /**
3195  * Grabs the ni data from the ni structure and fills the out
3196  * parameters
3197  *
3198  * \param[in] ni network        interface structure
3199  * \param[out] cfg_ni           NI config information
3200  * \param[out] tun              network and LND tunables
3201  */
3202 static void
3203 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
3204                    struct lnet_ioctl_config_lnd_tunables *tun,
3205                    struct lnet_ioctl_element_stats *stats,
3206                    __u32 tun_size)
3207 {
3208         size_t min_size = 0;
3209         int i;
3210
3211         if (!ni || !cfg_ni || !tun || !nid_is_nid4(&ni->ni_nid))
3212                 return;
3213
3214         if (ni->ni_interface != NULL) {
3215                 strncpy(cfg_ni->lic_ni_intf,
3216                         ni->ni_interface,
3217                         sizeof(cfg_ni->lic_ni_intf));
3218         }
3219
3220         cfg_ni->lic_nid = lnet_nid_to_nid4(&ni->ni_nid);
3221         cfg_ni->lic_status = lnet_ni_get_status_locked(ni);
3222         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
3223
3224         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
3225
3226         if (stats) {
3227                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
3228                                                        LNET_STATS_TYPE_SEND);
3229                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
3230                                                        LNET_STATS_TYPE_RECV);
3231                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
3232                                                        LNET_STATS_TYPE_DROP);
3233         }
3234
3235         /*
3236          * tun->lt_tun will always be present, but in order to be
3237          * backwards compatible, we need to deal with the cases when
3238          * tun->lt_tun is smaller than what the kernel has, because it
3239          * comes from an older version of a userspace program, then we'll
3240          * need to copy as much information as we have available space.
3241          */
3242         min_size = tun_size - sizeof(tun->lt_cmn);
3243         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
3244
3245         /* copy over the cpts */
3246         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
3247             ni->ni_cpts == NULL)  {
3248                 for (i = 0; i < ni->ni_ncpts; i++)
3249                         cfg_ni->lic_cpts[i] = i;
3250         } else {
3251                 for (i = 0;
3252                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
3253                      i < LNET_MAX_SHOW_NUM_CPT;
3254                      i++)
3255                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
3256         }
3257         cfg_ni->lic_ncpts = ni->ni_ncpts;
3258 }
3259
3260 /**
3261  * NOTE: This is a legacy function left in the code to be backwards
3262  * compatible with older userspace programs. It should eventually be
3263  * removed.
3264  *
3265  * Grabs the ni data from the ni structure and fills the out
3266  * parameters
3267  *
3268  * \param[in] ni network        interface structure
3269  * \param[out] config           config information
3270  */
3271 static void
3272 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
3273                          struct lnet_ioctl_config_data *config)
3274 {
3275         struct lnet_ioctl_net_config *net_config;
3276         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
3277         size_t min_size, tunable_size = 0;
3278         int i;
3279
3280         if (!ni || !config || !nid_is_nid4(&ni->ni_nid))
3281                 return;
3282
3283         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
3284         if (!net_config)
3285                 return;
3286
3287         if (!ni->ni_interface)
3288                 return;
3289
3290         strncpy(net_config->ni_interface,
3291                 ni->ni_interface,
3292                 sizeof(net_config->ni_interface));
3293
3294         config->cfg_nid = lnet_nid_to_nid4(&ni->ni_nid);
3295         config->cfg_config_u.cfg_net.net_peer_timeout =
3296                 ni->ni_net->net_tunables.lct_peer_timeout;
3297         config->cfg_config_u.cfg_net.net_max_tx_credits =
3298                 ni->ni_net->net_tunables.lct_max_tx_credits;
3299         config->cfg_config_u.cfg_net.net_peer_tx_credits =
3300                 ni->ni_net->net_tunables.lct_peer_tx_credits;
3301         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
3302                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
3303
3304         net_config->ni_status = lnet_ni_get_status_locked(ni);
3305
3306         if (ni->ni_cpts) {
3307                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
3308
3309                 for (i = 0; i < num_cpts; i++)
3310                         net_config->ni_cpts[i] = ni->ni_cpts[i];
3311
3312                 config->cfg_ncpts = num_cpts;
3313         }
3314
3315         /*
3316          * See if user land tools sent in a newer and larger version
3317          * of struct lnet_tunables than what the kernel uses.
3318          */
3319         min_size = sizeof(*config) + sizeof(*net_config);
3320
3321         if (config->cfg_hdr.ioc_len > min_size)
3322                 tunable_size = config->cfg_hdr.ioc_len - min_size;
3323
3324         /* Don't copy too much data to user space */
3325         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
3326         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
3327
3328         if (lnd_cfg && min_size) {
3329                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
3330                 config->cfg_config_u.cfg_net.net_interface_count = 1;
3331
3332                 /* Tell user land that kernel side has less data */
3333                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
3334                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
3335                         config->cfg_hdr.ioc_len -= min_size;
3336                 }
3337         }
3338 }
3339
3340 struct lnet_ni *
3341 lnet_get_ni_idx_locked(int idx)
3342 {
3343         struct lnet_ni          *ni;
3344         struct lnet_net         *net;
3345
3346         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3347                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3348                         if (idx-- == 0)
3349                                 return ni;
3350                 }
3351         }
3352
3353         return NULL;
3354 }
3355
3356 int lnet_get_net_healthv_locked(struct lnet_net *net)
3357 {
3358         struct lnet_ni *ni;
3359         int best_healthv = 0;
3360         int healthv, ni_fatal;
3361
3362         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3363                 healthv = atomic_read(&ni->ni_healthv);
3364                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3365                 if (!ni_fatal && healthv > best_healthv)
3366                         best_healthv = healthv;
3367         }
3368
3369         return best_healthv;
3370 }
3371
3372 struct lnet_ni *
3373 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3374 {
3375         struct lnet_ni          *ni;
3376         struct lnet_net         *net = mynet;
3377
3378         /*
3379          * It is possible that the net has been cleaned out while there is
3380          * a message being sent. This function accessed the net without
3381          * checking if the list is empty
3382          */
3383         if (!prev) {
3384                 if (!net)
3385                         net = list_first_entry(&the_lnet.ln_nets,
3386                                                struct lnet_net,
3387                                                net_list);
3388                 if (list_empty(&net->net_ni_list))
3389                         return NULL;
3390                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3391                                       ni_netlist);
3392
3393                 return ni;
3394         }
3395
3396         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3397                 /* if you reached the end of the ni list and the net is
3398                  * specified, then there are no more nis in that net */
3399                 if (net != NULL)
3400                         return NULL;
3401
3402                 /* we reached the end of this net ni list. move to the
3403                  * next net */
3404                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3405                         /* no more nets and no more NIs. */
3406                         return NULL;
3407
3408                 /* get the next net */
3409                 net = list_first_entry(&prev->ni_net->net_list, struct lnet_net,
3410                                        net_list);
3411                 if (list_empty(&net->net_ni_list))
3412                         return NULL;
3413                 /* get the ni on it */
3414                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3415                                       ni_netlist);
3416
3417                 return ni;
3418         }
3419
3420         if (list_empty(&prev->ni_netlist))
3421                 return NULL;
3422
3423         /* there are more nis left */
3424         ni = list_first_entry(&prev->ni_netlist, struct lnet_ni, ni_netlist);
3425
3426         return ni;
3427 }
3428
3429 static int
3430 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3431 {
3432         struct lnet_ni *ni;
3433         int cpt;
3434         int rc = -ENOENT;
3435         int idx = config->cfg_count;
3436
3437         cpt = lnet_net_lock_current();
3438
3439         ni = lnet_get_ni_idx_locked(idx);
3440
3441         if (ni != NULL) {
3442                 rc = 0;
3443                 lnet_ni_lock(ni);
3444                 lnet_fill_ni_info_legacy(ni, config);
3445                 lnet_ni_unlock(ni);
3446         }
3447
3448         lnet_net_unlock(cpt);
3449         return rc;
3450 }
3451
3452 static int
3453 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3454                    struct lnet_ioctl_config_lnd_tunables *tun,
3455                    struct lnet_ioctl_element_stats *stats,
3456                    __u32 tun_size)
3457 {
3458         struct lnet_ni          *ni;
3459         int                     cpt;
3460         int                     rc = -ENOENT;
3461
3462         if (!cfg_ni || !tun || !stats)
3463                 return -EINVAL;
3464
3465         cpt = lnet_net_lock_current();
3466
3467         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3468
3469         if (ni) {
3470                 rc = 0;
3471                 lnet_ni_lock(ni);
3472                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3473                 lnet_ni_unlock(ni);
3474         }
3475
3476         lnet_net_unlock(cpt);
3477         return rc;
3478 }
3479
3480 static int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3481 {
3482         struct lnet_ni *ni;
3483         int rc = -ENOENT;
3484
3485         if (!msg_stats)
3486                 return -EINVAL;
3487
3488         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3489
3490         if (ni) {
3491                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3492                 rc = 0;
3493         }
3494
3495         return rc;
3496 }
3497
3498 static int lnet_add_net_common(struct lnet_net *net,
3499                                struct lnet_ioctl_config_lnd_tunables *tun)
3500 {
3501         struct lnet_handle_md ping_mdh;
3502         struct lnet_ping_buffer *pbuf;
3503         struct lnet_remotenet *rnet;
3504         struct lnet_ni *ni;
3505         u32 net_id;
3506         int rc;
3507
3508         lnet_net_lock(LNET_LOCK_EX);
3509         rnet = lnet_find_rnet_locked(net->net_id);
3510         lnet_net_unlock(LNET_LOCK_EX);
3511         /*
3512          * make sure that the net added doesn't invalidate the current
3513          * configuration LNet is keeping
3514          */
3515         if (rnet) {
3516                 CERROR("Adding net %s will invalidate routing configuration\n",
3517                        libcfs_net2str(net->net_id));
3518                 lnet_net_free(net);
3519                 return -EUSERS;
3520         }
3521
3522         if (tun)
3523                 memcpy(&net->net_tunables,
3524                        &tun->lt_cmn, sizeof(net->net_tunables));
3525         else
3526                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3527
3528         net_id = net->net_id;
3529
3530         rc = lnet_startup_lndnet(net,
3531                                  (tun) ? &tun->lt_tun : NULL);
3532         if (rc < 0)
3533                 return rc;
3534
3535         /* make sure you calculate the correct number of slots in the ping
3536          * buffer. Since the ping info is a flattened list of all the NIs,
3537          * we should allocate enough slots to accomodate the number of NIs
3538          * which will be added.
3539          */
3540         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3541                                     LNET_PING_INFO_HDR_SIZE +
3542                                     lnet_get_ni_bytes(),
3543                                     false);
3544         if (rc < 0) {
3545                 lnet_shutdown_lndnet(net);
3546                 return rc;
3547         }
3548
3549         lnet_net_lock(LNET_LOCK_EX);
3550         net = lnet_get_net_locked(net_id);
3551         LASSERT(net);
3552
3553         /* apply the UDSPs */
3554         rc = lnet_udsp_apply_policies_on_net(net);
3555         if (rc)
3556                 CERROR("Failed to apply UDSPs on local net %s\n",
3557                        libcfs_net2str(net->net_id));
3558
3559         /* At this point we lost track of which NI was just added, so we
3560          * just re-apply the policies on all of the NIs on this net
3561          */
3562         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3563                 rc = lnet_udsp_apply_policies_on_ni(ni);
3564                 if (rc)
3565                         CERROR("Failed to apply UDSPs on ni %s\n",
3566                                libcfs_nidstr(&ni->ni_nid));
3567         }
3568         lnet_net_unlock(LNET_LOCK_EX);
3569
3570         /*
3571          * Start the acceptor thread if this is the first network
3572          * being added that requires the thread.
3573          */
3574         if (net->net_lnd->lnd_accept) {
3575                 rc = lnet_acceptor_start();
3576                 if (rc < 0) {
3577                         /* shutdown the net that we just started */
3578                         CERROR("Failed to start up acceptor thread\n");
3579                         lnet_shutdown_lndnet(net);
3580                         goto failed;
3581                 }
3582         }
3583
3584         lnet_net_lock(LNET_LOCK_EX);
3585         lnet_peer_net_added(net);
3586         lnet_net_unlock(LNET_LOCK_EX);
3587
3588         lnet_ping_target_update(pbuf, ping_mdh);
3589
3590         return 0;
3591
3592 failed:
3593         lnet_ping_md_unlink(pbuf, &ping_mdh);
3594         lnet_ping_buffer_decref(pbuf);
3595         return rc;
3596 }
3597
3598 static void
3599 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3600 {
3601         if (tun) {
3602                 if (tun->lt_cmn.lct_peer_timeout < 0)
3603                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3604                 if (!tun->lt_cmn.lct_peer_tx_credits)
3605                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3606                 if (!tun->lt_cmn.lct_max_tx_credits)
3607                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3608         }
3609 }
3610
3611 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3612                                       struct lnet_ioctl_config_lnd_tunables *tun)
3613 {
3614         struct lnet_net *net;
3615         const char *nets;
3616         int rc;
3617         LIST_HEAD(net_head);
3618
3619         rc = lnet_parse_ip2nets(&nets, ip2nets);
3620         if (rc < 0)
3621                 return rc;
3622
3623         rc = lnet_parse_networks(&net_head, nets);
3624         if (rc < 0)
3625                 return rc;
3626
3627         lnet_set_tune_defaults(tun);
3628
3629         mutex_lock(&the_lnet.ln_api_mutex);
3630         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3631                 rc = -ESHUTDOWN;
3632                 goto out;
3633         }
3634
3635         while ((net = list_first_entry_or_null(&net_head,
3636                                                struct lnet_net,
3637                                                net_list)) != NULL) {
3638                 list_del_init(&net->net_list);
3639                 rc = lnet_add_net_common(net, tun);
3640                 if (rc < 0)
3641                         goto out;
3642         }
3643
3644 out:
3645         mutex_unlock(&the_lnet.ln_api_mutex);
3646
3647         while ((net = list_first_entry_or_null(&net_head,
3648                                                struct lnet_net,
3649                                                net_list)) != NULL) {
3650                 list_del_init(&net->net_list);
3651                 lnet_net_free(net);
3652         }
3653         return rc;
3654 }
3655
3656 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf, u32 net_id,
3657                     struct lnet_ioctl_config_lnd_tunables *tun)
3658 {
3659         struct lnet_net *net;
3660         struct lnet_ni *ni;
3661         int rc, i;
3662         u32 lnd_type;
3663
3664         /* handle legacy ip2nets from DLC */
3665         if (conf->lic_legacy_ip2nets[0] != '\0')
3666                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3667                                                   tun);
3668
3669         lnd_type = LNET_NETTYP(net_id);
3670
3671         if (!libcfs_isknown_lnd(lnd_type)) {
3672                 CERROR("No valid net and lnd information provided\n");
3673                 return -ENOENT;
3674         }
3675
3676         net = lnet_net_alloc(net_id, NULL);
3677         if (!net)
3678                 return -ENOMEM;
3679
3680         for (i = 0; i < conf->lic_ncpts; i++) {
3681                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER) {
3682                         lnet_net_free(net);
3683                         return -ERANGE;
3684                 }
3685         }
3686
3687         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3688                                        conf->lic_ni_intf);
3689         if (!ni) {
3690                 lnet_net_free(net);
3691                 return -ENOMEM;
3692         }
3693
3694         lnet_set_tune_defaults(tun);
3695
3696         mutex_lock(&the_lnet.ln_api_mutex);
3697         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3698                 lnet_net_free(net);
3699                 rc = -ESHUTDOWN;
3700         } else {
3701                 rc = lnet_add_net_common(net, tun);
3702         }
3703
3704         mutex_unlock(&the_lnet.ln_api_mutex);
3705
3706         /* If NI already exist delete this new unused copy */
3707         if (rc == -EEXIST)
3708                 lnet_ni_free(ni);
3709
3710         return rc;
3711 }
3712
3713 int lnet_dyn_del_ni(struct lnet_nid *nid)
3714 {
3715         struct lnet_net *net;
3716         struct lnet_ni *ni;
3717         u32 net_id = LNET_NID_NET(nid);
3718         struct lnet_ping_buffer *pbuf;
3719         struct lnet_handle_md ping_mdh;
3720         int net_bytes, rc;
3721         bool net_empty;
3722
3723         /* don't allow userspace to shutdown the LOLND */
3724         if (LNET_NETTYP(net_id) == LOLND)
3725                 return -EINVAL;
3726
3727         mutex_lock(&the_lnet.ln_api_mutex);
3728         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3729                 rc = -ESHUTDOWN;
3730                 goto unlock_api_mutex;
3731         }
3732
3733         lnet_net_lock(0);
3734
3735         net = lnet_get_net_locked(net_id);
3736         if (!net) {
3737                 CERROR("net %s not found\n",
3738                        libcfs_net2str(net_id));
3739                 rc = -ENOENT;
3740                 goto unlock_net;
3741         }
3742
3743         if (!nid_addr_is_set(nid)) {
3744                 /* remove the entire net */
3745                 net_bytes = lnet_get_net_ni_bytes_locked(net);
3746
3747                 lnet_net_unlock(0);
3748
3749                 /* create and link a new ping info, before removing the old one */
3750                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3751                                             LNET_PING_INFO_HDR_SIZE +
3752                                             lnet_get_ni_bytes() - net_bytes,
3753                                             false);
3754                 if (rc != 0)
3755                         goto unlock_api_mutex;
3756
3757                 lnet_shutdown_lndnet(net);
3758
3759                 lnet_acceptor_stop();
3760
3761                 lnet_ping_target_update(pbuf, ping_mdh);
3762
3763                 goto unlock_api_mutex;
3764         }
3765
3766         ni = lnet_nid_to_ni_locked(nid, 0);
3767         if (!ni) {
3768                 CERROR("nid %s not found\n", libcfs_nidstr(nid));
3769                 rc = -ENOENT;
3770                 goto unlock_net;
3771         }
3772
3773         net_bytes = lnet_get_net_ni_bytes_locked(net);
3774         net_empty = list_is_singular(&net->net_ni_list);
3775
3776         lnet_net_unlock(0);
3777
3778         /* create and link a new ping info, before removing the old one */
3779         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3780                                     (LNET_PING_INFO_HDR_SIZE +
3781                                      lnet_get_ni_bytes() -
3782                                      lnet_ping_sts_size(&ni->ni_nid)),
3783                                     false);
3784         if (rc != 0)
3785                 goto unlock_api_mutex;
3786
3787         lnet_shutdown_lndni(ni);
3788
3789         lnet_acceptor_stop();
3790
3791         lnet_ping_target_update(pbuf, ping_mdh);
3792
3793         /* check if the net is empty and remove it if it is */
3794         if (net_empty)
3795                 lnet_shutdown_lndnet(net);
3796
3797         goto unlock_api_mutex;
3798
3799 unlock_net:
3800         lnet_net_unlock(0);
3801 unlock_api_mutex:
3802         mutex_unlock(&the_lnet.ln_api_mutex);
3803
3804         return rc;
3805 }
3806
3807 /*
3808  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3809  * They are only expected to be called for unique networks.
3810  * That can be as a result of older DLC library
3811  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3812  */
3813 int
3814 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3815 {
3816         struct lnet_net *net;
3817         LIST_HEAD(net_head);
3818         int rc;
3819         struct lnet_ioctl_config_lnd_tunables tun;
3820         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3821
3822         /* Create a net/ni structures for the network string */
3823         rc = lnet_parse_networks(&net_head, nets);
3824         if (rc <= 0)
3825                 return rc == 0 ? -EINVAL : rc;
3826
3827         mutex_lock(&the_lnet.ln_api_mutex);
3828         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3829                 rc = -ESHUTDOWN;
3830                 goto out_unlock_clean;
3831         }
3832
3833         if (rc > 1) {
3834                 rc = -EINVAL; /* only add one network per call */
3835                 goto out_unlock_clean;
3836         }
3837
3838         net = list_first_entry(&net_head, struct lnet_net, net_list);
3839         list_del_init(&net->net_list);
3840
3841         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3842
3843         memset(&tun, 0, sizeof(tun));
3844
3845         tun.lt_cmn.lct_peer_timeout =
3846           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3847                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3848         tun.lt_cmn.lct_peer_tx_credits =
3849           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3850                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3851         tun.lt_cmn.lct_peer_rtr_credits =
3852           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3853         tun.lt_cmn.lct_max_tx_credits =
3854           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3855                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3856
3857         rc = lnet_add_net_common(net, &tun);
3858
3859 out_unlock_clean:
3860         mutex_unlock(&the_lnet.ln_api_mutex);
3861         /* net_head list is empty in success case */
3862         while ((net = list_first_entry_or_null(&net_head,
3863                                                struct lnet_net,
3864                                                net_list)) != NULL) {
3865                 list_del_init(&net->net_list);
3866                 lnet_net_free(net);
3867         }
3868         return rc;
3869 }
3870
3871 int
3872 lnet_dyn_del_net(u32 net_id)
3873 {
3874         struct lnet_net *net;
3875         struct lnet_ping_buffer *pbuf;
3876         struct lnet_handle_md ping_mdh;
3877         int net_ni_bytes, rc;
3878
3879         /* don't allow userspace to shutdown the LOLND */
3880         if (LNET_NETTYP(net_id) == LOLND)
3881                 return -EINVAL;
3882
3883         mutex_lock(&the_lnet.ln_api_mutex);
3884         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3885                 rc = -ESHUTDOWN;
3886                 goto out;
3887         }
3888
3889         lnet_net_lock(0);
3890
3891         net = lnet_get_net_locked(net_id);
3892         if (net == NULL) {
3893                 lnet_net_unlock(0);
3894                 rc = -EINVAL;
3895                 goto out;
3896         }
3897
3898         net_ni_bytes = lnet_get_net_ni_bytes_locked(net);
3899
3900         lnet_net_unlock(0);
3901
3902         /* create and link a new ping info, before removing the old one */
3903         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3904                                     LNET_PING_INFO_HDR_SIZE +
3905                                     lnet_get_ni_bytes() - net_ni_bytes,
3906                                     false);
3907         if (rc != 0)
3908                 goto out;
3909
3910         lnet_shutdown_lndnet(net);
3911
3912         lnet_acceptor_stop();
3913
3914         lnet_ping_target_update(pbuf, ping_mdh);
3915
3916 out:
3917         mutex_unlock(&the_lnet.ln_api_mutex);
3918
3919         return rc;
3920 }
3921
3922 void lnet_mark_ping_buffer_for_update(void)
3923 {
3924         if (the_lnet.ln_routing)
3925                 return;
3926
3927         atomic_set(&the_lnet.ln_update_ping_buf, 1);
3928         complete(&the_lnet.ln_mt_wait_complete);
3929 }
3930 EXPORT_SYMBOL(lnet_mark_ping_buffer_for_update);
3931
3932 void lnet_update_ping_buffer(void)
3933 {
3934         struct lnet_ping_buffer *pbuf;
3935         struct lnet_handle_md ping_mdh;
3936
3937         if (atomic_dec_if_positive(&the_lnet.ln_update_ping_buf) < 0)
3938                 return;
3939
3940         mutex_lock(&the_lnet.ln_api_mutex);
3941
3942         if (!lnet_ping_target_setup(&pbuf, &ping_mdh,
3943                                     LNET_PING_INFO_HDR_SIZE +
3944                                     lnet_get_ni_bytes(),
3945                                     false))
3946                 lnet_ping_target_update(pbuf, ping_mdh);
3947
3948         mutex_unlock(&the_lnet.ln_api_mutex);
3949 }
3950
3951 void lnet_incr_dlc_seq(void)
3952 {
3953         atomic_inc(&lnet_dlc_seq_no);
3954 }
3955
3956 __u32 lnet_get_dlc_seq_locked(void)
3957 {
3958         return atomic_read(&lnet_dlc_seq_no);
3959 }
3960
3961 static void
3962 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3963 {
3964         struct lnet_net *net;
3965         struct lnet_ni *ni;
3966
3967         lnet_net_lock(LNET_LOCK_EX);
3968         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3969                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3970                         if (all || (nid_is_nid4(&ni->ni_nid) &&
3971                                     lnet_nid_to_nid4(&ni->ni_nid) == nid)) {
3972                                 atomic_set(&ni->ni_healthv, value);
3973                                 if (list_empty(&ni->ni_recovery) &&
3974                                     value < LNET_MAX_HEALTH_VALUE) {
3975                                         CERROR("manually adding local NI %s to recovery\n",
3976                                                libcfs_nidstr(&ni->ni_nid));
3977                                         list_add_tail(&ni->ni_recovery,
3978                                                       &the_lnet.ln_mt_localNIRecovq);
3979                                         lnet_ni_addref_locked(ni, 0);
3980                                 }
3981                                 if (!all) {
3982                                         lnet_net_unlock(LNET_LOCK_EX);
3983                                         return;
3984                                 }
3985                         }
3986                 }
3987         }
3988         lnet_net_unlock(LNET_LOCK_EX);
3989 }
3990
3991 static void
3992 lnet_ni_set_conns_per_peer(lnet_nid_t nid, int value, bool all)
3993 {
3994         struct lnet_net *net;
3995         struct lnet_ni *ni;
3996
3997         lnet_net_lock(LNET_LOCK_EX);
3998         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3999                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4000                         if (lnet_nid_to_nid4(&ni->ni_nid) != nid && !all)
4001                                 continue;
4002                         if (LNET_NETTYP(net->net_id) == SOCKLND)
4003                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_sock.lnd_conns_per_peer = value;
4004                         else if (LNET_NETTYP(net->net_id) == O2IBLND)
4005                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib.lnd_conns_per_peer = value;
4006                         if (!all) {
4007                                 lnet_net_unlock(LNET_LOCK_EX);
4008                                 return;
4009                         }
4010                 }
4011         }
4012         lnet_net_unlock(LNET_LOCK_EX);
4013 }
4014
4015 static int
4016 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
4017 {
4018         int cpt, rc = 0;
4019         struct lnet_ni *ni;
4020         struct lnet_nid nid;
4021
4022         lnet_nid4_to_nid(stats->hlni_nid, &nid);
4023         cpt = lnet_net_lock_current();
4024         ni = lnet_nid_to_ni_locked(&nid, cpt);
4025         if (!ni) {
4026                 rc = -ENOENT;
4027                 goto unlock;
4028         }
4029
4030         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
4031         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
4032         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
4033         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
4034         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
4035         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
4036         stats->hlni_fatal_error = atomic_read(&ni->ni_fatal_error_on);
4037         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
4038         stats->hlni_ping_count = ni->ni_ping_count;
4039         stats->hlni_next_ping = ni->ni_next_ping;
4040
4041 unlock:
4042         lnet_net_unlock(cpt);
4043
4044         return rc;
4045 }
4046
4047 static int
4048 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4049 {
4050         struct lnet_ni *ni;
4051         int i = 0;
4052
4053         lnet_net_lock(LNET_LOCK_EX);
4054         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
4055                 if (!nid_is_nid4(&ni->ni_nid))
4056                         continue;
4057                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&ni->ni_nid);
4058                 i++;
4059                 if (i >= LNET_MAX_SHOW_NUM_NID)
4060                         break;
4061         }
4062         lnet_net_unlock(LNET_LOCK_EX);
4063         list->rlst_num_nids = i;
4064
4065         return 0;
4066 }
4067
4068 static int
4069 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4070 {
4071         struct lnet_peer_ni *lpni;
4072         int i = 0;
4073
4074         lnet_net_lock(LNET_LOCK_EX);
4075         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
4076                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&lpni->lpni_nid);
4077                 i++;
4078                 if (i >= LNET_MAX_SHOW_NUM_NID)
4079                         break;
4080         }
4081         lnet_net_unlock(LNET_LOCK_EX);
4082         list->rlst_num_nids = i;
4083
4084         return 0;
4085 }
4086
4087 /**
4088  * LNet ioctl handler.
4089  *
4090  */
4091 int
4092 LNetCtl(unsigned int cmd, void *arg)
4093 {
4094         struct libcfs_ioctl_data *data = arg;
4095         struct lnet_ioctl_config_data *config;
4096         struct lnet_ni           *ni;
4097         struct lnet_nid           nid;
4098         int                       rc;
4099
4100         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
4101                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
4102
4103         switch (cmd) {
4104         case IOC_LIBCFS_GET_NI: {
4105                 struct lnet_processid id = {};
4106
4107                 rc = LNetGetId(data->ioc_count, &id, false);
4108                 data->ioc_nid = lnet_nid_to_nid4(&id.nid);
4109                 return rc;
4110         }
4111         case IOC_LIBCFS_FAIL_NID:
4112                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
4113
4114         case IOC_LIBCFS_ADD_ROUTE: {
4115                 /* default router sensitivity to 1 */
4116                 unsigned int sensitivity = 1;
4117                 config = arg;
4118
4119                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4120                         return -EINVAL;
4121
4122                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
4123                         sensitivity =
4124                           config->cfg_config_u.cfg_route.rtr_sensitivity;
4125                 }
4126
4127                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4128                 mutex_lock(&the_lnet.ln_api_mutex);
4129                 rc = lnet_add_route(config->cfg_net,
4130                                     config->cfg_config_u.cfg_route.rtr_hop,
4131                                     &nid,
4132                                     config->cfg_config_u.cfg_route.
4133                                         rtr_priority, sensitivity);
4134                 mutex_unlock(&the_lnet.ln_api_mutex);
4135                 return rc;
4136         }
4137
4138         case IOC_LIBCFS_DEL_ROUTE:
4139                 config = arg;
4140
4141                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4142                         return -EINVAL;
4143
4144                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4145                 mutex_lock(&the_lnet.ln_api_mutex);
4146                 rc = lnet_del_route(config->cfg_net, &nid);
4147                 mutex_unlock(&the_lnet.ln_api_mutex);
4148                 return rc;
4149
4150         case IOC_LIBCFS_GET_ROUTE:
4151                 config = arg;
4152
4153                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4154                         return -EINVAL;
4155
4156                 mutex_lock(&the_lnet.ln_api_mutex);
4157                 rc = lnet_get_route(config->cfg_count,
4158                                     &config->cfg_net,
4159                                     &config->cfg_config_u.cfg_route.rtr_hop,
4160                                     &config->cfg_nid,
4161                                     &config->cfg_config_u.cfg_route.rtr_flags,
4162                                     &config->cfg_config_u.cfg_route.
4163                                         rtr_priority,
4164                                     &config->cfg_config_u.cfg_route.
4165                                         rtr_sensitivity);
4166                 mutex_unlock(&the_lnet.ln_api_mutex);
4167                 return rc;
4168
4169         case IOC_LIBCFS_GET_LOCAL_NI: {
4170                 struct lnet_ioctl_config_ni *cfg_ni;
4171                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
4172                 struct lnet_ioctl_element_stats *stats;
4173                 __u32 tun_size;
4174
4175                 cfg_ni = arg;
4176
4177                 /* get the tunables if they are available */
4178                 if (cfg_ni->lic_cfg_hdr.ioc_len <
4179                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
4180                         return -EINVAL;
4181
4182                 stats = (struct lnet_ioctl_element_stats *)
4183                         cfg_ni->lic_bulk;
4184                 tun = (struct lnet_ioctl_config_lnd_tunables *)
4185                                 (cfg_ni->lic_bulk + sizeof(*stats));
4186
4187                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
4188                         sizeof(*stats);
4189
4190                 mutex_lock(&the_lnet.ln_api_mutex);
4191                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
4192                 mutex_unlock(&the_lnet.ln_api_mutex);
4193                 return rc;
4194         }
4195
4196         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
4197                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
4198                 int cpt;
4199
4200                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
4201                         return -EINVAL;
4202
4203                 mutex_lock(&the_lnet.ln_api_mutex);
4204
4205                 cpt = lnet_net_lock_current();
4206                 rc = lnet_get_ni_stats(msg_stats);
4207                 lnet_net_unlock(cpt);
4208
4209                 mutex_unlock(&the_lnet.ln_api_mutex);
4210
4211                 return rc;
4212         }
4213
4214         case IOC_LIBCFS_GET_NET: {
4215                 size_t total = sizeof(*config) +
4216                                sizeof(struct lnet_ioctl_net_config);
4217                 config = arg;
4218
4219                 if (config->cfg_hdr.ioc_len < total)
4220                         return -EINVAL;
4221
4222                 mutex_lock(&the_lnet.ln_api_mutex);
4223                 rc = lnet_get_net_config(config);
4224                 mutex_unlock(&the_lnet.ln_api_mutex);
4225                 return rc;
4226         }
4227
4228         case IOC_LIBCFS_GET_LNET_STATS:
4229         {
4230                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
4231
4232                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
4233                         return -EINVAL;
4234
4235                 mutex_lock(&the_lnet.ln_api_mutex);
4236                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
4237                 mutex_unlock(&the_lnet.ln_api_mutex);
4238                 return rc;
4239         }
4240
4241         case IOC_LIBCFS_RESET_LNET_STATS:
4242         {
4243                 mutex_lock(&the_lnet.ln_api_mutex);
4244                 lnet_counters_reset();
4245                 mutex_unlock(&the_lnet.ln_api_mutex);
4246                 return 0;
4247         }
4248
4249         case IOC_LIBCFS_CONFIG_RTR:
4250                 config = arg;
4251
4252                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4253                         return -EINVAL;
4254
4255                 mutex_lock(&the_lnet.ln_api_mutex);
4256                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
4257                         rc = lnet_rtrpools_enable();
4258                         mutex_unlock(&the_lnet.ln_api_mutex);
4259                         return rc;
4260                 }
4261                 lnet_rtrpools_disable();
4262                 mutex_unlock(&the_lnet.ln_api_mutex);
4263                 return 0;
4264
4265         case IOC_LIBCFS_ADD_BUF:
4266                 config = arg;
4267
4268                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4269                         return -EINVAL;
4270
4271                 mutex_lock(&the_lnet.ln_api_mutex);
4272                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4273                                                 buf_tiny,
4274                                           config->cfg_config_u.cfg_buffers.
4275                                                 buf_small,
4276                                           config->cfg_config_u.cfg_buffers.
4277                                                 buf_large);
4278                 mutex_unlock(&the_lnet.ln_api_mutex);
4279                 return rc;
4280
4281         case IOC_LIBCFS_SET_NUMA_RANGE: {
4282                 struct lnet_ioctl_set_value *numa;
4283                 numa = arg;
4284                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4285                         return -EINVAL;
4286                 lnet_net_lock(LNET_LOCK_EX);
4287                 lnet_numa_range = numa->sv_value;
4288                 lnet_net_unlock(LNET_LOCK_EX);
4289                 return 0;
4290         }
4291
4292         case IOC_LIBCFS_GET_NUMA_RANGE: {
4293                 struct lnet_ioctl_set_value *numa;
4294                 numa = arg;
4295                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4296                         return -EINVAL;
4297                 numa->sv_value = lnet_numa_range;
4298                 return 0;
4299         }
4300
4301         case IOC_LIBCFS_GET_BUF: {
4302                 struct lnet_ioctl_pool_cfg *pool_cfg;
4303                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4304
4305                 config = arg;
4306
4307                 if (config->cfg_hdr.ioc_len < total)
4308                         return -EINVAL;
4309
4310                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4311
4312                 mutex_lock(&the_lnet.ln_api_mutex);
4313                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4314                 mutex_unlock(&the_lnet.ln_api_mutex);
4315                 return rc;
4316         }
4317
4318         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4319                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4320
4321                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4322                         return -EINVAL;
4323
4324                 mutex_lock(&the_lnet.ln_api_mutex);
4325                 rc = lnet_get_local_ni_hstats(stats);
4326                 mutex_unlock(&the_lnet.ln_api_mutex);
4327
4328                 return rc;
4329         }
4330
4331         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4332                 struct lnet_ioctl_recovery_list *list = arg;
4333                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4334                         return -EINVAL;
4335
4336                 mutex_lock(&the_lnet.ln_api_mutex);
4337                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4338                         rc = lnet_get_local_ni_recovery_list(list);
4339                 else
4340                         rc = lnet_get_peer_ni_recovery_list(list);
4341                 mutex_unlock(&the_lnet.ln_api_mutex);
4342                 return rc;
4343         }
4344
4345         case IOC_LIBCFS_ADD_PEER_NI: {
4346                 struct lnet_ioctl_peer_cfg *cfg = arg;
4347                 struct lnet_nid prim_nid;
4348
4349                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4350                         return -EINVAL;
4351
4352                 mutex_lock(&the_lnet.ln_api_mutex);
4353                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4354                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4355                 rc = lnet_user_add_peer_ni(&prim_nid, &nid, cfg->prcfg_mr,
4356                                            cfg->prcfg_count == 1);
4357                 mutex_unlock(&the_lnet.ln_api_mutex);
4358                 return rc;
4359         }
4360
4361         case IOC_LIBCFS_DEL_PEER_NI: {
4362                 struct lnet_ioctl_peer_cfg *cfg = arg;
4363                 struct lnet_nid prim_nid;
4364
4365                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4366                         return -EINVAL;
4367
4368                 mutex_lock(&the_lnet.ln_api_mutex);
4369                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4370                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4371                 rc = lnet_del_peer_ni(&prim_nid,
4372                                       &nid,
4373                                       cfg->prcfg_count);
4374                 mutex_unlock(&the_lnet.ln_api_mutex);
4375                 return rc;
4376         }
4377
4378         case IOC_LIBCFS_GET_PEER_INFO: {
4379                 struct lnet_ioctl_peer *peer_info = arg;
4380
4381                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4382                         return -EINVAL;
4383
4384                 mutex_lock(&the_lnet.ln_api_mutex);
4385                 rc = lnet_get_peer_ni_info(
4386                    peer_info->pr_count,
4387                    &peer_info->pr_nid,
4388                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4389                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4390                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4391                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4392                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4393                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4394                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4395                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4396                 mutex_unlock(&the_lnet.ln_api_mutex);
4397                 return rc;
4398         }
4399
4400         case IOC_LIBCFS_GET_PEER_NI: {
4401                 struct lnet_ioctl_peer_cfg *cfg = arg;
4402
4403                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4404                         return -EINVAL;
4405
4406                 mutex_lock(&the_lnet.ln_api_mutex);
4407                 rc = lnet_get_peer_info(cfg,
4408                                         (void __user *)cfg->prcfg_bulk);
4409                 mutex_unlock(&the_lnet.ln_api_mutex);
4410                 return rc;
4411         }
4412
4413         case IOC_LIBCFS_GET_PEER_LIST: {
4414                 struct lnet_ioctl_peer_cfg *cfg = arg;
4415
4416                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4417                         return -EINVAL;
4418
4419                 mutex_lock(&the_lnet.ln_api_mutex);
4420                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4421                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4422                 mutex_unlock(&the_lnet.ln_api_mutex);
4423                 return rc;
4424         }
4425
4426         case IOC_LIBCFS_SET_HEALHV: {
4427                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4428                 int value;
4429                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4430                         return -EINVAL;
4431                 if (cfg->rh_value < 0 ||
4432                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4433                         value = LNET_MAX_HEALTH_VALUE;
4434                 else
4435                         value = cfg->rh_value;
4436                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4437                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4438                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4439                 mutex_lock(&the_lnet.ln_api_mutex);
4440                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
4441                         lnet_ni_set_healthv(cfg->rh_nid, value,
4442                                              cfg->rh_all);
4443                 else
4444                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
4445                                                   cfg->rh_all);
4446                 mutex_unlock(&the_lnet.ln_api_mutex);
4447                 return 0;
4448         }
4449
4450         case IOC_LIBCFS_SET_PEER: {
4451                 struct lnet_ioctl_peer_cfg *cfg = arg;
4452                 struct lnet_peer *lp;
4453
4454                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4455                         return -EINVAL;
4456
4457                 mutex_lock(&the_lnet.ln_api_mutex);
4458                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &nid);
4459                 lp = lnet_find_peer(&nid);
4460                 if (!lp) {
4461                         mutex_unlock(&the_lnet.ln_api_mutex);
4462                         return -ENOENT;
4463                 }
4464                 spin_lock(&lp->lp_lock);
4465                 lp->lp_state = cfg->prcfg_state;
4466                 spin_unlock(&lp->lp_lock);
4467                 lnet_peer_decref_locked(lp);
4468                 mutex_unlock(&the_lnet.ln_api_mutex);
4469                 CDEBUG(D_NET, "Set peer %s state to %u\n",
4470                        libcfs_nid2str(cfg->prcfg_prim_nid), cfg->prcfg_state);
4471                 return 0;
4472         }
4473
4474         case IOC_LIBCFS_SET_CONNS_PER_PEER: {
4475                 struct lnet_ioctl_reset_conns_per_peer_cfg *cfg = arg;
4476                 int value;
4477
4478                 if (cfg->rcpp_hdr.ioc_len < sizeof(*cfg))
4479                         return -EINVAL;
4480                 if (cfg->rcpp_value < 0)
4481                         value = 1;
4482                 else
4483                         value = cfg->rcpp_value;
4484                 CDEBUG(D_NET,
4485                        "Setting conns_per_peer to %d for %s. all = %d\n",
4486                        value, libcfs_nid2str(cfg->rcpp_nid), cfg->rcpp_all);
4487                 mutex_lock(&the_lnet.ln_api_mutex);
4488                 lnet_ni_set_conns_per_peer(cfg->rcpp_nid, value, cfg->rcpp_all);
4489                 mutex_unlock(&the_lnet.ln_api_mutex);
4490                 return 0;
4491         }
4492
4493         case IOC_LIBCFS_NOTIFY_ROUTER: {
4494                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
4495
4496                 /* The deadline passed in by the user should be some time in
4497                  * seconds in the future since the UNIX epoch. We have to map
4498                  * that deadline to the wall clock.
4499                  */
4500                 deadline += ktime_get_seconds();
4501                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4502                 return lnet_notify(NULL, &nid, data->ioc_flags, false,
4503                                    deadline);
4504         }
4505
4506         case IOC_LIBCFS_LNET_DIST:
4507                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4508                 rc = LNetDist(&nid, &nid, &data->ioc_u32[1]);
4509                 if (rc < 0 && rc != -EHOSTUNREACH)
4510                         return rc;
4511
4512                 data->ioc_nid = lnet_nid_to_nid4(&nid);
4513                 data->ioc_u32[0] = rc;
4514                 return 0;
4515
4516         case IOC_LIBCFS_TESTPROTOCOMPAT:
4517                 the_lnet.ln_testprotocompat = data->ioc_flags;
4518                 return 0;
4519
4520         case IOC_LIBCFS_LNET_FAULT:
4521                 return lnet_fault_ctl(data->ioc_flags, data);
4522
4523         case IOC_LIBCFS_PING_PEER: {
4524                 struct lnet_ioctl_ping_data *ping = arg;
4525                 struct lnet_process_id __user *ids = ping->ping_buf;
4526                 struct lnet_nid src_nid = LNET_ANY_NID;
4527                 struct lnet_genl_ping_list plist;
4528                 struct lnet_processid id;
4529                 struct lnet_peer *lp;
4530                 signed long timeout;
4531                 int count, i;
4532
4533                 /* Check if the supplied ping data supports source nid
4534                  * NB: This check is sufficient if lnet_ioctl_ping_data has
4535                  * additional fields added, but if they are re-ordered or
4536                  * fields removed then this will break. It is expected that
4537                  * these ioctls will be replaced with netlink implementation, so
4538                  * it is probably not worth coming up with a more robust version
4539                  * compatibility scheme.
4540                  */
4541                 if (ping->ping_hdr.ioc_len >= sizeof(struct lnet_ioctl_ping_data))
4542                         lnet_nid4_to_nid(ping->ping_src, &src_nid);
4543
4544                 /* If timeout is negative then set default of 3 minutes */
4545                 if (((s32)ping->op_param) <= 0 ||
4546                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4547                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4548                 else
4549                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4550
4551                 id.pid = ping->ping_id.pid;
4552                 lnet_nid4_to_nid(ping->ping_id.nid, &id.nid);
4553                 rc = lnet_ping(&id, &src_nid, timeout, &plist,
4554                                ping->ping_count);
4555                 if (rc < 0)
4556                         goto report_ping_err;
4557                 count = rc;
4558                 rc = 0;
4559
4560                 for (i = 0; i < count; i++) {
4561                         struct lnet_processid *result;
4562                         struct lnet_process_id tmpid;
4563
4564                         result = genradix_ptr(&plist.lgpl_list, i);
4565                         memset(&tmpid, 0, sizeof(tmpid));
4566                         tmpid.pid = result->pid;
4567                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4568                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4569                                 rc = -EFAULT;
4570                                 goto report_ping_err;
4571                         }
4572                 }
4573
4574                 mutex_lock(&the_lnet.ln_api_mutex);
4575                 lp = lnet_find_peer(&id.nid);
4576                 if (lp) {
4577                         ping->ping_id.nid =
4578                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4579                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4580                         lnet_peer_decref_locked(lp);
4581                 }
4582                 mutex_unlock(&the_lnet.ln_api_mutex);
4583
4584                 ping->ping_count = count;
4585 report_ping_err:
4586                 genradix_free(&plist.lgpl_list);
4587                 return rc;
4588         }
4589
4590         case IOC_LIBCFS_DISCOVER: {
4591                 struct lnet_ioctl_ping_data *discover = arg;
4592                 struct lnet_peer *lp;
4593
4594                 rc = lnet_discover(discover->ping_id, discover->op_param,
4595                                    discover->ping_buf,
4596                                    discover->ping_count);
4597                 if (rc < 0)
4598                         return rc;
4599
4600                 mutex_lock(&the_lnet.ln_api_mutex);
4601                 lnet_nid4_to_nid(discover->ping_id.nid, &nid);
4602                 lp = lnet_find_peer(&nid);
4603                 if (lp) {
4604                         discover->ping_id.nid =
4605                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4606                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4607                         lnet_peer_decref_locked(lp);
4608                 }
4609                 mutex_unlock(&the_lnet.ln_api_mutex);
4610
4611                 discover->ping_count = rc;
4612                 return 0;
4613         }
4614
4615         case IOC_LIBCFS_ADD_UDSP: {
4616                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4617                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4618
4619                 mutex_lock(&the_lnet.ln_api_mutex);
4620                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4621                 if (!rc) {
4622                         rc = lnet_udsp_apply_policies(NULL, false);
4623                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4624                         rc = 0;
4625                 }
4626                 mutex_unlock(&the_lnet.ln_api_mutex);
4627
4628                 return rc;
4629         }
4630
4631         case IOC_LIBCFS_DEL_UDSP: {
4632                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4633                 int idx = ioc_udsp->iou_idx;
4634
4635                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4636                         return -EINVAL;
4637
4638                 mutex_lock(&the_lnet.ln_api_mutex);
4639                 rc = lnet_udsp_del_policy(idx);
4640                 mutex_unlock(&the_lnet.ln_api_mutex);
4641
4642                 return rc;
4643         }
4644
4645         case IOC_LIBCFS_GET_UDSP_SIZE: {
4646                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4647                 struct lnet_udsp *udsp;
4648
4649                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4650                         return -EINVAL;
4651
4652                 rc = 0;
4653
4654                 mutex_lock(&the_lnet.ln_api_mutex);
4655                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4656                 if (!udsp) {
4657                         rc = -ENOENT;
4658                 } else {
4659                         /* coming in iou_idx will hold the idx of the udsp
4660                          * to get the size of. going out the iou_idx will
4661                          * hold the size of the UDSP found at the passed
4662                          * in index.
4663                          */
4664                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4665                         if (ioc_udsp->iou_idx < 0)
4666                                 rc = -EINVAL;
4667                 }
4668                 mutex_unlock(&the_lnet.ln_api_mutex);
4669
4670                 return rc;
4671         }
4672
4673         case IOC_LIBCFS_GET_UDSP: {
4674                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4675                 struct lnet_udsp *udsp;
4676
4677                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4678                         return -EINVAL;
4679
4680                 rc = 0;
4681
4682                 mutex_lock(&the_lnet.ln_api_mutex);
4683                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4684                 if (!udsp)
4685                         rc = -ENOENT;
4686                 else
4687                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4688                 mutex_unlock(&the_lnet.ln_api_mutex);
4689
4690                 return rc;
4691         }
4692
4693         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4694                 struct lnet_ioctl_construct_udsp_info *info = arg;
4695
4696                 if (info->cud_hdr.ioc_len < sizeof(*info))
4697                         return -EINVAL;
4698
4699                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4700                        libcfs_nid2str(info->cud_nid));
4701
4702                 lnet_nid4_to_nid(info->cud_nid, &nid);
4703                 mutex_lock(&the_lnet.ln_api_mutex);
4704                 lnet_net_lock(0);
4705                 lnet_udsp_get_construct_info(info, &nid);
4706                 lnet_net_unlock(0);
4707                 mutex_unlock(&the_lnet.ln_api_mutex);
4708
4709                 return 0;
4710         }
4711
4712         default:
4713                 ni = lnet_net2ni_addref(data->ioc_net);
4714                 if (ni == NULL)
4715                         return -EINVAL;
4716
4717                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4718                         rc = -EINVAL;
4719                 else
4720                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4721
4722                 lnet_ni_decref(ni);
4723                 return rc <= 0 ? rc : 0;
4724         }
4725         /* not reached */
4726 }
4727 EXPORT_SYMBOL(LNetCtl);
4728
4729 /* This is the keys for the UDSP info which is used by many
4730  * Netlink commands.
4731  */
4732 static const struct ln_key_list udsp_info_list = {
4733         .lkl_maxattr                    = LNET_UDSP_INFO_ATTR_MAX,
4734         .lkl_list                       = {
4735                 [LNET_UDSP_INFO_ATTR_NET_PRIORITY]              = {
4736                         .lkp_value      = "net priority",
4737                         .lkp_data_type  = NLA_S32
4738                 },
4739                 [LNET_UDSP_INFO_ATTR_NID_PRIORITY]              = {
4740                         .lkp_value      = "nid priority",
4741                         .lkp_data_type  = NLA_S32
4742                 },
4743                 [LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST]        = {
4744                         .lkp_value      = "Preferred gateway NIDs",
4745                         .lkp_key_format = LNKF_MAPPING,
4746                         .lkp_data_type  = NLA_NESTED,
4747                 },
4748                 [LNET_UDSP_INFO_ATTR_PREF_NIDS_LIST]            = {
4749                         .lkp_value      = "Preferred source NIDs",
4750                         .lkp_key_format = LNKF_MAPPING,
4751                         .lkp_data_type  = NLA_NESTED,
4752                 },
4753         },
4754 };
4755
4756 static const struct ln_key_list udsp_info_pref_nids_list = {
4757         .lkl_maxattr                    = LNET_UDSP_INFO_PREF_NIDS_ATTR_MAX,
4758         .lkl_list                       = {
4759                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX]           = {
4760                         .lkp_value      = "NID-0",
4761                         .lkp_data_type  = NLA_NUL_STRING,
4762                 },
4763                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_NID]             = {
4764                         .lkp_value      = "0@lo",
4765                         .lkp_data_type  = NLA_STRING,
4766                 },
4767         },
4768 };
4769
4770 static int lnet_udsp_info_send(struct sk_buff *msg, int attr,
4771                                struct lnet_nid *nid, bool remote)
4772 {
4773         struct lnet_ioctl_construct_udsp_info *udsp;
4774         struct nlattr *udsp_attr, *udsp_info;
4775         struct nlattr *udsp_list_attr;
4776         struct nlattr *udsp_list_info;
4777         int i;
4778
4779         CFS_ALLOC_PTR(udsp);
4780         if (!udsp)
4781                 return -ENOMEM;
4782
4783         udsp->cud_peer = remote;
4784         lnet_udsp_get_construct_info(udsp, nid);
4785
4786         udsp_info = nla_nest_start(msg, attr);
4787         udsp_attr = nla_nest_start(msg, 0);
4788         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NET_PRIORITY,
4789                     udsp->cud_net_priority);
4790         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NID_PRIORITY,
4791                     udsp->cud_nid_priority);
4792
4793         if (udsp->cud_pref_rtr_nid[0] == 0)
4794                 goto skip_list;
4795
4796         udsp_list_info = nla_nest_start(msg,
4797                                         LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST);
4798         for (i = 0; i < LNET_MAX_SHOW_NUM_NID; i++) {
4799                 char tmp[8]; /* NID-"3 number"\0 */
4800
4801                 if (udsp->cud_pref_rtr_nid[i] == 0)
4802                         break;
4803
4804                 udsp_list_attr = nla_nest_start(msg, i);
4805                 snprintf(tmp, sizeof(tmp), "NID-%d", i);
4806                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX,
4807                                tmp);
4808                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_NID,
4809                                libcfs_nid2str(udsp->cud_pref_rtr_nid[i]));
4810                 nla_nest_end(msg, udsp_list_attr);
4811         }
4812         nla_nest_end(msg, udsp_list_info);
4813 skip_list:
4814         nla_nest_end(msg, udsp_attr);
4815         nla_nest_end(msg, udsp_info);
4816         LIBCFS_FREE(udsp, sizeof(*udsp));
4817
4818         return 0;
4819 }
4820
4821 /* LNet NI handling */
4822 static const struct ln_key_list net_props_list = {
4823         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
4824         .lkl_list                       = {
4825                 [LNET_NET_ATTR_HDR]             = {
4826                         .lkp_value              = "net",
4827                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4828                         .lkp_data_type          = NLA_NUL_STRING,
4829                 },
4830                 [LNET_NET_ATTR_TYPE]            = {
4831                         .lkp_value              = "net type",
4832                         .lkp_data_type          = NLA_STRING
4833                 },
4834                 [LNET_NET_ATTR_LOCAL]           = {
4835                         .lkp_value              = "local NI(s)",
4836                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4837                         .lkp_data_type          = NLA_NESTED
4838                 },
4839         },
4840 };
4841
4842 static struct ln_key_list local_ni_list = {
4843         .lkl_maxattr                    = LNET_NET_LOCAL_NI_ATTR_MAX,
4844         .lkl_list                       = {
4845                 [LNET_NET_LOCAL_NI_ATTR_NID]            = {
4846                         .lkp_value              = "nid",
4847                         .lkp_data_type          = NLA_STRING
4848                 },
4849                 [LNET_NET_LOCAL_NI_ATTR_STATUS]         = {
4850                         .lkp_value              = "status",
4851                         .lkp_data_type          = NLA_STRING
4852                 },
4853                 [LNET_NET_LOCAL_NI_ATTR_INTERFACE]      = {
4854                         .lkp_value              = "interfaces",
4855                         .lkp_key_format         = LNKF_MAPPING,
4856                         .lkp_data_type          = NLA_NESTED
4857                 },
4858                 [LNET_NET_LOCAL_NI_ATTR_STATS]          = {
4859                         .lkp_value              = "statistics",
4860                         .lkp_key_format         = LNKF_MAPPING,
4861                         .lkp_data_type          = NLA_NESTED
4862                 },
4863                 [LNET_NET_LOCAL_NI_ATTR_UDSP_INFO]      = {
4864                         .lkp_value              = "udsp info",
4865                         .lkp_key_format         = LNKF_MAPPING,
4866                         .lkp_data_type          = NLA_NESTED
4867                 },
4868                 [LNET_NET_LOCAL_NI_ATTR_SEND_STATS]     = {
4869                         .lkp_value              = "sent_stats",
4870                         .lkp_key_format         = LNKF_MAPPING,
4871                         .lkp_data_type          = NLA_NESTED
4872                 },
4873                 [LNET_NET_LOCAL_NI_ATTR_RECV_STATS]     = {
4874                         .lkp_value              = "received_stats",
4875                         .lkp_key_format         = LNKF_MAPPING,
4876                         .lkp_data_type          = NLA_NESTED
4877                 },
4878                 [LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS]  = {
4879                         .lkp_value              = "dropped_stats",
4880                         .lkp_key_format         = LNKF_MAPPING,
4881                         .lkp_data_type          = NLA_NESTED
4882
4883                 },
4884                 [LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS]   = {
4885                         .lkp_value              = "health stats",
4886                         .lkp_key_format         = LNKF_MAPPING,
4887                         .lkp_data_type          = NLA_NESTED
4888                 },
4889                 [LNET_NET_LOCAL_NI_ATTR_TUNABLES]       = {
4890                         .lkp_value              = "tunables",
4891                         .lkp_key_format         = LNKF_MAPPING,
4892                         .lkp_data_type          = NLA_NESTED
4893                 },
4894                 [LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES]   = {
4895                         .lkp_value              = "lnd tunables",
4896                         .lkp_key_format         = LNKF_MAPPING,
4897                         .lkp_data_type          = NLA_NESTED
4898                 },
4899                 [LNET_NET_LOCAL_NI_DEV_CPT]             = {
4900                         .lkp_value              = "dev cpt",
4901                         .lkp_data_type          = NLA_S32,
4902                 },
4903                 [LNET_NET_LOCAL_NI_CPTS]                = {
4904                         .lkp_value              = "CPT",
4905                         .lkp_data_type          = NLA_STRING,
4906                 },
4907         },
4908 };
4909
4910 static const struct ln_key_list local_ni_interfaces_list = {
4911         .lkl_maxattr                    = LNET_NET_LOCAL_NI_INTF_ATTR_MAX,
4912         .lkl_list                       = {
4913                 [LNET_NET_LOCAL_NI_INTF_ATTR_TYPE] = {
4914                         .lkp_value      = "0",
4915                         .lkp_data_type  = NLA_STRING
4916                 },
4917         },
4918 };
4919
4920 static const struct ln_key_list local_ni_stats_list = {
4921         .lkl_maxattr                    = LNET_NET_LOCAL_NI_STATS_ATTR_MAX,
4922         .lkl_list                       = {
4923                 [LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT]       = {
4924                         .lkp_value      = "send_count",
4925                         .lkp_data_type  = NLA_U32
4926                 },
4927                 [LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT]       = {
4928                         .lkp_value      = "recv_count",
4929                         .lkp_data_type  = NLA_U32
4930                 },
4931                 [LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT]       = {
4932                         .lkp_value      = "drop_count",
4933                         .lkp_data_type  = NLA_U32
4934                 },
4935         },
4936 };
4937
4938 static const struct ln_key_list local_ni_msg_stats_list = {
4939         .lkl_maxattr                    = LNET_NET_LOCAL_NI_MSG_STATS_ATTR_MAX,
4940         .lkl_list                       = {
4941                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT]    = {
4942                         .lkp_value      = "put",
4943                         .lkp_data_type  = NLA_U32
4944                 },
4945                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT]    = {
4946                         .lkp_value      = "get",
4947                         .lkp_data_type  = NLA_U32
4948                 },
4949                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT]  = {
4950                         .lkp_value      = "reply",
4951                         .lkp_data_type  = NLA_U32
4952                 },
4953                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT]    = {
4954                         .lkp_value      = "ack",
4955                         .lkp_data_type  = NLA_U32
4956                 },
4957                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT]  = {
4958                         .lkp_value      = "hello",
4959                         .lkp_data_type  = NLA_U32
4960                 },
4961         },
4962 };
4963
4964 static const struct ln_key_list local_ni_health_stats_list = {
4965         .lkl_maxattr                    = LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_MAX,
4966         .lkl_list                       = {
4967                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS] = {
4968                         .lkp_value      = "fatal_error",
4969                         .lkp_data_type  = NLA_S32
4970                 },
4971                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL] = {
4972                         .lkp_value      = "health value",
4973                         .lkp_data_type  = NLA_S32
4974                 },
4975                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS] = {
4976                         .lkp_value      = "interrupts",
4977                         .lkp_data_type  = NLA_U32
4978                 },
4979                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED] = {
4980                         .lkp_value      = "dropped",
4981                         .lkp_data_type  = NLA_U32
4982                 },
4983                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED] = {
4984                         .lkp_value      = "aborted",
4985                         .lkp_data_type  = NLA_U32
4986                 },
4987                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE] = {
4988                         .lkp_value      = "no route",
4989                         .lkp_data_type  = NLA_U32
4990                 },
4991                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS] = {
4992                         .lkp_value      = "timeouts",
4993                         .lkp_data_type  = NLA_U32
4994                 },
4995                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR] = {
4996                         .lkp_value      = "error",
4997                         .lkp_data_type  = NLA_U32
4998                 },
4999                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT] = {
5000                         .lkp_value      = "ping_count",
5001                         .lkp_data_type  = NLA_U32,
5002                 },
5003                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING] = {
5004                         .lkp_value      = "next_ping",
5005                         .lkp_data_type  = NLA_U64
5006                 },
5007         },
5008 };
5009
5010 static const struct ln_key_list local_ni_tunables_list = {
5011         .lkl_maxattr                    = LNET_NET_LOCAL_NI_TUNABLES_ATTR_MAX,
5012         .lkl_list                       = {
5013                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT]  = {
5014                         .lkp_value      = "peer_timeout",
5015                         .lkp_data_type  = NLA_S32
5016                 },
5017                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS]  = {
5018                         .lkp_value      = "peer_credits",
5019                         .lkp_data_type  = NLA_S32
5020                 },
5021                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS] = {
5022                         .lkp_value      = "peer_buffer_credits",
5023                         .lkp_data_type  = NLA_S32
5024                 },
5025                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS] = {
5026                         .lkp_value      = "credits",
5027                         .lkp_data_type  = NLA_S32
5028                 },
5029         },
5030 };
5031
5032 /* Use an index since the traversal is across LNet nets and ni collections */
5033 struct lnet_genl_net_list {
5034         unsigned int    lngl_net_id;
5035         unsigned int    lngl_idx;
5036 };
5037
5038 static inline struct lnet_genl_net_list *
5039 lnet_net_dump_ctx(struct netlink_callback *cb)
5040 {
5041         return (struct lnet_genl_net_list *)cb->args[0];
5042 }
5043
5044 static int lnet_net_show_done(struct netlink_callback *cb)
5045 {
5046         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5047
5048         if (nlist) {
5049                 LIBCFS_FREE(nlist, sizeof(*nlist));
5050                 cb->args[0] = 0;
5051         }
5052
5053         return 0;
5054 }
5055
5056 /* LNet net ->start() handler for GET requests */
5057 static int lnet_net_show_start(struct netlink_callback *cb)
5058 {
5059         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5060 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5061         struct netlink_ext_ack *extack = NULL;
5062 #endif
5063         struct lnet_genl_net_list *nlist;
5064         int msg_len = genlmsg_len(gnlh);
5065         struct nlattr *params, *top;
5066         int rem, rc = 0;
5067
5068 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5069         extack = cb->extack;
5070 #endif
5071         if (the_lnet.ln_refcount == 0) {
5072                 NL_SET_ERR_MSG(extack, "LNet stack down");
5073                 return -ENETDOWN;
5074         }
5075
5076         LIBCFS_ALLOC(nlist, sizeof(*nlist));
5077         if (!nlist)
5078                 return -ENOMEM;
5079
5080         nlist->lngl_net_id = LNET_NET_ANY;
5081         nlist->lngl_idx = 0;
5082         cb->args[0] = (long)nlist;
5083
5084         if (!msg_len)
5085                 return 0;
5086
5087         params = genlmsg_data(gnlh);
5088         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
5089                 NL_SET_ERR_MSG(extack, "invalid configuration");
5090                 return -EINVAL;
5091         }
5092
5093         nla_for_each_nested(top, params, rem) {
5094                 struct nlattr *net;
5095                 int rem2;
5096
5097                 nla_for_each_nested(net, top, rem2) {
5098                         char filter[LNET_NIDSTR_SIZE];
5099
5100                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE ||
5101                             nla_strcmp(net, "net type") != 0)
5102                                 continue;
5103
5104                         net = nla_next(net, &rem2);
5105                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE) {
5106                                 NL_SET_ERR_MSG(extack, "invalid config param");
5107                                 GOTO(report_err, rc = -EINVAL);
5108                         }
5109
5110                         rc = nla_strscpy(filter, net, sizeof(filter));
5111                         if (rc < 0) {
5112                                 NL_SET_ERR_MSG(extack, "failed to get param");
5113                                 GOTO(report_err, rc);
5114                         }
5115                         rc = 0;
5116
5117                         nlist->lngl_net_id = libcfs_str2net(filter);
5118                         if (nlist->lngl_net_id == LNET_NET_ANY) {
5119                                 NL_SET_ERR_MSG(extack, "cannot parse net");
5120                                 GOTO(report_err, rc = -ENOENT);
5121                         }
5122                 }
5123         }
5124 report_err:
5125         if (rc < 0)
5126                 lnet_net_show_done(cb);
5127
5128         return rc;
5129 }
5130
5131 static int lnet_net_show_dump(struct sk_buff *msg,
5132                               struct netlink_callback *cb)
5133 {
5134         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5135 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5136         struct netlink_ext_ack *extack = NULL;
5137 #endif
5138         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5139         int portid = NETLINK_CB(cb->skb).portid;
5140         bool found = false, started = true;
5141         const struct lnet_lnd *lnd = NULL;
5142         int idx = nlist->lngl_idx, rc = 0;
5143         int seq = cb->nlh->nlmsg_seq;
5144         struct lnet_net *net;
5145         void *hdr = NULL;
5146
5147 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5148         extack = cb->extack;
5149 #endif
5150         lnet_net_lock(LNET_LOCK_EX);
5151
5152         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
5153                 struct nlattr *local_ni, *ni_attr;
5154                 struct lnet_ni *ni;
5155                 int dev = 0;
5156
5157                 if (nlist->lngl_net_id != LNET_NET_ANY &&
5158                     nlist->lngl_net_id != net->net_id)
5159                         continue;
5160
5161                 if (gnlh->version && LNET_NETTYP(net->net_id) != LOLND) {
5162                         if (!net->net_lnd) {
5163                                 NL_SET_ERR_MSG(extack,
5164                                                "LND not setup for NI");
5165                                 GOTO(net_unlock, rc = -ENODEV);
5166                         }
5167                         if (net->net_lnd != lnd)
5168                                 lnd = net->net_lnd;
5169                         else
5170                                 lnd = NULL;
5171                 }
5172
5173                 /* We need to resend the key table every time the base LND
5174                  * changed.
5175                  */
5176                 if (!idx || lnd) {
5177                         const struct ln_key_list *all[] = {
5178                                 &net_props_list, &local_ni_list,
5179                                 &local_ni_interfaces_list,
5180                                 &local_ni_stats_list,
5181                                 &udsp_info_list,
5182                                 &udsp_info_pref_nids_list,
5183                                 &udsp_info_pref_nids_list,
5184                                 &local_ni_msg_stats_list,
5185                                 &local_ni_msg_stats_list,
5186                                 &local_ni_msg_stats_list,
5187                                 &local_ni_health_stats_list,
5188                                 &local_ni_tunables_list,
5189                                 NULL, /* lnd tunables */
5190                                 NULL
5191                         };
5192                         int flags = NLM_F_CREATE | NLM_F_MULTI;
5193
5194                         if (lnd) {
5195                                 all[ARRAY_SIZE(all) - 2] = lnd->lnd_keys;
5196                                 if (idx)
5197                                         flags |= NLM_F_REPLACE;
5198                                 started = true;
5199                         }
5200
5201                         rc = lnet_genl_send_scalar_list(msg, portid, seq,
5202                                                         &lnet_family, flags,
5203                                                         LNET_CMD_NETS, all);
5204                         if (rc < 0) {
5205                                 NL_SET_ERR_MSG(extack, "failed to send key table");
5206                                 GOTO(net_unlock, rc);
5207                         }
5208                 }
5209
5210                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5211                                   NLM_F_MULTI, LNET_CMD_NETS);
5212                 if (!hdr) {
5213                         NL_SET_ERR_MSG(extack, "failed to send values");
5214                         GOTO(net_unlock, rc = -EMSGSIZE);
5215                 }
5216
5217                 if (started) {
5218                         nla_put_string(msg, LNET_NET_ATTR_HDR, "");
5219                         started = false;
5220                 }
5221
5222                 nla_put_string(msg, LNET_NET_ATTR_TYPE,
5223                                libcfs_net2str(net->net_id));
5224
5225                 local_ni = nla_nest_start(msg, LNET_NET_ATTR_LOCAL);
5226                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
5227                         char *status = "up";
5228
5229                         if (idx++ < nlist->lngl_idx)
5230                                 continue;
5231
5232                         ni_attr = nla_nest_start(msg, dev++);
5233                         found = true;
5234                         lnet_ni_lock(ni);
5235                         nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_NID,
5236                                        libcfs_nidstr(&ni->ni_nid));
5237                         if (!nid_is_lo0(&ni->ni_nid) &&
5238                             *ni->ni_status != LNET_NI_STATUS_UP)
5239                                 status = "down";
5240                         nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_STATUS,
5241                                        status);
5242
5243                         if (!nid_is_lo0(&ni->ni_nid) && ni->ni_interface) {
5244                                 struct nlattr *intf_nest, *intf_attr;
5245
5246                                 intf_nest = nla_nest_start(msg,
5247                                                            LNET_NET_LOCAL_NI_ATTR_INTERFACE);
5248                                 intf_attr = nla_nest_start(msg, 0);
5249                                 nla_put_string(msg,
5250                                                LNET_NET_LOCAL_NI_INTF_ATTR_TYPE,
5251                                                ni->ni_interface);
5252                                 nla_nest_end(msg, intf_attr);
5253                                 nla_nest_end(msg, intf_nest);
5254                         }
5255
5256                         if (gnlh->version) {
5257                                 char cpts[LNET_MAX_SHOW_NUM_CPT * 4 + 4], *cpt;
5258                                 struct lnet_ioctl_element_msg_stats msg_stats;
5259                                 struct lnet_ioctl_element_stats stats;
5260                                 size_t buf_len = sizeof(cpts), len;
5261                                 struct nlattr *health_attr, *health_stats;
5262                                 struct nlattr *send_attr, *send_stats;
5263                                 struct nlattr *recv_attr, *recv_stats;
5264                                 struct nlattr *drop_attr, *drop_stats;
5265                                 struct nlattr *stats_attr, *ni_stats;
5266                                 struct nlattr *tun_attr, *ni_tun;
5267                                 int j;
5268
5269                                 stats.iel_send_count = lnet_sum_stats(&ni->ni_stats,
5270                                                                       LNET_STATS_TYPE_SEND);
5271                                 stats.iel_recv_count = lnet_sum_stats(&ni->ni_stats,
5272                                                                       LNET_STATS_TYPE_RECV);
5273                                 stats.iel_drop_count = lnet_sum_stats(&ni->ni_stats,
5274                                                                       LNET_STATS_TYPE_DROP);
5275                                 lnet_ni_unlock(ni);
5276
5277                                 stats_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_STATS);
5278                                 ni_stats = nla_nest_start(msg, 0);
5279                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT,
5280                                             stats.iel_send_count);
5281                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT,
5282                                             stats.iel_recv_count);
5283                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT,
5284                                             stats.iel_drop_count);
5285                                 nla_nest_end(msg, ni_stats);
5286                                 nla_nest_end(msg, stats_attr);
5287
5288                                 if (gnlh->version < 4)
5289                                         goto skip_udsp;
5290
5291                                 /* UDSP info */
5292                                 rc = lnet_udsp_info_send(msg, LNET_NET_LOCAL_NI_ATTR_UDSP_INFO,
5293                                                          &ni->ni_nid, false);
5294                                 if (rc < 0) {
5295                                         NL_SET_ERR_MSG(extack,
5296                                                        "Failed to get udsp info");
5297                                         genlmsg_cancel(msg, hdr);
5298                                         GOTO(net_unlock, rc = -ENOMEM);
5299                                 }
5300 skip_udsp:
5301                                 if (gnlh->version < 2)
5302                                         goto skip_msg_stats;
5303
5304                                 msg_stats.im_idx = idx - 1;
5305                                 rc = lnet_get_ni_stats(&msg_stats);
5306                                 if (rc < 0) {
5307                                         NL_SET_ERR_MSG(extack,
5308                                                        "failed to get msg stats");
5309                                         genlmsg_cancel(msg, hdr);
5310                                         GOTO(net_unlock, rc = -ENOMEM);
5311                                 }
5312
5313                                 send_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_SEND_STATS);
5314                                 send_attr = nla_nest_start(msg, 0);
5315                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5316                                             msg_stats.im_send_stats.ico_get_count);
5317                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5318                                             msg_stats.im_send_stats.ico_put_count);
5319                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5320                                             msg_stats.im_send_stats.ico_reply_count);
5321                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5322                                             msg_stats.im_send_stats.ico_ack_count);
5323                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5324                                             msg_stats.im_send_stats.ico_hello_count);
5325                                 nla_nest_end(msg, send_attr);
5326                                 nla_nest_end(msg, send_stats);
5327
5328                                 recv_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_RECV_STATS);
5329                                 recv_attr = nla_nest_start(msg, 0);
5330                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5331                                             msg_stats.im_recv_stats.ico_get_count);
5332                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5333                                             msg_stats.im_recv_stats.ico_put_count);
5334                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5335                                             msg_stats.im_recv_stats.ico_reply_count);
5336                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5337                                             msg_stats.im_recv_stats.ico_ack_count);
5338                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5339                                             msg_stats.im_recv_stats.ico_hello_count);
5340                                 nla_nest_end(msg, recv_attr);
5341                                 nla_nest_end(msg, recv_stats);
5342
5343                                 drop_stats = nla_nest_start(msg,
5344                                                             LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS);
5345                                 drop_attr = nla_nest_start(msg, 0);
5346                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5347                                             msg_stats.im_drop_stats.ico_get_count);
5348                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5349                                             msg_stats.im_drop_stats.ico_put_count);
5350                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5351                                             msg_stats.im_drop_stats.ico_reply_count);
5352                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5353                                             msg_stats.im_drop_stats.ico_ack_count);
5354                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5355                                             msg_stats.im_drop_stats.ico_hello_count);
5356                                 nla_nest_end(msg, drop_attr);
5357                                 nla_nest_end(msg, drop_stats);
5358
5359                                 /* health stats */
5360                                 health_stats = nla_nest_start(msg,
5361                                                               LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS);
5362                                 health_attr = nla_nest_start(msg, 0);
5363                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS,
5364                                             atomic_read(&ni->ni_fatal_error_on));
5365                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL,
5366                                             atomic_read(&ni->ni_healthv));
5367                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS,
5368                                             atomic_read(&ni->ni_hstats.hlt_local_interrupt));
5369                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED,
5370                                             atomic_read(&ni->ni_hstats.hlt_local_dropped));
5371                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED,
5372                                             atomic_read(&ni->ni_hstats.hlt_local_aborted));
5373                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE,
5374                                             atomic_read(&ni->ni_hstats.hlt_local_no_route));
5375                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS,
5376                                             atomic_read(&ni->ni_hstats.hlt_local_timeout));
5377                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR,
5378                                             atomic_read(&ni->ni_hstats.hlt_local_error));
5379                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT,
5380                                             ni->ni_ping_count);
5381                                 nla_put_u64_64bit(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING,
5382                                                   ni->ni_next_ping,
5383                                                   LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PAD);
5384                                 nla_nest_end(msg, health_attr);
5385                                 nla_nest_end(msg, health_stats);
5386 skip_msg_stats:
5387                                 /* Report net tunables */
5388                                 tun_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_TUNABLES);
5389                                 ni_tun = nla_nest_start(msg, 0);
5390                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT,
5391                                             ni->ni_net->net_tunables.lct_peer_timeout);
5392                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS,
5393                                             ni->ni_net->net_tunables.lct_peer_tx_credits);
5394                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS,
5395                                             ni->ni_net->net_tunables.lct_peer_rtr_credits);
5396                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS,
5397                                             ni->ni_net->net_tunables.lct_max_tx_credits);
5398                                 nla_nest_end(msg, ni_tun);
5399
5400                                 nla_nest_end(msg, tun_attr);
5401
5402                                 if (lnd && lnd->lnd_nl_get && lnd->lnd_keys) {
5403                                         struct nlattr *lnd_tun_attr, *lnd_ni_tun;
5404
5405                                         lnd_tun_attr = nla_nest_start(msg,
5406                                                                       LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES);
5407                                         lnd_ni_tun = nla_nest_start(msg, 0);
5408                                         rc = lnd->lnd_nl_get(LNET_CMD_NETS, msg,
5409                                                              LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES,
5410                                                              ni);
5411                                         if (rc < 0) {
5412                                                 NL_SET_ERR_MSG(extack,
5413                                                                "failed to get lnd tunables");
5414                                                 genlmsg_cancel(msg, hdr);
5415                                                 GOTO(net_unlock, rc);
5416                                         }
5417                                         nla_nest_end(msg, lnd_ni_tun);
5418                                         nla_nest_end(msg, lnd_tun_attr);
5419                                 }
5420
5421                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_DEV_CPT, ni->ni_dev_cpt);
5422
5423                                 /* Report cpts. We could send this as a nested list
5424                                  * of integers but older versions of the tools
5425                                  * except a string. The new versions can handle
5426                                  * both formats so in the future we can change
5427                                  * this to a nested list.
5428                                  */
5429                                 len = snprintf(cpts, buf_len, "\"[");
5430                                 cpt = cpts + len;
5431                                 buf_len -= len;
5432
5433                                 if (ni->ni_ncpts == LNET_CPT_NUMBER && !ni->ni_cpts)  {
5434                                         for (j = 0; j < ni->ni_ncpts; j++) {
5435                                                 len = snprintf(cpt, buf_len, "%d,", j);
5436                                                 buf_len -= len;
5437                                                 cpt += len;
5438                                         }
5439                                 } else {
5440                                         for (j = 0;
5441                                              ni->ni_cpts && j < ni->ni_ncpts &&
5442                                              j < LNET_MAX_SHOW_NUM_CPT; j++) {
5443                                                 len = snprintf(cpt, buf_len, "%d,",
5444                                                                ni->ni_cpts[j]);
5445                                                 buf_len -= len;
5446                                                 cpt += len;
5447                                         }
5448                                 }
5449                                 snprintf(cpt - 1, sizeof(cpts), "]\"");
5450
5451                                 nla_put_string(msg, LNET_NET_LOCAL_NI_CPTS, cpts);
5452                         } else {
5453                                 lnet_ni_unlock(ni);
5454                         }
5455                         nla_nest_end(msg, ni_attr);
5456                 }
5457                 nla_nest_end(msg, local_ni);
5458
5459                 genlmsg_end(msg, hdr);
5460         }
5461
5462         if (!found) {
5463                 struct nlmsghdr *nlh = nlmsg_hdr(msg);
5464
5465                 nlmsg_cancel(msg, nlh);
5466                 NL_SET_ERR_MSG(extack, "Network is down");
5467                 rc = -ESRCH;
5468         }
5469         nlist->lngl_idx = idx;
5470 net_unlock:
5471         lnet_net_unlock(LNET_LOCK_EX);
5472
5473         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5474 }
5475
5476 #ifndef HAVE_NETLINK_CALLBACK_START
5477 static int lnet_old_net_show_dump(struct sk_buff *msg,
5478                                    struct netlink_callback *cb)
5479 {
5480         if (!cb->args[0]) {
5481                 int rc = lnet_net_show_start(cb);
5482
5483                 if (rc < 0)
5484                         return rc;
5485         }
5486
5487         return lnet_net_show_dump(msg, cb);
5488 }
5489 #endif
5490
5491 static int lnet_genl_parse_tunables(struct nlattr *settings,
5492                                     struct lnet_ioctl_config_lnd_tunables *tun)
5493 {
5494         struct nlattr *param;
5495         int rem, rc = 0;
5496
5497         nla_for_each_nested(param, settings, rem) {
5498                 int type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_UNSPEC;
5499                 s64 num;
5500
5501                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5502                         continue;
5503
5504                 if (nla_strcmp(param, "peer_timeout") == 0)
5505                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT;
5506                 else if (nla_strcmp(param, "peer_credits") == 0)
5507                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS;
5508                 else if (nla_strcmp(param, "peer_buffer_credits") == 0)
5509                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS;
5510                 else if (nla_strcmp(param, "credits") == 0)
5511                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS;
5512
5513                 param = nla_next(param, &rem);
5514                 if (nla_type(param) != LN_SCALAR_ATTR_INT_VALUE)
5515                         return -EINVAL;
5516
5517                 num = nla_get_s64(param);
5518                 switch (type) {
5519                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT:
5520                         if (num >= 0)
5521                                 tun->lt_cmn.lct_peer_timeout = num;
5522                         break;
5523                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS:
5524                         if (num > 0)
5525                                 tun->lt_cmn.lct_peer_tx_credits = num;
5526                         break;
5527                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS:
5528                         if (num > 0)
5529                                 tun->lt_cmn.lct_peer_rtr_credits = num;
5530                         break;
5531                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS:
5532                         if (num > 0)
5533                                 tun->lt_cmn.lct_max_tx_credits = num;
5534                         break;
5535                 default:
5536                         rc = -EINVAL;
5537                         break;
5538                 }
5539         }
5540         return rc;
5541 }
5542
5543 static int lnet_genl_parse_lnd_tunables(struct nlattr *settings,
5544                                         struct lnet_lnd_tunables *tun,
5545                                         const struct lnet_lnd *lnd)
5546 {
5547         const struct ln_key_list *list = lnd->lnd_keys;
5548         struct nlattr *param;
5549         int rem, rc = 0;
5550         int i = 1;
5551
5552         /* silently ignore these setting if the LND driver doesn't
5553          * support any LND tunables
5554          */
5555         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5556                 return 0;
5557
5558         nla_for_each_nested(param, settings, rem) {
5559                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5560                         continue;
5561
5562                 for (i = 1; i <= list->lkl_maxattr; i++) {
5563                         if (!list->lkl_list[i].lkp_value ||
5564                             nla_strcmp(param, list->lkl_list[i].lkp_value) != 0)
5565                                 continue;
5566
5567                         param = nla_next(param, &rem);
5568                         rc = lnd->lnd_nl_set(LNET_CMD_NETS, param, i, tun);
5569                         if (rc < 0)
5570                                 return rc;
5571                 }
5572         }
5573
5574         return rc;
5575 }
5576
5577 static int
5578 lnet_genl_parse_local_ni(struct nlattr *entry, struct genl_info *info,
5579                          int net_id, struct lnet_ioctl_config_ni *conf,
5580                          bool *ni_list)
5581 {
5582         bool create = info->nlhdr->nlmsg_flags & NLM_F_CREATE;
5583         struct lnet_ioctl_config_lnd_tunables *tun;
5584         struct nlattr *settings;
5585         int rem3, rc = 0;
5586
5587         LIBCFS_ALLOC(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5588         if (!tun) {
5589                 GENL_SET_ERR_MSG(info, "cannot allocate memory for tunables");
5590                 GOTO(out, rc = -ENOMEM);
5591         }
5592
5593         /* Use LND defaults */
5594         tun->lt_cmn.lct_peer_timeout = -1;
5595         tun->lt_cmn.lct_peer_tx_credits = -1;
5596         tun->lt_cmn.lct_peer_rtr_credits = -1;
5597         tun->lt_cmn.lct_max_tx_credits = -1;
5598         conf->lic_ncpts = 0;
5599
5600         nla_for_each_nested(settings, entry, rem3) {
5601                 if (nla_type(settings) != LN_SCALAR_ATTR_VALUE)
5602                         continue;
5603
5604                 if (nla_strcmp(settings, "interfaces") == 0) {
5605                         struct nlattr *intf;
5606                         int rem4;
5607
5608                         settings = nla_next(settings, &rem3);
5609                         if (nla_type(settings) !=
5610                             LN_SCALAR_ATTR_LIST) {
5611                                 GENL_SET_ERR_MSG(info,
5612                                                  "invalid interfaces");
5613                                 GOTO(out, rc = -EINVAL);
5614                         }
5615
5616                         nla_for_each_nested(intf, settings, rem4) {
5617                                 intf = nla_next(intf, &rem4);
5618                                 if (nla_type(intf) !=
5619                                     LN_SCALAR_ATTR_VALUE) {
5620                                         GENL_SET_ERR_MSG(info,
5621                                                          "cannot parse interface");
5622                                         GOTO(out, rc = -EINVAL);
5623                                 }
5624
5625                                 rc = nla_strscpy(conf->lic_ni_intf, intf,
5626                                                  sizeof(conf->lic_ni_intf));
5627                                 if (rc < 0) {
5628                                         GENL_SET_ERR_MSG(info,
5629                                                          "failed to parse interfaces");
5630                                         GOTO(out, rc);
5631                                 }
5632                         }
5633                         *ni_list = true;
5634                 } else if (nla_strcmp(settings, "tunables") == 0) {
5635                         settings = nla_next(settings, &rem3);
5636                         if (nla_type(settings) !=
5637                             LN_SCALAR_ATTR_LIST) {
5638                                 GENL_SET_ERR_MSG(info,
5639                                                  "invalid tunables");
5640                                 GOTO(out, rc = -EINVAL);
5641                         }
5642
5643                         rc = lnet_genl_parse_tunables(settings, tun);
5644                         if (rc < 0) {
5645                                 GENL_SET_ERR_MSG(info,
5646                                                  "failed to parse tunables");
5647                                 GOTO(out, rc);
5648                         }
5649                 } else if ((nla_strcmp(settings, "lnd tunables") == 0)) {
5650                         const struct lnet_lnd *lnd;
5651
5652                         lnd = lnet_load_lnd(LNET_NETTYP(net_id));
5653                         if (IS_ERR(lnd)) {
5654                                 GENL_SET_ERR_MSG(info,
5655                                                  "LND type not supported");
5656                                 GOTO(out, rc = PTR_ERR(lnd));
5657                         }
5658
5659                         settings = nla_next(settings, &rem3);
5660                         if (nla_type(settings) !=
5661                             LN_SCALAR_ATTR_LIST) {
5662                                 GENL_SET_ERR_MSG(info,
5663                                                  "lnd tunables should be list\n");
5664                                 GOTO(out, rc = -EINVAL);
5665                         }
5666
5667                         rc = lnet_genl_parse_lnd_tunables(settings,
5668                                                           &tun->lt_tun, lnd);
5669                         if (rc < 0) {
5670                                 GENL_SET_ERR_MSG(info,
5671                                                  "failed to parse lnd tunables");
5672                                 GOTO(out, rc);
5673                         }
5674                 } else if (nla_strcmp(settings, "CPT") == 0) {
5675                         struct nlattr *cpt;
5676                         int rem4;
5677
5678                         settings = nla_next(settings, &rem3);
5679                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
5680                                 GENL_SET_ERR_MSG(info,
5681                                                  "CPT should be list");
5682                                 GOTO(out, rc = -EINVAL);
5683                         }
5684
5685                         nla_for_each_nested(cpt, settings, rem4) {
5686                                 s64 core;
5687
5688                                 if (nla_type(cpt) !=
5689                                     LN_SCALAR_ATTR_INT_VALUE) {
5690                                         GENL_SET_ERR_MSG(info,
5691                                                          "invalid CPT config");
5692                                         GOTO(out, rc = -EINVAL);
5693                                 }
5694
5695                                 core = nla_get_s64(cpt);
5696                                 if (core >= LNET_CPT_NUMBER) {
5697                                         GENL_SET_ERR_MSG(info,
5698                                                          "invalid CPT value");
5699                                         GOTO(out, rc = -ERANGE);
5700                                 }
5701
5702                                 conf->lic_cpts[conf->lic_ncpts] = core;
5703                                 conf->lic_ncpts++;
5704                         }
5705                 }
5706         }
5707
5708         if (!create) {
5709                 struct lnet_net *net;
5710                 struct lnet_ni *ni;
5711
5712                 rc = -ENODEV;
5713                 if (!strlen(conf->lic_ni_intf)) {
5714                         GENL_SET_ERR_MSG(info,
5715                                          "interface is missing");
5716                         GOTO(out, rc);
5717                 }
5718
5719                 lnet_net_lock(LNET_LOCK_EX);
5720                 net = lnet_get_net_locked(net_id);
5721                 if (!net) {
5722                         GENL_SET_ERR_MSG(info,
5723                                          "LNet net doesn't exist");
5724                         lnet_net_unlock(LNET_LOCK_EX);
5725                         GOTO(out, rc);
5726                 }
5727
5728                 list_for_each_entry(ni, &net->net_ni_list,
5729                                     ni_netlist) {
5730                         if (!ni->ni_interface ||
5731                             strcmp(ni->ni_interface,
5732                                   conf->lic_ni_intf) != 0)
5733                                 continue;
5734
5735                         lnet_net_unlock(LNET_LOCK_EX);
5736                         rc = lnet_dyn_del_ni(&ni->ni_nid);
5737                         if (rc < 0) {
5738                                 GENL_SET_ERR_MSG(info,
5739                                                  "cannot del LNet NI");
5740                                 GOTO(out, rc);
5741                         }
5742                         break;
5743                 }
5744
5745                 if (rc < 0) { /* will be -ENODEV */
5746                         GENL_SET_ERR_MSG(info,
5747                                          "interface invalid for deleting LNet NI");
5748                         lnet_net_unlock(LNET_LOCK_EX);
5749                 }
5750         } else {
5751                 if (!strlen(conf->lic_ni_intf)) {
5752                         GENL_SET_ERR_MSG(info,
5753                                          "interface is missing");
5754                         GOTO(out, rc);
5755                 }
5756
5757                 rc = lnet_dyn_add_ni(conf, net_id, tun);
5758                 switch (rc) {
5759                 case -ENOENT:
5760                         GENL_SET_ERR_MSG(info,
5761                                          "cannot parse net");
5762                         break;
5763                 case -ERANGE:
5764                         GENL_SET_ERR_MSG(info,
5765                                          "invalid CPT set");
5766                         break;
5767                 default:
5768                         GENL_SET_ERR_MSG(info,
5769                                          "cannot add LNet NI");
5770                 case 0:
5771                         break;
5772                 }
5773         }
5774 out:
5775         if (tun)
5776                 LIBCFS_FREE(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5777
5778         return rc;
5779 }
5780
5781 static int lnet_net_cmd(struct sk_buff *skb, struct genl_info *info)
5782 {
5783         struct nlmsghdr *nlh = nlmsg_hdr(skb);
5784         struct genlmsghdr *gnlh = nlmsg_data(nlh);
5785         struct nlattr *params = genlmsg_data(gnlh);
5786         int msg_len, rem, rc = 0;
5787         struct nlattr *attr;
5788
5789         msg_len = genlmsg_len(gnlh);
5790         if (!msg_len) {
5791                 GENL_SET_ERR_MSG(info, "no configuration");
5792                 return -ENOMSG;
5793         }
5794
5795         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
5796                 GENL_SET_ERR_MSG(info, "invalid configuration");
5797                 return -EINVAL;
5798         }
5799
5800         nla_for_each_nested(attr, params, rem) {
5801                 bool ni_list = false, ipnets = false;
5802                 struct lnet_ioctl_config_ni conf;
5803                 u32 net_id = LNET_NET_ANY;
5804                 struct nlattr *entry;
5805                 int rem2;
5806
5807                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
5808                         continue;
5809
5810                 nla_for_each_nested(entry, attr, rem2) {
5811                         switch (nla_type(entry)) {
5812                         case LN_SCALAR_ATTR_VALUE: {
5813                                 ssize_t len;
5814
5815                                 memset(&conf, 0, sizeof(conf));
5816                                 if (nla_strcmp(entry, "ip2net") == 0) {
5817                                         entry = nla_next(entry, &rem2);
5818                                         if (nla_type(entry) !=
5819                                             LN_SCALAR_ATTR_VALUE) {
5820                                                 GENL_SET_ERR_MSG(info,
5821                                                                  "ip2net has invalid key");
5822                                                 GOTO(out, rc = -EINVAL);
5823                                         }
5824
5825                                         len = nla_strscpy(conf.lic_legacy_ip2nets,
5826                                                           entry,
5827                                                           sizeof(conf.lic_legacy_ip2nets));
5828                                         if (len < 0) {
5829                                                 GENL_SET_ERR_MSG(info,
5830                                                                  "ip2net key string is invalid");
5831                                                 GOTO(out, rc = len);
5832                                         }
5833                                         ni_list = true;
5834                                         ipnets = true;
5835                                 } else if (nla_strcmp(entry, "net type") == 0) {
5836                                         char tmp[LNET_NIDSTR_SIZE];
5837
5838                                         entry = nla_next(entry, &rem2);
5839                                         if (nla_type(entry) !=
5840                                             LN_SCALAR_ATTR_VALUE) {
5841                                                 GENL_SET_ERR_MSG(info,
5842                                                                  "net type has invalid key");
5843                                                 GOTO(out, rc = -EINVAL);
5844                                         }
5845
5846                                         len = nla_strscpy(tmp, entry,
5847                                                           sizeof(tmp));
5848                                         if (len < 0) {
5849                                                 GENL_SET_ERR_MSG(info,
5850                                                                  "net type key string is invalid");
5851                                                 GOTO(out, rc = len);
5852                                         }
5853
5854                                         net_id = libcfs_str2net(tmp);
5855                                         if (!net_id) {
5856                                                 GENL_SET_ERR_MSG(info,
5857                                                                  "cannot parse net");
5858                                                 GOTO(out, rc = -ENODEV);
5859                                         }
5860                                         if (LNET_NETTYP(net_id) == LOLND) {
5861                                                 GENL_SET_ERR_MSG(info,
5862                                                                  "setting @lo not allowed");
5863                                                 GOTO(out, rc = -ENODEV);
5864                                         }
5865                                         conf.lic_legacy_ip2nets[0] = '\0';
5866                                         conf.lic_ni_intf[0] = '\0';
5867                                         ni_list = false;
5868                                 }
5869                                 if (rc < 0)
5870                                         GOTO(out, rc);
5871                                 break;
5872                         }
5873                         case LN_SCALAR_ATTR_LIST: {
5874                                 struct nlattr *interface;
5875                                 int rem3;
5876
5877                                 ipnets = false;
5878                                 nla_for_each_nested(interface, entry, rem3) {
5879                                         rc = lnet_genl_parse_local_ni(interface, info,
5880                                                                       net_id, &conf,
5881                                                                       &ni_list);
5882                                         if (rc < 0)
5883                                                 GOTO(out, rc);
5884                                 }
5885                                 break;
5886                         }
5887                         /* it is possible a newer version of the user land send
5888                          * values older kernels doesn't handle. So silently
5889                          * ignore these values
5890                          */
5891                         default:
5892                                 break;
5893                         }
5894                 }
5895
5896                 /* Handle case of just sent NET with no list of NIDs */
5897                 if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE) && !ni_list) {
5898                         rc = lnet_dyn_del_net(net_id);
5899                         if (rc < 0) {
5900                                 GENL_SET_ERR_MSG(info,
5901                                                  "cannot del network");
5902                         }
5903                 } else if ((info->nlhdr->nlmsg_flags & NLM_F_CREATE) &&
5904                            ipnets && ni_list) {
5905                         rc = lnet_handle_legacy_ip2nets(conf.lic_legacy_ip2nets,
5906                                                         NULL);
5907                         if (rc < 0)
5908                                 GENL_SET_ERR_MSG(info,
5909                                                  "cannot setup ip2nets");
5910                 }
5911         }
5912 out:
5913         return rc;
5914 }
5915
5916 /** LNet route handling */
5917
5918 /* We can't use struct lnet_ioctl_config_data since it lacks
5919  * support for large NIDS
5920  */
5921 struct lnet_route_properties {
5922         struct lnet_nid         lrp_gateway;
5923         u32                     lrp_net;
5924         s32                     lrp_hop;
5925         u32                     lrp_flags;
5926         u32                     lrp_priority;
5927         u32                     lrp_sensitivity;
5928 };
5929
5930 struct lnet_genl_route_list {
5931         unsigned int                            lgrl_index;
5932         unsigned int                            lgrl_count;
5933         GENRADIX(struct lnet_route_properties)  lgrl_list;
5934 };
5935
5936 static inline struct lnet_genl_route_list *
5937 lnet_route_dump_ctx(struct netlink_callback *cb)
5938 {
5939         return (struct lnet_genl_route_list *)cb->args[0];
5940 }
5941
5942 static int lnet_route_show_done(struct netlink_callback *cb)
5943 {
5944         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
5945
5946         if (rlist) {
5947                 genradix_free(&rlist->lgrl_list);
5948                 CFS_FREE_PTR(rlist);
5949         }
5950         cb->args[0] = 0;
5951
5952         return 0;
5953 }
5954
5955 static int lnet_scan_route(struct lnet_genl_route_list *rlist,
5956                     struct lnet_route_properties *settings)
5957 {
5958         struct lnet_remotenet *rnet;
5959         struct list_head *rn_list;
5960         struct lnet_route *route;
5961         int cpt, i, rc = 0;
5962
5963         cpt = lnet_net_lock_current();
5964
5965         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
5966                 rn_list = &the_lnet.ln_remote_nets_hash[i];
5967                 list_for_each_entry(rnet, rn_list, lrn_list) {
5968                         if (settings->lrp_net != LNET_NET_ANY &&
5969                             settings->lrp_net != rnet->lrn_net)
5970                                 continue;
5971
5972                         list_for_each_entry(route, &rnet->lrn_routes,
5973                                             lr_list) {
5974                                 struct lnet_route_properties *prop;
5975
5976                                 if (!LNET_NID_IS_ANY(&settings->lrp_gateway) &&
5977                                     !nid_same(&settings->lrp_gateway,
5978                                               &route->lr_nid)) {
5979                                         continue;
5980                                 }
5981
5982                                 if (settings->lrp_hop != -1 &&
5983                                     settings->lrp_hop != route->lr_hops)
5984                                         continue;
5985
5986                                 if (settings->lrp_priority != -1 &&
5987                                     settings->lrp_priority != route->lr_priority)
5988                                         continue;
5989
5990                                 if (settings->lrp_sensitivity != -1 &&
5991                                     settings->lrp_sensitivity !=
5992                                     route->lr_gateway->lp_health_sensitivity)
5993                                         continue;
5994
5995                                 prop = genradix_ptr_alloc(&rlist->lgrl_list,
5996                                                           rlist->lgrl_count++,
5997                                                           GFP_KERNEL);
5998                                 if (!prop)
5999                                         GOTO(failed_alloc, rc = -ENOMEM);
6000
6001                                 prop->lrp_net = rnet->lrn_net;
6002                                 prop->lrp_gateway = route->lr_nid;
6003                                 prop->lrp_hop = route->lr_hops;
6004                                 prop->lrp_priority = route->lr_priority;
6005                                 prop->lrp_sensitivity =
6006                                         route->lr_gateway->lp_health_sensitivity;
6007                                 if (lnet_is_route_alive(route))
6008                                         prop->lrp_flags |= LNET_RT_ALIVE;
6009                                 else
6010                                         prop->lrp_flags &= ~LNET_RT_ALIVE;
6011                                 if (route->lr_single_hop)
6012                                         prop->lrp_flags &= ~LNET_RT_MULTI_HOP;
6013                                 else
6014                                         prop->lrp_flags |= LNET_RT_MULTI_HOP;
6015                         }
6016                 }
6017         }
6018
6019 failed_alloc:
6020         lnet_net_unlock(cpt);
6021         return rc;
6022 }
6023
6024 /* LNet route ->start() handler for GET requests */
6025 static int lnet_route_show_start(struct netlink_callback *cb)
6026 {
6027         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6028 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6029         struct netlink_ext_ack *extack = NULL;
6030 #endif
6031         struct lnet_genl_route_list *rlist;
6032         int msg_len = genlmsg_len(gnlh);
6033         int rc = 0;
6034
6035 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6036         extack = cb->extack;
6037 #endif
6038         if (the_lnet.ln_refcount == 0 ||
6039             the_lnet.ln_state != LNET_STATE_RUNNING) {
6040                 NL_SET_ERR_MSG(extack, "Network is down");
6041                 return -ENETDOWN;
6042         }
6043
6044         CFS_ALLOC_PTR(rlist);
6045         if (!rlist) {
6046                 NL_SET_ERR_MSG(extack, "No memory for route list");
6047                 return -ENOMEM;
6048         }
6049
6050         genradix_init(&rlist->lgrl_list);
6051         rlist->lgrl_count = 0;
6052         rlist->lgrl_index = 0;
6053         cb->args[0] = (long)rlist;
6054
6055         mutex_lock(&the_lnet.ln_api_mutex);
6056         if (!msg_len) {
6057                 struct lnet_route_properties tmp = {
6058                         .lrp_gateway            = LNET_ANY_NID,
6059                         .lrp_net                = LNET_NET_ANY,
6060                         .lrp_hop                = -1,
6061                         .lrp_priority           = -1,
6062                         .lrp_sensitivity        = -1,
6063                 };
6064
6065                 rc = lnet_scan_route(rlist, &tmp);
6066                 if (rc < 0) {
6067                         NL_SET_ERR_MSG(extack,
6068                                        "failed to allocate router data");
6069                         GOTO(report_err, rc);
6070                 }
6071         } else {
6072                 struct nlattr *params = genlmsg_data(gnlh);
6073                 struct nlattr *attr;
6074                 int rem;
6075
6076                 nla_for_each_nested(attr, params, rem) {
6077                         struct lnet_route_properties tmp = {
6078                                 .lrp_gateway            = LNET_ANY_NID,
6079                                 .lrp_net                = LNET_NET_ANY,
6080                                 .lrp_hop                = -1,
6081                                 .lrp_priority           = -1,
6082                                 .lrp_sensitivity        = -1,
6083                         };
6084                         struct nlattr *route;
6085                         int rem2;
6086
6087                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6088                                 continue;
6089
6090                         nla_for_each_nested(route, attr, rem2) {
6091                                 if (nla_type(route) != LN_SCALAR_ATTR_VALUE)
6092                                         continue;
6093
6094                                 if (nla_strcmp(route, "net") == 0) {
6095                                         char nw[LNET_NIDSTR_SIZE];
6096
6097                                         route = nla_next(route, &rem2);
6098                                         if (nla_type(route) !=
6099                                             LN_SCALAR_ATTR_VALUE) {
6100                                                 NL_SET_ERR_MSG(extack,
6101                                                                "invalid net param");
6102                                                 GOTO(report_err, rc = -EINVAL);
6103                                         }
6104
6105                                         rc = nla_strscpy(nw, route, sizeof(nw));
6106                                         if (rc < 0) {
6107                                                 NL_SET_ERR_MSG(extack,
6108                                                                "failed to get route param");
6109                                                 GOTO(report_err, rc);
6110                                         }
6111                                         rc = 0;
6112                                         tmp.lrp_net = libcfs_str2net(strim(nw));
6113                                 } else if (nla_strcmp(route, "gateway") == 0) {
6114                                         char gw[LNET_NIDSTR_SIZE];
6115
6116                                         route = nla_next(route, &rem2);
6117                                         if (nla_type(route) !=
6118                                             LN_SCALAR_ATTR_VALUE) {
6119                                                 NL_SET_ERR_MSG(extack,
6120                                                                "invalid gateway param");
6121                                                 GOTO(report_err, rc = -EINVAL);
6122                                         }
6123
6124                                         rc = nla_strscpy(gw, route, sizeof(gw));
6125                                         if (rc < 0) {
6126                                                 NL_SET_ERR_MSG(extack,
6127                                                                "failed to get route param");
6128                                                 GOTO(report_err, rc);
6129                                         }
6130                                         rc = 0;
6131                                         libcfs_strnid(&tmp.lrp_gateway, strim(gw));
6132                                 } else if (nla_strcmp(route, "hop") == 0) {
6133                                         route = nla_next(route, &rem2);
6134                                         if (nla_type(route) !=
6135                                             LN_SCALAR_ATTR_INT_VALUE) {
6136                                                 NL_SET_ERR_MSG(extack,
6137                                                                "invalid hop param");
6138                                                 GOTO(report_err, rc = -EINVAL);
6139                                         }
6140
6141                                         tmp.lrp_hop = nla_get_s64(route);
6142                                         if (tmp.lrp_hop != -1)
6143                                                 clamp_t(s32, tmp.lrp_hop, 1, 127);
6144                                 } else if (nla_strcmp(route, "priority") == 0) {
6145                                         route = nla_next(route, &rem2);
6146                                         if (nla_type(route) !=
6147                                             LN_SCALAR_ATTR_INT_VALUE) {
6148                                                 NL_SET_ERR_MSG(extack,
6149                                                                "invalid priority param");
6150                                                 GOTO(report_err, rc = -EINVAL);
6151                                         }
6152
6153                                         tmp.lrp_priority = nla_get_s64(route);
6154                                 }
6155                         }
6156
6157                         rc = lnet_scan_route(rlist, &tmp);
6158                         if (rc < 0) {
6159                                 NL_SET_ERR_MSG(extack,
6160                                                "failed to allocate router data");
6161                                 GOTO(report_err, rc);
6162                         }
6163                 }
6164         }
6165 report_err:
6166         mutex_unlock(&the_lnet.ln_api_mutex);
6167
6168         if (rc < 0)
6169                 lnet_route_show_done(cb);
6170
6171         return rc;
6172 }
6173
6174 static const struct ln_key_list route_props_list = {
6175         .lkl_maxattr                    = LNET_ROUTE_ATTR_MAX,
6176         .lkl_list                       = {
6177                 [LNET_ROUTE_ATTR_HDR]                   = {
6178                         .lkp_value                      = "route",
6179                         .lkp_key_format                 = LNKF_SEQUENCE | LNKF_MAPPING,
6180                         .lkp_data_type                  = NLA_NUL_STRING,
6181                 },
6182                 [LNET_ROUTE_ATTR_NET]                   = {
6183                         .lkp_value                      = "net",
6184                         .lkp_data_type                  = NLA_STRING
6185                 },
6186                 [LNET_ROUTE_ATTR_GATEWAY]               = {
6187                         .lkp_value                      = "gateway",
6188                         .lkp_data_type                  = NLA_STRING
6189                 },
6190                 [LNET_ROUTE_ATTR_HOP]                   = {
6191                         .lkp_value                      = "hop",
6192                         .lkp_data_type                  = NLA_S32
6193                 },
6194                 [LNET_ROUTE_ATTR_PRIORITY]              = {
6195                         .lkp_value                      = "priority",
6196                         .lkp_data_type                  = NLA_U32
6197                 },
6198                 [LNET_ROUTE_ATTR_HEALTH_SENSITIVITY]    = {
6199                         .lkp_value                      = "health_sensitivity",
6200                         .lkp_data_type                  = NLA_U32
6201                 },
6202                 [LNET_ROUTE_ATTR_STATE] = {
6203                         .lkp_value                      = "state",
6204                         .lkp_data_type                  = NLA_STRING,
6205                 },
6206                 [LNET_ROUTE_ATTR_TYPE]  = {
6207                         .lkp_value                      = "type",
6208                         .lkp_data_type                  = NLA_STRING,
6209                 },
6210         },
6211 };
6212
6213
6214 static int lnet_route_show_dump(struct sk_buff *msg,
6215                                 struct netlink_callback *cb)
6216 {
6217         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
6218         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6219 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6220         struct netlink_ext_ack *extack = NULL;
6221 #endif
6222         int portid = NETLINK_CB(cb->skb).portid;
6223         int seq = cb->nlh->nlmsg_seq;
6224         int idx = rlist->lgrl_index;
6225         int rc = 0;
6226
6227 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6228         extack = cb->extack;
6229 #endif
6230         if (!rlist->lgrl_count) {
6231                 NL_SET_ERR_MSG(extack, "No routes found");
6232                 GOTO(send_error, rc = -ENOENT);
6233         }
6234
6235         if (!idx) {
6236                 const struct ln_key_list *all[] = {
6237                         &route_props_list, NULL
6238                 };
6239
6240                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
6241                                                 &lnet_family,
6242                                                 NLM_F_CREATE | NLM_F_MULTI,
6243                                                 LNET_CMD_ROUTES, all);
6244                 if (rc < 0) {
6245                         NL_SET_ERR_MSG(extack, "failed to send key table");
6246                         GOTO(send_error, rc);
6247                 }
6248         }
6249
6250         /* If not routes found send an empty message and not an error */
6251         if (!rlist->lgrl_count) {
6252                 void *hdr;
6253
6254                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6255                                   NLM_F_MULTI, LNET_CMD_ROUTES);
6256                 if (!hdr) {
6257                         NL_SET_ERR_MSG(extack, "failed to send values");
6258                         genlmsg_cancel(msg, hdr);
6259                         GOTO(send_error, rc = -EMSGSIZE);
6260                 }
6261                 genlmsg_end(msg, hdr);
6262
6263                 goto send_error;
6264         }
6265
6266         while (idx < rlist->lgrl_count) {
6267                 struct lnet_route_properties *prop;
6268                 void *hdr;
6269
6270                 prop = genradix_ptr(&rlist->lgrl_list, idx++);
6271
6272                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6273                                   NLM_F_MULTI, LNET_CMD_ROUTES);
6274                 if (!hdr) {
6275                         NL_SET_ERR_MSG(extack, "failed to send values");
6276                         genlmsg_cancel(msg, hdr);
6277                         GOTO(send_error, rc = -EMSGSIZE);
6278                 }
6279
6280                 if (idx == 1)
6281                         nla_put_string(msg, LNET_ROUTE_ATTR_HDR, "");
6282
6283                 nla_put_string(msg, LNET_ROUTE_ATTR_NET,
6284                                libcfs_net2str(prop->lrp_net));
6285                 nla_put_string(msg, LNET_ROUTE_ATTR_GATEWAY,
6286                                libcfs_nidstr(&prop->lrp_gateway));
6287                 if (gnlh->version) {
6288                         nla_put_s32(msg, LNET_ROUTE_ATTR_HOP, prop->lrp_hop);
6289                         nla_put_u32(msg, LNET_ROUTE_ATTR_PRIORITY, prop->lrp_priority);
6290                         nla_put_u32(msg, LNET_ROUTE_ATTR_HEALTH_SENSITIVITY,
6291                                     prop->lrp_sensitivity);
6292
6293                         nla_put_string(msg, LNET_ROUTE_ATTR_STATE,
6294                                        prop->lrp_flags & LNET_RT_ALIVE ?
6295                                        "up" : "down");
6296                         nla_put_string(msg, LNET_ROUTE_ATTR_TYPE,
6297                                        prop->lrp_flags & LNET_RT_MULTI_HOP ?
6298                                        "multi-hop" : "single-hop");
6299                 }
6300                 genlmsg_end(msg, hdr);
6301         }
6302         rlist->lgrl_index = idx;
6303 send_error:
6304         return lnet_nl_send_error(cb->skb, portid, seq, rc);
6305 };
6306
6307 #ifndef HAVE_NETLINK_CALLBACK_START
6308 static int lnet_old_route_show_dump(struct sk_buff *msg,
6309                                     struct netlink_callback *cb)
6310 {
6311         if (!cb->args[0]) {
6312                 int rc = lnet_route_show_start(cb);
6313
6314                 if (rc < 0)
6315                         return rc;
6316         }
6317
6318         return lnet_route_show_dump(msg, cb);
6319 }
6320 #endif /* !HAVE_NETLINK_CALLBACK_START */
6321
6322 static inline struct lnet_genl_ping_list *
6323 lnet_ping_dump_ctx(struct netlink_callback *cb)
6324 {
6325         return (struct lnet_genl_ping_list *)cb->args[0];
6326 }
6327
6328 static int lnet_ping_show_done(struct netlink_callback *cb)
6329 {
6330         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
6331
6332         if (plist) {
6333                 genradix_free(&plist->lgpl_failed);
6334                 genradix_free(&plist->lgpl_list);
6335                 LIBCFS_FREE(plist, sizeof(*plist));
6336                 cb->args[0] = 0;
6337         }
6338
6339         return 0;
6340 }
6341
6342 /* LNet ping ->start() handler for GET requests */
6343 static int lnet_ping_show_start(struct netlink_callback *cb)
6344 {
6345         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6346 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6347         struct netlink_ext_ack *extack = NULL;
6348 #endif
6349         struct lnet_genl_ping_list *plist;
6350         int msg_len = genlmsg_len(gnlh);
6351         struct nlattr *params, *top;
6352         int rem, rc = 0;
6353
6354 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6355         extack = cb->extack;
6356 #endif
6357         if (the_lnet.ln_refcount == 0) {
6358                 NL_SET_ERR_MSG(extack, "Network is down");
6359                 return -ENETDOWN;
6360         }
6361
6362         if (!msg_len) {
6363                 NL_SET_ERR_MSG(extack, "Ping needs NID targets");
6364                 return -ENOENT;
6365         }
6366
6367         LIBCFS_ALLOC(plist, sizeof(*plist));
6368         if (!plist) {
6369                 NL_SET_ERR_MSG(extack, "failed to setup ping list");
6370                 return -ENOMEM;
6371         }
6372         genradix_init(&plist->lgpl_list);
6373         plist->lgpl_timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
6374         plist->lgpl_src_nid = LNET_ANY_NID;
6375         plist->lgpl_index = 0;
6376         plist->lgpl_list_count = 0;
6377         cb->args[0] = (long)plist;
6378
6379         params = genlmsg_data(gnlh);
6380         nla_for_each_attr(top, params, msg_len, rem) {
6381                 struct nlattr *nids;
6382                 int rem2;
6383
6384                 switch (nla_type(top)) {
6385                 case LN_SCALAR_ATTR_VALUE:
6386                         if (nla_strcmp(top, "timeout") == 0) {
6387                                 s64 timeout;
6388
6389                                 top = nla_next(top, &rem);
6390                                 if (nla_type(top) != LN_SCALAR_ATTR_INT_VALUE) {
6391                                         NL_SET_ERR_MSG(extack,
6392                                                        "invalid timeout param");
6393                                         GOTO(report_err, rc = -EINVAL);
6394                                 }
6395
6396                                 /* If timeout is negative then set default of
6397                                  * 3 minutes
6398                                  */
6399                                 timeout = nla_get_s64(top);
6400                                 if (timeout > 0 &&
6401                                     timeout < (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
6402                                         plist->lgpl_timeout =
6403                                                 nsecs_to_jiffies(timeout * NSEC_PER_MSEC);
6404                         } else if (nla_strcmp(top, "source") == 0) {
6405                                 char nidstr[LNET_NIDSTR_SIZE + 1];
6406
6407                                 top = nla_next(top, &rem);
6408                                 if (nla_type(top) != LN_SCALAR_ATTR_VALUE) {
6409                                         NL_SET_ERR_MSG(extack,
6410                                                        "invalid source param");
6411                                         GOTO(report_err, rc = -EINVAL);
6412                                 }
6413
6414                                 rc = nla_strscpy(nidstr, top, sizeof(nidstr));
6415                                 if (rc < 0) {
6416                                         NL_SET_ERR_MSG(extack,
6417                                                        "failed to parse source nid");
6418                                         GOTO(report_err, rc);
6419                                 }
6420
6421                                 rc = libcfs_strnid(&plist->lgpl_src_nid,
6422                                                    strim(nidstr));
6423                                 if (rc < 0) {
6424                                         NL_SET_ERR_MSG(extack,
6425                                                        "invalid source nid");
6426                                         GOTO(report_err, rc);
6427                                 }
6428                                 rc = 0;
6429                         }
6430                         break;
6431                 case LN_SCALAR_ATTR_LIST:
6432                         nla_for_each_nested(nids, top, rem2) {
6433                                 char nid[LNET_NIDSTR_SIZE + 1];
6434                                 struct lnet_processid *id;
6435
6436                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
6437                                         continue;
6438
6439                                 memset(nid, 0, sizeof(nid));
6440                                 rc = nla_strscpy(nid, nids, sizeof(nid));
6441                                 if (rc < 0) {
6442                                         NL_SET_ERR_MSG(extack,
6443                                                        "failed to get NID");
6444                                         GOTO(report_err, rc);
6445                                 }
6446
6447                                 id = genradix_ptr_alloc(&plist->lgpl_list,
6448                                                         plist->lgpl_list_count++,
6449                                                         GFP_ATOMIC);
6450                                 if (!id) {
6451                                         NL_SET_ERR_MSG(extack,
6452                                                        "failed to allocate NID");
6453                                         GOTO(report_err, rc = -ENOMEM);
6454                                 }
6455
6456                                 rc = libcfs_strid(id, strim(nid));
6457                                 if (rc < 0) {
6458                                         NL_SET_ERR_MSG(extack, "invalid NID");
6459                                         GOTO(report_err, rc);
6460                                 }
6461                                 rc = 0;
6462                         }
6463                         fallthrough;
6464                 default:
6465                         break;
6466                 }
6467         }
6468 report_err:
6469         if (rc < 0)
6470                 lnet_ping_show_done(cb);
6471
6472         return rc;
6473 }
6474
6475 static const struct ln_key_list ping_props_list = {
6476         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
6477         .lkl_list                       = {
6478                 [LNET_PING_ATTR_HDR]            = {
6479                         .lkp_value              = "ping",
6480                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
6481                         .lkp_data_type          = NLA_NUL_STRING,
6482                 },
6483                 [LNET_PING_ATTR_PRIMARY_NID]    = {
6484                         .lkp_value              = "primary nid",
6485                         .lkp_data_type          = NLA_STRING
6486                 },
6487                 [LNET_PING_ATTR_ERRNO]          = {
6488                         .lkp_value              = "errno",
6489                         .lkp_data_type          = NLA_S16
6490                 },
6491                 [LNET_PING_ATTR_MULTIRAIL]      = {
6492                         .lkp_value              = "Multi-Rail",
6493                         .lkp_data_type          = NLA_FLAG
6494                 },
6495                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
6496                         .lkp_value              = "peer_ni",
6497                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
6498                         .lkp_data_type          = NLA_NESTED
6499                 },
6500         },
6501 };
6502
6503 static struct ln_key_list ping_peer_ni_list = {
6504         .lkl_maxattr                    = LNET_PING_PEER_NI_ATTR_MAX,
6505         .lkl_list                       = {
6506                 [LNET_PING_PEER_NI_ATTR_NID]    = {
6507                         .lkp_value              = "nid",
6508                         .lkp_data_type          = NLA_STRING
6509                 },
6510         },
6511 };
6512
6513 static int lnet_ping_show_dump(struct sk_buff *msg,
6514                                struct netlink_callback *cb)
6515 {
6516         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
6517         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6518 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6519         struct netlink_ext_ack *extack = NULL;
6520 #endif
6521         int portid = NETLINK_CB(cb->skb).portid;
6522         int seq = cb->nlh->nlmsg_seq;
6523         int idx = plist->lgpl_index;
6524         int rc = 0, i = 0;
6525
6526 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6527         extack = cb->extack;
6528 #endif
6529         if (!plist->lgpl_index) {
6530                 const struct ln_key_list *all[] = {
6531                         &ping_props_list, &ping_peer_ni_list, NULL
6532                 };
6533
6534                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
6535                                                 &lnet_family,
6536                                                 NLM_F_CREATE | NLM_F_MULTI,
6537                                                 LNET_CMD_PING, all);
6538                 if (rc < 0) {
6539                         NL_SET_ERR_MSG(extack, "failed to send key table");
6540                         GOTO(send_error, rc);
6541                 }
6542
6543                 genradix_init(&plist->lgpl_failed);
6544         }
6545
6546         while (idx < plist->lgpl_list_count) {
6547                 struct lnet_nid primary_nid = LNET_ANY_NID;
6548                 struct lnet_genl_ping_list peers;
6549                 struct lnet_processid *id;
6550                 struct nlattr *nid_list;
6551                 struct lnet_peer *lp;
6552                 bool mr_flag = false;
6553                 unsigned int count;
6554                 void *hdr = NULL;
6555
6556                 id = genradix_ptr(&plist->lgpl_list, idx++);
6557                 if (nid_is_lo0(&id->nid))
6558                         continue;
6559
6560                 rc = lnet_ping(id, &plist->lgpl_src_nid, plist->lgpl_timeout,
6561                                &peers, lnet_interfaces_max);
6562                 if (rc < 0) {
6563                         struct lnet_fail_ping *fail;
6564
6565                         fail = genradix_ptr_alloc(&plist->lgpl_failed,
6566                                                   plist->lgpl_failed_count++,
6567                                                   GFP_ATOMIC);
6568                         if (!fail) {
6569                                 NL_SET_ERR_MSG(extack,
6570                                                "failed to allocate failed NID");
6571                                 GOTO(send_error, rc);
6572                         }
6573                         fail->lfp_id = *id;
6574                         fail->lfp_errno = rc;
6575                         goto cant_reach;
6576                 }
6577
6578                 mutex_lock(&the_lnet.ln_api_mutex);
6579                 lp = lnet_find_peer(&id->nid);
6580                 if (lp) {
6581                         primary_nid = lp->lp_primary_nid;
6582                         mr_flag = lnet_peer_is_multi_rail(lp);
6583                         lnet_peer_decref_locked(lp);
6584                 }
6585                 mutex_unlock(&the_lnet.ln_api_mutex);
6586
6587                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6588                                   NLM_F_MULTI, LNET_CMD_PING);
6589                 if (!hdr) {
6590                         NL_SET_ERR_MSG(extack, "failed to send values");
6591                         genlmsg_cancel(msg, hdr);
6592                         GOTO(send_error, rc = -EMSGSIZE);
6593                 }
6594
6595                 if (i++ == 0)
6596                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
6597
6598                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
6599                                libcfs_nidstr(&primary_nid));
6600                 if (mr_flag)
6601                         nla_put_flag(msg, LNET_PING_ATTR_MULTIRAIL);
6602
6603                 nid_list = nla_nest_start(msg, LNET_PING_ATTR_PEER_NI_LIST);
6604                 for (count = 0; count < rc; count++) {
6605                         struct lnet_processid *result;
6606                         struct nlattr *nid_attr;
6607                         char *idstr;
6608
6609                         result = genradix_ptr(&peers.lgpl_list, count);
6610                         if (nid_is_lo0(&result->nid))
6611                                 continue;
6612
6613                         nid_attr = nla_nest_start(msg, count + 1);
6614                         if (gnlh->version == 1)
6615                                 idstr = libcfs_nidstr(&result->nid);
6616                         else
6617                                 idstr = libcfs_idstr(result);
6618                         nla_put_string(msg, LNET_PING_PEER_NI_ATTR_NID, idstr);
6619                         nla_nest_end(msg, nid_attr);
6620                 }
6621                 nla_nest_end(msg, nid_list);
6622                 genlmsg_end(msg, hdr);
6623 cant_reach:
6624                 genradix_free(&peers.lgpl_list);
6625         }
6626
6627         for (i = 0; i < plist->lgpl_failed_count; i++) {
6628                 struct lnet_fail_ping *fail;
6629                 void *hdr;
6630
6631                 fail = genradix_ptr(&plist->lgpl_failed, i);
6632
6633                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6634                                   NLM_F_MULTI, LNET_CMD_PING);
6635                 if (!hdr) {
6636                         NL_SET_ERR_MSG(extack, "failed to send failed values");
6637                         genlmsg_cancel(msg, hdr);
6638                         GOTO(send_error, rc = -EMSGSIZE);
6639                 }
6640
6641                 if (i == 0)
6642                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
6643
6644                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
6645                                libcfs_nidstr(&fail->lfp_id.nid));
6646                 nla_put_s16(msg, LNET_PING_ATTR_ERRNO, fail->lfp_errno);
6647                 genlmsg_end(msg, hdr);
6648         }
6649         rc = 0; /* don't treat it as an error */
6650
6651         plist->lgpl_index = idx;
6652 send_error:
6653         return lnet_nl_send_error(cb->skb, portid, seq, rc);
6654 }
6655
6656 #ifndef HAVE_NETLINK_CALLBACK_START
6657 static int lnet_old_ping_show_dump(struct sk_buff *msg,
6658                                    struct netlink_callback *cb)
6659 {
6660         if (!cb->args[0]) {
6661                 int rc = lnet_ping_show_start(cb);
6662
6663                 if (rc < 0)
6664                         return rc;
6665         }
6666
6667         return lnet_ping_show_dump(msg, cb);
6668 }
6669 #endif
6670
6671 static const struct genl_multicast_group lnet_mcast_grps[] = {
6672         { .name =       "ip2net",       },
6673         { .name =       "net",          },
6674         { .name =       "route",        },
6675         { .name =       "ping",         },
6676 };
6677
6678 static const struct genl_ops lnet_genl_ops[] = {
6679         {
6680                 .cmd            = LNET_CMD_NETS,
6681                 .flags          = GENL_ADMIN_PERM,
6682 #ifdef HAVE_NETLINK_CALLBACK_START
6683                 .start          = lnet_net_show_start,
6684                 .dumpit         = lnet_net_show_dump,
6685 #else
6686                 .dumpit         = lnet_old_net_show_dump,
6687 #endif
6688                 .done           = lnet_net_show_done,
6689                 .doit           = lnet_net_cmd,
6690         },
6691         {
6692                 .cmd            = LNET_CMD_ROUTES,
6693 #ifdef HAVE_NETLINK_CALLBACK_START
6694                 .start          = lnet_route_show_start,
6695                 .dumpit         = lnet_route_show_dump,
6696 #else
6697                 .dumpit         = lnet_old_route_show_dump,
6698 #endif
6699                 .done           = lnet_route_show_done,
6700         },
6701         {
6702                 .cmd            = LNET_CMD_PING,
6703 #ifdef HAVE_NETLINK_CALLBACK_START
6704                 .start          = lnet_ping_show_start,
6705                 .dumpit         = lnet_ping_show_dump,
6706 #else
6707                 .dumpit         = lnet_old_ping_show_dump,
6708 #endif
6709                 .done           = lnet_ping_show_done,
6710         },
6711 };
6712
6713 static struct genl_family lnet_family = {
6714         .name           = LNET_GENL_NAME,
6715         .version        = LNET_GENL_VERSION,
6716         .module         = THIS_MODULE,
6717         .netnsok        = true,
6718         .ops            = lnet_genl_ops,
6719         .n_ops          = ARRAY_SIZE(lnet_genl_ops),
6720         .mcgrps         = lnet_mcast_grps,
6721         .n_mcgrps       = ARRAY_SIZE(lnet_mcast_grps),
6722 #ifdef GENL_FAMILY_HAS_RESV_START_OP
6723         .resv_start_op  = __LNET_CMD_MAX_PLUS_ONE,
6724 #endif
6725 };
6726
6727 void LNetDebugPeer(struct lnet_processid *id)
6728 {
6729         lnet_debug_peer(&id->nid);
6730 }
6731 EXPORT_SYMBOL(LNetDebugPeer);
6732
6733 /**
6734  * Determine if the specified peer \a nid is on the local node.
6735  *
6736  * \param nid   peer nid to check
6737  *
6738  * \retval true         If peer NID is on the local node.
6739  * \retval false        If peer NID is not on the local node.
6740  */
6741 bool LNetIsPeerLocal(struct lnet_nid *nid)
6742 {
6743         struct lnet_net *net;
6744         struct lnet_ni *ni;
6745         int cpt;
6746
6747         cpt = lnet_net_lock_current();
6748         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6749                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6750                         if (nid_same(&ni->ni_nid, nid)) {
6751                                 lnet_net_unlock(cpt);
6752                                 return true;
6753                         }
6754                 }
6755         }
6756         lnet_net_unlock(cpt);
6757
6758         return false;
6759 }
6760 EXPORT_SYMBOL(LNetIsPeerLocal);
6761
6762 /**
6763  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
6764  * Note that all interfaces share a same PID, as requested by LNetNIInit().
6765  *
6766  * @index       Index of the interface to look up.
6767  * @id          On successful return, this location will hold the
6768  *              struct lnet_process_id ID of the interface.
6769  * @large_nids  Report large NIDs if this is true.
6770  *
6771  * RETURN       0 If an interface exists at \a index.
6772  *              -ENOENT If no interface has been found.
6773  */
6774 int
6775 LNetGetId(unsigned int index, struct lnet_processid *id, bool large_nids)
6776 {
6777         struct lnet_ni   *ni;
6778         struct lnet_net  *net;
6779         int               cpt;
6780         int               rc = -ENOENT;
6781
6782         LASSERT(the_lnet.ln_refcount > 0);
6783
6784         cpt = lnet_net_lock_current();
6785
6786         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6787                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6788                         if (!large_nids && !nid_is_nid4(&ni->ni_nid))
6789                                 continue;
6790
6791                         if (index-- != 0)
6792                                 continue;
6793
6794                         id->nid = ni->ni_nid;
6795                         id->pid = the_lnet.ln_pid;
6796                         rc = 0;
6797                         break;
6798                 }
6799         }
6800
6801         lnet_net_unlock(cpt);
6802         return rc;
6803 }
6804 EXPORT_SYMBOL(LNetGetId);
6805
6806 struct ping_data {
6807         int rc;
6808         int replied;
6809         int pd_unlinked;
6810         struct lnet_handle_md mdh;
6811         struct completion completion;
6812 };
6813
6814 static void
6815 lnet_ping_event_handler(struct lnet_event *event)
6816 {
6817         struct ping_data *pd = event->md_user_ptr;
6818
6819         CDEBUG(D_NET, "ping event (%d %d)%s\n",
6820                event->type, event->status,
6821                event->unlinked ? " unlinked" : "");
6822
6823         if (event->status) {
6824                 if (!pd->rc)
6825                         pd->rc = event->status;
6826         } else if (event->type == LNET_EVENT_REPLY) {
6827                 pd->replied = 1;
6828                 pd->rc = event->mlength;
6829         }
6830
6831         if (event->unlinked)
6832                 pd->pd_unlinked = 1;
6833
6834         if (event->unlinked ||
6835             (event->type == LNET_EVENT_SEND && event->status))
6836                 complete(&pd->completion);
6837 }
6838
6839 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
6840                      signed long timeout, struct lnet_genl_ping_list *plist,
6841                      int n_ids)
6842 {
6843         int id_bytes = sizeof(struct lnet_ni_status); /* For 0@lo */
6844         struct lnet_md md = { NULL };
6845         struct ping_data pd = { 0 };
6846         struct lnet_ping_buffer *pbuf;
6847         struct lnet_processid pid;
6848         struct lnet_ping_iter pi;
6849         int i = 0;
6850         u32 *st;
6851         int nob;
6852         int rc;
6853         int rc2;
6854
6855         genradix_init(&plist->lgpl_list);
6856
6857         /* n_ids limit is arbitrary */
6858         if (n_ids <= 0 || LNET_NID_IS_ANY(&id->nid))
6859                 return -EINVAL;
6860
6861         /* if the user buffer has more space than the lnet_interfaces_max
6862          * then only fill it up to lnet_interfaces_max
6863          */
6864         if (n_ids > lnet_interfaces_max)
6865                 n_ids = lnet_interfaces_max;
6866
6867         if (id->pid == LNET_PID_ANY)
6868                 id->pid = LNET_PID_LUSTRE;
6869
6870         id_bytes += lnet_ping_sts_size(&id->nid) * n_ids;
6871         pbuf = lnet_ping_buffer_alloc(id_bytes, GFP_NOFS);
6872         if (!pbuf)
6873                 return -ENOMEM;
6874
6875         /* initialize md content */
6876         md.start     = &pbuf->pb_info;
6877         md.length    = id_bytes;
6878         md.threshold = 2; /* GET/REPLY */
6879         md.max_size  = 0;
6880         md.options   = LNET_MD_TRUNCATE;
6881         md.user_ptr  = &pd;
6882         md.handler   = lnet_ping_event_handler;
6883
6884         init_completion(&pd.completion);
6885
6886         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
6887         if (rc != 0) {
6888                 CERROR("Can't bind MD: %d\n", rc);
6889                 goto fail_ping_buffer_decref;
6890         }
6891
6892         rc = LNetGet(src_nid, pd.mdh, id, LNET_RESERVED_PORTAL,
6893                      LNET_PROTO_PING_MATCHBITS, 0, false);
6894         if (rc != 0) {
6895                 /* Don't CERROR; this could be deliberate! */
6896                 rc2 = LNetMDUnlink(pd.mdh);
6897                 LASSERT(rc2 == 0);
6898
6899                 /* NB must wait for the UNLINK event below... */
6900         }
6901
6902         /* Ensure completion in finite time... */
6903         wait_for_completion_timeout(&pd.completion, timeout);
6904         if (!pd.pd_unlinked) {
6905                 LNetMDUnlink(pd.mdh);
6906                 wait_for_completion(&pd.completion);
6907         }
6908
6909         if (!pd.replied) {
6910                 rc = pd.rc ?: -EIO;
6911                 goto fail_ping_buffer_decref;
6912         }
6913
6914         nob = pd.rc;
6915         LASSERT(nob >= 0 && nob <= id_bytes);
6916
6917         rc = -EPROTO;           /* if I can't parse... */
6918
6919         if (nob < LNET_PING_INFO_HDR_SIZE) {
6920                 CERROR("%s: ping info too short %d\n",
6921                        libcfs_idstr(id), nob);
6922                 goto fail_ping_buffer_decref;
6923         }
6924
6925         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
6926                 lnet_swap_pinginfo(pbuf);
6927         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
6928                 CERROR("%s: Unexpected magic %08x\n",
6929                        libcfs_idstr(id), pbuf->pb_info.pi_magic);
6930                 goto fail_ping_buffer_decref;
6931         }
6932
6933         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
6934                 CERROR("%s: ping w/o NI status: 0x%x\n",
6935                        libcfs_idstr(id), pbuf->pb_info.pi_features);
6936                 goto fail_ping_buffer_decref;
6937         }
6938
6939         /* Test if smaller than lnet_pinginfo with just one pi_ni status info.
6940          * That one might contain size when large nids are used.
6941          */
6942         if (nob < offsetof(struct lnet_ping_info, pi_ni[1])) {
6943                 CERROR("%s: Short reply %d(%lu min)\n",
6944                        libcfs_idstr(id), nob,
6945                        offsetof(struct lnet_ping_info, pi_ni[1]));
6946                 goto fail_ping_buffer_decref;
6947         }
6948
6949         if (ping_info_count_entries(pbuf) < n_ids) {
6950                 n_ids = ping_info_count_entries(pbuf);
6951                 id_bytes = lnet_ping_info_size(&pbuf->pb_info);
6952         }
6953
6954         if (nob < id_bytes) {
6955                 CERROR("%s: Short reply %d(%d expected)\n",
6956                        libcfs_idstr(id), nob, id_bytes);
6957                 goto fail_ping_buffer_decref;
6958         }
6959
6960         for (st = ping_iter_first(&pi, pbuf, &pid.nid);
6961              st;
6962              st = ping_iter_next(&pi, &pid.nid)) {
6963                 id = genradix_ptr_alloc(&plist->lgpl_list, i++, GFP_ATOMIC);
6964                 if (!id) {
6965                         rc = -ENOMEM;
6966                         goto fail_ping_buffer_decref;
6967                 }
6968
6969                 id->pid = pbuf->pb_info.pi_pid;
6970                 id->nid = pid.nid;
6971         }
6972         rc = i;
6973 fail_ping_buffer_decref:
6974         lnet_ping_buffer_decref(pbuf);
6975         return rc;
6976 }
6977
6978 static int
6979 lnet_discover(struct lnet_process_id id4, __u32 force,
6980               struct lnet_process_id __user *ids, int n_ids)
6981 {
6982         struct lnet_peer_ni *lpni;
6983         struct lnet_peer_ni *p;
6984         struct lnet_peer *lp;
6985         struct lnet_process_id *buf;
6986         struct lnet_processid id;
6987         int cpt;
6988         int i;
6989         int rc;
6990
6991         if (n_ids <= 0 ||
6992             id4.nid == LNET_NID_ANY)
6993                 return -EINVAL;
6994
6995         lnet_pid4_to_pid(id4, &id);
6996         if (id.pid == LNET_PID_ANY)
6997                 id.pid = LNET_PID_LUSTRE;
6998
6999         /*
7000          * If the user buffer has more space than the lnet_interfaces_max,
7001          * then only fill it up to lnet_interfaces_max.
7002          */
7003         if (n_ids > lnet_interfaces_max)
7004                 n_ids = lnet_interfaces_max;
7005
7006         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
7007         if (!buf)
7008                 return -ENOMEM;
7009
7010         cpt = lnet_net_lock_current();
7011         lpni = lnet_peerni_by_nid_locked(&id.nid, NULL, cpt);
7012         if (IS_ERR(lpni)) {
7013                 rc = PTR_ERR(lpni);
7014                 goto out;
7015         }
7016
7017         /*
7018          * Clearing the NIDS_UPTODATE flag ensures the peer will
7019          * be discovered, provided discovery has not been disabled.
7020          */
7021         lp = lpni->lpni_peer_net->lpn_peer;
7022         spin_lock(&lp->lp_lock);
7023         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
7024         /* If the force flag is set, force a PING and PUSH as well. */
7025         if (force)
7026                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
7027         spin_unlock(&lp->lp_lock);
7028         rc = lnet_discover_peer_locked(lpni, cpt, true);
7029         if (rc)
7030                 goto out_decref;
7031
7032         /* The lpni (or lp) for this NID may have changed and our ref is
7033          * the only thing keeping the old one around. Release the ref
7034          * and lookup the lpni again
7035          */
7036         lnet_peer_ni_decref_locked(lpni);
7037         lpni = lnet_peer_ni_find_locked(&id.nid);
7038         if (!lpni) {
7039                 rc = -ENOENT;
7040                 goto out;
7041         }
7042         lp = lpni->lpni_peer_net->lpn_peer;
7043
7044         i = 0;
7045         p = NULL;
7046         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
7047                 buf[i].pid = id.pid;
7048                 buf[i].nid = lnet_nid_to_nid4(&p->lpni_nid);
7049                 if (++i >= n_ids)
7050                         break;
7051         }
7052         rc = i;
7053
7054 out_decref:
7055         lnet_peer_ni_decref_locked(lpni);
7056 out:
7057         lnet_net_unlock(cpt);
7058
7059         if (rc >= 0)
7060                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
7061                         rc = -EFAULT;
7062         CFS_FREE_PTR_ARRAY(buf, n_ids);
7063
7064         return rc;
7065 }
7066
7067 /**
7068  * Retrieve peer discovery status.
7069  *
7070  * \retval 1 if lnet_peer_discovery_disabled is 0
7071  * \retval 0 if lnet_peer_discovery_disabled is 1
7072  */
7073 int
7074 LNetGetPeerDiscoveryStatus(void)
7075 {
7076         return !lnet_peer_discovery_disabled;
7077 }
7078 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);