Whamcloud - gitweb
LU-17592 build: kernel 6.8 -Werror=missing-prototypes
[fs/lustre-release.git] / lnet / lnet / api-ni.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 /* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
4  * Use is subject to license terms.
5  *
6  * Copyright (c) 2011, 2017, Intel Corporation.
7  */
8
9 /* This file is part of Lustre, http://www.lustre.org/ */
10
11 #define DEBUG_SUBSYSTEM S_LNET
12
13 #include <linux/ctype.h>
14 #include <linux/generic-radix-tree.h>
15 #include <linux/log2.h>
16 #include <linux/ktime.h>
17 #include <linux/moduleparam.h>
18 #include <linux/uaccess.h>
19 #ifdef HAVE_SCHED_HEADERS
20 #include <linux/sched/signal.h>
21 #endif
22 #include <net/genetlink.h>
23
24 #include <libcfs/linux/linux-net.h>
25 #include <lnet/udsp.h>
26 #include <lnet/lib-lnet.h>
27
28 #define D_LNI D_CONSOLE
29
30 /*
31  * initialize ln_api_mutex statically, since it needs to be used in
32  * discovery_set callback. That module parameter callback can be called
33  * before module init completes. The mutex needs to be ready for use then.
34  */
35 struct lnet the_lnet = {
36         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
37 };              /* THE state of the network */
38 EXPORT_SYMBOL(the_lnet);
39
40 static char *ip2nets = "";
41 module_param(ip2nets, charp, 0444);
42 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
43
44 static char *networks = "";
45 module_param(networks, charp, 0444);
46 MODULE_PARM_DESC(networks, "local networks");
47
48 static char *routes = "";
49 module_param(routes, charp, 0444);
50 MODULE_PARM_DESC(routes, "routes to non-local networks");
51
52 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
53 module_param(rnet_htable_size, int, 0444);
54 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
55
56 static int use_tcp_bonding;
57 module_param(use_tcp_bonding, int, 0444);
58 MODULE_PARM_DESC(use_tcp_bonding,
59                  "use_tcp_bonding parameter has been removed");
60
61 unsigned int lnet_numa_range = 0;
62 module_param(lnet_numa_range, uint, 0444);
63 MODULE_PARM_DESC(lnet_numa_range,
64                 "NUMA range to consider during Multi-Rail selection");
65
66 /*
67  * lnet_health_sensitivity determines by how much we decrement the health
68  * value on sending error. The value defaults to 100, which means health
69  * interface health is decremented by 100 points every failure.
70  */
71 unsigned int lnet_health_sensitivity = 100;
72 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
73 #ifdef HAVE_KERNEL_PARAM_OPS
74 static struct kernel_param_ops param_ops_health_sensitivity = {
75         .set = sensitivity_set,
76         .get = param_get_int,
77 };
78 #define param_check_health_sensitivity(name, p) \
79                 __param_check(name, p, int)
80 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
81 #else
82 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
83                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
84 #endif
85 MODULE_PARM_DESC(lnet_health_sensitivity,
86                 "Value to decrement the health value by on error");
87
88 /*
89  * lnet_recovery_interval determines how often we should perform recovery
90  * on unhealthy interfaces.
91  */
92 unsigned int lnet_recovery_interval = 1;
93 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
94 #ifdef HAVE_KERNEL_PARAM_OPS
95 static struct kernel_param_ops param_ops_recovery_interval = {
96         .set = recovery_interval_set,
97         .get = param_get_int,
98 };
99 #define param_check_recovery_interval(name, p) \
100                 __param_check(name, p, int)
101 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
102 #else
103 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
104                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
105 #endif
106 MODULE_PARM_DESC(lnet_recovery_interval,
107                 "DEPRECATED - Interval to recover unhealthy interfaces in seconds");
108
109 unsigned int lnet_recovery_limit;
110 module_param(lnet_recovery_limit, uint, 0644);
111 MODULE_PARM_DESC(lnet_recovery_limit,
112                  "How long to attempt recovery of unhealthy peer interfaces in seconds. Set to 0 to allow indefinite recovery");
113
114 unsigned int lnet_max_recovery_ping_interval = 900;
115 unsigned int lnet_max_recovery_ping_count = 9;
116 static int max_recovery_ping_interval_set(const char *val,
117                                           cfs_kernel_param_arg_t *kp);
118
119 #define param_check_max_recovery_ping_interval(name, p) \
120                 __param_check(name, p, int)
121
122 #ifdef HAVE_KERNEL_PARAM_OPS
123 static struct kernel_param_ops param_ops_max_recovery_ping_interval = {
124         .set = max_recovery_ping_interval_set,
125         .get = param_get_int,
126 };
127 module_param(lnet_max_recovery_ping_interval, max_recovery_ping_interval, 0644);
128 #else
129 module_param_call(lnet_max_recovery_ping_interval, max_recovery_ping_interval,
130                   param_get_int, &lnet_max_recovery_ping_interval, 0644);
131 #endif
132 MODULE_PARM_DESC(lnet_max_recovery_ping_interval,
133                  "The max interval between LNet recovery pings, in seconds");
134
135 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
136 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
137
138 static struct kernel_param_ops param_ops_interfaces_max = {
139         .set = intf_max_set,
140         .get = param_get_int,
141 };
142
143 #define param_check_interfaces_max(name, p) \
144                 __param_check(name, p, int)
145
146 #ifdef HAVE_KERNEL_PARAM_OPS
147 module_param(lnet_interfaces_max, interfaces_max, 0644);
148 #else
149 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
150                   &param_ops_interfaces_max, 0644);
151 #endif
152 MODULE_PARM_DESC(lnet_interfaces_max,
153                 "Maximum number of interfaces in a node.");
154
155 unsigned lnet_peer_discovery_disabled = 0;
156 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
157
158 static struct kernel_param_ops param_ops_discovery_disabled = {
159         .set = discovery_set,
160         .get = param_get_int,
161 };
162
163 #define param_check_discovery_disabled(name, p) \
164                 __param_check(name, p, int)
165 #ifdef HAVE_KERNEL_PARAM_OPS
166 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
167 #else
168 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
169                   &param_ops_discovery_disabled, 0644);
170 #endif
171 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
172                 "Set to 1 to disable peer discovery on this node.");
173
174 unsigned int lnet_drop_asym_route;
175 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
176
177 static struct kernel_param_ops param_ops_drop_asym_route = {
178         .set = drop_asym_route_set,
179         .get = param_get_int,
180 };
181
182 #define param_check_drop_asym_route(name, p)    \
183         __param_check(name, p, int)
184 #ifdef HAVE_KERNEL_PARAM_OPS
185 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
186 #else
187 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
188                   &param_ops_drop_asym_route, 0644);
189 #endif
190 MODULE_PARM_DESC(lnet_drop_asym_route,
191                  "Set to 1 to drop asymmetrical route messages.");
192
193 #define LNET_TRANSACTION_TIMEOUT_DEFAULT 150
194 unsigned int lnet_transaction_timeout = LNET_TRANSACTION_TIMEOUT_DEFAULT;
195 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
196 #ifdef HAVE_KERNEL_PARAM_OPS
197 static struct kernel_param_ops param_ops_transaction_timeout = {
198         .set = transaction_to_set,
199         .get = param_get_int,
200 };
201
202 #define param_check_transaction_timeout(name, p) \
203                 __param_check(name, p, int)
204 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
205 #else
206 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
207                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
208 #endif
209 MODULE_PARM_DESC(lnet_transaction_timeout,
210                 "Maximum number of seconds to wait for a peer response.");
211
212 #define LNET_RETRY_COUNT_DEFAULT 2
213 unsigned int lnet_retry_count = LNET_RETRY_COUNT_DEFAULT;
214 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
215 #ifdef HAVE_KERNEL_PARAM_OPS
216 static struct kernel_param_ops param_ops_retry_count = {
217         .set = retry_count_set,
218         .get = param_get_int,
219 };
220
221 #define param_check_retry_count(name, p) \
222                 __param_check(name, p, int)
223 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
224 #else
225 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
226                   &lnet_retry_count, S_IRUGO|S_IWUSR);
227 #endif
228 MODULE_PARM_DESC(lnet_retry_count,
229                  "Maximum number of times to retry transmitting a message");
230
231 unsigned int lnet_response_tracking = 3;
232 static int response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp);
233
234 #ifdef HAVE_KERNEL_PARAM_OPS
235 static struct kernel_param_ops param_ops_response_tracking = {
236         .set = response_tracking_set,
237         .get = param_get_int,
238 };
239
240 #define param_check_response_tracking(name, p)  \
241         __param_check(name, p, int)
242 module_param(lnet_response_tracking, response_tracking, 0644);
243 #else
244 module_param_call(lnet_response_tracking, response_tracking_set, param_get_int,
245                   &lnet_response_tracking, 0644);
246 #endif
247 MODULE_PARM_DESC(lnet_response_tracking,
248                  "(0|1|2|3) LNet Internal Only|GET Reply only|PUT ACK only|Full Tracking (default)");
249
250 int lock_prim_nid = 1;
251 module_param(lock_prim_nid, int, 0444);
252 MODULE_PARM_DESC(lock_prim_nid,
253                  "Whether nid passed down by Lustre is locked as primary");
254
255 #define LNET_LND_TIMEOUT_DEFAULT ((LNET_TRANSACTION_TIMEOUT_DEFAULT - 1) / \
256                                   (LNET_RETRY_COUNT_DEFAULT + 1))
257 unsigned int lnet_lnd_timeout = LNET_LND_TIMEOUT_DEFAULT;
258 static void lnet_set_lnd_timeout(void)
259 {
260         lnet_lnd_timeout = max((lnet_transaction_timeout - 1) /
261                                (lnet_retry_count + 1), 1U);
262 }
263
264 /*
265  * This sequence number keeps track of how many times DLC was used to
266  * update the local NIs. It is incremented when a NI is added or
267  * removed and checked when sending a message to determine if there is
268  * a need to re-run the selection algorithm. See lnet_select_pathway()
269  * for more details on its usage.
270  */
271 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
272
273 struct lnet_fail_ping {
274         struct lnet_processid           lfp_id;
275         int                             lfp_errno;
276         char                            lfp_msg[256];
277 };
278
279 struct lnet_genl_ping_list {
280         unsigned int                    lgpl_index;
281         unsigned int                    lgpl_list_count;
282         unsigned int                    lgpl_failed_count;
283         signed long                     lgpl_timeout;
284         struct lnet_nid                 lgpl_src_nid;
285         GENRADIX(struct lnet_fail_ping) lgpl_failed;
286         GENRADIX(struct lnet_processid) lgpl_list;
287 };
288
289 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
290                      signed long timeout, struct lnet_genl_ping_list *plist,
291                      int n_ids);
292
293 static int lnet_discover(struct lnet_processid *id, u32 force,
294                          struct lnet_genl_ping_list *dlists);
295
296 static int
297 sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
298 {
299         int rc;
300         unsigned *sensitivity = (unsigned *)kp->arg;
301         unsigned long value;
302
303         rc = kstrtoul(val, 0, &value);
304         if (rc) {
305                 CERROR("Invalid module parameter value for 'lnet_health_sensitivity'\n");
306                 return rc;
307         }
308
309         /*
310          * The purpose of locking the api_mutex here is to ensure that
311          * the correct value ends up stored properly.
312          */
313         mutex_lock(&the_lnet.ln_api_mutex);
314
315         if (value > LNET_MAX_HEALTH_VALUE) {
316                 mutex_unlock(&the_lnet.ln_api_mutex);
317                 CERROR("Invalid health value. Maximum: %d value = %lu\n",
318                        LNET_MAX_HEALTH_VALUE, value);
319                 return -EINVAL;
320         }
321
322         if (*sensitivity != 0 && value == 0 && lnet_retry_count != 0) {
323                 lnet_retry_count = 0;
324                 lnet_set_lnd_timeout();
325         }
326
327         *sensitivity = value;
328
329         mutex_unlock(&the_lnet.ln_api_mutex);
330
331         return 0;
332 }
333
334 static int
335 recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
336 {
337         CWARN("'lnet_recovery_interval' has been deprecated\n");
338
339         return 0;
340 }
341
342 static int
343 max_recovery_ping_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
344 {
345         int rc;
346         unsigned long value;
347
348         rc = kstrtoul(val, 0, &value);
349         if (rc) {
350                 CERROR("Invalid module parameter value for 'lnet_max_recovery_ping_interval'\n");
351                 return rc;
352         }
353
354         if (!value) {
355                 CERROR("Invalid max ping timeout. Must be strictly positive\n");
356                 return -EINVAL;
357         }
358
359         /* The purpose of locking the api_mutex here is to ensure that
360          * the correct value ends up stored properly.
361          */
362         mutex_lock(&the_lnet.ln_api_mutex);
363         lnet_max_recovery_ping_interval = value;
364         lnet_max_recovery_ping_count = 0;
365         value >>= 1;
366         while (value) {
367                 lnet_max_recovery_ping_count++;
368                 value >>= 1;
369         }
370         mutex_unlock(&the_lnet.ln_api_mutex);
371
372         return 0;
373 }
374
375 static int
376 discovery_set(const char *val, cfs_kernel_param_arg_t *kp)
377 {
378         int rc;
379         unsigned *discovery_off = (unsigned *)kp->arg;
380         unsigned long value;
381         struct lnet_ping_buffer *pbuf;
382
383         rc = kstrtoul(val, 0, &value);
384         if (rc) {
385                 CERROR("Invalid module parameter value for 'lnet_peer_discovery_disabled'\n");
386                 return rc;
387         }
388
389         value = (value) ? 1 : 0;
390
391         /*
392          * The purpose of locking the api_mutex here is to ensure that
393          * the correct value ends up stored properly.
394          */
395         mutex_lock(&the_lnet.ln_api_mutex);
396
397         if (value == *discovery_off) {
398                 mutex_unlock(&the_lnet.ln_api_mutex);
399                 return 0;
400         }
401
402         /*
403          * We still want to set the discovery value even when LNet is not
404          * running. This is the case when LNet is being loaded and we want
405          * the module parameters to take effect. Otherwise if we're
406          * changing the value dynamically, we want to set it after
407          * updating the peers
408          */
409         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
410                 *discovery_off = value;
411                 mutex_unlock(&the_lnet.ln_api_mutex);
412                 return 0;
413         }
414
415         /* tell peers that discovery setting has changed */
416         lnet_net_lock(LNET_LOCK_EX);
417         pbuf = the_lnet.ln_ping_target;
418         if (value)
419                 pbuf->pb_info.pi_features &= ~LNET_PING_FEAT_DISCOVERY;
420         else
421                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
422         lnet_net_unlock(LNET_LOCK_EX);
423
424         /* only send a push when we're turning off discovery */
425         if (*discovery_off <= 0 && value > 0)
426                 lnet_push_update_to_peers(1);
427         *discovery_off = value;
428
429         mutex_unlock(&the_lnet.ln_api_mutex);
430
431         return 0;
432 }
433
434 static int
435 drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp)
436 {
437         int rc;
438         unsigned int *drop_asym_route = (unsigned int *)kp->arg;
439         unsigned long value;
440
441         rc = kstrtoul(val, 0, &value);
442         if (rc) {
443                 CERROR("Invalid module parameter value for "
444                        "'lnet_drop_asym_route'\n");
445                 return rc;
446         }
447
448         /*
449          * The purpose of locking the api_mutex here is to ensure that
450          * the correct value ends up stored properly.
451          */
452         mutex_lock(&the_lnet.ln_api_mutex);
453
454         if (value == *drop_asym_route) {
455                 mutex_unlock(&the_lnet.ln_api_mutex);
456                 return 0;
457         }
458
459         *drop_asym_route = value;
460
461         mutex_unlock(&the_lnet.ln_api_mutex);
462
463         return 0;
464 }
465
466 static int
467 transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp)
468 {
469         int rc;
470         unsigned *transaction_to = (unsigned *)kp->arg;
471         unsigned long value;
472
473         rc = kstrtoul(val, 0, &value);
474         if (rc) {
475                 CERROR("Invalid module parameter value for 'lnet_transaction_timeout'\n");
476                 return rc;
477         }
478
479         /*
480          * The purpose of locking the api_mutex here is to ensure that
481          * the correct value ends up stored properly.
482          */
483         mutex_lock(&the_lnet.ln_api_mutex);
484
485         if (value <= lnet_retry_count || value == 0) {
486                 mutex_unlock(&the_lnet.ln_api_mutex);
487                 CERROR("Invalid value for lnet_transaction_timeout (%lu). "
488                        "Has to be greater than lnet_retry_count (%u)\n",
489                        value, lnet_retry_count);
490                 return -EINVAL;
491         }
492
493         if (value == *transaction_to) {
494                 mutex_unlock(&the_lnet.ln_api_mutex);
495                 return 0;
496         }
497
498         *transaction_to = value;
499         /* Update the lnet_lnd_timeout now that we've modified the
500          * transaction timeout
501          */
502         lnet_set_lnd_timeout();
503
504         mutex_unlock(&the_lnet.ln_api_mutex);
505
506         return 0;
507 }
508
509 static int
510 retry_count_set(const char *val, cfs_kernel_param_arg_t *kp)
511 {
512         int rc;
513         unsigned *retry_count = (unsigned *)kp->arg;
514         unsigned long value;
515
516         rc = kstrtoul(val, 0, &value);
517         if (rc) {
518                 CERROR("Invalid module parameter value for 'lnet_retry_count'\n");
519                 return rc;
520         }
521
522         /*
523          * The purpose of locking the api_mutex here is to ensure that
524          * the correct value ends up stored properly.
525          */
526         mutex_lock(&the_lnet.ln_api_mutex);
527
528         if (lnet_health_sensitivity == 0 && value > 0) {
529                 mutex_unlock(&the_lnet.ln_api_mutex);
530                 CERROR("Can not set lnet_retry_count when health feature is turned off\n");
531                 return -EINVAL;
532         }
533
534         if (value > lnet_transaction_timeout) {
535                 mutex_unlock(&the_lnet.ln_api_mutex);
536                 CERROR("Invalid value for lnet_retry_count (%lu). "
537                        "Has to be smaller than lnet_transaction_timeout (%u)\n",
538                        value, lnet_transaction_timeout);
539                 return -EINVAL;
540         }
541
542         *retry_count = value;
543
544         /* Update the lnet_lnd_timeout now that we've modified the
545          * retry count
546          */
547         lnet_set_lnd_timeout();
548
549         mutex_unlock(&the_lnet.ln_api_mutex);
550
551         return 0;
552 }
553
554 static int
555 intf_max_set(const char *val, cfs_kernel_param_arg_t *kp)
556 {
557         int value, rc;
558
559         rc = kstrtoint(val, 0, &value);
560         if (rc) {
561                 CERROR("Invalid module parameter value for 'lnet_interfaces_max'\n");
562                 return rc;
563         }
564
565         if (value < LNET_INTERFACES_MIN) {
566                 CWARN("max interfaces provided are too small, setting to %d\n",
567                       LNET_INTERFACES_MAX_DEFAULT);
568                 value = LNET_INTERFACES_MAX_DEFAULT;
569         }
570
571         *(int *)kp->arg = value;
572
573         return 0;
574 }
575
576 static int
577 response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp)
578 {
579         int rc;
580         unsigned long new_value;
581
582         rc = kstrtoul(val, 0, &new_value);
583         if (rc) {
584                 CERROR("Invalid value for 'lnet_response_tracking'\n");
585                 return -EINVAL;
586         }
587
588         if (new_value < 0 || new_value > 3) {
589                 CWARN("Invalid value (%lu) for 'lnet_response_tracking'\n",
590                       new_value);
591                 return -EINVAL;
592         }
593
594         lnet_response_tracking = new_value;
595
596         return 0;
597 }
598
599 static const char *
600 lnet_get_routes(void)
601 {
602         return routes;
603 }
604
605 static const char *
606 lnet_get_networks(void)
607 {
608         const char *nets;
609         int rc;
610
611         if (*networks != 0 && *ip2nets != 0) {
612                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
613                                    "'ip2nets' but not both at once\n");
614                 return NULL;
615         }
616
617         if (*ip2nets != 0) {
618                 rc = lnet_parse_ip2nets(&nets, ip2nets);
619                 return (rc == 0) ? nets : NULL;
620         }
621
622         if (*networks != 0)
623                 return networks;
624
625         return "tcp";
626 }
627
628 static void
629 lnet_init_locks(void)
630 {
631         spin_lock_init(&the_lnet.ln_eq_wait_lock);
632         spin_lock_init(&the_lnet.ln_msg_resend_lock);
633         init_completion(&the_lnet.ln_mt_wait_complete);
634         mutex_init(&the_lnet.ln_lnd_mutex);
635 }
636
637 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
638 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
639                                             *  MDs kmem_cache */
640 struct kmem_cache *lnet_udsp_cachep;       /* udsp cache */
641 struct kmem_cache *lnet_rspt_cachep;       /* response tracker cache */
642 struct kmem_cache *lnet_msg_cachep;
643
644 static int
645 lnet_slab_setup(void)
646 {
647         /* create specific kmem_cache for MEs and small MDs (i.e., originally
648          * allocated in <size-xxx> kmem_cache).
649          */
650         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(struct lnet_me),
651                                             0, 0, NULL);
652         if (!lnet_mes_cachep)
653                 return -ENOMEM;
654
655         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
656                                                   LNET_SMALL_MD_SIZE, 0, 0,
657                                                   NULL);
658         if (!lnet_small_mds_cachep)
659                 return -ENOMEM;
660
661         lnet_udsp_cachep = kmem_cache_create("lnet_udsp",
662                                              sizeof(struct lnet_udsp),
663                                              0, 0, NULL);
664         if (!lnet_udsp_cachep)
665                 return -ENOMEM;
666
667         lnet_rspt_cachep = kmem_cache_create("lnet_rspt", sizeof(struct lnet_rsp_tracker),
668                                             0, 0, NULL);
669         if (!lnet_rspt_cachep)
670                 return -ENOMEM;
671
672         lnet_msg_cachep = kmem_cache_create("lnet_msg", sizeof(struct lnet_msg),
673                                             0, 0, NULL);
674         if (!lnet_msg_cachep)
675                 return -ENOMEM;
676
677         return 0;
678 }
679
680 static void
681 lnet_slab_cleanup(void)
682 {
683         if (lnet_msg_cachep) {
684                 kmem_cache_destroy(lnet_msg_cachep);
685                 lnet_msg_cachep = NULL;
686         }
687
688         if (lnet_rspt_cachep) {
689                 kmem_cache_destroy(lnet_rspt_cachep);
690                 lnet_rspt_cachep = NULL;
691         }
692
693         if (lnet_udsp_cachep) {
694                 kmem_cache_destroy(lnet_udsp_cachep);
695                 lnet_udsp_cachep = NULL;
696         }
697
698         if (lnet_small_mds_cachep) {
699                 kmem_cache_destroy(lnet_small_mds_cachep);
700                 lnet_small_mds_cachep = NULL;
701         }
702
703         if (lnet_mes_cachep) {
704                 kmem_cache_destroy(lnet_mes_cachep);
705                 lnet_mes_cachep = NULL;
706         }
707 }
708
709 static int
710 lnet_create_remote_nets_table(void)
711 {
712         int               i;
713         struct list_head *hash;
714
715         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
716         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
717         CFS_ALLOC_PTR_ARRAY(hash, LNET_REMOTE_NETS_HASH_SIZE);
718         if (hash == NULL) {
719                 CERROR("Failed to create remote nets hash table\n");
720                 return -ENOMEM;
721         }
722
723         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
724                 INIT_LIST_HEAD(&hash[i]);
725         the_lnet.ln_remote_nets_hash = hash;
726         return 0;
727 }
728
729 static void
730 lnet_destroy_remote_nets_table(void)
731 {
732         int i;
733
734         if (the_lnet.ln_remote_nets_hash == NULL)
735                 return;
736
737         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
738                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
739
740         CFS_FREE_PTR_ARRAY(the_lnet.ln_remote_nets_hash,
741                            LNET_REMOTE_NETS_HASH_SIZE);
742         the_lnet.ln_remote_nets_hash = NULL;
743 }
744
745 static void
746 lnet_destroy_locks(void)
747 {
748         if (the_lnet.ln_res_lock != NULL) {
749                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
750                 the_lnet.ln_res_lock = NULL;
751         }
752
753         if (the_lnet.ln_net_lock != NULL) {
754                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
755                 the_lnet.ln_net_lock = NULL;
756         }
757 }
758
759 static int
760 lnet_create_locks(void)
761 {
762         lnet_init_locks();
763
764         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
765         if (the_lnet.ln_res_lock == NULL)
766                 goto failed;
767
768         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
769         if (the_lnet.ln_net_lock == NULL)
770                 goto failed;
771
772         return 0;
773
774  failed:
775         lnet_destroy_locks();
776         return -ENOMEM;
777 }
778
779 static void lnet_assert_wire_constants(void)
780 {
781         /* Wire protocol assertions generated by 'wirecheck'
782          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
783          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
784          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7)
785          */
786
787         /* Constants... */
788         BUILD_BUG_ON(LNET_PROTO_TCP_MAGIC != 0xeebc0ded);
789         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MAJOR != 1);
790         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MINOR != 0);
791         BUILD_BUG_ON(LNET_MSG_ACK != 0);
792         BUILD_BUG_ON(LNET_MSG_PUT != 1);
793         BUILD_BUG_ON(LNET_MSG_GET != 2);
794         BUILD_BUG_ON(LNET_MSG_REPLY != 3);
795         BUILD_BUG_ON(LNET_MSG_HELLO != 4);
796
797         BUILD_BUG_ON((int)sizeof(lnet_nid_t) != 8);
798         BUILD_BUG_ON((int)sizeof(lnet_pid_t) != 4);
799
800         /* Checks for struct lnet_nid */
801         BUILD_BUG_ON((int)sizeof(struct lnet_nid) != 20);
802         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_size) != 0);
803         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_size) != 1);
804         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_type) != 1);
805         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_type) != 1);
806         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_num) != 2);
807         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_num) != 2);
808         BUILD_BUG_ON((int)offsetof(struct lnet_nid, nid_addr) != 4);
809         BUILD_BUG_ON((int)sizeof(((struct lnet_nid *)0)->nid_addr) != 16);
810
811         /* Checks for struct lnet_process_id_packed */
812         BUILD_BUG_ON((int)sizeof(struct lnet_process_id_packed) != 12);
813         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, nid) != 0);
814         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->nid) != 8);
815         BUILD_BUG_ON((int)offsetof(struct lnet_process_id_packed, pid) != 8);
816         BUILD_BUG_ON((int)sizeof(((struct lnet_process_id_packed *)0)->pid) != 4);
817
818         /* Checks for struct lnet_handle_wire */
819         BUILD_BUG_ON((int)sizeof(struct lnet_handle_wire) != 16);
820         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
821                                    wh_interface_cookie) != 0);
822         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) != 8);
823         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
824                                    wh_object_cookie) != 8);
825         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) != 8);
826
827         /* Checks for struct struct lnet_magicversion */
828         BUILD_BUG_ON((int)sizeof(struct lnet_magicversion) != 8);
829         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, magic) != 0);
830         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->magic) != 4);
831         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, version_major) != 4);
832         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_major) != 2);
833         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion,
834                                    version_minor) != 6);
835         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_minor) != 2);
836
837         /* Checks for struct _lnet_hdr_nid4 */
838         BUILD_BUG_ON((int)sizeof(struct _lnet_hdr_nid4) != 72);
839         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, dest_nid) != 0);
840         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->dest_nid) != 8);
841         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, src_nid) != 8);
842         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->src_nid) != 8);
843         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, dest_pid) != 16);
844         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->dest_pid) != 4);
845         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, src_pid) != 20);
846         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->src_pid) != 4);
847         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, type) != 24);
848         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->type) != 4);
849         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, payload_length) != 28);
850         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->payload_length) != 4);
851         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg) != 32);
852         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg) != 40);
853
854         /* Ack */
855         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.dst_wmd) != 32);
856         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.dst_wmd) != 16);
857         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.match_bits) != 48);
858         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.match_bits) != 8);
859         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.ack.mlength) != 56);
860         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.ack.mlength) != 4);
861
862         /* Put */
863         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.ack_wmd) != 32);
864         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.ack_wmd) != 16);
865         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.match_bits) != 48);
866         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.match_bits) != 8);
867         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.hdr_data) != 56);
868         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.hdr_data) != 8);
869         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.ptl_index) != 64);
870         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.ptl_index) != 4);
871         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.put.offset) != 68);
872         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.put.offset) != 4);
873
874         /* Get */
875         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.return_wmd) != 32);
876         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.return_wmd) != 16);
877         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.match_bits) != 48);
878         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.match_bits) != 8);
879         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.ptl_index) != 56);
880         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.ptl_index) != 4);
881         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.src_offset) != 60);
882         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.src_offset) != 4);
883         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.get.sink_length) != 64);
884         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.get.sink_length) != 4);
885
886         /* Reply */
887         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.reply.dst_wmd) != 32);
888         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.reply.dst_wmd) != 16);
889
890         /* Hello */
891         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.hello.incarnation) != 32);
892         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.hello.incarnation) != 8);
893         BUILD_BUG_ON((int)offsetof(struct _lnet_hdr_nid4, msg.hello.type) != 40);
894         BUILD_BUG_ON((int)sizeof(((struct _lnet_hdr_nid4 *)0)->msg.hello.type) != 4);
895
896         /* Checks for struct lnet_ni_status and related constants */
897         BUILD_BUG_ON(LNET_NI_STATUS_INVALID != 0x00000000);
898         BUILD_BUG_ON(LNET_NI_STATUS_UP != 0x15aac0de);
899         BUILD_BUG_ON(LNET_NI_STATUS_DOWN != 0xdeadface);
900
901         /* Checks for struct lnet_ni_status */
902         BUILD_BUG_ON((int)sizeof(struct lnet_ni_status) != 16);
903         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_nid) != 0);
904         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_nid) != 8);
905         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_status) != 8);
906         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_status) != 4);
907         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_msg_size) != 12);
908         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_msg_size) != 4);
909
910         /* Checks for struct lnet_ni_large_status */
911         BUILD_BUG_ON((int)sizeof(struct lnet_ni_large_status) != 24);
912         BUILD_BUG_ON((int)offsetof(struct lnet_ni_large_status, ns_status) != 0);
913         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_large_status *)0)->ns_status) != 4);
914         BUILD_BUG_ON((int)offsetof(struct lnet_ni_large_status, ns_nid) != 4);
915         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_large_status *)0)->ns_nid) != 20);
916
917         /* Checks for struct lnet_ping_info and related constants */
918         BUILD_BUG_ON(LNET_PROTO_PING_MAGIC != 0x70696E67);
919         BUILD_BUG_ON(LNET_PING_FEAT_INVAL != 0);
920         BUILD_BUG_ON(LNET_PING_FEAT_BASE != 1);
921         BUILD_BUG_ON(LNET_PING_FEAT_NI_STATUS != 2);
922         BUILD_BUG_ON(LNET_PING_FEAT_RTE_DISABLED != 4);
923         BUILD_BUG_ON(LNET_PING_FEAT_MULTI_RAIL != 8);
924         BUILD_BUG_ON(LNET_PING_FEAT_DISCOVERY != 16);
925         BUILD_BUG_ON(LNET_PING_FEAT_LARGE_ADDR != 32);
926         BUILD_BUG_ON(LNET_PING_FEAT_PRIMARY_LARGE != 64);
927         BUILD_BUG_ON(LNET_PING_FEAT_BITS != 127);
928
929         /* Checks for struct lnet_ping_info */
930         BUILD_BUG_ON((int)sizeof(struct lnet_ping_info) != 16);
931         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_magic) != 0);
932         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_magic) != 4);
933         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_features) != 4);
934         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_features) != 4);
935         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_pid) != 8);
936         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_pid) != 4);
937         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_nnis) != 12);
938         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_nnis) != 4);
939         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_ni) != 16);
940         BUILD_BUG_ON(offsetof(struct lnet_ping_info, pi_ni) != sizeof(struct lnet_ping_info));
941
942         /* Acceptor connection request */
943         BUILD_BUG_ON(LNET_PROTO_ACCEPTOR_VERSION != 1);
944
945         /* Checks for struct lnet_acceptor_connreq */
946         BUILD_BUG_ON((int)sizeof(struct lnet_acceptor_connreq) != 16);
947         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_magic) != 0);
948         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_magic) != 4);
949         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_version) != 4);
950         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_version) != 4);
951         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq, acr_nid) != 8);
952         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq *)0)->acr_nid) != 8);
953
954         /* Checks for struct lnet_acceptor_connreq_v2 */
955         BUILD_BUG_ON((int)sizeof(struct lnet_acceptor_connreq_v2) != 28);
956         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_magic) != 0);
957         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_magic) != 4);
958         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_version) != 4);
959         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_version) != 4);
960         BUILD_BUG_ON((int)offsetof(struct lnet_acceptor_connreq_v2, acr_nid) != 8);
961         BUILD_BUG_ON((int)sizeof(((struct lnet_acceptor_connreq_v2 *)0)->acr_nid) != 20);
962
963         /* Checks for struct lnet_counters_common */
964         BUILD_BUG_ON((int)sizeof(struct lnet_counters_common) != 60);
965         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_alloc) != 0);
966         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_alloc) != 4);
967         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_msgs_max) != 4);
968         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_msgs_max) != 4);
969         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_errors) != 8);
970         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_errors) != 4);
971         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_count) != 12);
972         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_count) != 4);
973         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_count) != 16);
974         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_count) != 4);
975         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_count) != 20);
976         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_count) != 4);
977         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_count) != 24);
978         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_count) != 4);
979         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_send_length) != 28);
980         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_send_length) != 8);
981         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_recv_length) != 36);
982         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_recv_length) != 8);
983         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_route_length) != 44);
984         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_route_length) != 8);
985         BUILD_BUG_ON((int)offsetof(struct lnet_counters_common, lcc_drop_length) != 52);
986         BUILD_BUG_ON((int)sizeof(((struct lnet_counters_common *)0)->lcc_drop_length) != 8);
987 }
988
989 static const struct lnet_lnd *lnet_find_lnd_by_type(__u32 type)
990 {
991         const struct lnet_lnd *lnd;
992
993         /* holding lnd mutex */
994         if (type >= NUM_LNDS)
995                 return NULL;
996         lnd = the_lnet.ln_lnds[type];
997         LASSERT(!lnd || lnd->lnd_type == type);
998
999         return lnd;
1000 }
1001
1002 unsigned int
1003 lnet_get_lnd_timeout(void)
1004 {
1005         return lnet_lnd_timeout;
1006 }
1007 EXPORT_SYMBOL(lnet_get_lnd_timeout);
1008
1009 void
1010 lnet_register_lnd(const struct lnet_lnd *lnd)
1011 {
1012         mutex_lock(&the_lnet.ln_lnd_mutex);
1013
1014         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
1015         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
1016
1017         the_lnet.ln_lnds[lnd->lnd_type] = lnd;
1018
1019         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
1020
1021         mutex_unlock(&the_lnet.ln_lnd_mutex);
1022 }
1023 EXPORT_SYMBOL(lnet_register_lnd);
1024
1025 void
1026 lnet_unregister_lnd(const struct lnet_lnd *lnd)
1027 {
1028         mutex_lock(&the_lnet.ln_lnd_mutex);
1029
1030         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
1031
1032         the_lnet.ln_lnds[lnd->lnd_type] = NULL;
1033         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
1034
1035         mutex_unlock(&the_lnet.ln_lnd_mutex);
1036 }
1037 EXPORT_SYMBOL(lnet_unregister_lnd);
1038
1039 static void
1040 lnet_counters_get_common_locked(struct lnet_counters_common *common)
1041 {
1042         struct lnet_counters *ctr;
1043         int i;
1044
1045         /* FIXME !!! Their is no assert_lnet_net_locked() to ensure this
1046          * actually called under the protection of the lnet_net_lock.
1047          */
1048         memset(common, 0, sizeof(*common));
1049
1050         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
1051                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
1052                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
1053                 common->lcc_errors       += ctr->lct_common.lcc_errors;
1054                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
1055                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
1056                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
1057                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
1058                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
1059                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
1060                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
1061                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
1062         }
1063 }
1064
1065 void
1066 lnet_counters_get_common(struct lnet_counters_common *common)
1067 {
1068         lnet_net_lock(LNET_LOCK_EX);
1069         lnet_counters_get_common_locked(common);
1070         lnet_net_unlock(LNET_LOCK_EX);
1071 }
1072 EXPORT_SYMBOL(lnet_counters_get_common);
1073
1074 int
1075 lnet_counters_get(struct lnet_counters *counters)
1076 {
1077         struct lnet_counters *ctr;
1078         struct lnet_counters_health *health = &counters->lct_health;
1079         int i, rc = 0;
1080
1081         memset(counters, 0, sizeof(*counters));
1082
1083         lnet_net_lock(LNET_LOCK_EX);
1084
1085         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1086                 GOTO(out_unlock, rc = -ENODEV);
1087
1088         lnet_counters_get_common_locked(&counters->lct_common);
1089
1090         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
1091                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
1092                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
1093                 health->lch_response_timeout_count +=
1094                                 ctr->lct_health.lch_response_timeout_count;
1095                 health->lch_local_interrupt_count +=
1096                                 ctr->lct_health.lch_local_interrupt_count;
1097                 health->lch_local_dropped_count +=
1098                                 ctr->lct_health.lch_local_dropped_count;
1099                 health->lch_local_aborted_count +=
1100                                 ctr->lct_health.lch_local_aborted_count;
1101                 health->lch_local_no_route_count +=
1102                                 ctr->lct_health.lch_local_no_route_count;
1103                 health->lch_local_timeout_count +=
1104                                 ctr->lct_health.lch_local_timeout_count;
1105                 health->lch_local_error_count +=
1106                                 ctr->lct_health.lch_local_error_count;
1107                 health->lch_remote_dropped_count +=
1108                                 ctr->lct_health.lch_remote_dropped_count;
1109                 health->lch_remote_error_count +=
1110                                 ctr->lct_health.lch_remote_error_count;
1111                 health->lch_remote_timeout_count +=
1112                                 ctr->lct_health.lch_remote_timeout_count;
1113                 health->lch_network_timeout_count +=
1114                                 ctr->lct_health.lch_network_timeout_count;
1115         }
1116 out_unlock:
1117         lnet_net_unlock(LNET_LOCK_EX);
1118         return rc;
1119 }
1120 EXPORT_SYMBOL(lnet_counters_get);
1121
1122 void
1123 lnet_counters_reset(void)
1124 {
1125         struct lnet_counters *counters;
1126         int             i;
1127
1128         lnet_net_lock(LNET_LOCK_EX);
1129
1130         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1131                 goto avoid_reset;
1132
1133         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
1134                 memset(counters, 0, sizeof(struct lnet_counters));
1135 avoid_reset:
1136         lnet_net_unlock(LNET_LOCK_EX);
1137 }
1138
1139 static char *
1140 lnet_res_type2str(int type)
1141 {
1142         switch (type) {
1143         default:
1144                 LBUG();
1145         case LNET_COOKIE_TYPE_MD:
1146                 return "MD";
1147         case LNET_COOKIE_TYPE_ME:
1148                 return "ME";
1149         case LNET_COOKIE_TYPE_EQ:
1150                 return "EQ";
1151         }
1152 }
1153
1154 static void
1155 lnet_res_container_cleanup(struct lnet_res_container *rec)
1156 {
1157         int     count = 0;
1158
1159         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
1160                 return;
1161
1162         while (!list_empty(&rec->rec_active)) {
1163                 struct list_head *e = rec->rec_active.next;
1164
1165                 list_del_init(e);
1166                 if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
1167                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
1168
1169                 } else { /* NB: Active MEs should be attached on portals */
1170                         LBUG();
1171                 }
1172                 count++;
1173         }
1174
1175         if (count > 0) {
1176                 /* Found alive MD/ME/EQ, user really should unlink/free
1177                  * all of them before finalize LNet, but if someone didn't,
1178                  * we have to recycle garbage for him */
1179                 CERROR("%d active elements on exit of %s container\n",
1180                        count, lnet_res_type2str(rec->rec_type));
1181         }
1182
1183         if (rec->rec_lh_hash != NULL) {
1184                 CFS_FREE_PTR_ARRAY(rec->rec_lh_hash, LNET_LH_HASH_SIZE);
1185                 rec->rec_lh_hash = NULL;
1186         }
1187
1188         rec->rec_type = 0; /* mark it as finalized */
1189 }
1190
1191 static int
1192 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
1193 {
1194         int     rc = 0;
1195         int     i;
1196
1197         LASSERT(rec->rec_type == 0);
1198
1199         rec->rec_type = type;
1200         INIT_LIST_HEAD(&rec->rec_active);
1201
1202         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1203
1204         /* Arbitrary choice of hash table size */
1205         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1206                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1207         if (rec->rec_lh_hash == NULL) {
1208                 rc = -ENOMEM;
1209                 goto out;
1210         }
1211
1212         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1213                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1214
1215         return 0;
1216
1217 out:
1218         CERROR("Failed to setup %s resource container\n",
1219                lnet_res_type2str(type));
1220         lnet_res_container_cleanup(rec);
1221         return rc;
1222 }
1223
1224 static void
1225 lnet_res_containers_destroy(struct lnet_res_container **recs)
1226 {
1227         struct lnet_res_container       *rec;
1228         int                             i;
1229
1230         cfs_percpt_for_each(rec, i, recs)
1231                 lnet_res_container_cleanup(rec);
1232
1233         cfs_percpt_free(recs);
1234 }
1235
1236 static struct lnet_res_container **
1237 lnet_res_containers_create(int type)
1238 {
1239         struct lnet_res_container       **recs;
1240         struct lnet_res_container       *rec;
1241         int                             rc;
1242         int                             i;
1243
1244         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1245         if (recs == NULL) {
1246                 CERROR("Failed to allocate %s resource containers\n",
1247                        lnet_res_type2str(type));
1248                 return NULL;
1249         }
1250
1251         cfs_percpt_for_each(rec, i, recs) {
1252                 rc = lnet_res_container_setup(rec, i, type);
1253                 if (rc != 0) {
1254                         lnet_res_containers_destroy(recs);
1255                         return NULL;
1256                 }
1257         }
1258
1259         return recs;
1260 }
1261
1262 struct lnet_libhandle *
1263 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1264 {
1265         /* ALWAYS called with lnet_res_lock held */
1266         struct list_head        *head;
1267         struct lnet_libhandle   *lh;
1268         unsigned int            hash;
1269
1270         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1271                 return NULL;
1272
1273         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1274         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1275
1276         list_for_each_entry(lh, head, lh_hash_chain) {
1277                 if (lh->lh_cookie == cookie)
1278                         return lh;
1279         }
1280
1281         return NULL;
1282 }
1283
1284 void
1285 lnet_res_lh_initialize(struct lnet_res_container *rec,
1286                        struct lnet_libhandle *lh)
1287 {
1288         /* ALWAYS called with lnet_res_lock held */
1289         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1290         unsigned int    hash;
1291
1292         lh->lh_cookie = rec->rec_lh_cookie;
1293         rec->rec_lh_cookie += 1 << ibits;
1294
1295         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1296
1297         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1298 }
1299
1300 struct list_head **
1301 lnet_create_array_of_queues(void)
1302 {
1303         struct list_head **qs;
1304         struct list_head *q;
1305         int i;
1306
1307         qs = cfs_percpt_alloc(lnet_cpt_table(),
1308                               sizeof(struct list_head));
1309         if (!qs) {
1310                 CERROR("Failed to allocate queues\n");
1311                 return NULL;
1312         }
1313
1314         cfs_percpt_for_each(q, i, qs)
1315                 INIT_LIST_HEAD(q);
1316
1317         return qs;
1318 }
1319
1320 static int lnet_unprepare(void);
1321
1322 static int
1323 lnet_prepare(lnet_pid_t requested_pid)
1324 {
1325         /* Prepare to bring up the network */
1326         struct lnet_res_container **recs;
1327         int                       rc = 0;
1328
1329         if (requested_pid == LNET_PID_ANY) {
1330                 /* Don't instantiate LNET just for me */
1331                 return -ENETDOWN;
1332         }
1333
1334         LASSERT(the_lnet.ln_refcount == 0);
1335
1336         the_lnet.ln_routing = 0;
1337
1338         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1339         the_lnet.ln_pid = requested_pid;
1340
1341         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1342         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1343         INIT_LIST_HEAD(&the_lnet.ln_nets);
1344         INIT_LIST_HEAD(&the_lnet.ln_routers);
1345         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1346         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1347         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1348         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1349         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1350         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1351         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1352         INIT_LIST_HEAD(&the_lnet.ln_udsp_list);
1353         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1354         the_lnet.ln_mt_handler = NULL;
1355         init_completion(&the_lnet.ln_started);
1356         atomic_set(&the_lnet.ln_late_msg_count, 0);
1357         atomic64_set(&the_lnet.ln_late_msg_nsecs, 0);
1358
1359         rc = lnet_slab_setup();
1360         if (rc != 0)
1361                 goto failed;
1362
1363         rc = lnet_create_remote_nets_table();
1364         if (rc != 0)
1365                 goto failed;
1366
1367         /*
1368          * NB the interface cookie in wire handles guards against delayed
1369          * replies and ACKs appearing valid after reboot.
1370          */
1371         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1372
1373         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1374                                                 sizeof(struct lnet_counters));
1375         if (the_lnet.ln_counters == NULL) {
1376                 CERROR("Failed to allocate counters for LNet\n");
1377                 rc = -ENOMEM;
1378                 goto failed;
1379         }
1380
1381         rc = lnet_peer_tables_create();
1382         if (rc != 0)
1383                 goto failed;
1384
1385         rc = lnet_msg_containers_create();
1386         if (rc != 0)
1387                 goto failed;
1388
1389         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1390                                       LNET_COOKIE_TYPE_EQ);
1391         if (rc != 0)
1392                 goto failed;
1393
1394         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1395         if (recs == NULL) {
1396                 rc = -ENOMEM;
1397                 goto failed;
1398         }
1399
1400         the_lnet.ln_md_containers = recs;
1401
1402         rc = lnet_portals_create();
1403         if (rc != 0) {
1404                 CERROR("Failed to create portals for LNet: %d\n", rc);
1405                 goto failed;
1406         }
1407
1408         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1409         if (!the_lnet.ln_mt_zombie_rstqs) {
1410                 rc = -ENOMEM;
1411                 goto failed;
1412         }
1413
1414         return 0;
1415
1416  failed:
1417         lnet_unprepare();
1418         return rc;
1419 }
1420
1421 static int
1422 lnet_unprepare(void)
1423 {
1424         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1425          * have shut down already, so it is safe to unlink and free all
1426          * descriptors, even those that appear committed to a network op (eg MD
1427          * with non-zero pending count) */
1428
1429         lnet_fail_nid(LNET_NID_ANY, 0);
1430
1431         LASSERT(the_lnet.ln_refcount == 0);
1432         LASSERT(list_empty(&the_lnet.ln_test_peers));
1433         LASSERT(list_empty(&the_lnet.ln_nets));
1434
1435         if (the_lnet.ln_mt_zombie_rstqs) {
1436                 lnet_clean_zombie_rstqs();
1437                 the_lnet.ln_mt_zombie_rstqs = NULL;
1438         }
1439
1440         lnet_assert_handler_unused(the_lnet.ln_mt_handler, true);
1441         the_lnet.ln_mt_handler = NULL;
1442
1443         lnet_portals_destroy();
1444
1445         if (the_lnet.ln_md_containers != NULL) {
1446                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1447                 the_lnet.ln_md_containers = NULL;
1448         }
1449
1450         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1451
1452         lnet_msg_containers_destroy();
1453         lnet_peer_uninit();
1454         lnet_rtrpools_free(0);
1455
1456         if (the_lnet.ln_counters != NULL) {
1457                 cfs_percpt_free(the_lnet.ln_counters);
1458                 the_lnet.ln_counters = NULL;
1459         }
1460         lnet_destroy_remote_nets_table();
1461         lnet_udsp_destroy(true);
1462         lnet_slab_cleanup();
1463
1464         return 0;
1465 }
1466
1467 struct lnet_ni  *
1468 lnet_net2ni_locked(__u32 net_id, int cpt)
1469 {
1470         struct lnet_ni   *ni;
1471         struct lnet_net  *net;
1472
1473         LASSERT(cpt != LNET_LOCK_EX);
1474
1475         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1476                 if (net->net_id == net_id) {
1477                         ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
1478                                               ni_netlist);
1479                         return ni;
1480                 }
1481         }
1482
1483         return NULL;
1484 }
1485
1486 struct lnet_ni *
1487 lnet_net2ni_addref(__u32 net)
1488 {
1489         struct lnet_ni *ni;
1490
1491         lnet_net_lock(0);
1492         ni = lnet_net2ni_locked(net, 0);
1493         if (ni)
1494                 lnet_ni_addref_locked(ni, 0);
1495         lnet_net_unlock(0);
1496
1497         return ni;
1498 }
1499 EXPORT_SYMBOL(lnet_net2ni_addref);
1500
1501 struct lnet_net *
1502 lnet_get_net_locked(__u32 net_id)
1503 {
1504         struct lnet_net  *net;
1505
1506         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1507                 if (net->net_id == net_id)
1508                         return net;
1509         }
1510
1511         return NULL;
1512 }
1513
1514 void
1515 lnet_net_clr_pref_rtrs(struct lnet_net *net)
1516 {
1517         struct list_head zombies;
1518         struct lnet_nid_list *ne;
1519         struct lnet_nid_list *tmp;
1520
1521         INIT_LIST_HEAD(&zombies);
1522
1523         lnet_net_lock(LNET_LOCK_EX);
1524         list_splice_init(&net->net_rtr_pref_nids, &zombies);
1525         lnet_net_unlock(LNET_LOCK_EX);
1526
1527         list_for_each_entry_safe(ne, tmp, &zombies, nl_list) {
1528                 list_del_init(&ne->nl_list);
1529                 LIBCFS_FREE(ne, sizeof(*ne));
1530         }
1531 }
1532
1533 int
1534 lnet_net_add_pref_rtr(struct lnet_net *net,
1535                       struct lnet_nid *gw_nid)
1536 __must_hold(&the_lnet.ln_api_mutex)
1537 {
1538         struct lnet_nid_list *ne;
1539
1540         /* This function is called with api_mutex held. When the api_mutex
1541          * is held the list can not be modified, as it is only modified as
1542          * a result of applying a UDSP and that happens under api_mutex
1543          * lock.
1544          */
1545         list_for_each_entry(ne, &net->net_rtr_pref_nids, nl_list) {
1546                 if (nid_same(&ne->nl_nid, gw_nid))
1547                         return -EEXIST;
1548         }
1549
1550         LIBCFS_ALLOC(ne, sizeof(*ne));
1551         if (!ne)
1552                 return -ENOMEM;
1553
1554         ne->nl_nid = *gw_nid;
1555
1556         /* Lock the cpt to protect against addition and checks in the
1557          * selection algorithm
1558          */
1559         lnet_net_lock(LNET_LOCK_EX);
1560         list_add(&ne->nl_list, &net->net_rtr_pref_nids);
1561         lnet_net_unlock(LNET_LOCK_EX);
1562
1563         return 0;
1564 }
1565
1566 static unsigned int
1567 lnet_nid4_cpt_hash(lnet_nid_t nid, unsigned int number)
1568 {
1569         __u64 key = nid;
1570         __u16 lnd = LNET_NETTYP(LNET_NIDNET(nid));
1571         unsigned int cpt;
1572
1573         if (lnd == KFILND || lnd == GNILND) {
1574                 cpt = hash_long(key, LNET_CPT_BITS);
1575
1576                 /* NB: The number of CPTs needn't be a power of 2 */
1577                 if (cpt >= number)
1578                         cpt = (key + cpt + (cpt >> 1)) % number;
1579         } else {
1580                 __u64 pair_bits = 0x0001000100010001LLU;
1581                 __u64 mask = pair_bits * 0xFF;
1582                 __u64 pair_sum;
1583                 /* For ipv4 NIDs, use (sum-by-multiplication of nid bytes) mod
1584                  * (number of CPTs) to match nid to a CPT.
1585                  */
1586                 pair_sum = (key & mask) + ((key >> 8) & mask);
1587                 pair_sum = (pair_sum * pair_bits) >> 48;
1588                 cpt = (unsigned int)(pair_sum) % number;
1589         }
1590
1591         CDEBUG(D_NET, "Match nid %s to cpt %u\n",
1592                libcfs_nid2str(nid), cpt);
1593
1594         return cpt;
1595 }
1596
1597 unsigned int
1598 lnet_nid_cpt_hash(struct lnet_nid *nid, unsigned int number)
1599 {
1600         unsigned int val;
1601         u32 h = 0;
1602         int i;
1603
1604         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1605
1606         if (number == 1)
1607                 return 0;
1608
1609         if (nid_is_nid4(nid))
1610                 return lnet_nid4_cpt_hash(lnet_nid_to_nid4(nid), number);
1611
1612         for (i = 0; i < 4; i++)
1613                 h = cfs_hash_32(nid->nid_addr[i]^h, 32);
1614         val = cfs_hash_32(LNET_NID_NET(nid) ^ h, LNET_CPT_BITS);
1615         if (val < number)
1616                 return val;
1617         return (unsigned int)(h + val + (val >> 1)) % number;
1618 }
1619
1620 int
1621 lnet_cpt_of_nid_locked(struct lnet_nid *nid, struct lnet_ni *ni)
1622 {
1623         struct lnet_net *net;
1624
1625         /* must called with hold of lnet_net_lock */
1626         if (LNET_CPT_NUMBER == 1)
1627                 return 0; /* the only one */
1628
1629         /*
1630          * If NI is provided then use the CPT identified in the NI cpt
1631          * list if one exists. If one doesn't exist, then that NI is
1632          * associated with all CPTs and it follows that the net it belongs
1633          * to is implicitly associated with all CPTs, so just hash the nid
1634          * and return that.
1635          */
1636         if (ni != NULL) {
1637                 if (ni->ni_cpts != NULL)
1638                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1639                                                              ni->ni_ncpts)];
1640                 else
1641                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1642         }
1643
1644         /* no NI provided so look at the net */
1645         net = lnet_get_net_locked(LNET_NID_NET(nid));
1646
1647         if (net != NULL && net->net_cpts != NULL) {
1648                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1649         }
1650
1651         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1652 }
1653
1654 int
1655 lnet_nid2cpt(struct lnet_nid *nid, struct lnet_ni *ni)
1656 {
1657         int     cpt;
1658         int     cpt2;
1659
1660         if (LNET_CPT_NUMBER == 1)
1661                 return 0; /* the only one */
1662
1663         cpt = lnet_net_lock_current();
1664
1665         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1666
1667         lnet_net_unlock(cpt);
1668
1669         return cpt2;
1670 }
1671 EXPORT_SYMBOL(lnet_nid2cpt);
1672
1673 int
1674 lnet_cpt_of_nid(lnet_nid_t nid4, struct lnet_ni *ni)
1675 {
1676         struct lnet_nid nid;
1677
1678         if (LNET_CPT_NUMBER == 1)
1679                 return 0; /* the only one */
1680
1681         lnet_nid4_to_nid(nid4, &nid);
1682         return lnet_nid2cpt(&nid, ni);
1683 }
1684 EXPORT_SYMBOL(lnet_cpt_of_nid);
1685
1686 int
1687 lnet_islocalnet_locked(__u32 net_id)
1688 {
1689         struct lnet_net *net;
1690         bool local;
1691
1692         net = lnet_get_net_locked(net_id);
1693
1694         local = net != NULL;
1695
1696         return local;
1697 }
1698
1699 int
1700 lnet_islocalnet(__u32 net_id)
1701 {
1702         int cpt;
1703         bool local;
1704
1705         cpt = lnet_net_lock_current();
1706
1707         local = lnet_islocalnet_locked(net_id);
1708
1709         lnet_net_unlock(cpt);
1710
1711         return local;
1712 }
1713
1714 struct lnet_ni  *
1715 lnet_nid_to_ni_locked(struct lnet_nid *nid, int cpt)
1716 {
1717         struct lnet_net  *net;
1718         struct lnet_ni *ni;
1719
1720         LASSERT(cpt != LNET_LOCK_EX);
1721
1722         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1723                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1724                         if (nid_same(&ni->ni_nid, nid))
1725                                 return ni;
1726                 }
1727         }
1728
1729         return NULL;
1730 }
1731
1732 struct lnet_ni *
1733 lnet_nid_to_ni_addref(struct lnet_nid *nid)
1734 {
1735         struct lnet_ni *ni;
1736
1737         lnet_net_lock(0);
1738         ni = lnet_nid_to_ni_locked(nid, 0);
1739         if (ni)
1740                 lnet_ni_addref_locked(ni, 0);
1741         lnet_net_unlock(0);
1742
1743         return ni;
1744 }
1745 EXPORT_SYMBOL(lnet_nid_to_ni_addref);
1746
1747 int
1748 lnet_islocalnid(struct lnet_nid *nid)
1749 {
1750         struct lnet_ni  *ni;
1751         int             cpt;
1752
1753         cpt = lnet_net_lock_current();
1754         ni = lnet_nid_to_ni_locked(nid, cpt);
1755         lnet_net_unlock(cpt);
1756
1757         return ni != NULL;
1758 }
1759
1760 int
1761 lnet_count_acceptor_nets(void)
1762 {
1763         /* Return the # of NIs that need the acceptor. */
1764         int              count = 0;
1765         struct lnet_net  *net;
1766         int              cpt;
1767
1768         cpt = lnet_net_lock_current();
1769         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1770                 /* all socklnd type networks should have the acceptor
1771                  * thread started */
1772                 if (net->net_lnd->lnd_accept != NULL)
1773                         count++;
1774         }
1775
1776         lnet_net_unlock(cpt);
1777
1778         return count;
1779 }
1780
1781 struct lnet_ping_buffer *
1782 lnet_ping_buffer_alloc(int nbytes, gfp_t gfp)
1783 {
1784         struct lnet_ping_buffer *pbuf;
1785
1786         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nbytes), gfp);
1787         if (pbuf) {
1788                 pbuf->pb_nbytes = nbytes;       /* sizeof of pb_info */
1789                 pbuf->pb_needs_post = false;
1790                 atomic_set(&pbuf->pb_refcnt, 1);
1791         }
1792
1793         return pbuf;
1794 }
1795
1796 void
1797 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1798 {
1799         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1800         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nbytes));
1801 }
1802
1803 static struct lnet_ping_buffer *
1804 lnet_ping_target_create(int nbytes)
1805 {
1806         struct lnet_ping_buffer *pbuf;
1807
1808         pbuf = lnet_ping_buffer_alloc(nbytes, GFP_NOFS);
1809         if (pbuf == NULL) {
1810                 CERROR("Can't allocate ping source [%d]\n", nbytes);
1811                 return NULL;
1812         }
1813
1814         pbuf->pb_info.pi_nnis = 0;
1815         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1816         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1817         pbuf->pb_info.pi_features =
1818                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1819
1820         return pbuf;
1821 }
1822
1823 static inline int
1824 lnet_get_net_ni_bytes_locked(struct lnet_net *net)
1825 {
1826         struct lnet_ni *ni;
1827         int bytes = 0;
1828
1829         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1830                 bytes += lnet_ping_sts_size(&ni->ni_nid);
1831
1832         return bytes;
1833 }
1834
1835 static inline int
1836 lnet_get_ni_bytes(void)
1837 {
1838         struct lnet_ni *ni;
1839         struct lnet_net *net;
1840         int bytes = 0;
1841
1842         lnet_net_lock(0);
1843
1844         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1845                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1846                         bytes += lnet_ping_sts_size(&ni->ni_nid);
1847         }
1848
1849         lnet_net_unlock(0);
1850
1851         return bytes;
1852 }
1853
1854 void
1855 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1856 {
1857         struct lnet_ni_large_status *lstat, *lend;
1858         struct lnet_ni_status *stat, *end;
1859         int nnis;
1860         int i;
1861
1862         __swab32s(&pbuf->pb_info.pi_magic);
1863         __swab32s(&pbuf->pb_info.pi_features);
1864         __swab32s(&pbuf->pb_info.pi_pid);
1865         __swab32s(&pbuf->pb_info.pi_nnis);
1866         nnis = pbuf->pb_info.pi_nnis;
1867         stat = &pbuf->pb_info.pi_ni[0];
1868         end = (void *)&pbuf->pb_info + pbuf->pb_nbytes;
1869         for (i = 0; i < nnis && stat + 1 <= end; i++, stat++) {
1870                 __swab64s(&stat->ns_nid);
1871                 __swab32s(&stat->ns_status);
1872                 if (i == 0)
1873                         /* Might be total size */
1874                         __swab32s(&stat->ns_msg_size);
1875         }
1876         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_LARGE_ADDR))
1877                 return;
1878
1879         lstat = (struct lnet_ni_large_status *)stat;
1880         lend = (void *)end;
1881         while (lstat + 1 <= lend) {
1882                 __swab32s(&lstat->ns_status);
1883                 /* struct lnet_nid never needs to be swabed */
1884                 lstat = lnet_ping_sts_next(lstat);
1885         }
1886 }
1887
1888 int
1889 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1890 {
1891         if (!pinfo)
1892                 return -EINVAL;
1893         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1894                 return -EPROTO;
1895         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1896                 return -EPROTO;
1897         /* Loopback is guaranteed to be present */
1898         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1899                 return -ERANGE;
1900         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1901                 return -EPROTO;
1902         return 0;
1903 }
1904
1905 static void
1906 lnet_ping_target_destroy(void)
1907 {
1908         struct lnet_net *net;
1909         struct lnet_ni  *ni;
1910
1911         lnet_net_lock(LNET_LOCK_EX);
1912
1913         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1914                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1915                         lnet_ni_lock(ni);
1916                         ni->ni_status = NULL;
1917                         lnet_ni_unlock(ni);
1918                 }
1919         }
1920
1921         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1922         the_lnet.ln_ping_target = NULL;
1923
1924         lnet_net_unlock(LNET_LOCK_EX);
1925 }
1926
1927 static void
1928 lnet_ping_target_event_handler(struct lnet_event *event)
1929 {
1930         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1931
1932         if (event->unlinked)
1933                 lnet_ping_buffer_decref(pbuf);
1934 }
1935
1936 static int
1937 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1938                        struct lnet_handle_md *ping_mdh,
1939                        int ni_bytes, bool set_eq)
1940 {
1941         struct lnet_processid id = {
1942                 .nid = LNET_ANY_NID,
1943                 .pid = LNET_PID_ANY
1944         };
1945         struct lnet_me *me;
1946         struct lnet_md md = { NULL };
1947         int rc;
1948
1949         if (set_eq)
1950                 the_lnet.ln_ping_target_handler =
1951                         lnet_ping_target_event_handler;
1952
1953         *ppbuf = lnet_ping_target_create(ni_bytes);
1954         if (*ppbuf == NULL) {
1955                 rc = -ENOMEM;
1956                 goto fail_free_eq;
1957         }
1958
1959         /* Ping target ME/MD */
1960         me = LNetMEAttach(LNET_RESERVED_PORTAL, &id,
1961                           LNET_PROTO_PING_MATCHBITS, 0,
1962                           LNET_UNLINK, LNET_INS_AFTER);
1963         if (IS_ERR(me)) {
1964                 rc = PTR_ERR(me);
1965                 CERROR("Can't create ping target ME: %d\n", rc);
1966                 goto fail_decref_ping_buffer;
1967         }
1968
1969         /* initialize md content */
1970         md.start     = &(*ppbuf)->pb_info;
1971         md.length    = (*ppbuf)->pb_nbytes;
1972         md.threshold = LNET_MD_THRESH_INF;
1973         md.max_size  = 0;
1974         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1975                        LNET_MD_MANAGE_REMOTE;
1976         md.handler   = the_lnet.ln_ping_target_handler;
1977         md.user_ptr  = *ppbuf;
1978
1979         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
1980         if (rc != 0) {
1981                 CERROR("Can't attach ping target MD: %d\n", rc);
1982                 goto fail_decref_ping_buffer;
1983         }
1984         lnet_ping_buffer_addref(*ppbuf);
1985
1986         return 0;
1987
1988 fail_decref_ping_buffer:
1989         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
1990         lnet_ping_buffer_decref(*ppbuf);
1991         *ppbuf = NULL;
1992 fail_free_eq:
1993         return rc;
1994 }
1995
1996 static void
1997 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1998                     struct lnet_handle_md *ping_mdh)
1999 {
2000         LNetMDUnlink(*ping_mdh);
2001         LNetInvalidateMDHandle(ping_mdh);
2002
2003         /* NB the MD could be busy; this just starts the unlink */
2004         wait_var_event_warning(&pbuf->pb_refcnt,
2005                                atomic_read(&pbuf->pb_refcnt) <= 1,
2006                                "Still waiting for ping data MD to unlink\n");
2007 }
2008
2009 static void
2010 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
2011 {
2012         struct lnet_ni *ni;
2013         struct lnet_net *net;
2014         struct lnet_ni_status *ns, *end;
2015         struct lnet_ni_large_status *lns, *lend;
2016         int rc;
2017
2018         pbuf->pb_info.pi_nnis = 0;
2019         ns = &pbuf->pb_info.pi_ni[0];
2020         end = (void *)&pbuf->pb_info + pbuf->pb_nbytes;
2021         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2022                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2023                         if (!nid_is_nid4(&ni->ni_nid)) {
2024                                 if (ns == &pbuf->pb_info.pi_ni[1]) {
2025                                         /* This is primary, and it is long */
2026                                         pbuf->pb_info.pi_features |=
2027                                                 LNET_PING_FEAT_PRIMARY_LARGE;
2028                                 }
2029                                 continue;
2030                         }
2031                         LASSERT(ns + 1 <= end);
2032                         ns->ns_nid = lnet_nid_to_nid4(&ni->ni_nid);
2033
2034                         lnet_ni_lock(ni);
2035                         ns->ns_status = lnet_ni_get_status_locked(ni);
2036                         ni->ni_status = &ns->ns_status;
2037                         lnet_ni_unlock(ni);
2038
2039                         pbuf->pb_info.pi_nnis++;
2040                         ns++;
2041                 }
2042         }
2043
2044         lns = (void *)ns;
2045         lend = (void *)end;
2046         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2047                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2048                         if (nid_is_nid4(&ni->ni_nid))
2049                                 continue;
2050                         LASSERT(lns + 1 <= lend);
2051
2052                         lns->ns_nid = ni->ni_nid;
2053
2054                         lnet_ni_lock(ni);
2055                         lns->ns_status = lnet_ni_get_status_locked(ni);
2056                         ni->ni_status = &lns->ns_status;
2057                         lnet_ni_unlock(ni);
2058
2059                         lns = lnet_ping_sts_next(lns);
2060                 }
2061         }
2062         if ((void *)lns > (void *)ns) {
2063                 /* Record total info size */
2064                 pbuf->pb_info.pi_ni[0].ns_msg_size =
2065                         (void *)lns - (void *)&pbuf->pb_info;
2066                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_LARGE_ADDR;
2067         }
2068
2069         /* We (ab)use the ns_status of the loopback interface to
2070          * transmit the sequence number. The first interface listed
2071          * must be the loopback interface.
2072          */
2073         rc = lnet_ping_info_validate(&pbuf->pb_info);
2074         if (rc) {
2075                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
2076                 LBUG();
2077         }
2078         LNET_PING_BUFFER_SEQNO(pbuf) =
2079                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
2080 }
2081
2082 static void
2083 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
2084                         struct lnet_handle_md ping_mdh)
2085 __must_hold(&the_lnet.ln_api_mutex)
2086 {
2087         struct lnet_ping_buffer *old_pbuf = NULL;
2088         struct lnet_handle_md old_ping_md;
2089
2090         /* switch the NIs to point to the new ping info created */
2091         lnet_net_lock(LNET_LOCK_EX);
2092
2093         if (!the_lnet.ln_routing)
2094                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
2095         if (!lnet_peer_discovery_disabled)
2096                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
2097
2098         /* Ensure only known feature bits have been set. */
2099         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
2100         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
2101
2102         lnet_ping_target_install_locked(pbuf);
2103
2104         if (the_lnet.ln_ping_target) {
2105                 old_pbuf = the_lnet.ln_ping_target;
2106                 old_ping_md = the_lnet.ln_ping_target_md;
2107         }
2108         the_lnet.ln_ping_target_md = ping_mdh;
2109         the_lnet.ln_ping_target = pbuf;
2110
2111         lnet_net_unlock(LNET_LOCK_EX);
2112
2113         if (old_pbuf) {
2114                 /* unlink and free the old ping info.
2115                  * There may be outstanding traffic on this MD, and
2116                  * ln_api_mutex may be required to finalize that
2117                  * traffic. Release ln_api_mutex while we wait for
2118                  * refs on this ping buffer to drop
2119                  */
2120                 mutex_unlock(&the_lnet.ln_api_mutex);
2121                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
2122                 mutex_lock(&the_lnet.ln_api_mutex);
2123                 lnet_ping_buffer_decref(old_pbuf);
2124         }
2125
2126         lnet_push_update_to_peers(0);
2127 }
2128
2129 static void
2130 lnet_ping_target_fini(void)
2131 {
2132         lnet_ping_md_unlink(the_lnet.ln_ping_target,
2133                             &the_lnet.ln_ping_target_md);
2134
2135         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler, true);
2136         lnet_ping_target_destroy();
2137 }
2138
2139 /* Resize the push target. */
2140 int lnet_push_target_resize(void)
2141 {
2142         struct lnet_handle_md mdh;
2143         struct lnet_handle_md old_mdh;
2144         struct lnet_ping_buffer *pbuf;
2145         struct lnet_ping_buffer *old_pbuf;
2146         int nbytes;
2147         int rc;
2148
2149 again:
2150         nbytes = the_lnet.ln_push_target_nbytes;
2151         if (nbytes <= 0) {
2152                 CDEBUG(D_NET, "Invalid nbytes %d\n", nbytes);
2153                 return -EINVAL;
2154         }
2155
2156         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
2157          * dropped when we need to resize again (see "old_pbuf" below) or when
2158          * LNet is shutdown (see lnet_push_target_fini())
2159          */
2160         pbuf = lnet_ping_buffer_alloc(nbytes, GFP_NOFS);
2161         if (!pbuf) {
2162                 CDEBUG(D_NET, "Can't allocate pbuf for nbytes %d\n", nbytes);
2163                 return -ENOMEM;
2164         }
2165
2166         rc = lnet_push_target_post(pbuf, &mdh);
2167         if (rc) {
2168                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
2169                 lnet_ping_buffer_decref(pbuf);
2170                 return rc;
2171         }
2172
2173         lnet_net_lock(LNET_LOCK_EX);
2174         old_pbuf = the_lnet.ln_push_target;
2175         old_mdh = the_lnet.ln_push_target_md;
2176         the_lnet.ln_push_target = pbuf;
2177         the_lnet.ln_push_target_md = mdh;
2178         lnet_net_unlock(LNET_LOCK_EX);
2179
2180         if (old_pbuf) {
2181                 LNetMDUnlink(old_mdh);
2182                 /* Drop ref set by lnet_ping_buffer_alloc() */
2183                 lnet_ping_buffer_decref(old_pbuf);
2184         }
2185
2186         /* Received another push or reply that requires a larger buffer */
2187         if (nbytes < the_lnet.ln_push_target_nbytes)
2188                 goto again;
2189
2190         CDEBUG(D_NET, "nbytes %d success\n", nbytes);
2191         return 0;
2192 }
2193
2194 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
2195                           struct lnet_handle_md *mdhp)
2196 {
2197         struct lnet_processid id = { LNET_ANY_NID, LNET_PID_ANY };
2198         struct lnet_md md = { NULL };
2199         struct lnet_me *me;
2200         int rc;
2201
2202         me = LNetMEAttach(LNET_RESERVED_PORTAL, &id,
2203                           LNET_PROTO_PING_MATCHBITS, 0,
2204                           LNET_UNLINK, LNET_INS_AFTER);
2205         if (IS_ERR(me)) {
2206                 rc = PTR_ERR(me);
2207                 CERROR("Can't create push target ME: %d\n", rc);
2208                 return rc;
2209         }
2210
2211         pbuf->pb_needs_post = false;
2212
2213         /* This reference is dropped by lnet_push_target_event_handler() */
2214         lnet_ping_buffer_addref(pbuf);
2215
2216         /* initialize md content */
2217         md.start     = &pbuf->pb_info;
2218         md.length    = pbuf->pb_nbytes;
2219         md.threshold = 1;
2220         md.max_size  = 0;
2221         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
2222         md.user_ptr  = pbuf;
2223         md.handler   = the_lnet.ln_push_target_handler;
2224
2225         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
2226         if (rc) {
2227                 CERROR("Can't attach push MD: %d\n", rc);
2228                 lnet_ping_buffer_decref(pbuf);
2229                 pbuf->pb_needs_post = true;
2230                 return rc;
2231         }
2232
2233         CDEBUG(D_NET, "posted push target %p\n", pbuf);
2234
2235         return 0;
2236 }
2237
2238 static void lnet_push_target_event_handler(struct lnet_event *ev)
2239 {
2240         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
2241
2242         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
2243                ev->unlinked);
2244
2245         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2246                 lnet_swap_pinginfo(pbuf);
2247
2248         if (ev->type == LNET_EVENT_UNLINK) {
2249                 /* Drop ref added by lnet_push_target_post() */
2250                 lnet_ping_buffer_decref(pbuf);
2251                 return;
2252         }
2253
2254         lnet_peer_push_event(ev);
2255         if (ev->unlinked)
2256                 /* Drop ref added by lnet_push_target_post */
2257                 lnet_ping_buffer_decref(pbuf);
2258 }
2259
2260 /* Initialize the push target. */
2261 static int lnet_push_target_init(void)
2262 {
2263         int rc;
2264
2265         if (the_lnet.ln_push_target)
2266                 return -EALREADY;
2267
2268         the_lnet.ln_push_target_handler =
2269                 lnet_push_target_event_handler;
2270
2271         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2272         LASSERT(rc == 0);
2273
2274         /* Start at the required minimum, we'll enlarge if required. */
2275         the_lnet.ln_push_target_nbytes = LNET_PING_INFO_MIN_SIZE;
2276
2277         rc = lnet_push_target_resize();
2278         if (rc) {
2279                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2280                 the_lnet.ln_push_target_handler = NULL;
2281         }
2282
2283         return rc;
2284 }
2285
2286 /* Clean up the push target. */
2287 static void lnet_push_target_fini(void)
2288 {
2289         if (!the_lnet.ln_push_target)
2290                 return;
2291
2292         /* Unlink and invalidate to prevent new references. */
2293         LNetMDUnlink(the_lnet.ln_push_target_md);
2294         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2295
2296         /* Wait for the unlink to complete. */
2297         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2298                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2299                                "Still waiting for ping data MD to unlink\n");
2300
2301         /* Drop ref set by lnet_ping_buffer_alloc() */
2302         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2303         the_lnet.ln_push_target = NULL;
2304         the_lnet.ln_push_target_nbytes = 0;
2305
2306         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2307         lnet_assert_handler_unused(the_lnet.ln_push_target_handler, true);
2308         the_lnet.ln_push_target_handler = NULL;
2309 }
2310
2311 static int
2312 lnet_ni_tq_credits(struct lnet_ni *ni)
2313 {
2314         int     credits;
2315
2316         LASSERT(ni->ni_ncpts >= 1);
2317
2318         if (ni->ni_ncpts == 1)
2319                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2320
2321         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2322         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2323         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2324
2325         return credits;
2326 }
2327
2328 static void
2329 lnet_ni_unlink_locked(struct lnet_ni *ni)
2330 {
2331         /* move it to zombie list and nobody can find it anymore */
2332         LASSERT(!list_empty(&ni->ni_netlist));
2333         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2334         lnet_ni_decref_locked(ni, 0);
2335 }
2336
2337 static void
2338 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2339 {
2340         int             i;
2341         int             islo;
2342         struct lnet_ni  *ni;
2343         struct list_head *zombie_list = &net->net_ni_zombie;
2344
2345         /*
2346          * Now wait for the NIs I just nuked to show up on the zombie
2347          * list and shut them down in guaranteed thread context
2348          */
2349         i = 2;
2350         while ((ni = list_first_entry_or_null(zombie_list,
2351                                               struct lnet_ni,
2352                                               ni_netlist)) != NULL) {
2353                 int *ref;
2354                 int j;
2355
2356                 list_del_init(&ni->ni_netlist);
2357                 /* the ni should be in deleting state. If it's not it's
2358                  * a bug */
2359                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2360                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2361                         if (*ref == 0)
2362                                 continue;
2363                         /* still busy, add it back to zombie list */
2364                         list_add(&ni->ni_netlist, zombie_list);
2365                         break;
2366                 }
2367
2368                 if (!list_empty(&ni->ni_netlist)) {
2369                         /* Unlock mutex while waiting to allow other
2370                          * threads to read the LNet state and fall through
2371                          * to avoid deadlock
2372                          */
2373                         lnet_net_unlock(LNET_LOCK_EX);
2374                         mutex_unlock(&the_lnet.ln_api_mutex);
2375
2376                         ++i;
2377                         if ((i & (-i)) == i) {
2378                                 CDEBUG(D_WARNING,
2379                                        "Waiting for zombie LNI %s\n",
2380                                        libcfs_nidstr(&ni->ni_nid));
2381                         }
2382                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2383
2384                         mutex_lock(&the_lnet.ln_api_mutex);
2385                         lnet_net_lock(LNET_LOCK_EX);
2386                         continue;
2387                 }
2388
2389                 lnet_net_unlock(LNET_LOCK_EX);
2390
2391                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2392
2393                 LASSERT(!in_interrupt());
2394                 /* Holding the LND mutex makes it safe for lnd_shutdown
2395                  * to call module_put(). Module unload cannot finish
2396                  * until lnet_unregister_lnd() completes, and that
2397                  * requires the LND mutex.
2398                  */
2399                 mutex_unlock(&the_lnet.ln_api_mutex);
2400                 mutex_lock(&the_lnet.ln_lnd_mutex);
2401                 (net->net_lnd->lnd_shutdown)(ni);
2402                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2403                 mutex_lock(&the_lnet.ln_api_mutex);
2404
2405                 if (!islo)
2406                         CDEBUG(D_LNI, "Removed LNI %s\n",
2407                               libcfs_nidstr(&ni->ni_nid));
2408
2409                 lnet_ni_free(ni);
2410                 i = 2;
2411                 lnet_net_lock(LNET_LOCK_EX);
2412         }
2413 }
2414
2415 /* shutdown down the NI and release refcount */
2416 static void
2417 lnet_shutdown_lndni(struct lnet_ni *ni)
2418 {
2419         int i;
2420         struct lnet_net *net = ni->ni_net;
2421
2422         lnet_net_lock(LNET_LOCK_EX);
2423         lnet_ni_lock(ni);
2424         ni->ni_state = LNET_NI_STATE_DELETING;
2425         lnet_ni_unlock(ni);
2426         lnet_ni_unlink_locked(ni);
2427         lnet_incr_dlc_seq();
2428         lnet_net_unlock(LNET_LOCK_EX);
2429
2430         /* clear messages for this NI on the lazy portal */
2431         for (i = 0; i < the_lnet.ln_nportals; i++)
2432                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2433
2434         lnet_net_lock(LNET_LOCK_EX);
2435         lnet_clear_zombies_nis_locked(net);
2436         lnet_net_unlock(LNET_LOCK_EX);
2437 }
2438
2439 static void
2440 lnet_shutdown_lndnet(struct lnet_net *net)
2441 {
2442         struct lnet_ni *ni;
2443
2444         lnet_net_lock(LNET_LOCK_EX);
2445
2446         list_del_init(&net->net_list);
2447
2448         while ((ni = list_first_entry_or_null(&net->net_ni_list,
2449                                               struct lnet_ni,
2450                                               ni_netlist)) != NULL) {
2451                 lnet_net_unlock(LNET_LOCK_EX);
2452                 lnet_shutdown_lndni(ni);
2453                 lnet_net_lock(LNET_LOCK_EX);
2454         }
2455
2456         lnet_net_unlock(LNET_LOCK_EX);
2457
2458         /* Do peer table cleanup for this net */
2459         lnet_peer_tables_cleanup(net);
2460
2461         lnet_net_free(net);
2462 }
2463
2464 static void
2465 lnet_shutdown_lndnets(void)
2466 {
2467         struct lnet_net *net;
2468         LIST_HEAD(resend);
2469         struct lnet_msg *msg, *tmp;
2470
2471         /* NB called holding the global mutex */
2472
2473         /* All quiet on the API front */
2474         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING ||
2475                 the_lnet.ln_state == LNET_STATE_STOPPING);
2476         LASSERT(the_lnet.ln_refcount == 0);
2477
2478         lnet_net_lock(LNET_LOCK_EX);
2479         the_lnet.ln_state = LNET_STATE_STOPPING;
2480
2481         /*
2482          * move the nets to the zombie list to avoid them being
2483          * picked up for new work. LONET is also included in the
2484          * Nets that will be moved to the zombie list
2485          */
2486         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2487
2488         /* Drop the cached loopback Net. */
2489         if (the_lnet.ln_loni != NULL) {
2490                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2491                 the_lnet.ln_loni = NULL;
2492         }
2493         lnet_net_unlock(LNET_LOCK_EX);
2494
2495         /* iterate through the net zombie list and delete each net */
2496         while ((net = list_first_entry_or_null(&the_lnet.ln_net_zombie,
2497                                                struct lnet_net,
2498                                                net_list)) != NULL)
2499                 lnet_shutdown_lndnet(net);
2500
2501         spin_lock(&the_lnet.ln_msg_resend_lock);
2502         list_splice(&the_lnet.ln_msg_resend, &resend);
2503         spin_unlock(&the_lnet.ln_msg_resend_lock);
2504
2505         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2506                 list_del_init(&msg->msg_list);
2507                 msg->msg_no_resend = true;
2508                 lnet_finalize(msg, -ECANCELED);
2509         }
2510
2511         lnet_net_lock(LNET_LOCK_EX);
2512         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2513         lnet_net_unlock(LNET_LOCK_EX);
2514 }
2515
2516 static int
2517 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2518 {
2519         int                     rc = -EINVAL;
2520         struct lnet_tx_queue    *tq;
2521         int                     i;
2522         struct lnet_net         *net = ni->ni_net;
2523
2524         mutex_lock(&the_lnet.ln_lnd_mutex);
2525
2526         if (tun) {
2527                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2528                 ni->ni_lnd_tunables_set = true;
2529         }
2530
2531         rc = (net->net_lnd->lnd_startup)(ni);
2532
2533         mutex_unlock(&the_lnet.ln_lnd_mutex);
2534
2535         if (rc != 0) {
2536                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2537                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2538                 goto failed0;
2539         }
2540
2541         /* We keep a reference on the loopback net through the loopback NI */
2542         if (net->net_lnd->lnd_type == LOLND) {
2543                 lnet_ni_addref(ni);
2544                 LASSERT(the_lnet.ln_loni == NULL);
2545                 the_lnet.ln_loni = ni;
2546                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2547                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2548                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2549                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2550                 return 0;
2551         }
2552
2553         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2554             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2555                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2556                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2557                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2558                                         "" : "per-peer ");
2559                 /* shutdown the NI since if we get here then it must've already
2560                  * been started
2561                  */
2562                 lnet_shutdown_lndni(ni);
2563                 return -EINVAL;
2564         }
2565
2566         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2567                 tq->tq_credits_min =
2568                 tq->tq_credits_max =
2569                 tq->tq_credits = lnet_ni_tq_credits(ni);
2570         }
2571
2572         atomic_set(&ni->ni_tx_credits,
2573                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2574         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2575
2576         /* Nodes with small feet have little entropy. The NID for this
2577          * node gives the most entropy in the low bits.
2578          */
2579         add_device_randomness(&ni->ni_nid, sizeof(ni->ni_nid));
2580
2581         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2582                 libcfs_nidstr(&ni->ni_nid),
2583                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2584                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2585                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2586                 ni->ni_net->net_tunables.lct_peer_timeout);
2587
2588         return 0;
2589 failed0:
2590         lnet_ni_free(ni);
2591         return rc;
2592 }
2593
2594 static const struct lnet_lnd *lnet_load_lnd(u32 lnd_type)
2595 {
2596         const struct lnet_lnd *lnd;
2597         int rc = 0;
2598
2599         mutex_lock(&the_lnet.ln_lnd_mutex);
2600         lnd = lnet_find_lnd_by_type(lnd_type);
2601         if (!lnd) {
2602                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2603                 rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2604                 mutex_lock(&the_lnet.ln_lnd_mutex);
2605
2606                 lnd = lnet_find_lnd_by_type(lnd_type);
2607                 if (!lnd) {
2608                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2609                         CERROR("Can't load LND %s, module %s, rc=%d\n",
2610                         libcfs_lnd2str(lnd_type),
2611                         libcfs_lnd2modname(lnd_type), rc);
2612 #ifndef HAVE_MODULE_LOADING_SUPPORT
2613                         LCONSOLE_ERROR_MSG(0x104,
2614                                            "Your kernel must be compiled with kernel module loading support.");
2615 #endif
2616                         return ERR_PTR(-EINVAL);
2617                 }
2618         }
2619         mutex_unlock(&the_lnet.ln_lnd_mutex);
2620
2621         return lnd;
2622 }
2623
2624 static int
2625 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2626 {
2627         struct lnet_ni *ni;
2628         struct lnet_net *net_l = NULL;
2629         LIST_HEAD(local_ni_list);
2630         int rc;
2631         int ni_count = 0;
2632         __u32 lnd_type;
2633         const struct lnet_lnd  *lnd;
2634         int peer_timeout =
2635                 net->net_tunables.lct_peer_timeout;
2636         int maxtxcredits =
2637                 net->net_tunables.lct_max_tx_credits;
2638         int peerrtrcredits =
2639                 net->net_tunables.lct_peer_rtr_credits;
2640
2641         /*
2642          * make sure that this net is unique. If it isn't then
2643          * we are adding interfaces to an already existing network, and
2644          * 'net' is just a convenient way to pass in the list.
2645          * if it is unique we need to find the LND and load it if
2646          * necessary.
2647          */
2648         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2649                 lnd_type = LNET_NETTYP(net->net_id);
2650
2651                 lnd = lnet_load_lnd(lnd_type);
2652                 if (IS_ERR(lnd)) {
2653                         rc = PTR_ERR(lnd);
2654                         goto failed0;
2655                 }
2656
2657                 mutex_lock(&the_lnet.ln_lnd_mutex);
2658                 net->net_lnd = lnd;
2659                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2660
2661                 net_l = net;
2662         }
2663
2664         /*
2665          * net_l: if the network being added is unique then net_l
2666          *        will point to that network
2667          *        if the network being added is not unique then
2668          *        net_l points to the existing network.
2669          *
2670          * When we enter the loop below, we'll pick NIs off he
2671          * network beign added and start them up, then add them to
2672          * a local ni list. Once we've successfully started all
2673          * the NIs then we join the local NI list (of started up
2674          * networks) with the net_l->net_ni_list, which should
2675          * point to the correct network to add the new ni list to
2676          *
2677          * If any of the new NIs fail to start up, then we want to
2678          * iterate through the local ni list, which should include
2679          * any NIs which were successfully started up, and shut
2680          * them down.
2681          *
2682          * After than we want to delete the network being added,
2683          * to avoid a memory leak.
2684          */
2685         while ((ni = list_first_entry_or_null(&net->net_ni_added,
2686                                               struct lnet_ni,
2687                                               ni_netlist)) != NULL) {
2688                 list_del_init(&ni->ni_netlist);
2689
2690                 /* make sure that the the NI we're about to start
2691                  * up is actually unique. if it's not fail. */
2692                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2693                                         ni->ni_interface)) {
2694                         rc = -EEXIST;
2695                         goto failed1;
2696                 }
2697
2698                 /* adjust the pointer the parent network, just in case it
2699                  * the net is a duplicate */
2700                 ni->ni_net = net_l;
2701
2702                 rc = lnet_startup_lndni(ni, tun);
2703
2704                 if (rc != 0)
2705                         goto failed1;
2706
2707                 lnet_ni_addref(ni);
2708                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2709
2710                 ni_count++;
2711         }
2712
2713         lnet_net_lock(LNET_LOCK_EX);
2714         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2715         lnet_incr_dlc_seq();
2716
2717         list_for_each_entry(ni, &net_l->net_ni_list, ni_netlist) {
2718                 if (!ni)
2719                         break;
2720                 lnet_ni_lock(ni);
2721                 ni->ni_state = LNET_NI_STATE_ACTIVE;
2722                 lnet_ni_unlock(ni);
2723         }
2724         lnet_net_unlock(LNET_LOCK_EX);
2725
2726         /* if the network is not unique then we don't want to keep
2727          * it around after we're done. Free it. Otherwise add that
2728          * net to the global the_lnet.ln_nets */
2729         if (net_l != net && net_l != NULL) {
2730                 /*
2731                  * TODO - note. currently the tunables can not be updated
2732                  * once added
2733                  */
2734                 lnet_net_free(net);
2735         } else {
2736                 /*
2737                  * restore tunables after it has been overwitten by the
2738                  * lnd
2739                  */
2740                 if (peer_timeout != -1)
2741                         net->net_tunables.lct_peer_timeout = peer_timeout;
2742                 if (maxtxcredits != -1)
2743                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2744                 if (peerrtrcredits != -1)
2745                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2746
2747                 lnet_net_lock(LNET_LOCK_EX);
2748                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2749                 lnet_net_unlock(LNET_LOCK_EX);
2750         }
2751
2752         return ni_count;
2753
2754 failed1:
2755         /*
2756          * shutdown the new NIs that are being started up
2757          * free the NET being started
2758          */
2759         while ((ni = list_first_entry_or_null(&local_ni_list,
2760                                               struct lnet_ni,
2761                                               ni_netlist)) != NULL)
2762                 lnet_shutdown_lndni(ni);
2763
2764 failed0:
2765         lnet_net_free(net);
2766
2767         return rc;
2768 }
2769
2770 static int
2771 lnet_startup_lndnets(struct list_head *netlist)
2772 {
2773         struct lnet_net         *net;
2774         int                     rc;
2775         int                     ni_count = 0;
2776
2777         /*
2778          * Change to running state before bringing up the LNDs. This
2779          * allows lnet_shutdown_lndnets() to assert that we've passed
2780          * through here.
2781          */
2782         lnet_net_lock(LNET_LOCK_EX);
2783         the_lnet.ln_state = LNET_STATE_RUNNING;
2784         lnet_net_unlock(LNET_LOCK_EX);
2785
2786         while ((net = list_first_entry_or_null(netlist,
2787                                                struct lnet_net,
2788                                                net_list)) != NULL) {
2789                 list_del_init(&net->net_list);
2790
2791                 rc = lnet_startup_lndnet(net, NULL);
2792
2793                 if (rc < 0)
2794                         goto failed;
2795
2796                 ni_count += rc;
2797         }
2798
2799         return ni_count;
2800 failed:
2801         lnet_shutdown_lndnets();
2802
2803         return rc;
2804 }
2805
2806 static int lnet_genl_parse_list(struct sk_buff *msg,
2807                                 const struct ln_key_list *data[], u16 idx)
2808 {
2809         const struct ln_key_list *list = data[idx];
2810         const struct ln_key_props *props;
2811         struct nlattr *node;
2812         u16 count;
2813
2814         if (!list)
2815                 return 0;
2816
2817         if (!list->lkl_maxattr)
2818                 return -ERANGE;
2819
2820         props = list->lkl_list;
2821         if (!props)
2822                 return -EINVAL;
2823
2824         node = nla_nest_start(msg, LN_SCALAR_ATTR_LIST);
2825         if (!node)
2826                 return -ENOBUFS;
2827
2828         for (count = 1; count <= list->lkl_maxattr; count++) {
2829                 struct nlattr *key = nla_nest_start(msg, count);
2830
2831                 if (!key)
2832                         return -EMSGSIZE;
2833
2834                 if (count == 1)
2835                         nla_put_u16(msg, LN_SCALAR_ATTR_LIST_SIZE,
2836                                     list->lkl_maxattr);
2837
2838                 nla_put_u16(msg, LN_SCALAR_ATTR_INDEX, count);
2839                 if (props[count].lkp_value)
2840                         nla_put_string(msg, LN_SCALAR_ATTR_VALUE,
2841                                        props[count].lkp_value);
2842                 if (props[count].lkp_key_format)
2843                         nla_put_u16(msg, LN_SCALAR_ATTR_KEY_FORMAT,
2844                                     props[count].lkp_key_format);
2845                 nla_put_u16(msg, LN_SCALAR_ATTR_NLA_TYPE,
2846                             props[count].lkp_data_type);
2847                 if (props[count].lkp_data_type == NLA_NESTED) {
2848                         int rc;
2849
2850                         rc = lnet_genl_parse_list(msg, data, ++idx);
2851                         if (rc < 0)
2852                                 return rc;
2853                         idx = rc;
2854                 }
2855
2856                 nla_nest_end(msg, key);
2857         }
2858
2859         nla_nest_end(msg, node);
2860         return idx;
2861 }
2862
2863 int lnet_genl_send_scalar_list(struct sk_buff *msg, u32 portid, u32 seq,
2864                                const struct genl_family *family, int flags,
2865                                u8 cmd, const struct ln_key_list *data[])
2866 {
2867         int rc = 0;
2868         void *hdr;
2869
2870         if (!data[0])
2871                 return -EINVAL;
2872
2873         hdr = genlmsg_put(msg, portid, seq, family, flags, cmd);
2874         if (!hdr)
2875                 GOTO(canceled, rc = -EMSGSIZE);
2876
2877         rc = lnet_genl_parse_list(msg, data, 0);
2878         if (rc < 0)
2879                 GOTO(canceled, rc);
2880
2881         genlmsg_end(msg, hdr);
2882 canceled:
2883         if (rc < 0)
2884                 genlmsg_cancel(msg, hdr);
2885         return rc > 0 ? 0 : rc;
2886 }
2887 EXPORT_SYMBOL(lnet_genl_send_scalar_list);
2888
2889 static struct genl_family lnet_family;
2890
2891 /**
2892  * Initialize LNet library.
2893  *
2894  * Automatically called at module loading time. Caller has to call
2895  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2896  * latter returned 0. It must be called exactly once.
2897  *
2898  * \retval 0 on success
2899  * \retval -ve on failures.
2900  */
2901 int lnet_lib_init(void)
2902 {
2903         int rc;
2904
2905         lnet_assert_wire_constants();
2906
2907         /* refer to global cfs_cpt_table for now */
2908         the_lnet.ln_cpt_table = cfs_cpt_tab;
2909         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2910
2911         LASSERT(the_lnet.ln_cpt_number > 0);
2912         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2913                 /* we are under risk of consuming all lh_cookie */
2914                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2915                        "please change setting of CPT-table and retry\n",
2916                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2917                 return -E2BIG;
2918         }
2919
2920         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2921                 the_lnet.ln_cpt_bits++;
2922
2923         rc = lnet_create_locks();
2924         if (rc != 0) {
2925                 CERROR("Can't create LNet global locks: %d\n", rc);
2926                 return rc;
2927         }
2928
2929         rc = genl_register_family(&lnet_family);
2930         if (rc != 0) {
2931                 lnet_destroy_locks();
2932                 CERROR("Can't register LNet netlink family: %d\n", rc);
2933                 return rc;
2934         }
2935
2936         the_lnet.ln_refcount = 0;
2937         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2938         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2939
2940         /* The hash table size is the number of bits it takes to express the set
2941          * ln_num_routes, minus 1 (better to under estimate than over so we
2942          * don't waste memory). */
2943         if (rnet_htable_size <= 0)
2944                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2945         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2946                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2947         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2948                                            order_base_2(rnet_htable_size) - 1);
2949
2950         /* All LNDs apart from the LOLND are in separate modules.  They
2951          * register themselves when their module loads, and unregister
2952          * themselves when their module is unloaded. */
2953         lnet_register_lnd(&the_lolnd);
2954         return 0;
2955 }
2956
2957 /**
2958  * Finalize LNet library.
2959  *
2960  * \pre lnet_lib_init() called with success.
2961  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2962  *
2963  * As this happens at module-unload, all lnds must already be unloaded,
2964  * so they must already be unregistered.
2965  */
2966 void lnet_lib_exit(void)
2967 {
2968         int i;
2969
2970         LASSERT(the_lnet.ln_refcount == 0);
2971         lnet_unregister_lnd(&the_lolnd);
2972         for (i = 0; i < NUM_LNDS; i++)
2973                 LASSERT(!the_lnet.ln_lnds[i]);
2974         lnet_destroy_locks();
2975         genl_unregister_family(&lnet_family);
2976 }
2977
2978 /**
2979  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2980  *
2981  * Users must call this function at least once before any other functions.
2982  * For each successful call there must be a corresponding call to
2983  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2984  * ignored.
2985  *
2986  * The PID used by LNet may be different from the one requested.
2987  * See LNetGetId().
2988  *
2989  * \param requested_pid PID requested by the caller.
2990  *
2991  * \return >= 0 on success, and < 0 error code on failures.
2992  */
2993 int
2994 LNetNIInit(lnet_pid_t requested_pid)
2995 {
2996         int im_a_router = 0;
2997         int rc;
2998         int ni_bytes;
2999         struct lnet_ping_buffer *pbuf;
3000         struct lnet_handle_md ping_mdh;
3001         LIST_HEAD(net_head);
3002         struct lnet_net *net;
3003
3004         mutex_lock(&the_lnet.ln_api_mutex);
3005
3006         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
3007
3008         if (the_lnet.ln_state == LNET_STATE_STOPPING) {
3009                 mutex_unlock(&the_lnet.ln_api_mutex);
3010                 return -ESHUTDOWN;
3011         }
3012
3013         if (the_lnet.ln_refcount > 0) {
3014                 rc = the_lnet.ln_refcount++;
3015                 mutex_unlock(&the_lnet.ln_api_mutex);
3016                 return rc;
3017         }
3018
3019         rc = lnet_prepare(requested_pid);
3020         if (rc != 0) {
3021                 mutex_unlock(&the_lnet.ln_api_mutex);
3022                 return rc;
3023         }
3024
3025         /* create a network for Loopback network */
3026         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
3027         if (net == NULL) {
3028                 rc = -ENOMEM;
3029                 goto err_empty_list;
3030         }
3031
3032         /* Add in the loopback NI */
3033         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
3034                 rc = -ENOMEM;
3035                 goto err_empty_list;
3036         }
3037
3038         if (use_tcp_bonding)
3039                 CWARN("use_tcp_bonding has been removed. Use Multi-Rail and Dynamic Discovery instead, see LU-13641\n");
3040
3041         /* If LNet is being initialized via DLC it is possible
3042          * that the user requests not to load module parameters (ones which
3043          * are supported by DLC) on initialization.  Therefore, make sure not
3044          * to load networks, routes and forwarding from module parameters
3045          * in this case.  On cleanup in case of failure only clean up
3046          * routes if it has been loaded */
3047         if (!the_lnet.ln_nis_from_mod_params) {
3048                 rc = lnet_parse_networks(&net_head, lnet_get_networks());
3049                 if (rc < 0)
3050                         goto err_empty_list;
3051         }
3052
3053         rc = lnet_startup_lndnets(&net_head);
3054         if (rc < 0)
3055                 goto err_empty_list;
3056
3057         if (!the_lnet.ln_nis_from_mod_params) {
3058                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
3059                 if (rc != 0)
3060                         goto err_shutdown_lndnis;
3061
3062                 rc = lnet_rtrpools_alloc(im_a_router);
3063                 if (rc != 0)
3064                         goto err_destroy_routes;
3065         }
3066
3067         rc = lnet_acceptor_start();
3068         if (rc != 0)
3069                 goto err_destroy_routes;
3070
3071         the_lnet.ln_refcount = 1;
3072         /* Now I may use my own API functions... */
3073
3074         ni_bytes = LNET_PING_INFO_HDR_SIZE;
3075         list_for_each_entry(net, &the_lnet.ln_nets, net_list)
3076                 ni_bytes += lnet_get_net_ni_bytes_locked(net);
3077
3078         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_bytes, true);
3079         if (rc != 0)
3080                 goto err_acceptor_stop;
3081
3082         lnet_ping_target_update(pbuf, ping_mdh);
3083
3084         the_lnet.ln_mt_handler = lnet_mt_event_handler;
3085
3086         rc = lnet_push_target_init();
3087         if (rc != 0)
3088                 goto err_stop_ping;
3089
3090         rc = lnet_monitor_thr_start();
3091         if (rc != 0)
3092                 goto err_destroy_push_target;
3093
3094         rc = lnet_peer_discovery_start();
3095         if (rc != 0)
3096                 goto err_stop_monitor_thr;
3097
3098         lnet_fault_init();
3099         lnet_router_debugfs_init();
3100
3101         mutex_unlock(&the_lnet.ln_api_mutex);
3102
3103         complete_all(&the_lnet.ln_started);
3104
3105         /* wait for all routers to start */
3106         lnet_wait_router_start();
3107
3108         return 0;
3109
3110 err_stop_monitor_thr:
3111         lnet_monitor_thr_stop();
3112 err_destroy_push_target:
3113         lnet_push_target_fini();
3114 err_stop_ping:
3115         lnet_ping_target_fini();
3116 err_acceptor_stop:
3117         the_lnet.ln_refcount = 0;
3118         lnet_acceptor_stop();
3119 err_destroy_routes:
3120         if (!the_lnet.ln_nis_from_mod_params)
3121                 lnet_destroy_routes();
3122 err_shutdown_lndnis:
3123         lnet_shutdown_lndnets();
3124 err_empty_list:
3125         lnet_unprepare();
3126         LASSERT(rc < 0);
3127         mutex_unlock(&the_lnet.ln_api_mutex);
3128         while ((net = list_first_entry_or_null(&net_head,
3129                                                struct lnet_net,
3130                                                net_list)) != NULL) {
3131                 list_del_init(&net->net_list);
3132                 lnet_net_free(net);
3133         }
3134         return rc;
3135 }
3136 EXPORT_SYMBOL(LNetNIInit);
3137
3138 /**
3139  * Stop LNet interfaces, routing, and forwarding.
3140  *
3141  * Users must call this function once for each successful call to LNetNIInit().
3142  * Once the LNetNIFini() operation has been started, the results of pending
3143  * API operations are undefined.
3144  *
3145  * \return always 0 for current implementation.
3146  */
3147 int
3148 LNetNIFini(void)
3149 {
3150         mutex_lock(&the_lnet.ln_api_mutex);
3151
3152         LASSERT(the_lnet.ln_refcount > 0);
3153
3154         if (the_lnet.ln_refcount != 1) {
3155                 the_lnet.ln_refcount--;
3156         } else {
3157                 LASSERT(!the_lnet.ln_niinit_self);
3158
3159                 lnet_net_lock(LNET_LOCK_EX);
3160                 the_lnet.ln_state = LNET_STATE_STOPPING;
3161                 lnet_net_unlock(LNET_LOCK_EX);
3162
3163                 lnet_fault_fini();
3164
3165                 lnet_router_debugfs_fini();
3166                 lnet_peer_discovery_stop();
3167                 lnet_monitor_thr_stop();
3168                 lnet_push_target_fini();
3169                 lnet_ping_target_fini();
3170
3171                 /* Teardown fns that use my own API functions BEFORE here */
3172                 the_lnet.ln_refcount = 0;
3173
3174                 lnet_acceptor_stop();
3175                 lnet_destroy_routes();
3176                 lnet_shutdown_lndnets();
3177                 lnet_unprepare();
3178         }
3179
3180         mutex_unlock(&the_lnet.ln_api_mutex);
3181         return 0;
3182 }
3183 EXPORT_SYMBOL(LNetNIFini);
3184
3185 /**
3186  * Grabs the ni data from the ni structure and fills the out
3187  * parameters
3188  *
3189  * \param[in] ni network        interface structure
3190  * \param[out] cfg_ni           NI config information
3191  * \param[out] tun              network and LND tunables
3192  */
3193 static void
3194 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
3195                    struct lnet_ioctl_config_lnd_tunables *tun,
3196                    struct lnet_ioctl_element_stats *stats,
3197                    __u32 tun_size)
3198 {
3199         size_t min_size = 0;
3200         int i;
3201
3202         if (!ni || !cfg_ni || !tun || !nid_is_nid4(&ni->ni_nid))
3203                 return;
3204
3205         if (ni->ni_interface != NULL) {
3206                 strncpy(cfg_ni->lic_ni_intf,
3207                         ni->ni_interface,
3208                         sizeof(cfg_ni->lic_ni_intf));
3209         }
3210
3211         cfg_ni->lic_nid = lnet_nid_to_nid4(&ni->ni_nid);
3212         cfg_ni->lic_status = lnet_ni_get_status_locked(ni);
3213         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
3214
3215         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
3216
3217         if (stats) {
3218                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
3219                                                        LNET_STATS_TYPE_SEND);
3220                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
3221                                                        LNET_STATS_TYPE_RECV);
3222                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
3223                                                        LNET_STATS_TYPE_DROP);
3224         }
3225
3226         /*
3227          * tun->lt_tun will always be present, but in order to be
3228          * backwards compatible, we need to deal with the cases when
3229          * tun->lt_tun is smaller than what the kernel has, because it
3230          * comes from an older version of a userspace program, then we'll
3231          * need to copy as much information as we have available space.
3232          */
3233         min_size = tun_size - sizeof(tun->lt_cmn);
3234         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
3235
3236         /* copy over the cpts */
3237         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
3238             ni->ni_cpts == NULL)  {
3239                 for (i = 0; i < ni->ni_ncpts; i++)
3240                         cfg_ni->lic_cpts[i] = i;
3241         } else {
3242                 for (i = 0;
3243                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
3244                      i < LNET_MAX_SHOW_NUM_CPT;
3245                      i++)
3246                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
3247         }
3248         cfg_ni->lic_ncpts = ni->ni_ncpts;
3249 }
3250
3251 /**
3252  * NOTE: This is a legacy function left in the code to be backwards
3253  * compatible with older userspace programs. It should eventually be
3254  * removed.
3255  *
3256  * Grabs the ni data from the ni structure and fills the out
3257  * parameters
3258  *
3259  * \param[in] ni network        interface structure
3260  * \param[out] config           config information
3261  */
3262 static void
3263 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
3264                          struct lnet_ioctl_config_data *config)
3265 {
3266         struct lnet_ioctl_net_config *net_config;
3267         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
3268         size_t min_size, tunable_size = 0;
3269         int i;
3270
3271         if (!ni || !config || !nid_is_nid4(&ni->ni_nid))
3272                 return;
3273
3274         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
3275         if (!net_config)
3276                 return;
3277
3278         if (!ni->ni_interface)
3279                 return;
3280
3281         strncpy(net_config->ni_interface,
3282                 ni->ni_interface,
3283                 sizeof(net_config->ni_interface));
3284
3285         config->cfg_nid = lnet_nid_to_nid4(&ni->ni_nid);
3286         config->cfg_config_u.cfg_net.net_peer_timeout =
3287                 ni->ni_net->net_tunables.lct_peer_timeout;
3288         config->cfg_config_u.cfg_net.net_max_tx_credits =
3289                 ni->ni_net->net_tunables.lct_max_tx_credits;
3290         config->cfg_config_u.cfg_net.net_peer_tx_credits =
3291                 ni->ni_net->net_tunables.lct_peer_tx_credits;
3292         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
3293                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
3294
3295         net_config->ni_status = lnet_ni_get_status_locked(ni);
3296
3297         if (ni->ni_cpts) {
3298                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
3299
3300                 for (i = 0; i < num_cpts; i++)
3301                         net_config->ni_cpts[i] = ni->ni_cpts[i];
3302
3303                 config->cfg_ncpts = num_cpts;
3304         }
3305
3306         /*
3307          * See if user land tools sent in a newer and larger version
3308          * of struct lnet_tunables than what the kernel uses.
3309          */
3310         min_size = sizeof(*config) + sizeof(*net_config);
3311
3312         if (config->cfg_hdr.ioc_len > min_size)
3313                 tunable_size = config->cfg_hdr.ioc_len - min_size;
3314
3315         /* Don't copy too much data to user space */
3316         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
3317         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
3318
3319         if (lnd_cfg && min_size) {
3320                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
3321                 config->cfg_config_u.cfg_net.net_interface_count = 1;
3322
3323                 /* Tell user land that kernel side has less data */
3324                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
3325                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
3326                         config->cfg_hdr.ioc_len -= min_size;
3327                 }
3328         }
3329 }
3330
3331 struct lnet_ni *
3332 lnet_get_ni_idx_locked(int idx)
3333 {
3334         struct lnet_ni          *ni;
3335         struct lnet_net         *net;
3336
3337         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3338                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3339                         if (idx-- == 0)
3340                                 return ni;
3341                 }
3342         }
3343
3344         return NULL;
3345 }
3346
3347 int lnet_get_net_healthv_locked(struct lnet_net *net)
3348 {
3349         struct lnet_ni *ni;
3350         int best_healthv = 0;
3351         int healthv, ni_fatal;
3352
3353         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3354                 healthv = atomic_read(&ni->ni_healthv);
3355                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3356                 if (!ni_fatal && healthv > best_healthv)
3357                         best_healthv = healthv;
3358         }
3359
3360         return best_healthv;
3361 }
3362
3363 struct lnet_ni *
3364 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3365 {
3366         struct lnet_ni          *ni;
3367         struct lnet_net         *net = mynet;
3368
3369         /*
3370          * It is possible that the net has been cleaned out while there is
3371          * a message being sent. This function accessed the net without
3372          * checking if the list is empty
3373          */
3374         if (!prev) {
3375                 if (!net)
3376                         net = list_first_entry(&the_lnet.ln_nets,
3377                                                struct lnet_net,
3378                                                net_list);
3379                 if (list_empty(&net->net_ni_list))
3380                         return NULL;
3381                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3382                                       ni_netlist);
3383
3384                 return ni;
3385         }
3386
3387         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3388                 /* if you reached the end of the ni list and the net is
3389                  * specified, then there are no more nis in that net */
3390                 if (net != NULL)
3391                         return NULL;
3392
3393                 /* we reached the end of this net ni list. move to the
3394                  * next net */
3395                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3396                         /* no more nets and no more NIs. */
3397                         return NULL;
3398
3399                 /* get the next net */
3400                 net = list_first_entry(&prev->ni_net->net_list, struct lnet_net,
3401                                        net_list);
3402                 if (list_empty(&net->net_ni_list))
3403                         return NULL;
3404                 /* get the ni on it */
3405                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3406                                       ni_netlist);
3407
3408                 return ni;
3409         }
3410
3411         if (list_empty(&prev->ni_netlist))
3412                 return NULL;
3413
3414         /* there are more nis left */
3415         ni = list_first_entry(&prev->ni_netlist, struct lnet_ni, ni_netlist);
3416
3417         return ni;
3418 }
3419
3420 static int
3421 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3422 {
3423         struct lnet_ni *ni;
3424         int cpt;
3425         int rc = -ENOENT;
3426         int idx = config->cfg_count;
3427
3428         cpt = lnet_net_lock_current();
3429
3430         ni = lnet_get_ni_idx_locked(idx);
3431
3432         if (ni != NULL) {
3433                 rc = 0;
3434                 lnet_ni_lock(ni);
3435                 lnet_fill_ni_info_legacy(ni, config);
3436                 lnet_ni_unlock(ni);
3437         }
3438
3439         lnet_net_unlock(cpt);
3440         return rc;
3441 }
3442
3443 static int
3444 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3445                    struct lnet_ioctl_config_lnd_tunables *tun,
3446                    struct lnet_ioctl_element_stats *stats,
3447                    __u32 tun_size)
3448 {
3449         struct lnet_ni          *ni;
3450         int                     cpt;
3451         int                     rc = -ENOENT;
3452
3453         if (!cfg_ni || !tun || !stats)
3454                 return -EINVAL;
3455
3456         cpt = lnet_net_lock_current();
3457
3458         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3459
3460         if (ni) {
3461                 rc = 0;
3462                 lnet_ni_lock(ni);
3463                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3464                 lnet_ni_unlock(ni);
3465         }
3466
3467         lnet_net_unlock(cpt);
3468         return rc;
3469 }
3470
3471 static int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3472 {
3473         struct lnet_ni *ni;
3474         int rc = -ENOENT;
3475
3476         if (!msg_stats)
3477                 return -EINVAL;
3478
3479         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3480
3481         if (ni) {
3482                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3483                 rc = 0;
3484         }
3485
3486         return rc;
3487 }
3488
3489 static int lnet_add_net_common(struct lnet_net *net,
3490                                struct lnet_ioctl_config_lnd_tunables *tun)
3491 {
3492         struct lnet_handle_md ping_mdh;
3493         struct lnet_ping_buffer *pbuf;
3494         struct lnet_remotenet *rnet;
3495         struct lnet_ni *ni;
3496         u32 net_id;
3497         int rc;
3498
3499         lnet_net_lock(LNET_LOCK_EX);
3500         rnet = lnet_find_rnet_locked(net->net_id);
3501         lnet_net_unlock(LNET_LOCK_EX);
3502         /*
3503          * make sure that the net added doesn't invalidate the current
3504          * configuration LNet is keeping
3505          */
3506         if (rnet) {
3507                 CERROR("Adding net %s will invalidate routing configuration\n",
3508                        libcfs_net2str(net->net_id));
3509                 lnet_net_free(net);
3510                 return -EUSERS;
3511         }
3512
3513         if (tun)
3514                 memcpy(&net->net_tunables,
3515                        &tun->lt_cmn, sizeof(net->net_tunables));
3516         else
3517                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3518
3519         net_id = net->net_id;
3520
3521         rc = lnet_startup_lndnet(net,
3522                                  (tun) ? &tun->lt_tun : NULL);
3523         if (rc < 0)
3524                 return rc;
3525
3526         /* make sure you calculate the correct number of slots in the ping
3527          * buffer. Since the ping info is a flattened list of all the NIs,
3528          * we should allocate enough slots to accomodate the number of NIs
3529          * which will be added.
3530          */
3531         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3532                                     LNET_PING_INFO_HDR_SIZE +
3533                                     lnet_get_ni_bytes(),
3534                                     false);
3535         if (rc < 0) {
3536                 lnet_shutdown_lndnet(net);
3537                 return rc;
3538         }
3539
3540         lnet_net_lock(LNET_LOCK_EX);
3541         net = lnet_get_net_locked(net_id);
3542         LASSERT(net);
3543
3544         /* apply the UDSPs */
3545         rc = lnet_udsp_apply_policies_on_net(net);
3546         if (rc)
3547                 CERROR("Failed to apply UDSPs on local net %s\n",
3548                        libcfs_net2str(net->net_id));
3549
3550         /* At this point we lost track of which NI was just added, so we
3551          * just re-apply the policies on all of the NIs on this net
3552          */
3553         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3554                 rc = lnet_udsp_apply_policies_on_ni(ni);
3555                 if (rc)
3556                         CERROR("Failed to apply UDSPs on ni %s\n",
3557                                libcfs_nidstr(&ni->ni_nid));
3558         }
3559         lnet_net_unlock(LNET_LOCK_EX);
3560
3561         /*
3562          * Start the acceptor thread if this is the first network
3563          * being added that requires the thread.
3564          */
3565         if (net->net_lnd->lnd_accept) {
3566                 rc = lnet_acceptor_start();
3567                 if (rc < 0) {
3568                         /* shutdown the net that we just started */
3569                         CERROR("Failed to start up acceptor thread\n");
3570                         lnet_shutdown_lndnet(net);
3571                         goto failed;
3572                 }
3573         }
3574
3575         lnet_net_lock(LNET_LOCK_EX);
3576         lnet_peer_net_added(net);
3577         lnet_net_unlock(LNET_LOCK_EX);
3578
3579         lnet_ping_target_update(pbuf, ping_mdh);
3580
3581         return 0;
3582
3583 failed:
3584         lnet_ping_md_unlink(pbuf, &ping_mdh);
3585         lnet_ping_buffer_decref(pbuf);
3586         return rc;
3587 }
3588
3589 static void
3590 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3591 {
3592         if (tun) {
3593                 if (tun->lt_cmn.lct_peer_timeout < 0)
3594                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3595                 if (!tun->lt_cmn.lct_peer_tx_credits)
3596                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3597                 if (!tun->lt_cmn.lct_max_tx_credits)
3598                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3599         }
3600 }
3601
3602 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3603                                       struct lnet_ioctl_config_lnd_tunables *tun)
3604 {
3605         struct lnet_net *net;
3606         const char *nets;
3607         int rc;
3608         LIST_HEAD(net_head);
3609
3610         rc = lnet_parse_ip2nets(&nets, ip2nets);
3611         if (rc < 0)
3612                 return rc;
3613
3614         rc = lnet_parse_networks(&net_head, nets);
3615         if (rc < 0)
3616                 return rc;
3617
3618         lnet_set_tune_defaults(tun);
3619
3620         mutex_lock(&the_lnet.ln_api_mutex);
3621         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3622                 rc = -ESHUTDOWN;
3623                 goto out;
3624         }
3625
3626         while ((net = list_first_entry_or_null(&net_head,
3627                                                struct lnet_net,
3628                                                net_list)) != NULL) {
3629                 list_del_init(&net->net_list);
3630                 rc = lnet_add_net_common(net, tun);
3631                 if (rc < 0)
3632                         goto out;
3633         }
3634
3635 out:
3636         mutex_unlock(&the_lnet.ln_api_mutex);
3637
3638         while ((net = list_first_entry_or_null(&net_head,
3639                                                struct lnet_net,
3640                                                net_list)) != NULL) {
3641                 list_del_init(&net->net_list);
3642                 lnet_net_free(net);
3643         }
3644         return rc;
3645 }
3646
3647 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf, u32 net_id,
3648                     struct lnet_nid *nid,
3649                     struct lnet_ioctl_config_lnd_tunables *tun)
3650 {
3651         struct lnet_net *net;
3652         struct lnet_ni *ni;
3653         int rc, i;
3654         u32 lnd_type;
3655
3656         /* handle legacy ip2nets from DLC */
3657         if (conf->lic_legacy_ip2nets[0] != '\0')
3658                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3659                                                   tun);
3660
3661         lnd_type = LNET_NETTYP(net_id);
3662
3663         if (!libcfs_isknown_lnd(lnd_type)) {
3664                 CERROR("No valid net and lnd information provided\n");
3665                 return -ENOENT;
3666         }
3667
3668         net = lnet_net_alloc(net_id, NULL);
3669         if (!net)
3670                 return -ENOMEM;
3671
3672         for (i = 0; i < conf->lic_ncpts; i++) {
3673                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER) {
3674                         lnet_net_free(net);
3675                         return -ERANGE;
3676                 }
3677         }
3678
3679         ni = lnet_ni_alloc_w_cpt_array(net, nid, conf->lic_cpts,
3680                                        conf->lic_ncpts, conf->lic_ni_intf);
3681         if (!ni) {
3682                 lnet_net_free(net);
3683                 return -ENOMEM;
3684         }
3685
3686         lnet_set_tune_defaults(tun);
3687
3688         mutex_lock(&the_lnet.ln_api_mutex);
3689         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3690                 lnet_net_free(net);
3691                 rc = -ESHUTDOWN;
3692         } else {
3693                 rc = lnet_add_net_common(net, tun);
3694         }
3695
3696         mutex_unlock(&the_lnet.ln_api_mutex);
3697
3698         /* If NI already exist delete this new unused copy */
3699         if (rc == -EEXIST)
3700                 lnet_ni_free(ni);
3701
3702         return rc;
3703 }
3704
3705 int lnet_dyn_del_ni(struct lnet_nid *nid)
3706 {
3707         struct lnet_net *net;
3708         struct lnet_ni *ni;
3709         u32 net_id = LNET_NID_NET(nid);
3710         struct lnet_ping_buffer *pbuf;
3711         struct lnet_handle_md ping_mdh;
3712         int net_bytes, rc;
3713         bool net_empty;
3714
3715         /* don't allow userspace to shutdown the LOLND */
3716         if (LNET_NETTYP(net_id) == LOLND)
3717                 return -EINVAL;
3718
3719         mutex_lock(&the_lnet.ln_api_mutex);
3720         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3721                 rc = -ESHUTDOWN;
3722                 goto unlock_api_mutex;
3723         }
3724
3725         lnet_net_lock(0);
3726
3727         net = lnet_get_net_locked(net_id);
3728         if (!net) {
3729                 CERROR("net %s not found\n",
3730                        libcfs_net2str(net_id));
3731                 rc = -ENOENT;
3732                 goto unlock_net;
3733         }
3734
3735         if (!nid_addr_is_set(nid)) {
3736                 /* remove the entire net */
3737                 net_bytes = lnet_get_net_ni_bytes_locked(net);
3738
3739                 lnet_net_unlock(0);
3740
3741                 /* create and link a new ping info, before removing the old one */
3742                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3743                                             LNET_PING_INFO_HDR_SIZE +
3744                                             lnet_get_ni_bytes() - net_bytes,
3745                                             false);
3746                 if (rc != 0)
3747                         goto unlock_api_mutex;
3748
3749                 lnet_shutdown_lndnet(net);
3750
3751                 lnet_acceptor_stop();
3752
3753                 lnet_ping_target_update(pbuf, ping_mdh);
3754
3755                 goto unlock_api_mutex;
3756         }
3757
3758         ni = lnet_nid_to_ni_locked(nid, 0);
3759         if (!ni) {
3760                 CERROR("nid %s not found\n", libcfs_nidstr(nid));
3761                 rc = -ENOENT;
3762                 goto unlock_net;
3763         }
3764
3765         net_bytes = lnet_get_net_ni_bytes_locked(net);
3766         net_empty = list_is_singular(&net->net_ni_list);
3767
3768         lnet_net_unlock(0);
3769
3770         /* create and link a new ping info, before removing the old one */
3771         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3772                                     (LNET_PING_INFO_HDR_SIZE +
3773                                      lnet_get_ni_bytes() -
3774                                      lnet_ping_sts_size(&ni->ni_nid)),
3775                                     false);
3776         if (rc != 0)
3777                 goto unlock_api_mutex;
3778
3779         lnet_shutdown_lndni(ni);
3780
3781         lnet_acceptor_stop();
3782
3783         lnet_ping_target_update(pbuf, ping_mdh);
3784
3785         /* check if the net is empty and remove it if it is */
3786         if (net_empty)
3787                 lnet_shutdown_lndnet(net);
3788
3789         goto unlock_api_mutex;
3790
3791 unlock_net:
3792         lnet_net_unlock(0);
3793 unlock_api_mutex:
3794         mutex_unlock(&the_lnet.ln_api_mutex);
3795
3796         return rc;
3797 }
3798
3799 /*
3800  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3801  * They are only expected to be called for unique networks.
3802  * That can be as a result of older DLC library
3803  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3804  */
3805 int
3806 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3807 {
3808         struct lnet_net *net;
3809         LIST_HEAD(net_head);
3810         int rc;
3811         struct lnet_ioctl_config_lnd_tunables tun;
3812         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3813
3814         /* Create a net/ni structures for the network string */
3815         rc = lnet_parse_networks(&net_head, nets);
3816         if (rc <= 0)
3817                 return rc == 0 ? -EINVAL : rc;
3818
3819         mutex_lock(&the_lnet.ln_api_mutex);
3820         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3821                 rc = -ESHUTDOWN;
3822                 goto out_unlock_clean;
3823         }
3824
3825         if (rc > 1) {
3826                 rc = -EINVAL; /* only add one network per call */
3827                 goto out_unlock_clean;
3828         }
3829
3830         net = list_first_entry(&net_head, struct lnet_net, net_list);
3831         list_del_init(&net->net_list);
3832
3833         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3834
3835         memset(&tun, 0, sizeof(tun));
3836
3837         tun.lt_cmn.lct_peer_timeout =
3838           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3839                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3840         tun.lt_cmn.lct_peer_tx_credits =
3841           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3842                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3843         tun.lt_cmn.lct_peer_rtr_credits =
3844           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3845         tun.lt_cmn.lct_max_tx_credits =
3846           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3847                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3848
3849         rc = lnet_add_net_common(net, &tun);
3850
3851 out_unlock_clean:
3852         mutex_unlock(&the_lnet.ln_api_mutex);
3853         /* net_head list is empty in success case */
3854         while ((net = list_first_entry_or_null(&net_head,
3855                                                struct lnet_net,
3856                                                net_list)) != NULL) {
3857                 list_del_init(&net->net_list);
3858                 lnet_net_free(net);
3859         }
3860         return rc;
3861 }
3862
3863 int
3864 lnet_dyn_del_net(u32 net_id)
3865 {
3866         struct lnet_net *net;
3867         struct lnet_ping_buffer *pbuf;
3868         struct lnet_handle_md ping_mdh;
3869         int net_ni_bytes, rc;
3870
3871         /* don't allow userspace to shutdown the LOLND */
3872         if (LNET_NETTYP(net_id) == LOLND)
3873                 return -EINVAL;
3874
3875         mutex_lock(&the_lnet.ln_api_mutex);
3876         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3877                 rc = -ESHUTDOWN;
3878                 goto out;
3879         }
3880
3881         lnet_net_lock(0);
3882
3883         net = lnet_get_net_locked(net_id);
3884         if (net == NULL) {
3885                 lnet_net_unlock(0);
3886                 rc = -EINVAL;
3887                 goto out;
3888         }
3889
3890         net_ni_bytes = lnet_get_net_ni_bytes_locked(net);
3891
3892         lnet_net_unlock(0);
3893
3894         /* create and link a new ping info, before removing the old one */
3895         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3896                                     LNET_PING_INFO_HDR_SIZE +
3897                                     lnet_get_ni_bytes() - net_ni_bytes,
3898                                     false);
3899         if (rc != 0)
3900                 goto out;
3901
3902         lnet_shutdown_lndnet(net);
3903
3904         lnet_acceptor_stop();
3905
3906         lnet_ping_target_update(pbuf, ping_mdh);
3907
3908 out:
3909         mutex_unlock(&the_lnet.ln_api_mutex);
3910
3911         return rc;
3912 }
3913
3914 void lnet_mark_ping_buffer_for_update(void)
3915 {
3916         if (the_lnet.ln_routing)
3917                 return;
3918
3919         atomic_set(&the_lnet.ln_update_ping_buf, 1);
3920         complete(&the_lnet.ln_mt_wait_complete);
3921 }
3922 EXPORT_SYMBOL(lnet_mark_ping_buffer_for_update);
3923
3924 static void lnet_update_ping_buffer(struct work_struct *work)
3925 {
3926         struct lnet_ping_buffer *pbuf;
3927         struct lnet_handle_md ping_mdh;
3928
3929         mutex_lock(&the_lnet.ln_api_mutex);
3930
3931         atomic_set(&the_lnet.ln_pb_update_ready, 1);
3932
3933         if ((the_lnet.ln_state == LNET_STATE_RUNNING) &&
3934             !lnet_ping_target_setup(&pbuf, &ping_mdh,
3935                                     LNET_PING_INFO_HDR_SIZE +
3936                                     lnet_get_ni_bytes(),
3937                                     false))
3938                 lnet_ping_target_update(pbuf, ping_mdh);
3939
3940         mutex_unlock(&the_lnet.ln_api_mutex);
3941 }
3942
3943 void lnet_queue_ping_buffer_update(void)
3944 {
3945         /* don't queue pb update if it is not needed */
3946         if (atomic_dec_if_positive(&the_lnet.ln_update_ping_buf) < 0)
3947                 return;
3948
3949         /* don't queue pb update if already queued and not processed */
3950         if (atomic_dec_if_positive(&the_lnet.ln_pb_update_ready) < 0)
3951                 return;
3952
3953         INIT_WORK(&the_lnet.ln_pb_update_work, lnet_update_ping_buffer);
3954         queue_work(the_lnet.ln_pb_update_wq, &the_lnet.ln_pb_update_work);
3955 }
3956
3957 void lnet_incr_dlc_seq(void)
3958 {
3959         atomic_inc(&lnet_dlc_seq_no);
3960 }
3961
3962 __u32 lnet_get_dlc_seq_locked(void)
3963 {
3964         return atomic_read(&lnet_dlc_seq_no);
3965 }
3966
3967 static void
3968 lnet_ni_set_healthv(struct lnet_nid *nid, int value)
3969 {
3970         bool all = nid_same(nid, &LNET_ANY_NID);
3971         struct lnet_net *net;
3972         struct lnet_ni *ni;
3973
3974         lnet_net_lock(LNET_LOCK_EX);
3975         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3976                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3977                         if (!all && !nid_same(&ni->ni_nid, nid))
3978                                 continue;
3979
3980                         atomic_set(&ni->ni_healthv, value);
3981                         if (list_empty(&ni->ni_recovery) &&
3982                             value < LNET_MAX_HEALTH_VALUE) {
3983                                 CERROR("manually adding local NI %s to recovery\n",
3984                                        libcfs_nidstr(&ni->ni_nid));
3985                                 list_add_tail(&ni->ni_recovery,
3986                                               &the_lnet.ln_mt_localNIRecovq);
3987                                 lnet_ni_addref_locked(ni, 0);
3988                         }
3989                         if (!all) {
3990                                 lnet_net_unlock(LNET_LOCK_EX);
3991                                 return;
3992                         }
3993                 }
3994         }
3995         lnet_net_unlock(LNET_LOCK_EX);
3996 }
3997
3998 static void
3999 lnet_ni_set_conns_per_peer(lnet_nid_t nid, int value, bool all)
4000 {
4001         struct lnet_net *net;
4002         struct lnet_ni *ni;
4003
4004         lnet_net_lock(LNET_LOCK_EX);
4005         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4006                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4007                         if (lnet_nid_to_nid4(&ni->ni_nid) != nid && !all)
4008                                 continue;
4009                         if (LNET_NETTYP(net->net_id) == SOCKLND)
4010                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_sock.lnd_conns_per_peer = value;
4011                         else if (LNET_NETTYP(net->net_id) == O2IBLND)
4012                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib.lnd_conns_per_peer = value;
4013                         if (!all) {
4014                                 lnet_net_unlock(LNET_LOCK_EX);
4015                                 return;
4016                         }
4017                 }
4018         }
4019         lnet_net_unlock(LNET_LOCK_EX);
4020 }
4021
4022 static int
4023 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
4024 {
4025         int cpt, rc = 0;
4026         struct lnet_ni *ni;
4027         struct lnet_nid nid;
4028
4029         lnet_nid4_to_nid(stats->hlni_nid, &nid);
4030         cpt = lnet_net_lock_current();
4031         ni = lnet_nid_to_ni_locked(&nid, cpt);
4032         if (!ni) {
4033                 rc = -ENOENT;
4034                 goto unlock;
4035         }
4036
4037         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
4038         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
4039         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
4040         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
4041         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
4042         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
4043         stats->hlni_fatal_error = atomic_read(&ni->ni_fatal_error_on);
4044         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
4045         stats->hlni_ping_count = ni->ni_ping_count;
4046         stats->hlni_next_ping = ni->ni_next_ping;
4047
4048 unlock:
4049         lnet_net_unlock(cpt);
4050
4051         return rc;
4052 }
4053
4054 static int
4055 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4056 {
4057         struct lnet_ni *ni;
4058         int i = 0;
4059
4060         lnet_net_lock(LNET_LOCK_EX);
4061         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
4062                 if (!nid_is_nid4(&ni->ni_nid))
4063                         continue;
4064                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&ni->ni_nid);
4065                 i++;
4066                 if (i >= LNET_MAX_SHOW_NUM_NID)
4067                         break;
4068         }
4069         lnet_net_unlock(LNET_LOCK_EX);
4070         list->rlst_num_nids = i;
4071
4072         return 0;
4073 }
4074
4075 static int
4076 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4077 {
4078         struct lnet_peer_ni *lpni;
4079         int i = 0;
4080
4081         lnet_net_lock(LNET_LOCK_EX);
4082         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
4083                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&lpni->lpni_nid);
4084                 i++;
4085                 if (i >= LNET_MAX_SHOW_NUM_NID)
4086                         break;
4087         }
4088         lnet_net_unlock(LNET_LOCK_EX);
4089         list->rlst_num_nids = i;
4090
4091         return 0;
4092 }
4093
4094 /**
4095  * LNet ioctl handler.
4096  *
4097  */
4098 int
4099 LNetCtl(unsigned int cmd, void *arg)
4100 {
4101         struct libcfs_ioctl_data *data = arg;
4102         struct lnet_ioctl_config_data *config;
4103         struct lnet_ni           *ni;
4104         struct lnet_nid           nid;
4105         int                       rc;
4106
4107         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
4108                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
4109
4110         switch (cmd) {
4111         case IOC_LIBCFS_GET_NI: {
4112                 struct lnet_processid id = {};
4113
4114                 rc = LNetGetId(data->ioc_count, &id, false);
4115                 data->ioc_nid = lnet_nid_to_nid4(&id.nid);
4116                 return rc;
4117         }
4118         case IOC_LIBCFS_FAIL_NID:
4119                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
4120
4121         case IOC_LIBCFS_ADD_ROUTE: {
4122                 /* default router sensitivity to 1 */
4123                 unsigned int sensitivity = 1;
4124                 config = arg;
4125
4126                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4127                         return -EINVAL;
4128
4129                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
4130                         sensitivity =
4131                           config->cfg_config_u.cfg_route.rtr_sensitivity;
4132                 }
4133
4134                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4135                 mutex_lock(&the_lnet.ln_api_mutex);
4136                 rc = lnet_add_route(config->cfg_net,
4137                                     config->cfg_config_u.cfg_route.rtr_hop,
4138                                     &nid,
4139                                     config->cfg_config_u.cfg_route.
4140                                         rtr_priority, sensitivity);
4141                 mutex_unlock(&the_lnet.ln_api_mutex);
4142                 return rc;
4143         }
4144
4145         case IOC_LIBCFS_DEL_ROUTE:
4146                 config = arg;
4147
4148                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4149                         return -EINVAL;
4150
4151                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4152                 mutex_lock(&the_lnet.ln_api_mutex);
4153                 rc = lnet_del_route(config->cfg_net, &nid);
4154                 mutex_unlock(&the_lnet.ln_api_mutex);
4155                 return rc;
4156
4157         case IOC_LIBCFS_GET_ROUTE:
4158                 config = arg;
4159
4160                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4161                         return -EINVAL;
4162
4163                 mutex_lock(&the_lnet.ln_api_mutex);
4164                 rc = lnet_get_route(config->cfg_count,
4165                                     &config->cfg_net,
4166                                     &config->cfg_config_u.cfg_route.rtr_hop,
4167                                     &config->cfg_nid,
4168                                     &config->cfg_config_u.cfg_route.rtr_flags,
4169                                     &config->cfg_config_u.cfg_route.
4170                                         rtr_priority,
4171                                     &config->cfg_config_u.cfg_route.
4172                                         rtr_sensitivity);
4173                 mutex_unlock(&the_lnet.ln_api_mutex);
4174                 return rc;
4175
4176         case IOC_LIBCFS_GET_LOCAL_NI: {
4177                 struct lnet_ioctl_config_ni *cfg_ni;
4178                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
4179                 struct lnet_ioctl_element_stats *stats;
4180                 __u32 tun_size;
4181
4182                 cfg_ni = arg;
4183
4184                 /* get the tunables if they are available */
4185                 if (cfg_ni->lic_cfg_hdr.ioc_len <
4186                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
4187                         return -EINVAL;
4188
4189                 stats = (struct lnet_ioctl_element_stats *)
4190                         cfg_ni->lic_bulk;
4191                 tun = (struct lnet_ioctl_config_lnd_tunables *)
4192                                 (cfg_ni->lic_bulk + sizeof(*stats));
4193
4194                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
4195                         sizeof(*stats);
4196
4197                 mutex_lock(&the_lnet.ln_api_mutex);
4198                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
4199                 mutex_unlock(&the_lnet.ln_api_mutex);
4200                 return rc;
4201         }
4202
4203         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
4204                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
4205                 int cpt;
4206
4207                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
4208                         return -EINVAL;
4209
4210                 mutex_lock(&the_lnet.ln_api_mutex);
4211
4212                 cpt = lnet_net_lock_current();
4213                 rc = lnet_get_ni_stats(msg_stats);
4214                 lnet_net_unlock(cpt);
4215
4216                 mutex_unlock(&the_lnet.ln_api_mutex);
4217
4218                 return rc;
4219         }
4220
4221         case IOC_LIBCFS_GET_NET: {
4222                 size_t total = sizeof(*config) +
4223                                sizeof(struct lnet_ioctl_net_config);
4224                 config = arg;
4225
4226                 if (config->cfg_hdr.ioc_len < total)
4227                         return -EINVAL;
4228
4229                 mutex_lock(&the_lnet.ln_api_mutex);
4230                 rc = lnet_get_net_config(config);
4231                 mutex_unlock(&the_lnet.ln_api_mutex);
4232                 return rc;
4233         }
4234
4235         case IOC_LIBCFS_GET_LNET_STATS:
4236         {
4237                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
4238
4239                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
4240                         return -EINVAL;
4241
4242                 mutex_lock(&the_lnet.ln_api_mutex);
4243                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
4244                 mutex_unlock(&the_lnet.ln_api_mutex);
4245                 return rc;
4246         }
4247
4248         case IOC_LIBCFS_RESET_LNET_STATS:
4249         {
4250                 mutex_lock(&the_lnet.ln_api_mutex);
4251                 lnet_counters_reset();
4252                 mutex_unlock(&the_lnet.ln_api_mutex);
4253                 return 0;
4254         }
4255
4256         case IOC_LIBCFS_CONFIG_RTR:
4257                 config = arg;
4258
4259                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4260                         return -EINVAL;
4261
4262                 mutex_lock(&the_lnet.ln_api_mutex);
4263                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
4264                         rc = lnet_rtrpools_enable();
4265                         mutex_unlock(&the_lnet.ln_api_mutex);
4266                         return rc;
4267                 }
4268                 lnet_rtrpools_disable();
4269                 mutex_unlock(&the_lnet.ln_api_mutex);
4270                 return 0;
4271
4272         case IOC_LIBCFS_ADD_BUF:
4273                 config = arg;
4274
4275                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4276                         return -EINVAL;
4277
4278                 mutex_lock(&the_lnet.ln_api_mutex);
4279                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4280                                                 buf_tiny,
4281                                           config->cfg_config_u.cfg_buffers.
4282                                                 buf_small,
4283                                           config->cfg_config_u.cfg_buffers.
4284                                                 buf_large);
4285                 mutex_unlock(&the_lnet.ln_api_mutex);
4286                 return rc;
4287
4288         case IOC_LIBCFS_SET_NUMA_RANGE: {
4289                 struct lnet_ioctl_set_value *numa;
4290                 numa = arg;
4291                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4292                         return -EINVAL;
4293                 lnet_net_lock(LNET_LOCK_EX);
4294                 lnet_numa_range = numa->sv_value;
4295                 lnet_net_unlock(LNET_LOCK_EX);
4296                 return 0;
4297         }
4298
4299         case IOC_LIBCFS_GET_NUMA_RANGE: {
4300                 struct lnet_ioctl_set_value *numa;
4301                 numa = arg;
4302                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4303                         return -EINVAL;
4304                 numa->sv_value = lnet_numa_range;
4305                 return 0;
4306         }
4307
4308         case IOC_LIBCFS_GET_BUF: {
4309                 struct lnet_ioctl_pool_cfg *pool_cfg;
4310                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4311
4312                 config = arg;
4313
4314                 if (config->cfg_hdr.ioc_len < total)
4315                         return -EINVAL;
4316
4317                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4318
4319                 mutex_lock(&the_lnet.ln_api_mutex);
4320                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4321                 mutex_unlock(&the_lnet.ln_api_mutex);
4322                 return rc;
4323         }
4324
4325         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4326                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4327
4328                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4329                         return -EINVAL;
4330
4331                 mutex_lock(&the_lnet.ln_api_mutex);
4332                 rc = lnet_get_local_ni_hstats(stats);
4333                 mutex_unlock(&the_lnet.ln_api_mutex);
4334
4335                 return rc;
4336         }
4337
4338         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4339                 struct lnet_ioctl_recovery_list *list = arg;
4340                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4341                         return -EINVAL;
4342
4343                 mutex_lock(&the_lnet.ln_api_mutex);
4344                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4345                         rc = lnet_get_local_ni_recovery_list(list);
4346                 else
4347                         rc = lnet_get_peer_ni_recovery_list(list);
4348                 mutex_unlock(&the_lnet.ln_api_mutex);
4349                 return rc;
4350         }
4351
4352         case IOC_LIBCFS_ADD_PEER_NI: {
4353                 struct lnet_ioctl_peer_cfg *cfg = arg;
4354                 struct lnet_nid prim_nid;
4355
4356                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4357                         return -EINVAL;
4358
4359                 mutex_lock(&the_lnet.ln_api_mutex);
4360                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4361                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4362                 rc = lnet_user_add_peer_ni(&prim_nid, &nid, cfg->prcfg_mr,
4363                                            cfg->prcfg_count == 1);
4364                 mutex_unlock(&the_lnet.ln_api_mutex);
4365                 return rc;
4366         }
4367
4368         case IOC_LIBCFS_DEL_PEER_NI: {
4369                 struct lnet_ioctl_peer_cfg *cfg = arg;
4370                 struct lnet_nid prim_nid;
4371
4372                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4373                         return -EINVAL;
4374
4375                 mutex_lock(&the_lnet.ln_api_mutex);
4376                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4377                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4378                 rc = lnet_del_peer_ni(&prim_nid,
4379                                       &nid,
4380                                       cfg->prcfg_count);
4381                 mutex_unlock(&the_lnet.ln_api_mutex);
4382                 return rc;
4383         }
4384
4385         case IOC_LIBCFS_GET_PEER_INFO: {
4386                 struct lnet_ioctl_peer *peer_info = arg;
4387
4388                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4389                         return -EINVAL;
4390
4391                 mutex_lock(&the_lnet.ln_api_mutex);
4392                 rc = lnet_get_peer_ni_info(
4393                    peer_info->pr_count,
4394                    &peer_info->pr_nid,
4395                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4396                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4397                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4398                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4399                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4400                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4401                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4402                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4403                 mutex_unlock(&the_lnet.ln_api_mutex);
4404                 return rc;
4405         }
4406
4407         case IOC_LIBCFS_GET_PEER_NI: {
4408                 struct lnet_ioctl_peer_cfg *cfg = arg;
4409
4410                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4411                         return -EINVAL;
4412
4413                 mutex_lock(&the_lnet.ln_api_mutex);
4414                 rc = lnet_get_peer_info(cfg,
4415                                         (void __user *)cfg->prcfg_bulk);
4416                 mutex_unlock(&the_lnet.ln_api_mutex);
4417                 return rc;
4418         }
4419
4420         case IOC_LIBCFS_GET_PEER_LIST: {
4421                 struct lnet_ioctl_peer_cfg *cfg = arg;
4422
4423                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4424                         return -EINVAL;
4425
4426                 mutex_lock(&the_lnet.ln_api_mutex);
4427                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4428                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4429                 mutex_unlock(&the_lnet.ln_api_mutex);
4430                 return rc;
4431         }
4432
4433         case IOC_LIBCFS_SET_HEALHV: {
4434                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4435                 int value;
4436
4437                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4438                         return -EINVAL;
4439                 if (cfg->rh_value < 0 ||
4440                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4441                         value = LNET_MAX_HEALTH_VALUE;
4442                 else
4443                         value = cfg->rh_value;
4444                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4445                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4446                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4447                 lnet_nid4_to_nid(cfg->rh_nid, &nid);
4448                 mutex_lock(&the_lnet.ln_api_mutex);
4449                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) {
4450                         if (cfg->rh_all)
4451                                 nid = LNET_ANY_NID;
4452                         lnet_ni_set_healthv(&nid, value);
4453                 } else {
4454                         lnet_peer_ni_set_healthv(&nid, value, cfg->rh_all);
4455                 }
4456                 mutex_unlock(&the_lnet.ln_api_mutex);
4457                 return 0;
4458         }
4459
4460         case IOC_LIBCFS_SET_PEER: {
4461                 struct lnet_ioctl_peer_cfg *cfg = arg;
4462                 struct lnet_peer *lp;
4463
4464                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4465                         return -EINVAL;
4466
4467                 mutex_lock(&the_lnet.ln_api_mutex);
4468                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &nid);
4469                 lp = lnet_find_peer(&nid);
4470                 if (!lp) {
4471                         mutex_unlock(&the_lnet.ln_api_mutex);
4472                         return -ENOENT;
4473                 }
4474                 spin_lock(&lp->lp_lock);
4475                 lp->lp_state = cfg->prcfg_state;
4476                 spin_unlock(&lp->lp_lock);
4477                 lnet_peer_decref_locked(lp);
4478                 mutex_unlock(&the_lnet.ln_api_mutex);
4479                 CDEBUG(D_NET, "Set peer %s state to %u\n",
4480                        libcfs_nid2str(cfg->prcfg_prim_nid), cfg->prcfg_state);
4481                 return 0;
4482         }
4483
4484         case IOC_LIBCFS_SET_CONNS_PER_PEER: {
4485                 struct lnet_ioctl_reset_conns_per_peer_cfg *cfg = arg;
4486                 int value;
4487
4488                 if (cfg->rcpp_hdr.ioc_len < sizeof(*cfg))
4489                         return -EINVAL;
4490                 if (cfg->rcpp_value < 0)
4491                         value = 1;
4492                 else
4493                         value = cfg->rcpp_value;
4494                 CDEBUG(D_NET,
4495                        "Setting conns_per_peer to %d for %s. all = %d\n",
4496                        value, libcfs_nid2str(cfg->rcpp_nid), cfg->rcpp_all);
4497                 mutex_lock(&the_lnet.ln_api_mutex);
4498                 lnet_ni_set_conns_per_peer(cfg->rcpp_nid, value, cfg->rcpp_all);
4499                 mutex_unlock(&the_lnet.ln_api_mutex);
4500                 return 0;
4501         }
4502
4503         case IOC_LIBCFS_NOTIFY_ROUTER: {
4504                 /* Convert the user-supplied real time to monotonic.
4505                  * NB: "when" is always in the past
4506                  */
4507                 time64_t when = ktime_get_seconds() -
4508                                 (ktime_get_real_seconds() - data->ioc_u64[0]);
4509
4510                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4511                 return lnet_notify(NULL, &nid, data->ioc_flags, false, when);
4512         }
4513
4514         case IOC_LIBCFS_LNET_DIST:
4515                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4516                 rc = LNetDist(&nid, &nid, &data->ioc_u32[1]);
4517                 if (rc < 0 && rc != -EHOSTUNREACH)
4518                         return rc;
4519
4520                 data->ioc_nid = lnet_nid_to_nid4(&nid);
4521                 data->ioc_u32[0] = rc;
4522                 return 0;
4523
4524         case IOC_LIBCFS_TESTPROTOCOMPAT:
4525                 the_lnet.ln_testprotocompat = data->ioc_flags;
4526                 return 0;
4527
4528         case IOC_LIBCFS_LNET_FAULT:
4529                 return lnet_fault_ctl(data->ioc_flags, data);
4530
4531         case IOC_LIBCFS_PING_PEER: {
4532                 struct lnet_ioctl_ping_data *ping = arg;
4533                 struct lnet_process_id __user *ids = ping->ping_buf;
4534                 struct lnet_nid src_nid = LNET_ANY_NID;
4535                 struct lnet_genl_ping_list plist;
4536                 struct lnet_processid id;
4537                 struct lnet_peer *lp;
4538                 signed long timeout;
4539                 int count, i;
4540
4541                 /* Check if the supplied ping data supports source nid
4542                  * NB: This check is sufficient if lnet_ioctl_ping_data has
4543                  * additional fields added, but if they are re-ordered or
4544                  * fields removed then this will break. It is expected that
4545                  * these ioctls will be replaced with netlink implementation, so
4546                  * it is probably not worth coming up with a more robust version
4547                  * compatibility scheme.
4548                  */
4549                 if (ping->ping_hdr.ioc_len >= sizeof(struct lnet_ioctl_ping_data))
4550                         lnet_nid4_to_nid(ping->ping_src, &src_nid);
4551
4552                 /* If timeout is negative then set default of 3 minutes */
4553                 if (((s32)ping->op_param) <= 0 ||
4554                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4555                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4556                 else
4557                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4558
4559                 id.pid = ping->ping_id.pid;
4560                 lnet_nid4_to_nid(ping->ping_id.nid, &id.nid);
4561                 rc = lnet_ping(&id, &src_nid, timeout, &plist,
4562                                ping->ping_count);
4563                 if (rc < 0)
4564                         goto report_ping_err;
4565                 count = rc;
4566                 rc = 0;
4567
4568                 for (i = 0; i < count; i++) {
4569                         struct lnet_processid *result;
4570                         struct lnet_process_id tmpid;
4571
4572                         result = genradix_ptr(&plist.lgpl_list, i);
4573                         memset(&tmpid, 0, sizeof(tmpid));
4574                         tmpid.pid = result->pid;
4575                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4576                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4577                                 rc = -EFAULT;
4578                                 goto report_ping_err;
4579                         }
4580                 }
4581
4582                 mutex_lock(&the_lnet.ln_api_mutex);
4583                 lp = lnet_find_peer(&id.nid);
4584                 if (lp) {
4585                         ping->ping_id.nid =
4586                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4587                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4588                         lnet_peer_decref_locked(lp);
4589                 }
4590                 mutex_unlock(&the_lnet.ln_api_mutex);
4591
4592                 ping->ping_count = count;
4593 report_ping_err:
4594                 genradix_free(&plist.lgpl_list);
4595                 return rc;
4596         }
4597
4598         case IOC_LIBCFS_DISCOVER: {
4599                 struct lnet_ioctl_ping_data *discover = arg;
4600                 struct lnet_process_id __user *ids;
4601                 struct lnet_genl_ping_list dlists;
4602                 struct lnet_processid id;
4603                 struct lnet_peer *lp;
4604                 int count, i;
4605
4606                 if (discover->ping_count <= 0)
4607                         return -EINVAL;
4608
4609                 genradix_init(&dlists.lgpl_list);
4610                 /* If the user buffer has more space than the lnet_interfaces_max,
4611                  * then only fill it up to lnet_interfaces_max.
4612                  */
4613                 if (discover->ping_count > lnet_interfaces_max)
4614                         discover->ping_count = lnet_interfaces_max;
4615
4616                 id.pid = discover->ping_id.pid;
4617                 lnet_nid4_to_nid(discover->ping_id.nid, &id.nid);
4618                 rc = lnet_discover(&id, discover->op_param, &dlists);
4619                 if (rc < 0)
4620                         goto report_discover_err;
4621                 count = rc;
4622
4623                 ids = discover->ping_buf;
4624                 for (i = 0; i < count; i++) {
4625                         struct lnet_processid *result;
4626                         struct lnet_process_id tmpid;
4627
4628                         result = genradix_ptr(&dlists.lgpl_list, i);
4629                         memset(&tmpid, 0, sizeof(tmpid));
4630                         tmpid.pid = result->pid;
4631                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4632                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4633                                 rc = -EFAULT;
4634                                 goto report_discover_err;
4635                         }
4636
4637                         if (i >= discover->ping_count)
4638                                 break;
4639                 }
4640                 rc = 0;
4641
4642                 mutex_lock(&the_lnet.ln_api_mutex);
4643                 lp = lnet_find_peer(&id.nid);
4644                 if (lp) {
4645                         discover->ping_id.nid =
4646                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4647                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4648                         lnet_peer_decref_locked(lp);
4649                 }
4650                 mutex_unlock(&the_lnet.ln_api_mutex);
4651
4652                 discover->ping_count = count;
4653 report_discover_err:
4654                 genradix_free(&dlists.lgpl_list);
4655                 return rc;
4656         }
4657
4658         case IOC_LIBCFS_ADD_UDSP: {
4659                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4660                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4661
4662                 mutex_lock(&the_lnet.ln_api_mutex);
4663                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4664                 if (!rc) {
4665                         rc = lnet_udsp_apply_policies(NULL, false);
4666                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4667                         rc = 0;
4668                 }
4669                 mutex_unlock(&the_lnet.ln_api_mutex);
4670
4671                 return rc;
4672         }
4673
4674         case IOC_LIBCFS_DEL_UDSP: {
4675                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4676                 int idx = ioc_udsp->iou_idx;
4677
4678                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4679                         return -EINVAL;
4680
4681                 mutex_lock(&the_lnet.ln_api_mutex);
4682                 rc = lnet_udsp_del_policy(idx);
4683                 mutex_unlock(&the_lnet.ln_api_mutex);
4684
4685                 return rc;
4686         }
4687
4688         case IOC_LIBCFS_GET_UDSP_SIZE: {
4689                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4690                 struct lnet_udsp *udsp;
4691
4692                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4693                         return -EINVAL;
4694
4695                 rc = 0;
4696
4697                 mutex_lock(&the_lnet.ln_api_mutex);
4698                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4699                 if (!udsp) {
4700                         rc = -ENOENT;
4701                 } else {
4702                         /* coming in iou_idx will hold the idx of the udsp
4703                          * to get the size of. going out the iou_idx will
4704                          * hold the size of the UDSP found at the passed
4705                          * in index.
4706                          */
4707                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4708                         if (ioc_udsp->iou_idx < 0)
4709                                 rc = -EINVAL;
4710                 }
4711                 mutex_unlock(&the_lnet.ln_api_mutex);
4712
4713                 return rc;
4714         }
4715
4716         case IOC_LIBCFS_GET_UDSP: {
4717                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4718                 struct lnet_udsp *udsp;
4719
4720                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4721                         return -EINVAL;
4722
4723                 rc = 0;
4724
4725                 mutex_lock(&the_lnet.ln_api_mutex);
4726                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4727                 if (!udsp)
4728                         rc = -ENOENT;
4729                 else
4730                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4731                 mutex_unlock(&the_lnet.ln_api_mutex);
4732
4733                 return rc;
4734         }
4735
4736         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4737                 struct lnet_ioctl_construct_udsp_info *info = arg;
4738
4739                 if (info->cud_hdr.ioc_len < sizeof(*info))
4740                         return -EINVAL;
4741
4742                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4743                        libcfs_nid2str(info->cud_nid));
4744
4745                 lnet_nid4_to_nid(info->cud_nid, &nid);
4746                 mutex_lock(&the_lnet.ln_api_mutex);
4747                 lnet_net_lock(0);
4748                 lnet_udsp_get_construct_info(info, &nid);
4749                 lnet_net_unlock(0);
4750                 mutex_unlock(&the_lnet.ln_api_mutex);
4751
4752                 return 0;
4753         }
4754
4755         default:
4756                 ni = lnet_net2ni_addref(data->ioc_net);
4757                 if (ni == NULL)
4758                         return -EINVAL;
4759
4760                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4761                         rc = -EINVAL;
4762                 else
4763                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4764
4765                 lnet_ni_decref(ni);
4766                 return rc <= 0 ? rc : 0;
4767         }
4768         /* not reached */
4769 }
4770 EXPORT_SYMBOL(LNetCtl);
4771
4772 static int lnet_net_conf_cmd(struct sk_buff *skb, struct genl_info *info)
4773 {
4774         int rc = 0;
4775
4776         if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
4777                 /* NLM_F_EXCL means ignore module parameters */
4778                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
4779                         the_lnet.ln_nis_from_mod_params = true;
4780
4781                 if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE)
4782                         the_lnet.ln_nis_use_large_nids = true;
4783
4784                 rc = lnet_configure(NULL);
4785                 switch (rc) {
4786                 case -ENETDOWN:
4787                         GENL_SET_ERR_MSG(info,
4788                                          "Network is down");
4789                         break;
4790                 case -ENODEV:
4791                         GENL_SET_ERR_MSG(info,
4792                                          "LNET is currently not loaded");
4793                         break;
4794                 case -EBUSY:
4795                         GENL_SET_ERR_MSG(info, "LNET busy");
4796                         break;
4797                 default:
4798                         break;
4799                 }
4800         } else {
4801                 rc = lnet_unconfigure();
4802         }
4803
4804         return rc;
4805 };
4806
4807 struct lnet_nid_cpt {
4808         struct lnet_nid lnc_nid;
4809         unsigned int lnc_cpt;
4810 };
4811
4812 struct lnet_genl_nid_cpt_list {
4813         unsigned int lgncl_index;
4814         unsigned int lgncl_list_count;
4815         GENRADIX(struct lnet_nid_cpt) lgncl_lnc_list;
4816 };
4817
4818 static inline struct lnet_genl_nid_cpt_list *
4819 lnet_cpt_of_nid_dump_ctx(struct netlink_callback *cb)
4820 {
4821         return (struct lnet_genl_nid_cpt_list *)cb->args[0];
4822 }
4823
4824 static int lnet_cpt_of_nid_show_done(struct netlink_callback *cb)
4825 {
4826         struct lnet_genl_nid_cpt_list *lgncl;
4827
4828         lgncl = lnet_cpt_of_nid_dump_ctx(cb);
4829
4830         if (lgncl) {
4831                 genradix_free(&lgncl->lgncl_lnc_list);
4832                 LIBCFS_FREE(lgncl, sizeof(*lgncl));
4833                 cb->args[0] = 0;
4834         }
4835
4836         return 0;
4837 }
4838
4839 static int lnet_cpt_of_nid_show_start(struct netlink_callback *cb)
4840 {
4841         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
4842 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4843         struct netlink_ext_ack *extack = NULL;
4844 #endif
4845         struct lnet_genl_nid_cpt_list *lgncl;
4846         int msg_len = genlmsg_len(gnlh);
4847         struct nlattr *params, *top;
4848         int rem, rc = 0;
4849
4850 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4851         extack = cb->extack;
4852 #endif
4853
4854         mutex_lock(&the_lnet.ln_api_mutex);
4855         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
4856                 NL_SET_ERR_MSG(extack, "Network is down");
4857                 mutex_unlock(&the_lnet.ln_api_mutex);
4858                 return -ENETDOWN;
4859         }
4860
4861         msg_len = genlmsg_len(gnlh);
4862         if (!msg_len) {
4863                 NL_SET_ERR_MSG(extack, "Missing NID argument(s)");
4864                 mutex_unlock(&the_lnet.ln_api_mutex);
4865                 return -ENOENT;
4866         }
4867
4868         LIBCFS_ALLOC(lgncl, sizeof(*lgncl));
4869         if (!lgncl) {
4870                 mutex_unlock(&the_lnet.ln_api_mutex);
4871                 return -ENOMEM;
4872         }
4873
4874         genradix_init(&lgncl->lgncl_lnc_list);
4875         lgncl->lgncl_list_count = 0;
4876         cb->args[0] = (long)lgncl;
4877
4878         params = genlmsg_data(gnlh);
4879         nla_for_each_attr(top, params, msg_len, rem) {
4880                 struct nlattr *nids;
4881                 int rem2;
4882
4883                 switch (nla_type(top)) {
4884                 case LN_SCALAR_ATTR_LIST:
4885                         nla_for_each_nested(nids, top, rem2) {
4886                                 char nidstr[LNET_NIDSTR_SIZE + 1];
4887                                 struct lnet_nid_cpt *lnc;
4888
4889                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
4890                                         continue;
4891
4892                                 memset(nidstr, 0, sizeof(nidstr));
4893                                 rc = nla_strscpy(nidstr, nids, sizeof(nidstr));
4894                                 if (rc < 0) {
4895                                         NL_SET_ERR_MSG(extack,
4896                                                        "failed to get NID");
4897                                         GOTO(report_err, rc);
4898                                 }
4899
4900                                 lnc = genradix_ptr_alloc(&lgncl->lgncl_lnc_list,
4901                                                       lgncl->lgncl_list_count++,
4902                                                       GFP_KERNEL);
4903                                 if (!lnc) {
4904                                         NL_SET_ERR_MSG(extack,
4905                                                       "failed to allocate NID");
4906                                         GOTO(report_err, rc = -ENOMEM);
4907                                 }
4908
4909                                 rc = libcfs_strnid(&lnc->lnc_nid,
4910                                                    strim(nidstr));
4911                                 if (rc < 0) {
4912                                         NL_SET_ERR_MSG(extack, "invalid NID");
4913                                         GOTO(report_err, rc);
4914                                 }
4915                                 rc = 0;
4916                                 CDEBUG(D_NET, "nid: %s\n",
4917                                        libcfs_nidstr(&lnc->lnc_nid));
4918                         }
4919                         fallthrough;
4920                 default:
4921                         break;
4922                 }
4923         }
4924 report_err:
4925         mutex_unlock(&the_lnet.ln_api_mutex);
4926
4927         if (rc < 0)
4928                 lnet_cpt_of_nid_show_done(cb);
4929
4930         return rc;
4931 }
4932
4933 static const struct ln_key_list cpt_of_nid_props_list = {
4934         .lkl_maxattr                    = LNET_CPT_OF_NID_ATTR_MAX,
4935         .lkl_list                       = {
4936                 [LNET_CPT_OF_NID_ATTR_HDR]      = {
4937                         .lkp_value              = "cpt-of-nid",
4938                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4939                         .lkp_data_type          = NLA_NUL_STRING,
4940                 },
4941                 [LNET_CPT_OF_NID_ATTR_NID]      = {
4942                         .lkp_value              = "nid",
4943                         .lkp_data_type          = NLA_STRING,
4944                 },
4945                 [LNET_CPT_OF_NID_ATTR_CPT]      = {
4946                         .lkp_value              = "cpt",
4947                         .lkp_data_type          = NLA_U32,
4948                 },
4949         },
4950 };
4951
4952 static int lnet_cpt_of_nid_show_dump(struct sk_buff *msg,
4953                                      struct netlink_callback *cb)
4954 {
4955         struct lnet_genl_nid_cpt_list *lgncl;
4956 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4957         struct netlink_ext_ack *extack = NULL;
4958 #endif
4959         int portid = NETLINK_CB(cb->skb).portid;
4960         int seq = cb->nlh->nlmsg_seq;
4961         int idx;
4962         int rc = 0;
4963         bool need_hdr = true;
4964
4965 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4966         extack = cb->extack;
4967 #endif
4968
4969         mutex_lock(&the_lnet.ln_api_mutex);
4970         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
4971                 NL_SET_ERR_MSG(extack, "Network is down");
4972                 GOTO(send_error, rc = -ENETDOWN);
4973         }
4974
4975         lgncl = lnet_cpt_of_nid_dump_ctx(cb);
4976         idx = lgncl->lgncl_index;
4977
4978         if (!lgncl->lgncl_index) {
4979                 const struct ln_key_list *all[] = {
4980                         &cpt_of_nid_props_list, NULL, NULL
4981                 };
4982
4983                 rc = lnet_genl_send_scalar_list(msg, portid, seq, &lnet_family,
4984                                                 NLM_F_CREATE | NLM_F_MULTI,
4985                                                 LNET_CMD_CPT_OF_NID, all);
4986                 if (rc < 0) {
4987                         NL_SET_ERR_MSG(extack, "failed to send key table");
4988                         GOTO(send_error, rc);
4989                 }
4990         }
4991
4992         while (idx < lgncl->lgncl_list_count) {
4993                 struct lnet_nid_cpt *lnc;
4994                 void *hdr;
4995                 int cpt;
4996
4997                 lnc = genradix_ptr(&lgncl->lgncl_lnc_list, idx++);
4998
4999                 cpt = lnet_nid_cpt_hash(&lnc->lnc_nid, LNET_CPT_NUMBER);
5000
5001                 CDEBUG(D_NET, "nid: %s cpt: %d\n", libcfs_nidstr(&lnc->lnc_nid), cpt);
5002                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5003                                   NLM_F_MULTI, LNET_CMD_CPT_OF_NID);
5004                 if (!hdr) {
5005                         NL_SET_ERR_MSG(extack, "failed to send values");
5006                         genlmsg_cancel(msg, hdr);
5007                         GOTO(send_error, rc = -EMSGSIZE);
5008                 }
5009
5010                 if (need_hdr) {
5011                         nla_put_string(msg, LNET_CPT_OF_NID_ATTR_HDR, "");
5012                         need_hdr = false;
5013                 }
5014
5015                 nla_put_string(msg, LNET_CPT_OF_NID_ATTR_NID,
5016                                libcfs_nidstr(&lnc->lnc_nid));
5017                 nla_put_u32(msg, LNET_CPT_OF_NID_ATTR_CPT, cpt);
5018
5019                 genlmsg_end(msg, hdr);
5020         }
5021
5022         genradix_free(&lgncl->lgncl_lnc_list);
5023         rc = 0;
5024         lgncl->lgncl_index = idx;
5025
5026 send_error:
5027         mutex_unlock(&the_lnet.ln_api_mutex);
5028
5029         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5030 }
5031
5032 #ifndef HAVE_NETLINK_CALLBACK_START
5033 static int lnet_old_cpt_of_nid_show_dump(struct sk_buff *msg,
5034                                          struct netlink_callback *cb)
5035 {
5036         if (!cb->args[0]) {
5037                 int rc = lnet_cpt_of_nid_show_start(cb);
5038
5039                 if (rc < 0)
5040                         return lnet_nl_send_error(cb->skb,
5041                                                   NETLINK_CB(cb->skb).portid,
5042                                                   cb->nlh->nlmsg_seq,
5043                                                   rc);
5044         }
5045
5046         return lnet_cpt_of_nid_show_dump(msg, cb);
5047 }
5048 #endif
5049
5050 /* This is the keys for the UDSP info which is used by many
5051  * Netlink commands.
5052  */
5053 static const struct ln_key_list udsp_info_list = {
5054         .lkl_maxattr                    = LNET_UDSP_INFO_ATTR_MAX,
5055         .lkl_list                       = {
5056                 [LNET_UDSP_INFO_ATTR_NET_PRIORITY]              = {
5057                         .lkp_value      = "net priority",
5058                         .lkp_data_type  = NLA_S32
5059                 },
5060                 [LNET_UDSP_INFO_ATTR_NID_PRIORITY]              = {
5061                         .lkp_value      = "nid priority",
5062                         .lkp_data_type  = NLA_S32
5063                 },
5064                 [LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST]        = {
5065                         .lkp_value      = "Preferred gateway NIDs",
5066                         .lkp_key_format = LNKF_MAPPING,
5067                         .lkp_data_type  = NLA_NESTED,
5068                 },
5069                 [LNET_UDSP_INFO_ATTR_PREF_NIDS_LIST]            = {
5070                         .lkp_value      = "Preferred source NIDs",
5071                         .lkp_key_format = LNKF_MAPPING,
5072                         .lkp_data_type  = NLA_NESTED,
5073                 },
5074         },
5075 };
5076
5077 static const struct ln_key_list udsp_info_pref_nids_list = {
5078         .lkl_maxattr                    = LNET_UDSP_INFO_PREF_NIDS_ATTR_MAX,
5079         .lkl_list                       = {
5080                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX]           = {
5081                         .lkp_value      = "NID-0",
5082                         .lkp_data_type  = NLA_NUL_STRING,
5083                 },
5084                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_NID]             = {
5085                         .lkp_value      = "0@lo",
5086                         .lkp_data_type  = NLA_STRING,
5087                 },
5088         },
5089 };
5090
5091 static int lnet_udsp_info_send(struct sk_buff *msg, int attr,
5092                                struct lnet_nid *nid, bool remote)
5093 {
5094         struct lnet_ioctl_construct_udsp_info *udsp;
5095         struct nlattr *udsp_attr, *udsp_info;
5096         struct nlattr *udsp_list_attr;
5097         struct nlattr *udsp_list_info;
5098         int i;
5099
5100         CFS_ALLOC_PTR(udsp);
5101         if (!udsp)
5102                 return -ENOMEM;
5103
5104         udsp->cud_peer = remote;
5105         lnet_udsp_get_construct_info(udsp, nid);
5106
5107         udsp_info = nla_nest_start(msg, attr);
5108         udsp_attr = nla_nest_start(msg, 0);
5109         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NET_PRIORITY,
5110                     udsp->cud_net_priority);
5111         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NID_PRIORITY,
5112                     udsp->cud_nid_priority);
5113
5114         if (udsp->cud_pref_rtr_nid[0] == 0)
5115                 goto skip_list;
5116
5117         udsp_list_info = nla_nest_start(msg,
5118                                         LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST);
5119         for (i = 0; i < LNET_MAX_SHOW_NUM_NID; i++) {
5120                 char tmp[8]; /* NID-"3 number"\0 */
5121
5122                 if (udsp->cud_pref_rtr_nid[i] == 0)
5123                         break;
5124
5125                 udsp_list_attr = nla_nest_start(msg, i);
5126                 snprintf(tmp, sizeof(tmp), "NID-%d", i);
5127                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX,
5128                                tmp);
5129                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_NID,
5130                                libcfs_nid2str(udsp->cud_pref_rtr_nid[i]));
5131                 nla_nest_end(msg, udsp_list_attr);
5132         }
5133         nla_nest_end(msg, udsp_list_info);
5134 skip_list:
5135         nla_nest_end(msg, udsp_attr);
5136         nla_nest_end(msg, udsp_info);
5137         LIBCFS_FREE(udsp, sizeof(*udsp));
5138
5139         return 0;
5140 }
5141
5142 /* LNet NI handling */
5143 static const struct ln_key_list net_props_list = {
5144         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
5145         .lkl_list                       = {
5146                 [LNET_NET_ATTR_HDR]             = {
5147                         .lkp_value              = "net",
5148                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5149                         .lkp_data_type          = NLA_NUL_STRING,
5150                 },
5151                 [LNET_NET_ATTR_TYPE]            = {
5152                         .lkp_value              = "net type",
5153                         .lkp_data_type          = NLA_STRING
5154                 },
5155                 [LNET_NET_ATTR_LOCAL]           = {
5156                         .lkp_value              = "local NI(s)",
5157                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5158                         .lkp_data_type          = NLA_NESTED
5159                 },
5160         },
5161 };
5162
5163 static struct ln_key_list local_ni_list = {
5164         .lkl_maxattr                    = LNET_NET_LOCAL_NI_ATTR_MAX,
5165         .lkl_list                       = {
5166                 [LNET_NET_LOCAL_NI_ATTR_NID]            = {
5167                         .lkp_value              = "nid",
5168                         .lkp_data_type          = NLA_STRING
5169                 },
5170                 [LNET_NET_LOCAL_NI_ATTR_STATUS]         = {
5171                         .lkp_value              = "status",
5172                         .lkp_data_type          = NLA_STRING
5173                 },
5174                 [LNET_NET_LOCAL_NI_ATTR_INTERFACE]      = {
5175                         .lkp_value              = "interfaces",
5176                         .lkp_key_format         = LNKF_MAPPING,
5177                         .lkp_data_type          = NLA_NESTED
5178                 },
5179                 [LNET_NET_LOCAL_NI_ATTR_STATS]          = {
5180                         .lkp_value              = "statistics",
5181                         .lkp_key_format         = LNKF_MAPPING,
5182                         .lkp_data_type          = NLA_NESTED
5183                 },
5184                 [LNET_NET_LOCAL_NI_ATTR_UDSP_INFO]      = {
5185                         .lkp_value              = "udsp info",
5186                         .lkp_key_format         = LNKF_MAPPING,
5187                         .lkp_data_type          = NLA_NESTED
5188                 },
5189                 [LNET_NET_LOCAL_NI_ATTR_SEND_STATS]     = {
5190                         .lkp_value              = "sent_stats",
5191                         .lkp_key_format         = LNKF_MAPPING,
5192                         .lkp_data_type          = NLA_NESTED
5193                 },
5194                 [LNET_NET_LOCAL_NI_ATTR_RECV_STATS]     = {
5195                         .lkp_value              = "received_stats",
5196                         .lkp_key_format         = LNKF_MAPPING,
5197                         .lkp_data_type          = NLA_NESTED
5198                 },
5199                 [LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS]  = {
5200                         .lkp_value              = "dropped_stats",
5201                         .lkp_key_format         = LNKF_MAPPING,
5202                         .lkp_data_type          = NLA_NESTED
5203
5204                 },
5205                 [LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS]   = {
5206                         .lkp_value              = "health stats",
5207                         .lkp_key_format         = LNKF_MAPPING,
5208                         .lkp_data_type          = NLA_NESTED
5209                 },
5210                 [LNET_NET_LOCAL_NI_ATTR_TUNABLES]       = {
5211                         .lkp_value              = "tunables",
5212                         .lkp_key_format         = LNKF_MAPPING,
5213                         .lkp_data_type          = NLA_NESTED
5214                 },
5215                 [LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES]   = {
5216                         .lkp_value              = "lnd tunables",
5217                         .lkp_key_format         = LNKF_MAPPING,
5218                         .lkp_data_type          = NLA_NESTED
5219                 },
5220                 [LNET_NET_LOCAL_NI_DEV_CPT]             = {
5221                         .lkp_value              = "dev cpt",
5222                         .lkp_data_type          = NLA_S32,
5223                 },
5224                 [LNET_NET_LOCAL_NI_CPTS]                = {
5225                         .lkp_value              = "CPT",
5226                         .lkp_data_type          = NLA_STRING,
5227                 },
5228         },
5229 };
5230
5231 static const struct ln_key_list local_ni_interfaces_list = {
5232         .lkl_maxattr                    = LNET_NET_LOCAL_NI_INTF_ATTR_MAX,
5233         .lkl_list                       = {
5234                 [LNET_NET_LOCAL_NI_INTF_ATTR_TYPE] = {
5235                         .lkp_value      = "0",
5236                         .lkp_data_type  = NLA_STRING
5237                 },
5238         },
5239 };
5240
5241 static const struct ln_key_list local_ni_stats_list = {
5242         .lkl_maxattr                    = LNET_NET_LOCAL_NI_STATS_ATTR_MAX,
5243         .lkl_list                       = {
5244                 [LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT]       = {
5245                         .lkp_value      = "send_count",
5246                         .lkp_data_type  = NLA_U32
5247                 },
5248                 [LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT]       = {
5249                         .lkp_value      = "recv_count",
5250                         .lkp_data_type  = NLA_U32
5251                 },
5252                 [LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT]       = {
5253                         .lkp_value      = "drop_count",
5254                         .lkp_data_type  = NLA_U32
5255                 },
5256         },
5257 };
5258
5259 static const struct ln_key_list local_ni_msg_stats_list = {
5260         .lkl_maxattr                    = LNET_NET_LOCAL_NI_MSG_STATS_ATTR_MAX,
5261         .lkl_list                       = {
5262                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT]    = {
5263                         .lkp_value      = "put",
5264                         .lkp_data_type  = NLA_U32
5265                 },
5266                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT]    = {
5267                         .lkp_value      = "get",
5268                         .lkp_data_type  = NLA_U32
5269                 },
5270                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT]  = {
5271                         .lkp_value      = "reply",
5272                         .lkp_data_type  = NLA_U32
5273                 },
5274                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT]    = {
5275                         .lkp_value      = "ack",
5276                         .lkp_data_type  = NLA_U32
5277                 },
5278                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT]  = {
5279                         .lkp_value      = "hello",
5280                         .lkp_data_type  = NLA_U32
5281                 },
5282         },
5283 };
5284
5285 static const struct ln_key_list local_ni_health_stats_list = {
5286         .lkl_maxattr                    = LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_MAX,
5287         .lkl_list                       = {
5288                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS] = {
5289                         .lkp_value      = "fatal_error",
5290                         .lkp_data_type  = NLA_S32
5291                 },
5292                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL] = {
5293                         .lkp_value      = "health value",
5294                         .lkp_data_type  = NLA_S32
5295                 },
5296                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS] = {
5297                         .lkp_value      = "interrupts",
5298                         .lkp_data_type  = NLA_U32
5299                 },
5300                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED] = {
5301                         .lkp_value      = "dropped",
5302                         .lkp_data_type  = NLA_U32
5303                 },
5304                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED] = {
5305                         .lkp_value      = "aborted",
5306                         .lkp_data_type  = NLA_U32
5307                 },
5308                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE] = {
5309                         .lkp_value      = "no route",
5310                         .lkp_data_type  = NLA_U32
5311                 },
5312                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS] = {
5313                         .lkp_value      = "timeouts",
5314                         .lkp_data_type  = NLA_U32
5315                 },
5316                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR] = {
5317                         .lkp_value      = "error",
5318                         .lkp_data_type  = NLA_U32
5319                 },
5320                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT] = {
5321                         .lkp_value      = "ping_count",
5322                         .lkp_data_type  = NLA_U32,
5323                 },
5324                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING] = {
5325                         .lkp_value      = "next_ping",
5326                         .lkp_data_type  = NLA_U64
5327                 },
5328         },
5329 };
5330
5331 static const struct ln_key_list local_ni_tunables_list = {
5332         .lkl_maxattr                    = LNET_NET_LOCAL_NI_TUNABLES_ATTR_MAX,
5333         .lkl_list                       = {
5334                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT]  = {
5335                         .lkp_value      = "peer_timeout",
5336                         .lkp_data_type  = NLA_S32
5337                 },
5338                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS]  = {
5339                         .lkp_value      = "peer_credits",
5340                         .lkp_data_type  = NLA_S32
5341                 },
5342                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS] = {
5343                         .lkp_value      = "peer_buffer_credits",
5344                         .lkp_data_type  = NLA_S32
5345                 },
5346                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS] = {
5347                         .lkp_value      = "credits",
5348                         .lkp_data_type  = NLA_S32
5349                 },
5350         },
5351 };
5352
5353 /* Use an index since the traversal is across LNet nets and ni collections */
5354 struct lnet_genl_net_list {
5355         unsigned int    lngl_net_id;
5356         unsigned int    lngl_idx;
5357 };
5358
5359 static inline struct lnet_genl_net_list *
5360 lnet_net_dump_ctx(struct netlink_callback *cb)
5361 {
5362         return (struct lnet_genl_net_list *)cb->args[0];
5363 }
5364
5365 static int lnet_net_show_done(struct netlink_callback *cb)
5366 {
5367         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5368
5369         if (nlist) {
5370                 LIBCFS_FREE(nlist, sizeof(*nlist));
5371                 cb->args[0] = 0;
5372         }
5373
5374         return 0;
5375 }
5376
5377 /* LNet net ->start() handler for GET requests */
5378 static int lnet_net_show_start(struct netlink_callback *cb)
5379 {
5380         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5381 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5382         struct netlink_ext_ack *extack = NULL;
5383 #endif
5384         struct lnet_genl_net_list *nlist;
5385         int msg_len = genlmsg_len(gnlh);
5386         struct nlattr *params, *top;
5387         int rem, rc = 0;
5388
5389 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5390         extack = cb->extack;
5391 #endif
5392         if (the_lnet.ln_refcount == 0) {
5393                 NL_SET_ERR_MSG(extack, "LNet stack down");
5394                 return -ENETDOWN;
5395         }
5396
5397         LIBCFS_ALLOC(nlist, sizeof(*nlist));
5398         if (!nlist)
5399                 return -ENOMEM;
5400
5401         nlist->lngl_net_id = LNET_NET_ANY;
5402         nlist->lngl_idx = 0;
5403         cb->args[0] = (long)nlist;
5404
5405         cb->min_dump_alloc = U16_MAX;
5406         if (!msg_len)
5407                 return 0;
5408
5409         params = genlmsg_data(gnlh);
5410         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
5411                 NL_SET_ERR_MSG(extack, "invalid configuration");
5412                 return -EINVAL;
5413         }
5414
5415         nla_for_each_nested(top, params, rem) {
5416                 struct nlattr *net;
5417                 int rem2;
5418
5419                 nla_for_each_nested(net, top, rem2) {
5420                         char filter[LNET_NIDSTR_SIZE];
5421
5422                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE ||
5423                             nla_strcmp(net, "net type") != 0)
5424                                 continue;
5425
5426                         net = nla_next(net, &rem2);
5427                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE) {
5428                                 NL_SET_ERR_MSG(extack, "invalid config param");
5429                                 GOTO(report_err, rc = -EINVAL);
5430                         }
5431
5432                         rc = nla_strscpy(filter, net, sizeof(filter));
5433                         if (rc < 0) {
5434                                 NL_SET_ERR_MSG(extack, "failed to get param");
5435                                 GOTO(report_err, rc);
5436                         }
5437                         rc = 0;
5438
5439                         nlist->lngl_net_id = libcfs_str2net(filter);
5440                         if (nlist->lngl_net_id == LNET_NET_ANY) {
5441                                 NL_SET_ERR_MSG(extack, "cannot parse net");
5442                                 GOTO(report_err, rc = -ENOENT);
5443                         }
5444                 }
5445         }
5446 report_err:
5447         if (rc < 0)
5448                 lnet_net_show_done(cb);
5449
5450         return rc;
5451 }
5452
5453 static const struct ln_key_list net_update_props_list = {
5454         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
5455         .lkl_list                       = {
5456                 [LNET_NET_ATTR_HDR]             = {
5457                         .lkp_value              = "",
5458                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5459                         .lkp_data_type          = NLA_NUL_STRING,
5460                 },
5461                 [LNET_NET_ATTR_TYPE]            = {
5462                         .lkp_value              = "net type",
5463                         .lkp_data_type          = NLA_STRING
5464                 },
5465                 [LNET_NET_ATTR_LOCAL]           = {
5466                         .lkp_value              = "local NI(s)",
5467                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5468                         .lkp_data_type          = NLA_NESTED
5469                 },
5470         },
5471 };
5472
5473 static int lnet_net_show_dump(struct sk_buff *msg,
5474                               struct netlink_callback *cb)
5475 {
5476         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5477 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5478         struct netlink_ext_ack *extack = NULL;
5479 #endif
5480         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5481         int portid = NETLINK_CB(cb->skb).portid;
5482         bool found = false, started = false;
5483         const struct lnet_lnd *lnd = NULL;
5484         int idx = nlist->lngl_idx, rc = 0;
5485         int seq = cb->nlh->nlmsg_seq;
5486         struct lnet_net *net;
5487         void *hdr = NULL;
5488
5489 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5490         extack = cb->extack;
5491 #endif
5492         lnet_net_lock(LNET_LOCK_EX);
5493
5494         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
5495                 struct nlattr *local_ni, *ni_attr;
5496                 struct lnet_ni *ni;
5497                 int dev = 0;
5498
5499                 if (nlist->lngl_net_id != LNET_NET_ANY &&
5500                     nlist->lngl_net_id != net->net_id)
5501                         continue;
5502
5503                 if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED &&
5504                     LNET_NETTYP(net->net_id) == LOLND)
5505                         continue;
5506
5507                 if (gnlh->version && LNET_NETTYP(net->net_id) != LOLND) {
5508                         if (!net->net_lnd) {
5509                                 NL_SET_ERR_MSG(extack,
5510                                                "LND not setup for NI");
5511                                 GOTO(net_unlock, rc = -ENODEV);
5512                         }
5513                         if (net->net_lnd != lnd)
5514                                 lnd = net->net_lnd;
5515                         else
5516                                 lnd = NULL;
5517                 }
5518
5519                 /* We need to resend the key table every time the base LND
5520                  * changed.
5521                  */
5522                 if (!idx || lnd) {
5523                         const struct ln_key_list *all[] = {
5524                                 &net_props_list, &local_ni_list,
5525                                 &local_ni_interfaces_list,
5526                                 &local_ni_stats_list,
5527                                 &udsp_info_list,
5528                                 &udsp_info_pref_nids_list,
5529                                 &udsp_info_pref_nids_list,
5530                                 &local_ni_msg_stats_list,
5531                                 &local_ni_msg_stats_list,
5532                                 &local_ni_msg_stats_list,
5533                                 &local_ni_health_stats_list,
5534                                 &local_ni_tunables_list,
5535                                 NULL, /* lnd tunables */
5536                                 NULL
5537                         };
5538                         int flags = NLM_F_CREATE | NLM_F_MULTI;
5539
5540                         if (lnd) {
5541                                 all[ARRAY_SIZE(all) - 2] = lnd->lnd_keys;
5542                                 if (idx) {
5543                                         all[0] = &net_update_props_list;
5544                                         flags |= NLM_F_REPLACE;
5545                                 }
5546                         }
5547
5548                         rc = lnet_genl_send_scalar_list(msg, portid, seq,
5549                                                         &lnet_family, flags,
5550                                                         LNET_CMD_NETS, all);
5551                         if (rc < 0) {
5552                                 NL_SET_ERR_MSG(extack, "failed to send key table");
5553                                 GOTO(net_unlock, rc);
5554                         }
5555                         started = true;
5556                 }
5557
5558                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5559                                   NLM_F_MULTI, LNET_CMD_NETS);
5560                 if (!hdr) {
5561                         NL_SET_ERR_MSG(extack, "failed to send values");
5562                         GOTO(net_unlock, rc = -EMSGSIZE);
5563                 }
5564
5565                 if (started) {
5566                         nla_put_string(msg, LNET_NET_ATTR_HDR, "");
5567                         started = false;
5568                 }
5569
5570                 nla_put_string(msg, LNET_NET_ATTR_TYPE,
5571                                libcfs_net2str(net->net_id));
5572
5573                 local_ni = nla_nest_start(msg, LNET_NET_ATTR_LOCAL);
5574                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
5575                         char *status = "up";
5576
5577                         if (idx++ < nlist->lngl_idx)
5578                                 continue;
5579
5580                         ni_attr = nla_nest_start(msg, dev++);
5581                         found = true;
5582                         lnet_ni_lock(ni);
5583                         if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)) {
5584                                 nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_NID,
5585                                                libcfs_nidstr(&ni->ni_nid));
5586                                 if (!nid_is_lo0(&ni->ni_nid) &&
5587                                     lnet_ni_get_status_locked(ni) != LNET_NI_STATUS_UP)
5588                                         status = "down";
5589                                 nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_STATUS,
5590                                                status);
5591                         }
5592
5593                         if (!nid_is_lo0(&ni->ni_nid) && ni->ni_interface) {
5594                                 struct nlattr *intf_nest, *intf_attr;
5595
5596                                 intf_nest = nla_nest_start(msg,
5597                                                            LNET_NET_LOCAL_NI_ATTR_INTERFACE);
5598                                 intf_attr = nla_nest_start(msg, 0);
5599                                 nla_put_string(msg,
5600                                                LNET_NET_LOCAL_NI_INTF_ATTR_TYPE,
5601                                                ni->ni_interface);
5602                                 nla_nest_end(msg, intf_attr);
5603                                 nla_nest_end(msg, intf_nest);
5604                         }
5605
5606                         if (gnlh->version) {
5607                                 char cpts[LNET_MAX_SHOW_NUM_CPT * 4 + 4], *cpt;
5608                                 struct lnet_ioctl_element_msg_stats msg_stats;
5609                                 struct lnet_ioctl_element_stats stats;
5610                                 size_t buf_len = sizeof(cpts), len;
5611                                 struct nlattr *health_attr, *health_stats;
5612                                 struct nlattr *send_attr, *send_stats;
5613                                 struct nlattr *recv_attr, *recv_stats;
5614                                 struct nlattr *drop_attr, *drop_stats;
5615                                 struct nlattr *stats_attr, *ni_stats;
5616                                 struct nlattr *tun_attr, *ni_tun;
5617                                 int j;
5618
5619                                 if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED) {
5620                                         lnet_ni_unlock(ni);
5621                                         goto skip_msg_stats;
5622                                 }
5623
5624                                 stats.iel_send_count = lnet_sum_stats(&ni->ni_stats,
5625                                                                       LNET_STATS_TYPE_SEND);
5626                                 stats.iel_recv_count = lnet_sum_stats(&ni->ni_stats,
5627                                                                       LNET_STATS_TYPE_RECV);
5628                                 stats.iel_drop_count = lnet_sum_stats(&ni->ni_stats,
5629                                                                       LNET_STATS_TYPE_DROP);
5630                                 lnet_ni_unlock(ni);
5631
5632                                 stats_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_STATS);
5633                                 ni_stats = nla_nest_start(msg, 0);
5634                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT,
5635                                             stats.iel_send_count);
5636                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT,
5637                                             stats.iel_recv_count);
5638                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT,
5639                                             stats.iel_drop_count);
5640                                 nla_nest_end(msg, ni_stats);
5641                                 nla_nest_end(msg, stats_attr);
5642
5643                                 if (gnlh->version < 4)
5644                                         goto skip_udsp;
5645
5646                                 /* UDSP info */
5647                                 rc = lnet_udsp_info_send(msg, LNET_NET_LOCAL_NI_ATTR_UDSP_INFO,
5648                                                          &ni->ni_nid, false);
5649                                 if (rc < 0) {
5650                                         NL_SET_ERR_MSG(extack,
5651                                                        "Failed to get udsp info");
5652                                         genlmsg_cancel(msg, hdr);
5653                                         GOTO(net_unlock, rc = -ENOMEM);
5654                                 }
5655 skip_udsp:
5656                                 if (gnlh->version < 2)
5657                                         goto skip_msg_stats;
5658
5659                                 msg_stats.im_idx = idx - 1;
5660                                 rc = lnet_get_ni_stats(&msg_stats);
5661                                 if (rc < 0) {
5662                                         NL_SET_ERR_MSG(extack,
5663                                                        "failed to get msg stats");
5664                                         genlmsg_cancel(msg, hdr);
5665                                         GOTO(net_unlock, rc = -ENOMEM);
5666                                 }
5667
5668                                 send_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_SEND_STATS);
5669                                 send_attr = nla_nest_start(msg, 0);
5670                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5671                                             msg_stats.im_send_stats.ico_get_count);
5672                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5673                                             msg_stats.im_send_stats.ico_put_count);
5674                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5675                                             msg_stats.im_send_stats.ico_reply_count);
5676                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5677                                             msg_stats.im_send_stats.ico_ack_count);
5678                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5679                                             msg_stats.im_send_stats.ico_hello_count);
5680                                 nla_nest_end(msg, send_attr);
5681                                 nla_nest_end(msg, send_stats);
5682
5683                                 recv_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_RECV_STATS);
5684                                 recv_attr = nla_nest_start(msg, 0);
5685                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5686                                             msg_stats.im_recv_stats.ico_get_count);
5687                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5688                                             msg_stats.im_recv_stats.ico_put_count);
5689                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5690                                             msg_stats.im_recv_stats.ico_reply_count);
5691                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5692                                             msg_stats.im_recv_stats.ico_ack_count);
5693                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5694                                             msg_stats.im_recv_stats.ico_hello_count);
5695                                 nla_nest_end(msg, recv_attr);
5696                                 nla_nest_end(msg, recv_stats);
5697
5698                                 drop_stats = nla_nest_start(msg,
5699                                                             LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS);
5700                                 drop_attr = nla_nest_start(msg, 0);
5701                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5702                                             msg_stats.im_drop_stats.ico_get_count);
5703                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5704                                             msg_stats.im_drop_stats.ico_put_count);
5705                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5706                                             msg_stats.im_drop_stats.ico_reply_count);
5707                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5708                                             msg_stats.im_drop_stats.ico_ack_count);
5709                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5710                                             msg_stats.im_drop_stats.ico_hello_count);
5711                                 nla_nest_end(msg, drop_attr);
5712                                 nla_nest_end(msg, drop_stats);
5713
5714                                 /* health stats */
5715                                 health_stats = nla_nest_start(msg,
5716                                                               LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS);
5717                                 health_attr = nla_nest_start(msg, 0);
5718                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS,
5719                                             atomic_read(&ni->ni_fatal_error_on));
5720                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL,
5721                                             atomic_read(&ni->ni_healthv));
5722                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS,
5723                                             atomic_read(&ni->ni_hstats.hlt_local_interrupt));
5724                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED,
5725                                             atomic_read(&ni->ni_hstats.hlt_local_dropped));
5726                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED,
5727                                             atomic_read(&ni->ni_hstats.hlt_local_aborted));
5728                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE,
5729                                             atomic_read(&ni->ni_hstats.hlt_local_no_route));
5730                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS,
5731                                             atomic_read(&ni->ni_hstats.hlt_local_timeout));
5732                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR,
5733                                             atomic_read(&ni->ni_hstats.hlt_local_error));
5734                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT,
5735                                             ni->ni_ping_count);
5736                                 nla_put_u64_64bit(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING,
5737                                                   ni->ni_next_ping,
5738                                                   LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PAD);
5739                                 nla_nest_end(msg, health_attr);
5740                                 nla_nest_end(msg, health_stats);
5741 skip_msg_stats:
5742                                 /* Report net tunables */
5743                                 tun_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_TUNABLES);
5744                                 ni_tun = nla_nest_start(msg, 0);
5745                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT,
5746                                             ni->ni_net->net_tunables.lct_peer_timeout);
5747                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS,
5748                                             ni->ni_net->net_tunables.lct_peer_tx_credits);
5749                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS,
5750                                             ni->ni_net->net_tunables.lct_peer_rtr_credits);
5751                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS,
5752                                             ni->ni_net->net_tunables.lct_max_tx_credits);
5753                                 nla_nest_end(msg, ni_tun);
5754
5755                                 nla_nest_end(msg, tun_attr);
5756
5757                                 if (lnd && lnd->lnd_nl_get && lnd->lnd_keys) {
5758                                         struct nlattr *lnd_tun_attr, *lnd_ni_tun;
5759
5760                                         lnd_tun_attr = nla_nest_start(msg,
5761                                                                       LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES);
5762                                         lnd_ni_tun = nla_nest_start(msg, 0);
5763                                         rc = lnd->lnd_nl_get(LNET_CMD_NETS, msg,
5764                                                              LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES,
5765                                                              ni);
5766                                         if (rc < 0) {
5767                                                 NL_SET_ERR_MSG(extack,
5768                                                                "failed to get lnd tunables");
5769                                                 genlmsg_cancel(msg, hdr);
5770                                                 GOTO(net_unlock, rc);
5771                                         }
5772                                         nla_nest_end(msg, lnd_ni_tun);
5773                                         nla_nest_end(msg, lnd_tun_attr);
5774                                 }
5775
5776                                 if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED))
5777                                         nla_put_s32(msg, LNET_NET_LOCAL_NI_DEV_CPT,
5778                                                     ni->ni_dev_cpt);
5779
5780                                 /* Report cpts. We could send this as a nested list
5781                                  * of integers but older versions of the tools
5782                                  * except a string. The new versions can handle
5783                                  * both formats so in the future we can change
5784                                  * this to a nested list.
5785                                  */
5786                                 len = snprintf(cpts, buf_len, "\"[");
5787                                 cpt = cpts + len;
5788                                 buf_len -= len;
5789
5790                                 if (ni->ni_ncpts == LNET_CPT_NUMBER && !ni->ni_cpts)  {
5791                                         for (j = 0; j < ni->ni_ncpts; j++) {
5792                                                 len = snprintf(cpt, buf_len, "%d,", j);
5793                                                 buf_len -= len;
5794                                                 cpt += len;
5795                                         }
5796                                 } else {
5797                                         for (j = 0;
5798                                              ni->ni_cpts && j < ni->ni_ncpts &&
5799                                              j < LNET_MAX_SHOW_NUM_CPT; j++) {
5800                                                 len = snprintf(cpt, buf_len, "%d,",
5801                                                                ni->ni_cpts[j]);
5802                                                 buf_len -= len;
5803                                                 cpt += len;
5804                                         }
5805                                 }
5806                                 snprintf(cpt - 1, sizeof(cpts), "]\"");
5807
5808                                 nla_put_string(msg, LNET_NET_LOCAL_NI_CPTS, cpts);
5809                         } else {
5810                                 lnet_ni_unlock(ni);
5811                         }
5812                         nla_nest_end(msg, ni_attr);
5813                 }
5814                 nla_nest_end(msg, local_ni);
5815
5816                 genlmsg_end(msg, hdr);
5817         }
5818
5819         if (!found) {
5820                 struct nlmsghdr *nlh = nlmsg_hdr(msg);
5821
5822                 nlmsg_cancel(msg, nlh);
5823                 NL_SET_ERR_MSG(extack, "Network is down");
5824                 rc = -ESRCH;
5825         }
5826         nlist->lngl_idx = idx;
5827 net_unlock:
5828         lnet_net_unlock(LNET_LOCK_EX);
5829
5830         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5831 }
5832
5833 #ifndef HAVE_NETLINK_CALLBACK_START
5834 static int lnet_old_net_show_dump(struct sk_buff *msg,
5835                                    struct netlink_callback *cb)
5836 {
5837         if (!cb->args[0]) {
5838                 int rc = lnet_net_show_start(cb);
5839
5840                 if (rc < 0)
5841                         return lnet_nl_send_error(cb->skb,
5842                                                   NETLINK_CB(cb->skb).portid,
5843                                                   cb->nlh->nlmsg_seq,
5844                                                   rc);
5845         }
5846
5847         return lnet_net_show_dump(msg, cb);
5848 }
5849 #endif
5850
5851 static int lnet_genl_parse_tunables(struct nlattr *settings,
5852                                     struct lnet_ioctl_config_lnd_tunables *tun)
5853 {
5854         struct nlattr *param;
5855         int rem, rc = 0;
5856
5857         nla_for_each_nested(param, settings, rem) {
5858                 int type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_UNSPEC;
5859                 s64 num;
5860
5861                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5862                         continue;
5863
5864                 if (nla_strcmp(param, "peer_timeout") == 0)
5865                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT;
5866                 else if (nla_strcmp(param, "peer_credits") == 0)
5867                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS;
5868                 else if (nla_strcmp(param, "peer_buffer_credits") == 0)
5869                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS;
5870                 else if (nla_strcmp(param, "credits") == 0)
5871                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS;
5872
5873                 param = nla_next(param, &rem);
5874                 if (nla_type(param) != LN_SCALAR_ATTR_INT_VALUE)
5875                         return -EINVAL;
5876
5877                 num = nla_get_s64(param);
5878                 switch (type) {
5879                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT:
5880                         if (num >= 0)
5881                                 tun->lt_cmn.lct_peer_timeout = num;
5882                         break;
5883                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS:
5884                         if (num > 0)
5885                                 tun->lt_cmn.lct_peer_tx_credits = num;
5886                         break;
5887                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS:
5888                         if (num > 0)
5889                                 tun->lt_cmn.lct_peer_rtr_credits = num;
5890                         break;
5891                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS:
5892                         if (num > 0)
5893                                 tun->lt_cmn.lct_max_tx_credits = num;
5894                         break;
5895                 default:
5896                         rc = -EINVAL;
5897                         break;
5898                 }
5899         }
5900         return rc;
5901 }
5902
5903 static int lnet_genl_parse_lnd_tunables(struct nlattr *settings,
5904                                         struct lnet_lnd_tunables *tun,
5905                                         const struct lnet_lnd *lnd)
5906 {
5907         const struct ln_key_list *list = lnd->lnd_keys;
5908         struct nlattr *param;
5909         int rem, rc = 0;
5910         int i = 1;
5911
5912         /* silently ignore these setting if the LND driver doesn't
5913          * support any LND tunables
5914          */
5915         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5916                 return 0;
5917
5918         nla_for_each_nested(param, settings, rem) {
5919                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5920                         continue;
5921
5922                 for (i = 1; i <= list->lkl_maxattr; i++) {
5923                         if (!list->lkl_list[i].lkp_value ||
5924                             nla_strcmp(param, list->lkl_list[i].lkp_value) != 0)
5925                                 continue;
5926
5927                         param = nla_next(param, &rem);
5928                         rc = lnd->lnd_nl_set(LNET_CMD_NETS, param, i, tun);
5929                         if (rc < 0)
5930                                 return rc;
5931                 }
5932         }
5933
5934         return rc;
5935 }
5936
5937 static inline void
5938 lnet_genl_init_tunables(const struct lnet_lnd *lnd,
5939                         struct lnet_ioctl_config_lnd_tunables *tun)
5940 {
5941         const struct ln_key_list *list = lnd ? lnd->lnd_keys : NULL;
5942         int i;
5943
5944         tun->lt_cmn.lct_peer_timeout = -1;
5945         tun->lt_cmn.lct_peer_tx_credits = -1;
5946         tun->lt_cmn.lct_peer_rtr_credits = -1;
5947         tun->lt_cmn.lct_max_tx_credits = -1;
5948
5949         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5950                 return;
5951
5952         /* init lnd tunables with default values */
5953         for (i = 1; i <= list->lkl_maxattr; i++)
5954                 lnd->lnd_nl_set(LNET_CMD_NETS, NULL, i, &tun->lt_tun);
5955 }
5956
5957 static int
5958 lnet_genl_parse_local_ni(struct nlattr *entry, struct genl_info *info,
5959                          int net_id, struct lnet_ioctl_config_ni *conf,
5960                          bool *ni_list)
5961 {
5962         struct lnet_ioctl_config_lnd_tunables *tun;
5963         struct lnet_nid nid = LNET_ANY_NID;
5964         const struct lnet_lnd *lnd = NULL;
5965         struct nlattr *settings;
5966         int healthv = -1;
5967         int rem3, rc = 0;
5968
5969         if (net_id != LNET_NET_ANY) {
5970                 lnd = lnet_load_lnd(LNET_NETTYP(net_id));
5971                 if (IS_ERR(lnd)) {
5972                         GENL_SET_ERR_MSG(info, "LND type not supported");
5973                         RETURN(PTR_ERR(lnd));
5974                 }
5975         }
5976
5977         LIBCFS_ALLOC(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5978         if (!tun) {
5979                 GENL_SET_ERR_MSG(info, "cannot allocate memory for tunables");
5980                 GOTO(out, rc = -ENOMEM);
5981         }
5982
5983         /* Use LND defaults */
5984         lnet_genl_init_tunables(lnd, tun);
5985         conf->lic_ncpts = 0;
5986
5987         nla_for_each_nested(settings, entry, rem3) {
5988                 if (nla_type(settings) != LN_SCALAR_ATTR_VALUE)
5989                         continue;
5990
5991                 if (nla_strcmp(settings, "interfaces") == 0) {
5992                         struct nlattr *intf;
5993                         int rem4;
5994
5995                         settings = nla_next(settings, &rem3);
5996                         if (nla_type(settings) !=
5997                             LN_SCALAR_ATTR_LIST) {
5998                                 GENL_SET_ERR_MSG(info,
5999                                                  "invalid interfaces");
6000                                 GOTO(out, rc = -EINVAL);
6001                         }
6002
6003                         nla_for_each_nested(intf, settings, rem4) {
6004                                 intf = nla_next(intf, &rem4);
6005                                 if (nla_type(intf) !=
6006                                     LN_SCALAR_ATTR_VALUE) {
6007                                         GENL_SET_ERR_MSG(info,
6008                                                          "cannot parse interface");
6009                                         GOTO(out, rc = -EINVAL);
6010                                 }
6011
6012                                 rc = nla_strscpy(conf->lic_ni_intf, intf,
6013                                                  sizeof(conf->lic_ni_intf));
6014                                 if (rc < 0) {
6015                                         GENL_SET_ERR_MSG(info,
6016                                                          "failed to parse interfaces");
6017                                         GOTO(out, rc);
6018                                 }
6019                         }
6020                         *ni_list = true;
6021                 } else if (nla_strcmp(settings, "nid") == 0 &&
6022                            net_id != LNET_NET_ANY) {
6023                         char nidstr[LNET_NIDSTR_SIZE];
6024
6025                         settings = nla_next(settings, &rem3);
6026                         if (nla_type(settings) != LN_SCALAR_ATTR_VALUE) {
6027                                 GENL_SET_ERR_MSG(info, "cannot parse NID");
6028                                 GOTO(out, rc = -EINVAL);
6029                         }
6030
6031                         rc = nla_strscpy(nidstr, settings, sizeof(nidstr));
6032                         if (rc < 0) {
6033                                 GENL_SET_ERR_MSG(info,
6034                                                  "failed to parse NID");
6035                                 GOTO(out, rc);
6036                         }
6037
6038                         CDEBUG(D_NET, "Requested NID %s\n", nidstr);
6039                         rc = libcfs_strnid(&nid, strim(nidstr));
6040                         if (rc < 0) {
6041                                 GENL_SET_ERR_MSG(info, "unsupported NID");
6042                                 GOTO(out, rc);
6043                         }
6044
6045                         if (!(info->nlhdr->nlmsg_flags & NLM_F_REPLACE) &&
6046                              nid_same(&nid, &LNET_ANY_NID)) {
6047                                 GENL_SET_ERR_MSG(info, "any NID not supported");
6048                                 GOTO(out, rc = -EINVAL);
6049                         }
6050                         *ni_list = true;
6051                 } else if (nla_strcmp(settings, "health stats") == 0 &&
6052                            info->nlhdr->nlmsg_flags & NLM_F_REPLACE) {
6053                         struct nlattr *health;
6054                         int rem4;
6055
6056                         settings = nla_next(settings, &rem3);
6057                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
6058                                 GENL_SET_ERR_MSG(info,
6059                                                  "cannot parse health stats");
6060                                 GOTO(out, rc = -EINVAL);
6061                         }
6062
6063                         nla_for_each_nested(health, settings, rem4) {
6064                                 if (nla_type(health) != LN_SCALAR_ATTR_VALUE ||
6065                                     nla_strcmp(health, "health value") != 0) {
6066                                         GENL_SET_ERR_MSG(info,
6067                                                          "wrong health config format");
6068                                         GOTO(out, rc = -EINVAL);
6069                                 }
6070
6071                                 health = nla_next(health, &rem4);
6072                                 if (nla_type(health) !=
6073                                     LN_SCALAR_ATTR_INT_VALUE) {
6074                                         GENL_SET_ERR_MSG(info,
6075                                                          "invalid health config format");
6076                                         GOTO(out, rc = -EINVAL);
6077                                 }
6078
6079                                 healthv = nla_get_s64(health);
6080                                 clamp_t(s64, healthv, 0, LNET_MAX_HEALTH_VALUE);
6081                         }
6082                 } else if (nla_strcmp(settings, "tunables") == 0) {
6083                         settings = nla_next(settings, &rem3);
6084                         if (nla_type(settings) !=
6085                             LN_SCALAR_ATTR_LIST) {
6086                                 GENL_SET_ERR_MSG(info,
6087                                                  "invalid tunables");
6088                                 GOTO(out, rc = -EINVAL);
6089                         }
6090
6091                         rc = lnet_genl_parse_tunables(settings, tun);
6092                         if (rc < 0) {
6093                                 GENL_SET_ERR_MSG(info,
6094                                                  "failed to parse tunables");
6095                                 GOTO(out, rc);
6096                         }
6097                 } else if ((nla_strcmp(settings, "lnd tunables") == 0)) {
6098                         settings = nla_next(settings, &rem3);
6099                         if (nla_type(settings) !=
6100                             LN_SCALAR_ATTR_LIST) {
6101                                 GENL_SET_ERR_MSG(info,
6102                                                  "lnd tunables should be list\n");
6103                                 GOTO(out, rc = -EINVAL);
6104                         }
6105
6106                         if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE &&
6107                             net_id == LNET_NET_ANY) {
6108                                 struct lnet_net *net;
6109
6110                                 lnet_net_lock(LNET_LOCK_EX);
6111                                 list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6112                                         struct lnet_ni *ni;
6113
6114                                         if (!net->net_lnd)
6115                                                 continue;
6116
6117                                         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6118                                                 if (!nid_same(&nid, &LNET_ANY_NID) &&
6119                                                     !nid_same(&nid, &ni->ni_nid))
6120                                                         continue;
6121
6122                                                 rc = lnet_genl_parse_lnd_tunables(settings,
6123                                                                                   &ni->ni_lnd_tunables,
6124                                                                                   net->net_lnd);
6125                                                 if (rc < 0) {
6126                                                         GENL_SET_ERR_MSG(info,
6127                                                                          "failed to parse lnd tunables");
6128                                                         lnet_net_unlock(LNET_LOCK_EX);
6129                                                         GOTO(out, rc);
6130                                                 }
6131                                         }
6132                                 }
6133                                 lnet_net_unlock(LNET_LOCK_EX);
6134                         } else {
6135                                 lnd = lnet_load_lnd(LNET_NETTYP(net_id));
6136                                 if (IS_ERR(lnd)) {
6137                                         GENL_SET_ERR_MSG(info,
6138                                                          "LND type not supported");
6139                                         GOTO(out, rc = PTR_ERR(lnd));
6140                                 }
6141
6142                                 rc = lnet_genl_parse_lnd_tunables(settings,
6143                                                                   &tun->lt_tun, lnd);
6144                                 if (rc < 0) {
6145                                         GENL_SET_ERR_MSG(info,
6146                                                          "failed to parse lnd tunables");
6147                                         GOTO(out, rc);
6148                                 }
6149                         }
6150                 } else if (nla_strcmp(settings, "CPT") == 0) {
6151                         struct nlattr *cpt;
6152                         int rem4;
6153
6154                         settings = nla_next(settings, &rem3);
6155                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
6156                                 GENL_SET_ERR_MSG(info,
6157                                                  "CPT should be list");
6158                                 GOTO(out, rc = -EINVAL);
6159                         }
6160
6161                         nla_for_each_nested(cpt, settings, rem4) {
6162                                 s64 core;
6163
6164                                 if (nla_type(cpt) !=
6165                                     LN_SCALAR_ATTR_INT_VALUE) {
6166                                         GENL_SET_ERR_MSG(info,
6167                                                          "invalid CPT config");
6168                                         GOTO(out, rc = -EINVAL);
6169                                 }
6170
6171                                 core = nla_get_s64(cpt);
6172                                 if (core >= LNET_CPT_NUMBER) {
6173                                         GENL_SET_ERR_MSG(info,
6174                                                          "invalid CPT value");
6175                                         GOTO(out, rc = -ERANGE);
6176                                 }
6177
6178                                 conf->lic_cpts[conf->lic_ncpts] = core;
6179                                 conf->lic_ncpts++;
6180                         }
6181                 }
6182         }
6183
6184         if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6185                 if (nid_same(&nid, &LNET_ANY_NID) &&
6186                     !strlen(conf->lic_ni_intf)) {
6187                         GENL_SET_ERR_MSG(info,
6188                                          "interface / NID is missing");
6189                         GOTO(out, rc);
6190                 }
6191
6192                 rc = lnet_dyn_add_ni(conf, net_id, &nid, tun);
6193                 switch (rc) {
6194                 case -ENOENT:
6195                         GENL_SET_ERR_MSG(info,
6196                                          "cannot parse net");
6197                         break;
6198                 case -ERANGE:
6199                         GENL_SET_ERR_MSG(info,
6200                                          "invalid CPT set");
6201                         break;
6202                 default:
6203                         GENL_SET_ERR_MSG(info,
6204                                          "cannot add LNet NI");
6205                 case 0:
6206                         break;
6207                 }
6208         } else if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE && healthv != -1) {
6209                 lnet_ni_set_healthv(&nid, healthv);
6210         } else if (!(info->nlhdr->nlmsg_flags & (NLM_F_CREATE | NLM_F_REPLACE))) {
6211                 struct lnet_ni *ni;
6212
6213                 /* delete case */
6214                 rc = -ENODEV;
6215                 if (!strlen(conf->lic_ni_intf) &&
6216                     nid_same(&nid, &LNET_ANY_NID)) {
6217                         GENL_SET_ERR_MSG(info,
6218                                          "interface / NID is missing");
6219                         GOTO(out, rc);
6220                 }
6221
6222                 if (nid_same(&nid, &LNET_ANY_NID)) {
6223                         struct lnet_net *net;
6224                         bool found = false;
6225
6226                         lnet_net_lock(LNET_LOCK_EX);
6227                         net = lnet_get_net_locked(net_id);
6228                         if (!net) {
6229                                 GENL_SET_ERR_MSG(info,
6230                                                  "LNet net doesn't exist");
6231                                 lnet_net_unlock(LNET_LOCK_EX);
6232                                 GOTO(out, rc);
6233                         }
6234
6235                         list_for_each_entry(ni, &net->net_ni_list,
6236                                             ni_netlist) {
6237                                 if (!ni->ni_interface ||
6238                                     strcmp(ni->ni_interface,
6239                                           conf->lic_ni_intf) != 0)
6240                                         continue;
6241
6242                                 found = true;
6243                                 lnet_net_unlock(LNET_LOCK_EX);
6244                                 rc = lnet_dyn_del_ni(&ni->ni_nid);
6245                                 break;
6246                         }
6247
6248                         if (rc < 0 && !found) { /* will be -ENODEV */
6249                                 GENL_SET_ERR_MSG(info,
6250                                                  "interface invalid for deleting LNet NI");
6251                                 lnet_net_unlock(LNET_LOCK_EX);
6252                         }
6253                 } else {
6254                         rc = lnet_dyn_del_ni(&nid);
6255                 }
6256
6257                 if (rc < 0) {
6258                         GENL_SET_ERR_MSG(info,
6259                                          "cannot del LNet NI");
6260                         GOTO(out, rc);
6261                 }
6262         }
6263 out:
6264         if (tun)
6265                 LIBCFS_FREE(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
6266
6267         return rc;
6268 }
6269
6270 static int lnet_net_cmd(struct sk_buff *skb, struct genl_info *info)
6271 {
6272         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6273         struct genlmsghdr *gnlh = nlmsg_data(nlh);
6274         struct nlattr *params = genlmsg_data(gnlh);
6275         int msg_len, rem, rc = 0;
6276         struct nlattr *attr;
6277
6278         msg_len = genlmsg_len(gnlh);
6279         if (!msg_len) {
6280                 GENL_SET_ERR_MSG(info, "no configuration");
6281                 return -ENOMSG;
6282         }
6283
6284         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
6285                 GENL_SET_ERR_MSG(info, "invalid configuration");
6286                 return -EINVAL;
6287         }
6288
6289         nla_for_each_nested(attr, params, rem) {
6290                 bool ni_list = false, ipnets = false;
6291                 struct lnet_ioctl_config_ni conf;
6292                 u32 net_id = LNET_NET_ANY;
6293                 struct nlattr *entry;
6294                 int rem2;
6295
6296                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6297                         continue;
6298
6299                 nla_for_each_nested(entry, attr, rem2) {
6300                         switch (nla_type(entry)) {
6301                         case LN_SCALAR_ATTR_VALUE: {
6302                                 ssize_t len;
6303
6304                                 memset(&conf, 0, sizeof(conf));
6305                                 if (nla_strcmp(entry, "ip2net") == 0) {
6306                                         entry = nla_next(entry, &rem2);
6307                                         if (nla_type(entry) !=
6308                                             LN_SCALAR_ATTR_VALUE) {
6309                                                 GENL_SET_ERR_MSG(info,
6310                                                                  "ip2net has invalid key");
6311                                                 GOTO(out, rc = -EINVAL);
6312                                         }
6313
6314                                         len = nla_strscpy(conf.lic_legacy_ip2nets,
6315                                                           entry,
6316                                                           sizeof(conf.lic_legacy_ip2nets));
6317                                         if (len < 0) {
6318                                                 GENL_SET_ERR_MSG(info,
6319                                                                  "ip2net key string is invalid");
6320                                                 GOTO(out, rc = len);
6321                                         }
6322                                         ni_list = true;
6323                                         ipnets = true;
6324                                 } else if (nla_strcmp(entry, "net type") == 0) {
6325                                         char tmp[LNET_NIDSTR_SIZE];
6326
6327                                         entry = nla_next(entry, &rem2);
6328                                         if (nla_type(entry) !=
6329                                             LN_SCALAR_ATTR_VALUE) {
6330                                                 GENL_SET_ERR_MSG(info,
6331                                                                  "net type has invalid key");
6332                                                 GOTO(out, rc = -EINVAL);
6333                                         }
6334
6335                                         len = nla_strscpy(tmp, entry,
6336                                                           sizeof(tmp));
6337                                         if (len < 0) {
6338                                                 GENL_SET_ERR_MSG(info,
6339                                                                  "net type key string is invalid");
6340                                                 GOTO(out, rc = len);
6341                                         }
6342
6343                                         net_id = libcfs_str2net(tmp);
6344                                         if (!net_id) {
6345                                                 GENL_SET_ERR_MSG(info,
6346                                                                  "cannot parse net");
6347                                                 GOTO(out, rc = -ENODEV);
6348                                         }
6349                                         if (LNET_NETTYP(net_id) == LOLND) {
6350                                                 GENL_SET_ERR_MSG(info,
6351                                                                  "setting @lo not allowed");
6352                                                 GOTO(out, rc = -ENODEV);
6353                                         }
6354                                         conf.lic_legacy_ip2nets[0] = '\0';
6355                                         conf.lic_ni_intf[0] = '\0';
6356                                         ni_list = false;
6357                                 }
6358                                 if (rc < 0)
6359                                         GOTO(out, rc);
6360                                 break;
6361                         }
6362                         case LN_SCALAR_ATTR_LIST: {
6363                                 struct nlattr *interface;
6364                                 int rem3;
6365
6366                                 ipnets = false;
6367                                 nla_for_each_nested(interface, entry, rem3) {
6368                                         rc = lnet_genl_parse_local_ni(interface, info,
6369                                                                       net_id, &conf,
6370                                                                       &ni_list);
6371                                         if (rc < 0)
6372                                                 GOTO(out, rc);
6373                                 }
6374                                 break;
6375                         }
6376                         /* it is possible a newer version of the user land send
6377                          * values older kernels doesn't handle. So silently
6378                          * ignore these values
6379                          */
6380                         default:
6381                                 break;
6382                         }
6383                 }
6384
6385                 /* Handle case of just sent NET with no list of NIDs */
6386                 if (!(info->nlhdr->nlmsg_flags & (NLM_F_CREATE | NLM_F_REPLACE)) &&
6387                     !ni_list) {
6388                         rc = lnet_dyn_del_net(net_id);
6389                         if (rc < 0) {
6390                                 GENL_SET_ERR_MSG(info,
6391                                                  "cannot del network");
6392                         }
6393                 } else if ((info->nlhdr->nlmsg_flags & NLM_F_CREATE) &&
6394                            ipnets && ni_list) {
6395                         rc = lnet_handle_legacy_ip2nets(conf.lic_legacy_ip2nets,
6396                                                         NULL);
6397                         if (rc < 0)
6398                                 GENL_SET_ERR_MSG(info,
6399                                                  "cannot setup ip2nets");
6400                 }
6401         }
6402 out:
6403         return rc;
6404 }
6405
6406 /* Called with ln_api_mutex */
6407 static int lnet_parse_peer_nis(struct nlattr *rlist, struct genl_info *info,
6408                                struct lnet_nid *pnid, bool mr,
6409                                bool *create_some)
6410 {
6411         struct lnet_nid snid = LNET_ANY_NID;
6412         struct nlattr *props;
6413         int rem, rc = 0;
6414         s64 num = -1;
6415
6416         nla_for_each_nested(props, rlist, rem) {
6417                 if (nla_type(props) != LN_SCALAR_ATTR_VALUE)
6418                         continue;
6419
6420                 if (nla_strcmp(props, "nid") == 0) {
6421                         char nidstr[LNET_NIDSTR_SIZE];
6422
6423                         props = nla_next(props, &rem);
6424                         if (nla_type(props) != LN_SCALAR_ATTR_VALUE) {
6425                                 GENL_SET_ERR_MSG(info,
6426                                                  "invalid secondary NID");
6427                                 GOTO(report_err, rc = -EINVAL);
6428                         }
6429
6430                         rc = nla_strscpy(nidstr, props, sizeof(nidstr));
6431                         if (rc < 0) {
6432                                 GENL_SET_ERR_MSG(info,
6433                                                  "failed to get secondary NID");
6434                                 GOTO(report_err, rc);
6435                         }
6436
6437                         rc = libcfs_strnid(&snid, strim(nidstr));
6438                         if (rc < 0) {
6439                                 GENL_SET_ERR_MSG(info, "unsupported secondary NID");
6440                                 GOTO(report_err, rc);
6441                         }
6442
6443                         if (LNET_NID_IS_ANY(&snid) || nid_same(&snid, pnid))
6444                                 *create_some = false;
6445                 } else if (nla_strcmp(props, "health stats") == 0) {
6446                         struct nlattr *health;
6447                         int rem2;
6448
6449                         props = nla_next(props, &rem);
6450                         if (nla_type(props) !=
6451                               LN_SCALAR_ATTR_LIST) {
6452                                 GENL_SET_ERR_MSG(info,
6453                                                  "invalid health configuration");
6454                                 GOTO(report_err, rc = -EINVAL);
6455                         }
6456
6457                         nla_for_each_nested(health, props, rem2) {
6458                                 if (nla_type(health) != LN_SCALAR_ATTR_VALUE ||
6459                                     nla_strcmp(health, "health value") != 0) {
6460                                         GENL_SET_ERR_MSG(info,
6461                                                          "wrong health config format");
6462                                         GOTO(report_err, rc = -EINVAL);
6463                                 }
6464
6465                                 health = nla_next(health, &rem2);
6466                                 if (nla_type(health) !=
6467                                     LN_SCALAR_ATTR_INT_VALUE) {
6468                                         GENL_SET_ERR_MSG(info,
6469                                                          "invalid health config format");
6470                                         GOTO(report_err, rc = -EINVAL);
6471                                 }
6472
6473                                 num = nla_get_s64(health);
6474                                 clamp_t(s64, num, 0, LNET_MAX_HEALTH_VALUE);
6475                         }
6476                 }
6477         }
6478
6479         if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE && num != -1) {
6480                 lnet_peer_ni_set_healthv(pnid, num, !*create_some);
6481         } else if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6482                 bool lock_prim = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6483
6484                 rc = lnet_user_add_peer_ni(pnid, &snid, mr, lock_prim);
6485                 if (rc < 0)
6486                         GENL_SET_ERR_MSG(info,
6487                                          "failed to add peer");
6488         } else if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE) && *create_some) {
6489                 bool force = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6490
6491                 rc = lnet_del_peer_ni(pnid, &snid, force);
6492                 if (rc < 0)
6493                         GENL_SET_ERR_MSG(info,
6494                                          "failed to del peer");
6495         }
6496 report_err:
6497         return rc;
6498 }
6499
6500 static int lnet_peer_ni_cmd(struct sk_buff *skb, struct genl_info *info)
6501 {
6502         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6503         struct genlmsghdr *gnlh = nlmsg_data(nlh);
6504         struct nlattr *params = genlmsg_data(gnlh);
6505         int msg_len, rem, rc = 0;
6506         struct lnet_nid pnid;
6507         struct nlattr *attr;
6508
6509         mutex_lock(&the_lnet.ln_api_mutex);
6510         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
6511                 GENL_SET_ERR_MSG(info, "Network is down");
6512                 mutex_unlock(&the_lnet.ln_api_mutex);
6513                 return -ENETDOWN;
6514         }
6515
6516         msg_len = genlmsg_len(gnlh);
6517         if (!msg_len) {
6518                 GENL_SET_ERR_MSG(info, "no configuration");
6519                 mutex_unlock(&the_lnet.ln_api_mutex);
6520                 return -ENOMSG;
6521         }
6522
6523         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
6524                 GENL_SET_ERR_MSG(info, "invalid configuration");
6525                 mutex_unlock(&the_lnet.ln_api_mutex);
6526                 return -EINVAL;
6527         }
6528
6529         nla_for_each_nested(attr, params, rem) {
6530                 bool parse_peer_nis = false;
6531                 struct nlattr *pnid_prop;
6532                 int rem2;
6533
6534                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6535                         continue;
6536
6537                 pnid = LNET_ANY_NID;
6538                 nla_for_each_nested(pnid_prop, attr, rem2) {
6539                         bool mr = true;
6540
6541                         if (nla_type(pnid_prop) != LN_SCALAR_ATTR_VALUE)
6542                                 continue;
6543
6544                         if (nla_strcmp(pnid_prop, "primary nid") == 0) {
6545                                 char nidstr[LNET_NIDSTR_SIZE];
6546
6547                                 pnid_prop = nla_next(pnid_prop, &rem2);
6548                                 if (nla_type(pnid_prop) !=
6549                                     LN_SCALAR_ATTR_VALUE) {
6550                                         GENL_SET_ERR_MSG(info,
6551                                                           "invalid primary NID type");
6552                                         GOTO(report_err, rc = -EINVAL);
6553                                 }
6554
6555                                 rc = nla_strscpy(nidstr, pnid_prop,
6556                                                  sizeof(nidstr));
6557                                 if (rc < 0) {
6558                                         GENL_SET_ERR_MSG(info,
6559                                                          "failed to get primary NID");
6560                                         GOTO(report_err, rc);
6561                                 }
6562
6563                                 rc = libcfs_strnid(&pnid, strim(nidstr));
6564                                 if (rc < 0) {
6565                                         GENL_SET_ERR_MSG(info,
6566                                                          "unsupported primary NID");
6567                                         GOTO(report_err, rc);
6568                                 }
6569
6570                                 /* we must create primary NID for peer ni
6571                                  * creation
6572                                  */
6573                                 if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6574                                         bool lock_prim;
6575
6576                                         lock_prim = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6577                                         rc = lnet_user_add_peer_ni(&pnid,
6578                                                                    &LNET_ANY_NID,
6579                                                                    true, lock_prim);
6580                                         if (rc < 0) {
6581                                                 GENL_SET_ERR_MSG(info,
6582                                                                  "failed to add primary peer");
6583                                                 GOTO(report_err, rc);
6584                                         }
6585                                 }
6586                         } else if (nla_strcmp(pnid_prop, "Multi-Rail") == 0) {
6587                                 pnid_prop = nla_next(pnid_prop, &rem2);
6588                                 if (nla_type(pnid_prop) !=
6589                                     LN_SCALAR_ATTR_INT_VALUE) {
6590                                         GENL_SET_ERR_MSG(info,
6591                                                           "invalid MR flag param");
6592                                         GOTO(report_err, rc = -EINVAL);
6593                                 }
6594
6595                                 if (nla_get_s64(pnid_prop) == 0)
6596                                         mr = false;
6597                         } else if (nla_strcmp(pnid_prop, "peer state") == 0) {
6598                                 struct lnet_peer_ni *lpni;
6599                                 struct lnet_peer *lp;
6600
6601                                 pnid_prop = nla_next(pnid_prop, &rem2);
6602                                 if (nla_type(pnid_prop) !=
6603                                     LN_SCALAR_ATTR_INT_VALUE) {
6604                                         GENL_SET_ERR_MSG(info,
6605                                                           "invalid peer state param");
6606                                         GOTO(report_err, rc = -EINVAL);
6607                                 }
6608
6609                                 lpni = lnet_peer_ni_find_locked(&pnid);
6610                                 if (!lpni) {
6611                                         GENL_SET_ERR_MSG(info,
6612                                                           "invalid peer state param");
6613                                         GOTO(report_err, rc = -ENOENT);
6614                                 }
6615                                 lnet_peer_ni_decref_locked(lpni);
6616                                 lp = lpni->lpni_peer_net->lpn_peer;
6617                                 lp->lp_state = nla_get_s64(pnid_prop);
6618                         } else if (nla_strcmp(pnid_prop, "peer ni") == 0) {
6619                                 struct nlattr *rlist;
6620                                 int rem3;
6621
6622                                 if (!(info->nlhdr->nlmsg_flags & NLM_F_REPLACE) &&
6623                                     LNET_NID_IS_ANY(&pnid)) {
6624                                         GENL_SET_ERR_MSG(info,
6625                                                          "missing required primary NID");
6626                                         GOTO(report_err, rc);
6627                                 }
6628
6629                                 pnid_prop = nla_next(pnid_prop, &rem2);
6630                                 if (nla_type(pnid_prop) !=
6631                                     LN_SCALAR_ATTR_LIST) {
6632                                         GENL_SET_ERR_MSG(info,
6633                                                           "invalid NIDs list");
6634                                         GOTO(report_err, rc = -EINVAL);
6635                                 }
6636
6637                                 parse_peer_nis = true;
6638                                 nla_for_each_nested(rlist, pnid_prop, rem3) {
6639                                         rc = lnet_parse_peer_nis(rlist, info,
6640                                                                  &pnid, mr,
6641                                                                  &parse_peer_nis);
6642                                         if (rc < 0)
6643                                                 GOTO(report_err, rc);
6644                                 }
6645                         }
6646                 }
6647
6648                 /* If we have remote peer ni's we already add /del peers */
6649                 if (parse_peer_nis)
6650                         continue;
6651
6652                 if (LNET_NID_IS_ANY(&pnid)) {
6653                         GENL_SET_ERR_MSG(info, "missing primary NID");
6654                         GOTO(report_err, rc);
6655                 }
6656
6657                 if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
6658                         bool force = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6659
6660                         rc = lnet_del_peer_ni(&pnid, &LNET_ANY_NID,
6661                                               force);
6662                         if (rc < 0) {
6663                                 GENL_SET_ERR_MSG(info,
6664                                                  "failed to del primary peer");
6665                                 GOTO(report_err, rc);
6666                         }
6667                 }
6668         }
6669 report_err:
6670         /* If we failed on creation and encounter a latter error then
6671          * delete the primary nid.
6672          */
6673         if (rc < 0 && info->nlhdr->nlmsg_flags & NLM_F_CREATE &&
6674             !LNET_NID_IS_ANY(&pnid))
6675                 lnet_del_peer_ni(&pnid, &LNET_ANY_NID,
6676                                  info->nlhdr->nlmsg_flags & NLM_F_EXCL);
6677         mutex_unlock(&the_lnet.ln_api_mutex);
6678
6679         return rc;
6680 }
6681
6682 /** LNet route handling */
6683
6684 /* We can't use struct lnet_ioctl_config_data since it lacks
6685  * support for large NIDS
6686  */
6687 struct lnet_route_properties {
6688         struct lnet_nid         lrp_gateway;
6689         u32                     lrp_net;
6690         s32                     lrp_hop;
6691         u32                     lrp_flags;
6692         u32                     lrp_priority;
6693         u32                     lrp_sensitivity;
6694 };
6695
6696 struct lnet_genl_route_list {
6697         unsigned int                            lgrl_index;
6698         unsigned int                            lgrl_count;
6699         GENRADIX(struct lnet_route_properties)  lgrl_list;
6700 };
6701
6702 static inline struct lnet_genl_route_list *
6703 lnet_route_dump_ctx(struct netlink_callback *cb)
6704 {
6705         return (struct lnet_genl_route_list *)cb->args[0];
6706 }
6707
6708 static int lnet_route_show_done(struct netlink_callback *cb)
6709 {
6710         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
6711
6712         if (rlist) {
6713                 genradix_free(&rlist->lgrl_list);
6714                 CFS_FREE_PTR(rlist);
6715         }
6716         cb->args[0] = 0;
6717
6718         return 0;
6719 }
6720
6721 static int lnet_scan_route(struct lnet_genl_route_list *rlist,
6722                     struct lnet_route_properties *settings)
6723 {
6724         struct lnet_remotenet *rnet;
6725         struct list_head *rn_list;
6726         struct lnet_route *route;
6727         int cpt, i, rc = 0;
6728
6729         cpt = lnet_net_lock_current();
6730
6731         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
6732                 rn_list = &the_lnet.ln_remote_nets_hash[i];
6733                 list_for_each_entry(rnet, rn_list, lrn_list) {
6734                         if (settings->lrp_net != LNET_NET_ANY &&
6735                             settings->lrp_net != rnet->lrn_net)
6736                                 continue;
6737
6738                         list_for_each_entry(route, &rnet->lrn_routes,
6739                                             lr_list) {
6740                                 struct lnet_route_properties *prop;
6741
6742                                 if (!LNET_NID_IS_ANY(&settings->lrp_gateway) &&
6743                                     !nid_same(&settings->lrp_gateway,
6744                                               &route->lr_nid)) {
6745                                         continue;
6746                                 }
6747
6748                                 if (settings->lrp_hop != -1 &&
6749                                     settings->lrp_hop != route->lr_hops)
6750                                         continue;
6751
6752                                 if (settings->lrp_priority != -1 &&
6753                                     settings->lrp_priority != route->lr_priority)
6754                                         continue;
6755
6756                                 if (settings->lrp_sensitivity != -1 &&
6757                                     settings->lrp_sensitivity !=
6758                                     route->lr_gateway->lp_health_sensitivity)
6759                                         continue;
6760
6761                                 prop = genradix_ptr_alloc(&rlist->lgrl_list,
6762                                                           rlist->lgrl_count++,
6763                                                           GFP_ATOMIC);
6764                                 if (!prop)
6765                                         GOTO(failed_alloc, rc = -ENOMEM);
6766
6767                                 prop->lrp_net = rnet->lrn_net;
6768                                 prop->lrp_gateway = route->lr_nid;
6769                                 prop->lrp_hop = route->lr_hops;
6770                                 prop->lrp_priority = route->lr_priority;
6771                                 prop->lrp_sensitivity =
6772                                         route->lr_gateway->lp_health_sensitivity;
6773                                 if (lnet_is_route_alive(route))
6774                                         prop->lrp_flags |= LNET_RT_ALIVE;
6775                                 else
6776                                         prop->lrp_flags &= ~LNET_RT_ALIVE;
6777                                 if (route->lr_single_hop)
6778                                         prop->lrp_flags &= ~LNET_RT_MULTI_HOP;
6779                                 else
6780                                         prop->lrp_flags |= LNET_RT_MULTI_HOP;
6781                         }
6782                 }
6783         }
6784
6785 failed_alloc:
6786         lnet_net_unlock(cpt);
6787         return rc;
6788 }
6789
6790 /* LNet route ->start() handler for GET requests */
6791 static int lnet_route_show_start(struct netlink_callback *cb)
6792 {
6793         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6794 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6795         struct netlink_ext_ack *extack = NULL;
6796 #endif
6797         struct lnet_genl_route_list *rlist;
6798         int msg_len = genlmsg_len(gnlh);
6799         int rc = 0;
6800
6801 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6802         extack = cb->extack;
6803 #endif
6804         if (the_lnet.ln_refcount == 0 ||
6805             the_lnet.ln_state != LNET_STATE_RUNNING) {
6806                 NL_SET_ERR_MSG(extack, "Network is down");
6807                 return -ENETDOWN;
6808         }
6809
6810         CFS_ALLOC_PTR(rlist);
6811         if (!rlist) {
6812                 NL_SET_ERR_MSG(extack, "No memory for route list");
6813                 return -ENOMEM;
6814         }
6815
6816         genradix_init(&rlist->lgrl_list);
6817         rlist->lgrl_count = 0;
6818         rlist->lgrl_index = 0;
6819         cb->args[0] = (long)rlist;
6820
6821         mutex_lock(&the_lnet.ln_api_mutex);
6822         if (!msg_len) {
6823                 struct lnet_route_properties tmp = {
6824                         .lrp_gateway            = LNET_ANY_NID,
6825                         .lrp_net                = LNET_NET_ANY,
6826                         .lrp_hop                = -1,
6827                         .lrp_priority           = -1,
6828                         .lrp_sensitivity        = -1,
6829                 };
6830
6831                 rc = lnet_scan_route(rlist, &tmp);
6832                 if (rc < 0) {
6833                         NL_SET_ERR_MSG(extack,
6834                                        "failed to allocate router data");
6835                         GOTO(report_err, rc);
6836                 }
6837         } else {
6838                 struct nlattr *params = genlmsg_data(gnlh);
6839                 struct nlattr *attr;
6840                 int rem;
6841
6842                 nla_for_each_nested(attr, params, rem) {
6843                         struct lnet_route_properties tmp = {
6844                                 .lrp_gateway            = LNET_ANY_NID,
6845                                 .lrp_net                = LNET_NET_ANY,
6846                                 .lrp_hop                = -1,
6847                                 .lrp_priority           = -1,
6848                                 .lrp_sensitivity        = -1,
6849                         };
6850                         struct nlattr *route;
6851                         int rem2;
6852
6853                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6854                                 continue;
6855
6856                         nla_for_each_nested(route, attr, rem2) {
6857                                 if (nla_type(route) != LN_SCALAR_ATTR_VALUE)
6858                                         continue;
6859
6860                                 if (nla_strcmp(route, "net") == 0) {
6861                                         char nw[LNET_NIDSTR_SIZE];
6862
6863                                         route = nla_next(route, &rem2);
6864                                         if (nla_type(route) !=
6865                                             LN_SCALAR_ATTR_VALUE) {
6866                                                 NL_SET_ERR_MSG(extack,
6867                                                                "invalid net param");
6868                                                 GOTO(report_err, rc = -EINVAL);
6869                                         }
6870
6871                                         rc = nla_strscpy(nw, route, sizeof(nw));
6872                                         if (rc < 0) {
6873                                                 NL_SET_ERR_MSG(extack,
6874                                                                "failed to get route param");
6875                                                 GOTO(report_err, rc);
6876                                         }
6877                                         rc = 0;
6878                                         tmp.lrp_net = libcfs_str2net(strim(nw));
6879                                 } else if (nla_strcmp(route, "gateway") == 0) {
6880                                         char gw[LNET_NIDSTR_SIZE];
6881
6882                                         route = nla_next(route, &rem2);
6883                                         if (nla_type(route) !=
6884                                             LN_SCALAR_ATTR_VALUE) {
6885                                                 NL_SET_ERR_MSG(extack,
6886                                                                "invalid gateway param");
6887                                                 GOTO(report_err, rc = -EINVAL);
6888                                         }
6889
6890                                         rc = nla_strscpy(gw, route, sizeof(gw));
6891                                         if (rc < 0) {
6892                                                 NL_SET_ERR_MSG(extack,
6893                                                                "failed to get route param");
6894                                                 GOTO(report_err, rc);
6895                                         }
6896
6897                                         rc = libcfs_strnid(&tmp.lrp_gateway, strim(gw));
6898                                         if (rc < 0) {
6899                                                 NL_SET_ERR_MSG(extack,
6900                                                                "cannot parse gateway");
6901                                                 GOTO(report_err, rc = -ENODEV);
6902                                         }
6903                                         rc = 0;
6904                                 } else if (nla_strcmp(route, "hop") == 0) {
6905                                         route = nla_next(route, &rem2);
6906                                         if (nla_type(route) !=
6907                                             LN_SCALAR_ATTR_INT_VALUE) {
6908                                                 NL_SET_ERR_MSG(extack,
6909                                                                "invalid hop param");
6910                                                 GOTO(report_err, rc = -EINVAL);
6911                                         }
6912
6913                                         tmp.lrp_hop = nla_get_s64(route);
6914                                         if (tmp.lrp_hop != -1)
6915                                                 clamp_t(s32, tmp.lrp_hop, 1, 127);
6916                                 } else if (nla_strcmp(route, "priority") == 0) {
6917                                         route = nla_next(route, &rem2);
6918                                         if (nla_type(route) !=
6919                                             LN_SCALAR_ATTR_INT_VALUE) {
6920                                                 NL_SET_ERR_MSG(extack,
6921                                                                "invalid priority param");
6922                                                 GOTO(report_err, rc = -EINVAL);
6923                                         }
6924
6925                                         tmp.lrp_priority = nla_get_s64(route);
6926                                 }
6927                         }
6928
6929                         rc = lnet_scan_route(rlist, &tmp);
6930                         if (rc < 0) {
6931                                 NL_SET_ERR_MSG(extack,
6932                                                "failed to allocate router data");
6933                                 GOTO(report_err, rc);
6934                         }
6935                 }
6936         }
6937 report_err:
6938         mutex_unlock(&the_lnet.ln_api_mutex);
6939
6940         if (rc < 0)
6941                 lnet_route_show_done(cb);
6942
6943         return rc;
6944 }
6945
6946 static const struct ln_key_list route_props_list = {
6947         .lkl_maxattr                    = LNET_ROUTE_ATTR_MAX,
6948         .lkl_list                       = {
6949                 [LNET_ROUTE_ATTR_HDR]                   = {
6950                         .lkp_value                      = "route",
6951                         .lkp_key_format                 = LNKF_SEQUENCE | LNKF_MAPPING,
6952                         .lkp_data_type                  = NLA_NUL_STRING,
6953                 },
6954                 [LNET_ROUTE_ATTR_NET]                   = {
6955                         .lkp_value                      = "net",
6956                         .lkp_data_type                  = NLA_STRING
6957                 },
6958                 [LNET_ROUTE_ATTR_GATEWAY]               = {
6959                         .lkp_value                      = "gateway",
6960                         .lkp_data_type                  = NLA_STRING
6961                 },
6962                 [LNET_ROUTE_ATTR_HOP]                   = {
6963                         .lkp_value                      = "hop",
6964                         .lkp_data_type                  = NLA_S32
6965                 },
6966                 [LNET_ROUTE_ATTR_PRIORITY]              = {
6967                         .lkp_value                      = "priority",
6968                         .lkp_data_type                  = NLA_U32
6969                 },
6970                 [LNET_ROUTE_ATTR_HEALTH_SENSITIVITY]    = {
6971                         .lkp_value                      = "health_sensitivity",
6972                         .lkp_data_type                  = NLA_U32
6973                 },
6974                 [LNET_ROUTE_ATTR_STATE] = {
6975                         .lkp_value                      = "state",
6976                         .lkp_data_type                  = NLA_STRING,
6977                 },
6978                 [LNET_ROUTE_ATTR_TYPE]  = {
6979                         .lkp_value                      = "type",
6980                         .lkp_data_type                  = NLA_STRING,
6981                 },
6982         },
6983 };
6984
6985
6986 static int lnet_route_show_dump(struct sk_buff *msg,
6987                                 struct netlink_callback *cb)
6988 {
6989         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
6990         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6991 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6992         struct netlink_ext_ack *extack = NULL;
6993 #endif
6994         int portid = NETLINK_CB(cb->skb).portid;
6995         int seq = cb->nlh->nlmsg_seq;
6996         int idx = rlist->lgrl_index;
6997         int msg_len = genlmsg_len(gnlh);
6998         int rc = 0;
6999
7000 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7001         extack = cb->extack;
7002 #endif
7003         if (!rlist->lgrl_count) {
7004                 NL_SET_ERR_MSG(extack, "No routes found");
7005                 GOTO(send_error, rc = msg_len ? -ENOENT : 0);
7006         }
7007
7008         if (!idx) {
7009                 const struct ln_key_list *all[] = {
7010                         &route_props_list, NULL
7011                 };
7012
7013                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
7014                                                 &lnet_family,
7015                                                 NLM_F_CREATE | NLM_F_MULTI,
7016                                                 LNET_CMD_ROUTES, all);
7017                 if (rc < 0) {
7018                         NL_SET_ERR_MSG(extack, "failed to send key table");
7019                         GOTO(send_error, rc);
7020                 }
7021         }
7022
7023         while (idx < rlist->lgrl_count) {
7024                 struct lnet_route_properties *prop;
7025                 void *hdr;
7026
7027                 prop = genradix_ptr(&rlist->lgrl_list, idx++);
7028
7029                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
7030                                   NLM_F_MULTI, LNET_CMD_ROUTES);
7031                 if (!hdr) {
7032                         NL_SET_ERR_MSG(extack, "failed to send values");
7033                         genlmsg_cancel(msg, hdr);
7034                         GOTO(send_error, rc = -EMSGSIZE);
7035                 }
7036
7037                 if (idx == 1)
7038                         nla_put_string(msg, LNET_ROUTE_ATTR_HDR, "");
7039
7040                 nla_put_string(msg, LNET_ROUTE_ATTR_NET,
7041                                libcfs_net2str(prop->lrp_net));
7042                 nla_put_string(msg, LNET_ROUTE_ATTR_GATEWAY,
7043                                libcfs_nidstr(&prop->lrp_gateway));
7044                 if (gnlh->version) {
7045                         nla_put_s32(msg, LNET_ROUTE_ATTR_HOP, prop->lrp_hop);
7046                         nla_put_u32(msg, LNET_ROUTE_ATTR_PRIORITY, prop->lrp_priority);
7047                         nla_put_u32(msg, LNET_ROUTE_ATTR_HEALTH_SENSITIVITY,
7048                                     prop->lrp_sensitivity);
7049
7050                         if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)) {
7051                                 nla_put_string(msg, LNET_ROUTE_ATTR_STATE,
7052                                                prop->lrp_flags & LNET_RT_ALIVE ?
7053                                                "up" : "down");
7054                                 nla_put_string(msg, LNET_ROUTE_ATTR_TYPE,
7055                                                prop->lrp_flags & LNET_RT_MULTI_HOP ?
7056                                                "multi-hop" : "single-hop");
7057                         }
7058                 }
7059                 genlmsg_end(msg, hdr);
7060         }
7061         rlist->lgrl_index = idx;
7062 send_error:
7063         return lnet_nl_send_error(cb->skb, portid, seq, rc);
7064 };
7065
7066 #ifndef HAVE_NETLINK_CALLBACK_START
7067 static int lnet_old_route_show_dump(struct sk_buff *msg,
7068                                     struct netlink_callback *cb)
7069 {
7070         if (!cb->args[0]) {
7071                 int rc = lnet_route_show_start(cb);
7072
7073                 if (rc < 0)
7074                         return lnet_nl_send_error(cb->skb,
7075                                                   NETLINK_CB(cb->skb).portid,
7076                                                   cb->nlh->nlmsg_seq,
7077                                                   rc);
7078         }
7079
7080         return lnet_route_show_dump(msg, cb);
7081 }
7082 #endif /* !HAVE_NETLINK_CALLBACK_START */
7083
7084 /** LNet peer handling */
7085 struct lnet_genl_processid_list {
7086         unsigned int                    lgpl_index;
7087         unsigned int                    lgpl_count;
7088         GENRADIX(struct lnet_processid) lgpl_list;
7089 };
7090
7091 static inline struct lnet_genl_processid_list *
7092 lnet_peer_dump_ctx(struct netlink_callback *cb)
7093 {
7094         return (struct lnet_genl_processid_list *)cb->args[0];
7095 }
7096
7097 static int lnet_peer_ni_show_done(struct netlink_callback *cb)
7098 {
7099         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
7100
7101         if (plist) {
7102                 genradix_free(&plist->lgpl_list);
7103                 CFS_FREE_PTR(plist);
7104         }
7105         cb->args[0] = 0;
7106
7107         return 0;
7108 }
7109
7110 /* LNet peer ->start() handler for GET requests */
7111 static int lnet_peer_ni_show_start(struct netlink_callback *cb)
7112 {
7113         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7114 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7115         struct netlink_ext_ack *extack = NULL;
7116 #endif
7117         struct lnet_genl_processid_list *plist;
7118         int msg_len = genlmsg_len(gnlh);
7119         int rc = 0;
7120
7121 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7122         extack = cb->extack;
7123 #endif
7124         mutex_lock(&the_lnet.ln_api_mutex);
7125         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7126                 NL_SET_ERR_MSG(extack, "Network is down");
7127                 mutex_unlock(&the_lnet.ln_api_mutex);
7128                 return -ENETDOWN;
7129         }
7130
7131         CFS_ALLOC_PTR(plist);
7132         if (!plist) {
7133                 NL_SET_ERR_MSG(extack, "No memory for peer list");
7134                 mutex_unlock(&the_lnet.ln_api_mutex);
7135                 return -ENOMEM;
7136         }
7137
7138         genradix_init(&plist->lgpl_list);
7139         plist->lgpl_count = 0;
7140         plist->lgpl_index = 0;
7141         cb->args[0] = (long)plist;
7142
7143         if (!msg_len) {
7144                 struct lnet_peer_table *ptable;
7145                 int cpt;
7146
7147                 cfs_percpt_for_each(ptable, cpt, the_lnet.ln_peer_tables) {
7148                         struct lnet_peer *lp;
7149
7150                         list_for_each_entry(lp, &ptable->pt_peer_list,
7151                                             lp_peer_list) {
7152                                 struct lnet_processid *lpi;
7153
7154                                 lpi = genradix_ptr_alloc(&plist->lgpl_list,
7155                                                          plist->lgpl_count++,
7156                                                          GFP_KERNEL);
7157                                 if (!lpi) {
7158                                         NL_SET_ERR_MSG(extack,
7159                                                       "failed to allocate NID");
7160                                         GOTO(report_err, rc = -ENOMEM);
7161                                 }
7162
7163                                 lpi->pid = LNET_PID_LUSTRE;
7164                                 lpi->nid = lp->lp_primary_nid;
7165                         }
7166                 }
7167         } else {
7168                 struct nlattr *params = genlmsg_data(gnlh);
7169                 struct nlattr *attr;
7170                 int rem;
7171
7172                 nla_for_each_nested(attr, params, rem) {
7173                         struct nlattr *nid;
7174                         int rem2;
7175
7176                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
7177                                 continue;
7178
7179                         nla_for_each_nested(nid, attr, rem2) {
7180                                 char addr[LNET_NIDSTR_SIZE];
7181                                 struct lnet_processid *id;
7182
7183                                 if (nla_type(nid) != LN_SCALAR_ATTR_VALUE ||
7184                                     nla_strcmp(nid, "primary nid") != 0)
7185                                         continue;
7186
7187                                 nid = nla_next(nid, &rem2);
7188                                 if (nla_type(nid) != LN_SCALAR_ATTR_VALUE) {
7189                                         NL_SET_ERR_MSG(extack,
7190                                                        "invalid primary nid param");
7191                                         GOTO(report_err, rc = -EINVAL);
7192                                 }
7193
7194                                 rc = nla_strscpy(addr, nid, sizeof(addr));
7195                                 if (rc < 0) {
7196                                         NL_SET_ERR_MSG(extack,
7197                                                        "failed to get primary nid param");
7198                                         GOTO(report_err, rc);
7199                                 }
7200
7201                                 id = genradix_ptr_alloc(&plist->lgpl_list,
7202                                                         plist->lgpl_count++,
7203                                                         GFP_KERNEL);
7204                                 if (!id) {
7205                                         NL_SET_ERR_MSG(extack, "failed to allocate NID");
7206                                         GOTO(report_err, rc = -ENOMEM);
7207                                 }
7208
7209                                 rc = libcfs_strid(id, strim(addr));
7210                                 if (rc < 0) {
7211                                         NL_SET_ERR_MSG(extack, "invalid NID");
7212                                         GOTO(report_err, rc);
7213                                 }
7214                                 rc = 0;
7215                         }
7216                 }
7217         }
7218 report_err:
7219         mutex_unlock(&the_lnet.ln_api_mutex);
7220
7221         if (rc < 0)
7222                 lnet_peer_ni_show_done(cb);
7223
7224         return rc;
7225 }
7226
7227 static const struct ln_key_list lnet_peer_ni_keys = {
7228         .lkl_maxattr                    = LNET_PEER_NI_ATTR_MAX,
7229         .lkl_list                       = {
7230                 [LNET_PEER_NI_ATTR_HDR]  = {
7231                         .lkp_value              = "peer",
7232                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
7233                         .lkp_data_type          = NLA_NUL_STRING,
7234                 },
7235                 [LNET_PEER_NI_ATTR_PRIMARY_NID] = {
7236                         .lkp_value              = "primary nid",
7237                         .lkp_data_type          = NLA_STRING,
7238                 },
7239                 [LNET_PEER_NI_ATTR_MULTIRAIL]   = {
7240                         .lkp_value              = "Multi-Rail",
7241                         .lkp_data_type          = NLA_FLAG
7242                 },
7243                 [LNET_PEER_NI_ATTR_STATE]       = {
7244                         .lkp_value              = "peer state",
7245                         .lkp_data_type          = NLA_U32
7246                 },
7247                 [LNET_PEER_NI_ATTR_PEER_NI_LIST] = {
7248                         .lkp_value              = "peer ni",
7249                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
7250                         .lkp_data_type          = NLA_NESTED,
7251                 },
7252         },
7253 };
7254
7255 static const struct ln_key_list lnet_peer_ni_list = {
7256         .lkl_maxattr                    = LNET_PEER_NI_LIST_ATTR_MAX,
7257         .lkl_list                       = {
7258                 [LNET_PEER_NI_LIST_ATTR_NID]            = {
7259                         .lkp_value                      = "nid",
7260                         .lkp_data_type                  = NLA_STRING,
7261                 },
7262                 [LNET_PEER_NI_LIST_ATTR_UDSP_INFO]      = {
7263                         .lkp_value                      = "udsp info",
7264                         .lkp_key_format                 = LNKF_MAPPING,
7265                         .lkp_data_type                  = NLA_NESTED,
7266                 },
7267                 [LNET_PEER_NI_LIST_ATTR_STATE]          = {
7268                         .lkp_value                      = "state",
7269                         .lkp_data_type                  = NLA_STRING,
7270                 },
7271                 [LNET_PEER_NI_LIST_ATTR_MAX_TX_CREDITS] = {
7272                         .lkp_value                      = "max_ni_tx_credits",
7273                         .lkp_data_type                  = NLA_U32,
7274                 },
7275                 [LNET_PEER_NI_LIST_ATTR_CUR_TX_CREDITS] = {
7276                         .lkp_value                      = "available_tx_credits",
7277                         .lkp_data_type                  = NLA_U32,
7278                 },
7279                 [LNET_PEER_NI_LIST_ATTR_MIN_TX_CREDITS] = {
7280                         .lkp_value                      = "min_tx_credits",
7281                         .lkp_data_type                  = NLA_U32,
7282                 },
7283                 [LNET_PEER_NI_LIST_ATTR_QUEUE_BUF_COUNT] = {
7284                         .lkp_value                      = "tx_q_num_of_buf",
7285                         .lkp_data_type                  = NLA_U32,
7286                 },
7287                 [LNET_PEER_NI_LIST_ATTR_CUR_RTR_CREDITS] = {
7288                         .lkp_value                      = "available_rtr_credits",
7289                         .lkp_data_type                  = NLA_U32,
7290                 },
7291                 [LNET_PEER_NI_LIST_ATTR_MIN_RTR_CREDITS] = {
7292                         .lkp_value                      = "min_rtr_credits",
7293                         .lkp_data_type                  = NLA_U32,
7294                 },
7295                 [LNET_PEER_NI_LIST_ATTR_REFCOUNT]       = {
7296                         .lkp_value                      = "refcount",
7297                         .lkp_data_type                  = NLA_U32,
7298                 },
7299                 [LNET_PEER_NI_LIST_ATTR_STATS_COUNT]    = {
7300                         .lkp_value                      = "statistics",
7301                         .lkp_key_format                 = LNKF_MAPPING,
7302                         .lkp_data_type                  = NLA_NESTED
7303                 },
7304                 [LNET_PEER_NI_LIST_ATTR_SENT_STATS]     = {
7305                         .lkp_value                      = "sent_stats",
7306                         .lkp_key_format                 = LNKF_MAPPING,
7307                         .lkp_data_type                  = NLA_NESTED
7308                 },
7309                 [LNET_PEER_NI_LIST_ATTR_RECV_STATS]     = {
7310                         .lkp_value                      = "received_stats",
7311                         .lkp_key_format                 = LNKF_MAPPING,
7312                         .lkp_data_type                  = NLA_NESTED
7313                 },
7314                 [LNET_PEER_NI_LIST_ATTR_DROP_STATS]     = {
7315                         .lkp_value                      = "dropped_stats",
7316                         .lkp_key_format                 = LNKF_MAPPING,
7317                         .lkp_data_type                  = NLA_NESTED
7318                 },
7319                 [LNET_PEER_NI_LIST_ATTR_HEALTH_STATS]   = {
7320                         .lkp_value                      = "health stats",
7321                         .lkp_key_format                 = LNKF_MAPPING,
7322                         .lkp_data_type                  = NLA_NESTED
7323                 },
7324         },
7325 };
7326
7327 static const struct ln_key_list lnet_peer_ni_list_stats_count = {
7328         .lkl_maxattr                    = LNET_PEER_NI_LIST_STATS_COUNT_ATTR_MAX,
7329         .lkl_list                       = {
7330                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_SEND_COUNT] = {
7331                         .lkp_value                              = "send_count",
7332                         .lkp_data_type                          = NLA_U32,
7333                 },
7334                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_RECV_COUNT] = {
7335                         .lkp_value                              = "recv_count",
7336                         .lkp_data_type                          = NLA_U32,
7337                 },
7338                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_DROP_COUNT] = {
7339                         .lkp_value                              = "drop_count",
7340                         .lkp_data_type                          = NLA_U32,
7341                 },
7342         },
7343 };
7344
7345 static const struct ln_key_list lnet_peer_ni_list_stats = {
7346         .lkl_maxattr                    = LNET_PEER_NI_LIST_STATS_ATTR_MAX,
7347         .lkl_list                       = {
7348                 [LNET_PEER_NI_LIST_STATS_ATTR_PUT]      = {
7349                         .lkp_value                      = "put",
7350                         .lkp_data_type                  = NLA_U32,
7351                 },
7352                 [LNET_PEER_NI_LIST_STATS_ATTR_GET]      = {
7353                         .lkp_value                      = "get",
7354                         .lkp_data_type                  = NLA_U32,
7355                 },
7356                 [LNET_PEER_NI_LIST_STATS_ATTR_REPLY]    = {
7357                         .lkp_value                      = "reply",
7358                         .lkp_data_type                  = NLA_U32,
7359                 },
7360                 [LNET_PEER_NI_LIST_STATS_ATTR_ACK]      = {
7361                         .lkp_value                      = "ack",
7362                         .lkp_data_type                  = NLA_U32,
7363                 },
7364                 [LNET_PEER_NI_LIST_STATS_ATTR_HELLO]    = {
7365                         .lkp_value                      = "hello",
7366                         .lkp_data_type                  = NLA_U32,
7367                 },
7368         },
7369 };
7370
7371 static const struct ln_key_list lnet_peer_ni_list_health = {
7372         .lkl_maxattr                    = LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_MAX,
7373         .lkl_list                       = {
7374                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_VALUE]     = {
7375                         .lkp_value                      = "health value",
7376                         .lkp_data_type                  = NLA_S32,
7377                 },
7378                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_DROPPED]   = {
7379                         .lkp_value                      = "dropped",
7380                         .lkp_data_type                  = NLA_U32,
7381                 },
7382                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_TIMEOUT]   = {
7383                         .lkp_value                      = "timeout",
7384                         .lkp_data_type                  = NLA_U32,
7385                 },
7386                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_ERROR]     = {
7387                         .lkp_value                      = "error",
7388                         .lkp_data_type                  = NLA_U32,
7389                 },
7390                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NETWORK_TIMEOUT] = {
7391                         .lkp_value                      = "network timeout",
7392                         .lkp_data_type                  = NLA_U32,
7393                 },
7394                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PING_COUNT] = {
7395                         .lkp_value                      = "ping_count",
7396                         .lkp_data_type                  = NLA_U32,
7397                 },
7398                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NEXT_PING] = {
7399                         .lkp_value                      = "next_ping",
7400                         .lkp_data_type                  = NLA_S64,
7401                 },
7402         },
7403 };
7404
7405 static int lnet_peer_ni_show_dump(struct sk_buff *msg,
7406                                   struct netlink_callback *cb)
7407 {
7408         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
7409         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7410 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7411         struct netlink_ext_ack *extack = NULL;
7412 #endif
7413         int portid = NETLINK_CB(cb->skb).portid;
7414         int seq = cb->nlh->nlmsg_seq;
7415         int idx = plist->lgpl_index;
7416         int msg_len = genlmsg_len(gnlh);
7417         int rc = 0;
7418
7419 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7420         extack = cb->extack;
7421 #endif
7422         if (!plist->lgpl_count) {
7423                 NL_SET_ERR_MSG(extack, "No peers found");
7424                 GOTO(send_error, rc = msg_len ? -ENOENT : 0);
7425         }
7426
7427         if (!idx) {
7428                 const struct ln_key_list *all[] = {
7429                         &lnet_peer_ni_keys, &lnet_peer_ni_list,
7430                         &udsp_info_list, &udsp_info_pref_nids_list,
7431                         &udsp_info_pref_nids_list,
7432                         &lnet_peer_ni_list_stats_count,
7433                         &lnet_peer_ni_list_stats, /* send_stats */
7434                         &lnet_peer_ni_list_stats, /* recv_stats */
7435                         &lnet_peer_ni_list_stats, /* drop stats */
7436                         &lnet_peer_ni_list_health,
7437                         NULL
7438                 };
7439
7440                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
7441                                                 &lnet_family,
7442                                                 NLM_F_CREATE | NLM_F_MULTI,
7443                                                 LNET_CMD_PEERS, all);
7444                 if (rc < 0) {
7445                         NL_SET_ERR_MSG(extack, "failed to send key table");
7446                         GOTO(send_error, rc);
7447                 }
7448         }
7449
7450         mutex_lock(&the_lnet.ln_api_mutex);
7451         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7452                 NL_SET_ERR_MSG(extack, "Network is down");
7453                 GOTO(unlock_api_mutex, rc = -ENETDOWN);
7454         }
7455
7456         while (idx < plist->lgpl_count) {
7457                 struct lnet_processid *id;
7458                 struct lnet_peer_ni *lpni = NULL;
7459                 struct nlattr *nid_list;
7460                 struct lnet_peer *lp;
7461                 int count = 1;
7462                 void *hdr;
7463
7464                 id = genradix_ptr(&plist->lgpl_list, idx++);
7465                 if (nid_is_lo0(&id->nid))
7466                         continue;
7467
7468                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
7469                                   NLM_F_MULTI, LNET_CMD_PEERS);
7470                 if (!hdr) {
7471                         NL_SET_ERR_MSG(extack, "failed to send values");
7472                         genlmsg_cancel(msg, hdr);
7473                         GOTO(unlock_api_mutex, rc = -EMSGSIZE);
7474                 }
7475
7476                 lp = lnet_find_peer(&id->nid);
7477                 if (!lp) {
7478                         NL_SET_ERR_MSG(extack, "cannot find peer");
7479                         GOTO(unlock_api_mutex, rc = -ENOENT);
7480                 }
7481
7482                 if (idx == 1)
7483                         nla_put_string(msg, LNET_PEER_NI_ATTR_HDR, "");
7484
7485                 nla_put_string(msg, LNET_PEER_NI_ATTR_PRIMARY_NID,
7486                                libcfs_nidstr(&lp->lp_primary_nid));
7487                 if (lnet_peer_is_multi_rail(lp))
7488                         nla_put_flag(msg, LNET_PEER_NI_ATTR_MULTIRAIL);
7489
7490                 if (gnlh->version >= 3)
7491                         nla_put_u32(msg, LNET_PEER_NI_ATTR_STATE, lp->lp_state);
7492
7493                 nid_list = nla_nest_start(msg, LNET_PEER_NI_ATTR_PEER_NI_LIST);
7494                 while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
7495                         struct nlattr *peer_nid = nla_nest_start(msg, count++);
7496
7497                         nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_NID,
7498                                        libcfs_nidstr(&lpni->lpni_nid));
7499
7500                         if (gnlh->version >= 4) {
7501                                 rc = lnet_udsp_info_send(msg,
7502                                                          LNET_PEER_NI_LIST_ATTR_UDSP_INFO,
7503                                                          &lpni->lpni_nid, true);
7504                                 if (rc < 0) {
7505                                         lnet_peer_decref_locked(lp);
7506                                         NL_SET_ERR_MSG(extack,
7507                                                        "failed to get UDSP info");
7508                                         GOTO(unlock_api_mutex, rc);
7509                                 }
7510                         }
7511
7512                         if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)
7513                                 goto skip_state;
7514
7515                         if (lnet_isrouter(lpni) ||
7516                             lnet_peer_aliveness_enabled(lpni)) {
7517                                 nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_STATE,
7518                                                lnet_is_peer_ni_alive(lpni) ?
7519                                                "up" : "down");
7520                         } else {
7521                                 nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_STATE,
7522                                                "NA");
7523                         }
7524 skip_state:
7525                         if (gnlh->version) {
7526                                 struct lnet_ioctl_element_msg_stats lpni_msg_stats;
7527                                 struct nlattr *send_stats_list, *send_stats;
7528                                 struct nlattr *recv_stats_list, *recv_stats;
7529                                 struct nlattr *drop_stats_list, *drop_stats;
7530                                 struct nlattr *health_list, *health_stats;
7531                                 struct lnet_ioctl_element_stats stats;
7532                                 struct nlattr *stats_attr, *ni_stats;
7533
7534                                 nla_put_u32(msg,
7535                                             LNET_PEER_NI_LIST_ATTR_MAX_TX_CREDITS,
7536                                             lpni->lpni_net ?
7537                                                 lpni->lpni_net->net_tunables.lct_peer_tx_credits : 0);
7538                                 nla_put_u32(msg,
7539                                             LNET_PEER_NI_LIST_ATTR_CUR_TX_CREDITS,
7540                                             lpni->lpni_txcredits);
7541                                 nla_put_u32(msg,
7542                                             LNET_PEER_NI_LIST_ATTR_MIN_TX_CREDITS,
7543                                             lpni->lpni_mintxcredits);
7544                                 nla_put_u32(msg,
7545                                             LNET_PEER_NI_LIST_ATTR_QUEUE_BUF_COUNT,
7546                                             lpni->lpni_txqnob);
7547                                 nla_put_u32(msg,
7548                                             LNET_PEER_NI_LIST_ATTR_CUR_RTR_CREDITS,
7549                                             lpni->lpni_rtrcredits);
7550                                 nla_put_u32(msg,
7551                                             LNET_PEER_NI_LIST_ATTR_MIN_RTR_CREDITS,
7552                                             lpni->lpni_minrtrcredits);
7553                                 nla_put_u32(msg,
7554                                             LNET_PEER_NI_LIST_ATTR_REFCOUNT,
7555                                             kref_read(&lpni->lpni_kref));
7556
7557                                 memset(&stats, 0, sizeof(stats));
7558                                 stats.iel_send_count = lnet_sum_stats(&lpni->lpni_stats,
7559                                                                       LNET_STATS_TYPE_SEND);
7560                                 stats.iel_recv_count = lnet_sum_stats(&lpni->lpni_stats,
7561                                                                       LNET_STATS_TYPE_RECV);
7562                                 stats.iel_drop_count = lnet_sum_stats(&lpni->lpni_stats,
7563                                                                       LNET_STATS_TYPE_DROP);
7564
7565                                 stats_attr = nla_nest_start(msg,
7566                                                             LNET_PEER_NI_LIST_ATTR_STATS_COUNT);
7567                                 ni_stats = nla_nest_start(msg, 0);
7568                                 nla_put_u32(msg,
7569                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_SEND_COUNT,
7570                                             stats.iel_send_count);
7571                                 nla_put_u32(msg,
7572                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_RECV_COUNT,
7573                                             stats.iel_recv_count);
7574                                 nla_put_u32(msg,
7575                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_DROP_COUNT,
7576                                             stats.iel_drop_count);
7577                                 nla_nest_end(msg, ni_stats);
7578                                 nla_nest_end(msg, stats_attr);
7579
7580                                 if (gnlh->version < 2)
7581                                         goto skip_msg_stats;
7582
7583                                 lnet_usr_translate_stats(&lpni_msg_stats, &lpni->lpni_stats);
7584
7585                                 send_stats_list = nla_nest_start(msg,
7586                                                                  LNET_PEER_NI_LIST_ATTR_SENT_STATS);
7587                                 send_stats = nla_nest_start(msg, 0);
7588                                 nla_put_u32(msg,
7589                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7590                                             lpni_msg_stats.im_send_stats.ico_put_count);
7591                                 nla_put_u32(msg,
7592                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7593                                             lpni_msg_stats.im_send_stats.ico_get_count);
7594                                 nla_put_u32(msg,
7595                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7596                                             lpni_msg_stats.im_send_stats.ico_reply_count);
7597                                 nla_put_u32(msg,
7598                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7599                                             lpni_msg_stats.im_send_stats.ico_ack_count);
7600                                 nla_put_u32(msg,
7601                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7602                                             lpni_msg_stats.im_send_stats.ico_hello_count);
7603                                 nla_nest_end(msg, send_stats);
7604                                 nla_nest_end(msg, send_stats_list);
7605
7606                                 recv_stats_list = nla_nest_start(msg,
7607                                                                  LNET_PEER_NI_LIST_ATTR_RECV_STATS);
7608                                 recv_stats = nla_nest_start(msg, 0);
7609                                 nla_put_u32(msg,
7610                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7611                                             lpni_msg_stats.im_recv_stats.ico_put_count);
7612                                 nla_put_u32(msg,
7613                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7614                                             lpni_msg_stats.im_recv_stats.ico_get_count);
7615                                 nla_put_u32(msg,
7616                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7617                                             lpni_msg_stats.im_recv_stats.ico_reply_count);
7618                                 nla_put_u32(msg,
7619                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7620                                             lpni_msg_stats.im_recv_stats.ico_ack_count);
7621                                 nla_put_u32(msg,
7622                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7623                                             lpni_msg_stats.im_recv_stats.ico_hello_count);
7624                                 nla_nest_end(msg, recv_stats);
7625                                 nla_nest_end(msg, recv_stats_list);
7626
7627                                 drop_stats_list = nla_nest_start(msg,
7628                                                                  LNET_PEER_NI_LIST_ATTR_DROP_STATS);
7629                                 drop_stats = nla_nest_start(msg, 0);
7630                                 nla_put_u32(msg,
7631                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7632                                             lpni_msg_stats.im_drop_stats.ico_put_count);
7633                                 nla_put_u32(msg,
7634                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7635                                             lpni_msg_stats.im_drop_stats.ico_get_count);
7636                                 nla_put_u32(msg,
7637                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7638                                             lpni_msg_stats.im_drop_stats.ico_reply_count);
7639                                 nla_put_u32(msg,
7640                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7641                                             lpni_msg_stats.im_drop_stats.ico_ack_count);
7642                                 nla_put_u32(msg,
7643                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7644                                             lpni_msg_stats.im_drop_stats.ico_hello_count);
7645                                 nla_nest_end(msg, drop_stats);
7646                                 nla_nest_end(msg, drop_stats_list);
7647
7648                                 health_list = nla_nest_start(msg,
7649                                                              LNET_PEER_NI_LIST_ATTR_HEALTH_STATS);
7650                                 health_stats = nla_nest_start(msg, 0);
7651                                 nla_put_s32(msg,
7652                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_VALUE,
7653                                             atomic_read(&lpni->lpni_healthv));
7654                                 nla_put_u32(msg,
7655                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_DROPPED,
7656                                             atomic_read(&lpni->lpni_hstats.hlt_remote_dropped));
7657                                 nla_put_u32(msg,
7658                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_TIMEOUT,
7659                                             atomic_read(&lpni->lpni_hstats.hlt_remote_timeout));
7660                                 nla_put_u32(msg,
7661                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_ERROR,
7662                                             atomic_read(&lpni->lpni_hstats.hlt_remote_error));
7663                                 nla_put_u32(msg,
7664                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NETWORK_TIMEOUT,
7665                                             atomic_read(&lpni->lpni_hstats.hlt_network_timeout));
7666                                 nla_put_u32(msg,
7667                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PING_COUNT,
7668                                             lpni->lpni_ping_count);
7669                                 nla_put_s64(msg,
7670                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NEXT_PING,
7671                                             lpni->lpni_next_ping,
7672                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PAD);
7673                                 nla_nest_end(msg, health_stats);
7674                                 nla_nest_end(msg, health_list);
7675                         }
7676 skip_msg_stats:
7677                         nla_nest_end(msg, peer_nid);
7678                 }
7679                 nla_nest_end(msg, nid_list);
7680
7681                 genlmsg_end(msg, hdr);
7682                 lnet_peer_decref_locked(lp);
7683         }
7684         plist->lgpl_index = idx;
7685 unlock_api_mutex:
7686         mutex_unlock(&the_lnet.ln_api_mutex);
7687 send_error:
7688         return lnet_nl_send_error(cb->skb, portid, seq, rc);
7689 };
7690
7691 #ifndef HAVE_NETLINK_CALLBACK_START
7692 static int lnet_old_peer_ni_show_dump(struct sk_buff *msg,
7693                                       struct netlink_callback *cb)
7694 {
7695         if (!cb->args[0]) {
7696                 int rc = lnet_peer_ni_show_start(cb);
7697
7698                 if (rc < 0)
7699                         return lnet_nl_send_error(cb->skb,
7700                                                   NETLINK_CB(cb->skb).portid,
7701                                                   cb->nlh->nlmsg_seq,
7702                                                   rc);
7703         }
7704
7705         return lnet_peer_ni_show_dump(msg, cb);
7706 }
7707 #endif
7708
7709 static int lnet_route_cmd(struct sk_buff *skb, struct genl_info *info)
7710 {
7711         struct nlmsghdr *nlh = nlmsg_hdr(skb);
7712         struct genlmsghdr *gnlh = nlmsg_data(nlh);
7713         struct nlattr *params = genlmsg_data(gnlh);
7714         int msg_len, rem, rc = 0;
7715         struct nlattr *attr;
7716
7717         mutex_lock(&the_lnet.ln_api_mutex);
7718         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7719                 GENL_SET_ERR_MSG(info, "Network is down");
7720                 mutex_unlock(&the_lnet.ln_api_mutex);
7721                 return -ENETDOWN;
7722         }
7723
7724         msg_len = genlmsg_len(gnlh);
7725         if (!msg_len) {
7726                 GENL_SET_ERR_MSG(info, "no configuration");
7727                 mutex_unlock(&the_lnet.ln_api_mutex);
7728                 return -ENOMSG;
7729         }
7730
7731         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
7732                 GENL_SET_ERR_MSG(info, "invalid configuration");
7733                 mutex_unlock(&the_lnet.ln_api_mutex);
7734                 return -EINVAL;
7735         }
7736
7737         nla_for_each_nested(attr, params, rem) {
7738                 u32 net_id = LNET_NET_ANY, hops = LNET_UNDEFINED_HOPS;
7739                 u32 priority = 0, sensitivity = 1;
7740                 struct lnet_nid gw_nid = LNET_ANY_NID;
7741                 struct nlattr *route_prop;
7742                 bool alive = true;
7743                 s64 when = 0;
7744                 int rem2;
7745
7746                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
7747                         continue;
7748
7749                 nla_for_each_nested(route_prop, attr, rem2) {
7750                         char tmp[LNET_NIDSTR_SIZE];
7751                         ssize_t len;
7752                         s64 num;
7753
7754                         if (nla_type(route_prop) != LN_SCALAR_ATTR_VALUE)
7755                                 continue;
7756
7757                         if (nla_strcmp(route_prop, "net") == 0) {
7758                                 route_prop = nla_next(route_prop, &rem2);
7759                                 if (nla_type(route_prop) !=
7760                                     LN_SCALAR_ATTR_VALUE) {
7761                                         GENL_SET_ERR_MSG(info,
7762                                                          "net is invalid key");
7763                                         GOTO(report_err, rc = -EINVAL);
7764                                 }
7765
7766                                 len = nla_strscpy(tmp, route_prop, sizeof(tmp));
7767                                 if (len < 0) {
7768                                         GENL_SET_ERR_MSG(info,
7769                                                          "net key string is invalid");
7770                                         GOTO(report_err, rc = len);
7771                                 }
7772
7773                                 net_id = libcfs_str2net(tmp);
7774                                 if (!net_id) {
7775                                         GENL_SET_ERR_MSG(info,
7776                                                          "cannot parse remote net");
7777                                         GOTO(report_err, rc = -ENODEV);
7778                                 }
7779
7780                                 if (LNET_NETTYP(net_id) == LOLND) {
7781                                         GENL_SET_ERR_MSG(info,
7782                                                          "setting @lo not allowed");
7783                                         GOTO(report_err, rc = -EACCES);
7784                                 }
7785
7786                                 if (net_id == LNET_NET_ANY) {
7787                                         GENL_SET_ERR_MSG(info,
7788                                                          "setting LNET_NET_ANY not allowed");
7789                                         GOTO(report_err, rc = -ENXIO);
7790                                 }
7791                         } else if (nla_strcmp(route_prop, "gateway") == 0) {
7792                                 route_prop = nla_next(route_prop, &rem2);
7793                                 if (nla_type(route_prop) !=
7794                                     LN_SCALAR_ATTR_VALUE) {
7795                                         GENL_SET_ERR_MSG(info,
7796                                                          "gateway is invalid key");
7797                                         GOTO(report_err, rc = -EINVAL);
7798                                 }
7799
7800                                 len = nla_strscpy(tmp, route_prop, sizeof(tmp));
7801                                 if (len < 0) {
7802                                         GENL_SET_ERR_MSG(info,
7803                                                          "gateway string is invalid");
7804                                         GOTO(report_err, rc = len);
7805                                 }
7806
7807                                 rc = libcfs_strnid(&gw_nid, strim(tmp));
7808                                 if (rc < 0) {
7809                                         GENL_SET_ERR_MSG(info,
7810                                                          "cannot parse gateway");
7811                                         GOTO(report_err, rc = -ENODEV);
7812                                 }
7813                         } else if (nla_strcmp(route_prop, "state") == 0) {
7814                                 route_prop = nla_next(route_prop, &rem2);
7815                                 if (nla_type(route_prop) !=
7816                                     LN_SCALAR_ATTR_VALUE) {
7817                                         GENL_SET_ERR_MSG(info,
7818                                                          "state is invalid key");
7819                                         GOTO(report_err, rc = -EINVAL);
7820                                 }
7821
7822                                 if (nla_strcmp(route_prop, "down") == 0) {
7823                                         alive = false;
7824                                 } else if (nla_strcmp(route_prop, "up") == 0) {
7825                                         alive = true;
7826                                 } else {
7827                                         GENL_SET_ERR_MSG(info,
7828                                                          "status string bad value");
7829                                         GOTO(report_err, rc = -EINVAL);
7830                                 }
7831                         } else if (nla_strcmp(route_prop, "notify_time") == 0) {
7832                                 route_prop = nla_next(route_prop, &rem2);
7833                                 if (nla_type(route_prop) !=
7834                                     LN_SCALAR_ATTR_INT_VALUE) {
7835                                         GENL_SET_ERR_MSG(info,
7836                                                          "notify_time is invalid key");
7837                                         GOTO(report_err, rc = -EINVAL);
7838                                 }
7839
7840                                 when = nla_get_s64(route_prop);
7841                                 if (ktime_get_real_seconds() < when) {
7842                                         GENL_SET_ERR_MSG(info,
7843                                                          "notify_time is in the future");
7844                                         GOTO(report_err, rc = -EINVAL);
7845                                 }
7846                         } else if (nla_strcmp(route_prop, "hop") == 0) {
7847                                 route_prop = nla_next(route_prop, &rem2);
7848                                 if (nla_type(route_prop) !=
7849                                     LN_SCALAR_ATTR_INT_VALUE) {
7850                                         GENL_SET_ERR_MSG(info,
7851                                                          "hop has invalid key");
7852                                         GOTO(report_err, rc = -EINVAL);
7853                                 }
7854
7855                                 hops = nla_get_s64(route_prop);
7856                                 if ((hops < 1 || hops > 255) && hops != -1) {
7857                                         GENL_SET_ERR_MSG(info,
7858                                                          "invalid hop count must be between 1 and 255");
7859                                         GOTO(report_err, rc = -EINVAL);
7860                                 }
7861                         } else if (nla_strcmp(route_prop, "priority") == 0) {
7862                                 route_prop = nla_next(route_prop, &rem2);
7863                                 if (nla_type(route_prop) !=
7864                                     LN_SCALAR_ATTR_INT_VALUE) {
7865                                         GENL_SET_ERR_MSG(info,
7866                                                          "priority has invalid key");
7867                                         GOTO(report_err, rc = -EINVAL);
7868                                 }
7869
7870                                 num = nla_get_s64(route_prop);
7871                                 if (num < 0) {
7872                                         GENL_SET_ERR_MSG(info,
7873                                                          "invalid priority, must not be negative");
7874                                         GOTO(report_err, rc = -EINVAL);
7875                                 }
7876                                 priority = num;
7877                         } else if (nla_strcmp(route_prop,
7878                                               "health_sensitivity") == 0) {
7879                                 route_prop = nla_next(route_prop, &rem2);
7880                                 if (nla_type(route_prop) !=
7881                                     LN_SCALAR_ATTR_INT_VALUE) {
7882                                         GENL_SET_ERR_MSG(info,
7883                                                          "sensitivity has invalid key");
7884                                         GOTO(report_err, rc = -EINVAL);
7885                                 }
7886
7887                                 num = nla_get_s64(route_prop);
7888                                 if (num < 1) {
7889                                         GENL_SET_ERR_MSG(info,
7890                                                          "invalid health sensitivity, must be 1 or greater");
7891                                         GOTO(report_err, rc = -EINVAL);
7892                                 }
7893                                 sensitivity = num;
7894                         }
7895                 }
7896
7897                 if (net_id == LNET_NET_ANY) {
7898                         GENL_SET_ERR_MSG(info,
7899                                          "missing mandatory parameter: network");
7900                         GOTO(report_err, rc = -ENODEV);
7901                 }
7902
7903                 if (LNET_NID_IS_ANY(&gw_nid)) {
7904                         GENL_SET_ERR_MSG(info,
7905                                          "missing mandatory parameter: gateway");
7906                         GOTO(report_err, rc = -ENODEV);
7907                 }
7908
7909                 if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE) {
7910                         /* Convert the user-supplied real time to monotonic.
7911                          * NB: "when" is always in the past
7912                          */
7913                         when = ktime_get_seconds() -
7914                                 (ktime_get_real_seconds() - when);
7915
7916                         mutex_unlock(&the_lnet.ln_api_mutex);
7917                         rc = lnet_notify(NULL, &gw_nid, alive, false, when);
7918                         mutex_lock(&the_lnet.ln_api_mutex);
7919                         if (rc < 0)
7920                                 GOTO(report_err, rc);
7921                         else if (the_lnet.ln_state != LNET_STATE_RUNNING)
7922                                 GOTO(report_err, rc = -ENETDOWN);
7923                 } else if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
7924                         rc = lnet_add_route(net_id, hops, &gw_nid, priority,
7925                                             sensitivity);
7926                         if (rc < 0) {
7927                                 switch (rc) {
7928                                 case -EINVAL:
7929                                         GENL_SET_ERR_MSG(info,
7930                                                          "invalid settings for route creation");
7931                                         break;
7932                                 case -EHOSTUNREACH:
7933                                         GENL_SET_ERR_MSG(info,
7934                                                          "No interface configured on the same net as gateway");
7935                                         break;
7936                                 case -ESHUTDOWN:
7937                                         GENL_SET_ERR_MSG(info,
7938                                                          "Network is down");
7939                                         break;
7940                                 case -EEXIST:
7941                                         GENL_SET_ERR_MSG(info,
7942                                                          "Route already exists or the specified network is local");
7943                                         break;
7944                                 default:
7945                                         GENL_SET_ERR_MSG(info,
7946                                                          "failed to create route");
7947                                         break;
7948                                 }
7949                                 GOTO(report_err, rc);
7950                         }
7951                 } else if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
7952                         rc = lnet_del_route(net_id, &gw_nid);
7953                         if (rc < 0) {
7954                                 GENL_SET_ERR_MSG(info,
7955                                                  "failed to delete route");
7956                                 GOTO(report_err, rc);
7957                         }
7958                 }
7959         }
7960 report_err:
7961         mutex_unlock(&the_lnet.ln_api_mutex);
7962
7963         return rc;
7964 }
7965
7966 static inline struct lnet_genl_ping_list *
7967 lnet_ping_dump_ctx(struct netlink_callback *cb)
7968 {
7969         return (struct lnet_genl_ping_list *)cb->args[0];
7970 }
7971
7972 static int lnet_ping_show_done(struct netlink_callback *cb)
7973 {
7974         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
7975
7976         if (plist) {
7977                 genradix_free(&plist->lgpl_failed);
7978                 genradix_free(&plist->lgpl_list);
7979                 LIBCFS_FREE(plist, sizeof(*plist));
7980                 cb->args[0] = 0;
7981         }
7982
7983         return 0;
7984 }
7985
7986 /* LNet ping ->start() handler for GET requests */
7987 static int lnet_ping_show_start(struct netlink_callback *cb)
7988 {
7989         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7990 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7991         struct netlink_ext_ack *extack = NULL;
7992 #endif
7993         struct lnet_genl_ping_list *plist;
7994         int msg_len = genlmsg_len(gnlh);
7995         struct nlattr *params, *top;
7996         int rem, rc = 0;
7997
7998 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7999         extack = cb->extack;
8000 #endif
8001         if (the_lnet.ln_refcount == 0) {
8002                 NL_SET_ERR_MSG(extack, "Network is down");
8003                 return -ENETDOWN;
8004         }
8005
8006         if (!msg_len) {
8007                 NL_SET_ERR_MSG(extack, "Ping needs NID targets");
8008                 return -ENOENT;
8009         }
8010
8011         LIBCFS_ALLOC(plist, sizeof(*plist));
8012         if (!plist) {
8013                 NL_SET_ERR_MSG(extack, "failed to setup ping list");
8014                 return -ENOMEM;
8015         }
8016         genradix_init(&plist->lgpl_list);
8017         plist->lgpl_timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
8018         plist->lgpl_src_nid = LNET_ANY_NID;
8019         plist->lgpl_index = 0;
8020         plist->lgpl_list_count = 0;
8021         cb->args[0] = (long)plist;
8022
8023         params = genlmsg_data(gnlh);
8024         nla_for_each_attr(top, params, msg_len, rem) {
8025                 struct nlattr *nids;
8026                 int rem2;
8027
8028                 switch (nla_type(top)) {
8029                 case LN_SCALAR_ATTR_VALUE:
8030                         if (nla_strcmp(top, "timeout") == 0) {
8031                                 s64 timeout;
8032
8033                                 top = nla_next(top, &rem);
8034                                 if (nla_type(top) != LN_SCALAR_ATTR_INT_VALUE) {
8035                                         NL_SET_ERR_MSG(extack,
8036                                                        "invalid timeout param");
8037                                         GOTO(report_err, rc = -EINVAL);
8038                                 }
8039
8040                                 /* If timeout is negative then set default of
8041                                  * 3 minutes
8042                                  */
8043                                 timeout = nla_get_s64(top);
8044                                 if (timeout > 0 &&
8045                                     timeout < (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
8046                                         plist->lgpl_timeout =
8047                                                 nsecs_to_jiffies(timeout * NSEC_PER_MSEC);
8048                         } else if (nla_strcmp(top, "source") == 0) {
8049                                 char nidstr[LNET_NIDSTR_SIZE + 1];
8050
8051                                 top = nla_next(top, &rem);
8052                                 if (nla_type(top) != LN_SCALAR_ATTR_VALUE) {
8053                                         NL_SET_ERR_MSG(extack,
8054                                                        "invalid source param");
8055                                         GOTO(report_err, rc = -EINVAL);
8056                                 }
8057
8058                                 rc = nla_strscpy(nidstr, top, sizeof(nidstr));
8059                                 if (rc < 0) {
8060                                         NL_SET_ERR_MSG(extack,
8061                                                        "failed to parse source nid");
8062                                         GOTO(report_err, rc);
8063                                 }
8064
8065                                 rc = libcfs_strnid(&plist->lgpl_src_nid,
8066                                                    strim(nidstr));
8067                                 if (rc < 0) {
8068                                         NL_SET_ERR_MSG(extack,
8069                                                        "invalid source nid");
8070                                         GOTO(report_err, rc);
8071                                 }
8072                                 rc = 0;
8073                         }
8074                         break;
8075                 case LN_SCALAR_ATTR_LIST:
8076                         nla_for_each_nested(nids, top, rem2) {
8077                                 char nid[LNET_NIDSTR_SIZE + 1];
8078                                 struct lnet_processid *id;
8079
8080                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8081                                         continue;
8082
8083                                 memset(nid, 0, sizeof(nid));
8084                                 rc = nla_strscpy(nid, nids, sizeof(nid));
8085                                 if (rc < 0) {
8086                                         NL_SET_ERR_MSG(extack,
8087                                                        "failed to get NID");
8088                                         GOTO(report_err, rc);
8089                                 }
8090
8091                                 id = genradix_ptr_alloc(&plist->lgpl_list,
8092                                                         plist->lgpl_list_count++,
8093                                                         GFP_KERNEL);
8094                                 if (!id) {
8095                                         NL_SET_ERR_MSG(extack,
8096                                                        "failed to allocate NID");
8097                                         GOTO(report_err, rc = -ENOMEM);
8098                                 }
8099
8100                                 rc = libcfs_strid(id, strim(nid));
8101                                 if (rc < 0) {
8102                                         NL_SET_ERR_MSG(extack, "cannot parse NID");
8103                                         GOTO(report_err, rc);
8104                                 }
8105                                 rc = 0;
8106                         }
8107                         fallthrough;
8108                 default:
8109                         break;
8110                 }
8111         }
8112 report_err:
8113         if (rc < 0)
8114                 lnet_ping_show_done(cb);
8115
8116         return rc;
8117 }
8118
8119 static const struct ln_key_list ping_err_props_list = {
8120         .lkl_maxattr                    = LNET_ERR_ATTR_MAX,
8121         .lkl_list                       = {
8122                 [LNET_ERR_ATTR_HDR]             = {
8123                         .lkp_value              = "manage",
8124                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8125                         .lkp_data_type          = NLA_NUL_STRING,
8126                 },
8127                 [LNET_ERR_ATTR_TYPE]            = {
8128                         .lkp_value              = "ping",
8129                         .lkp_data_type          = NLA_STRING,
8130                 },
8131                 [LNET_ERR_ATTR_ERRNO]           = {
8132                         .lkp_value              = "errno",
8133                         .lkp_data_type          = NLA_S16,
8134                 },
8135                 [LNET_ERR_ATTR_DESCR]           = {
8136                         .lkp_value              = "descr",
8137                         .lkp_data_type          = NLA_STRING,
8138                 },
8139         },
8140 };
8141
8142 static const struct ln_key_list ping_props_list = {
8143         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
8144         .lkl_list                       = {
8145                 [LNET_PING_ATTR_HDR]            = {
8146                         .lkp_value              = "ping",
8147                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8148                         .lkp_data_type          = NLA_NUL_STRING,
8149                 },
8150                 [LNET_PING_ATTR_PRIMARY_NID]    = {
8151                         .lkp_value              = "primary nid",
8152                         .lkp_data_type          = NLA_STRING
8153                 },
8154                 [LNET_PING_ATTR_ERRNO]          = {
8155                         .lkp_value              = "errno",
8156                         .lkp_data_type          = NLA_S16
8157                 },
8158                 [LNET_PING_ATTR_MULTIRAIL]      = {
8159                         .lkp_value              = "Multi-Rail",
8160                         .lkp_data_type          = NLA_FLAG
8161                 },
8162                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
8163                         .lkp_value              = "peer_ni",
8164                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8165                         .lkp_data_type          = NLA_NESTED
8166                 },
8167         },
8168 };
8169
8170 static const struct ln_key_list ping_peer_ni_list = {
8171         .lkl_maxattr                    = LNET_PING_PEER_NI_ATTR_MAX,
8172         .lkl_list                       = {
8173                 [LNET_PING_PEER_NI_ATTR_NID]    = {
8174                         .lkp_value              = "nid",
8175                         .lkp_data_type          = NLA_STRING
8176                 },
8177         },
8178 };
8179
8180 static int lnet_ping_show_dump(struct sk_buff *msg,
8181                                struct netlink_callback *cb)
8182 {
8183         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
8184 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8185         struct netlink_ext_ack *extack = NULL;
8186 #endif
8187         int portid = NETLINK_CB(cb->skb).portid;
8188         int seq = cb->nlh->nlmsg_seq;
8189         int idx = plist->lgpl_index;
8190         int rc = 0, i = 0;
8191
8192 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8193         extack = cb->extack;
8194 #endif
8195         if (!plist->lgpl_index) {
8196                 const struct ln_key_list *all[] = {
8197                         &ping_props_list, &ping_peer_ni_list, NULL
8198                 };
8199
8200                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
8201                                                 &lnet_family,
8202                                                 NLM_F_CREATE | NLM_F_MULTI,
8203                                                 LNET_CMD_PING, all);
8204                 if (rc < 0) {
8205                         NL_SET_ERR_MSG(extack, "failed to send key table");
8206                         GOTO(send_error, rc);
8207                 }
8208
8209                 genradix_init(&plist->lgpl_failed);
8210         }
8211
8212         while (idx < plist->lgpl_list_count) {
8213                 struct lnet_nid primary_nid = LNET_ANY_NID;
8214                 struct lnet_genl_ping_list peers;
8215                 struct lnet_processid *id;
8216                 struct nlattr *nid_list;
8217                 struct lnet_peer *lp;
8218                 bool mr_flag = false;
8219                 unsigned int count;
8220                 void *hdr = NULL;
8221
8222                 id = genradix_ptr(&plist->lgpl_list, idx++);
8223
8224                 rc = lnet_ping(id, &plist->lgpl_src_nid, plist->lgpl_timeout,
8225                                &peers, lnet_interfaces_max);
8226                 if (rc < 0) {
8227                         struct lnet_fail_ping *fail;
8228
8229                         fail = genradix_ptr_alloc(&plist->lgpl_failed,
8230                                                   plist->lgpl_failed_count++,
8231                                                   GFP_KERNEL);
8232                         if (!fail) {
8233                                 NL_SET_ERR_MSG(extack,
8234                                                "failed to allocate failed NID");
8235                                 GOTO(send_error, rc);
8236                         }
8237                         memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8238                         snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8239                                  "failed to ping %s",
8240                                  libcfs_nidstr(&id->nid));
8241                         fail->lfp_id = *id;
8242                         fail->lfp_errno = rc;
8243                         goto cant_reach;
8244                 }
8245
8246                 mutex_lock(&the_lnet.ln_api_mutex);
8247                 lp = lnet_find_peer(&id->nid);
8248                 if (lp) {
8249                         primary_nid = lp->lp_primary_nid;
8250                         mr_flag = lnet_peer_is_multi_rail(lp);
8251                         lnet_peer_decref_locked(lp);
8252                 }
8253                 mutex_unlock(&the_lnet.ln_api_mutex);
8254
8255                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8256                                   NLM_F_MULTI, LNET_CMD_PING);
8257                 if (!hdr) {
8258                         NL_SET_ERR_MSG(extack, "failed to send values");
8259                         genlmsg_cancel(msg, hdr);
8260                         GOTO(send_error, rc = -EMSGSIZE);
8261                 }
8262
8263                 if (i++ == 0)
8264                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
8265
8266                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
8267                                libcfs_nidstr(&primary_nid));
8268                 if (mr_flag)
8269                         nla_put_flag(msg, LNET_PING_ATTR_MULTIRAIL);
8270
8271                 nid_list = nla_nest_start(msg, LNET_PING_ATTR_PEER_NI_LIST);
8272                 for (count = 0; count < rc; count++) {
8273                         struct lnet_processid *result;
8274                         struct nlattr *nid_attr;
8275                         char *idstr;
8276
8277                         result = genradix_ptr(&peers.lgpl_list, count);
8278                         if (nid_is_lo0(&result->nid))
8279                                 continue;
8280
8281                         nid_attr = nla_nest_start(msg, count + 1);
8282                         if (id->pid == LNET_PID_LUSTRE)
8283                                 idstr = libcfs_nidstr(&result->nid);
8284                         else
8285                                 idstr = libcfs_idstr(result);
8286                         nla_put_string(msg, LNET_PING_PEER_NI_ATTR_NID, idstr);
8287                         nla_nest_end(msg, nid_attr);
8288                 }
8289                 nla_nest_end(msg, nid_list);
8290                 genlmsg_end(msg, hdr);
8291 cant_reach:
8292                 genradix_free(&peers.lgpl_list);
8293         }
8294
8295         if (plist->lgpl_failed_count) {
8296                 int flags = NLM_F_CREATE | NLM_F_REPLACE | NLM_F_MULTI;
8297                 const struct ln_key_list *fail[] = {
8298                         &ping_err_props_list, NULL
8299                 };
8300
8301                 rc = lnet_genl_send_scalar_list(msg, portid, seq, &lnet_family,
8302                                                 flags, LNET_CMD_PING, fail);
8303                 if (rc < 0) {
8304                         NL_SET_ERR_MSG(extack,
8305                                        "failed to send new key table");
8306                         GOTO(send_error, rc);
8307                 }
8308
8309                 for (i = 0; i < plist->lgpl_failed_count; i++) {
8310                         struct lnet_fail_ping *fail;
8311                         void *hdr;
8312
8313                         fail = genradix_ptr(&plist->lgpl_failed, i);
8314
8315                         hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8316                                           NLM_F_MULTI, LNET_CMD_PING);
8317                         if (!hdr) {
8318                                 NL_SET_ERR_MSG(extack,
8319                                                "failed to send failed values");
8320                                 genlmsg_cancel(msg, hdr);
8321                                 GOTO(send_error, rc = -EMSGSIZE);
8322                         }
8323
8324                         if (i == 0)
8325                                 nla_put_string(msg, LNET_ERR_ATTR_HDR, "");
8326
8327                         nla_put_string(msg, LNET_ERR_ATTR_TYPE, "\n");
8328                         nla_put_s16(msg, LNET_ERR_ATTR_ERRNO,
8329                                     fail->lfp_errno);
8330                         nla_put_string(msg, LNET_ERR_ATTR_DESCR,
8331                                        fail->lfp_msg);
8332                         genlmsg_end(msg, hdr);
8333                 }
8334         }
8335         genradix_free(&plist->lgpl_list);
8336         rc = 0; /* don't treat it as an error */
8337
8338         plist->lgpl_index = idx;
8339 send_error:
8340         return lnet_nl_send_error(cb->skb, portid, seq, rc);
8341 }
8342
8343 #ifndef HAVE_NETLINK_CALLBACK_START
8344 static int lnet_old_ping_show_dump(struct sk_buff *msg,
8345                                    struct netlink_callback *cb)
8346 {
8347         if (!cb->args[0]) {
8348                 int rc = lnet_ping_show_start(cb);
8349
8350                 if (rc < 0)
8351                         return lnet_nl_send_error(cb->skb,
8352                                                   NETLINK_CB(cb->skb).portid,
8353                                                   cb->nlh->nlmsg_seq,
8354                                                   rc);
8355         }
8356
8357         return lnet_ping_show_dump(msg, cb);
8358 }
8359 #endif
8360
8361 static const struct ln_key_list discover_err_props_list = {
8362         .lkl_maxattr                    = LNET_ERR_ATTR_MAX,
8363         .lkl_list                       = {
8364                 [LNET_ERR_ATTR_HDR]             = {
8365                         .lkp_value              = "manage",
8366                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8367                         .lkp_data_type          = NLA_NUL_STRING,
8368                 },
8369                 [LNET_ERR_ATTR_TYPE]            = {
8370                         .lkp_value              = "discover",
8371                         .lkp_data_type          = NLA_STRING,
8372                 },
8373                 [LNET_ERR_ATTR_ERRNO]           = {
8374                         .lkp_value              = "errno",
8375                         .lkp_data_type          = NLA_S16,
8376                 },
8377                 [LNET_ERR_ATTR_DESCR]           = {
8378                         .lkp_value              = "descr",
8379                         .lkp_data_type          = NLA_STRING,
8380                 },
8381         },
8382 };
8383
8384 static const struct ln_key_list discover_props_list = {
8385         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
8386         .lkl_list                       = {
8387                 [LNET_PING_ATTR_HDR]            = {
8388                         .lkp_value              = "discover",
8389                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8390                         .lkp_data_type          = NLA_NUL_STRING,
8391                 },
8392                 [LNET_PING_ATTR_PRIMARY_NID]    = {
8393                         .lkp_value              = "primary nid",
8394                         .lkp_data_type          = NLA_STRING
8395                 },
8396                 [LNET_PING_ATTR_ERRNO]          = {
8397                         .lkp_value              = "errno",
8398                         .lkp_data_type          = NLA_S16
8399                 },
8400                 [LNET_PING_ATTR_MULTIRAIL]      = {
8401                         .lkp_value              = "Multi-Rail",
8402                         .lkp_data_type          = NLA_FLAG
8403                 },
8404                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
8405                         .lkp_value              = "peer_ni",
8406                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8407                         .lkp_data_type          = NLA_NESTED
8408                 },
8409         },
8410 };
8411
8412 static int lnet_ping_cmd(struct sk_buff *skb, struct genl_info *info)
8413 {
8414         const struct ln_key_list *all[] = {
8415                 &discover_props_list, &ping_peer_ni_list, NULL
8416         };
8417         struct nlmsghdr *nlh = nlmsg_hdr(skb);
8418         struct genlmsghdr *gnlh = nlmsg_data(nlh);
8419         struct nlattr *params = genlmsg_data(gnlh);
8420         struct lnet_genl_ping_list dlists;
8421         int msg_len, rem, rc = 0, i;
8422         bool clear_hdr = false;
8423         struct sk_buff *reply;
8424         struct nlattr *attr;
8425         void *hdr = NULL;
8426
8427         msg_len = genlmsg_len(gnlh);
8428         if (!msg_len) {
8429                 GENL_SET_ERR_MSG(info, "no configuration");
8430                 return -ENOMSG;
8431         }
8432
8433         if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
8434                 GENL_SET_ERR_MSG(info, "only NLM_F_CREATE setting is allowed");
8435                 return -EINVAL;
8436         }
8437
8438         reply = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
8439         if (!reply) {
8440                 GENL_SET_ERR_MSG(info,
8441                                  "fail to allocate reply");
8442                 return -ENOMEM;
8443         }
8444
8445         genradix_init(&dlists.lgpl_failed);
8446         dlists.lgpl_failed_count = 0;
8447         genradix_init(&dlists.lgpl_list);
8448         dlists.lgpl_list_count = 0;
8449
8450         rc = lnet_genl_send_scalar_list(reply, info->snd_portid,
8451                                         info->snd_seq, &lnet_family,
8452                                         NLM_F_CREATE | NLM_F_MULTI,
8453                                         LNET_CMD_PING, all);
8454         if (rc < 0) {
8455                 GENL_SET_ERR_MSG(info,
8456                                  "failed to send key table");
8457                 GOTO(report_err, rc);
8458         }
8459
8460         nla_for_each_attr(attr, params, msg_len, rem) {
8461                 struct nlattr *nids;
8462                 int rem2;
8463
8464                 /* We only care about the NID list to discover with */
8465                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
8466                         continue;
8467
8468                 nla_for_each_nested(nids, attr, rem2) {
8469                         char nid[LNET_NIDSTR_SIZE + 1];
8470                         struct lnet_processid id;
8471                         struct nlattr *nid_list;
8472                         struct lnet_peer *lp;
8473                         ssize_t len;
8474
8475                         if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8476                                 continue;
8477
8478                         memset(nid, 0, sizeof(nid));
8479                         rc = nla_strscpy(nid, nids, sizeof(nid));
8480                         if (rc < 0) {
8481                                 GENL_SET_ERR_MSG(info,
8482                                                  "failed to get NID");
8483                                 GOTO(report_err, rc);
8484                         }
8485
8486                         len = libcfs_strid(&id, strim(nid));
8487                         if (len < 0) {
8488                                 struct lnet_fail_ping *fail;
8489
8490                                 fail = genradix_ptr_alloc(&dlists.lgpl_failed,
8491                                                           dlists.lgpl_failed_count++,
8492                                                           GFP_KERNEL);
8493                                 if (!fail) {
8494                                         GENL_SET_ERR_MSG(info,
8495                                                          "failed to allocate improper NID");
8496                                         GOTO(report_err, rc = -ENOMEM);
8497                                 }
8498                                 memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8499                                 snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8500                                          "cannot parse NID '%s'", strim(nid));
8501                                 fail->lfp_id = id;
8502                                 fail->lfp_errno = len;
8503                                 continue;
8504                         }
8505
8506                         if (LNET_NID_IS_ANY(&id.nid))
8507                                 continue;
8508
8509                         rc = lnet_discover(&id,
8510                                            info->nlhdr->nlmsg_flags & NLM_F_EXCL,
8511                                            &dlists);
8512                         if (rc < 0) {
8513                                 struct lnet_fail_ping *fail;
8514
8515                                 fail = genradix_ptr_alloc(&dlists.lgpl_failed,
8516                                                           dlists.lgpl_failed_count++,
8517                                                           GFP_KERNEL);
8518                                 if (!fail) {
8519                                         GENL_SET_ERR_MSG(info,
8520                                                          "failed to allocate failed NID");
8521                                         GOTO(report_err, rc = -ENOMEM);
8522                                 }
8523                                 memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8524                                 snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8525                                          "failed to discover %s",
8526                                          libcfs_nidstr(&id.nid));
8527                                 fail->lfp_id = id;
8528                                 fail->lfp_errno = rc;
8529                                 continue;
8530                         }
8531
8532                         /* create the genetlink message header */
8533                         hdr = genlmsg_put(reply, info->snd_portid, info->snd_seq,
8534                                           &lnet_family, NLM_F_MULTI, LNET_CMD_PING);
8535                         if (!hdr) {
8536                                 GENL_SET_ERR_MSG(info,
8537                                                  "failed to allocate hdr");
8538                                 GOTO(report_err, rc = -ENOMEM);
8539                         }
8540
8541                         if (!clear_hdr) {
8542                                 nla_put_string(reply, LNET_PING_ATTR_HDR, "");
8543                                 clear_hdr = true;
8544                         }
8545
8546                         lp = lnet_find_peer(&id.nid);
8547                         if (lp) {
8548                                 nla_put_string(reply, LNET_PING_ATTR_PRIMARY_NID,
8549                                                libcfs_nidstr(&lp->lp_primary_nid));
8550                                 if (lnet_peer_is_multi_rail(lp))
8551                                         nla_put_flag(reply, LNET_PING_ATTR_MULTIRAIL);
8552                                 lnet_peer_decref_locked(lp);
8553                         }
8554
8555                         nid_list = nla_nest_start(reply, LNET_PING_ATTR_PEER_NI_LIST);
8556                         for (i = 0; i < dlists.lgpl_list_count; i++) {
8557                                 struct lnet_processid *found;
8558                                 struct nlattr *nid_attr;
8559                                 char *idstr;
8560
8561                                 found = genradix_ptr(&dlists.lgpl_list, i);
8562                                 if (nid_is_lo0(&found->nid))
8563                                         continue;
8564
8565                                 nid_attr = nla_nest_start(reply, i + 1);
8566                                 if (id.pid == LNET_PID_LUSTRE)
8567                                         idstr = libcfs_nidstr(&found->nid);
8568                                 else
8569                                         idstr = libcfs_idstr(found);
8570                                 nla_put_string(reply, LNET_PING_PEER_NI_ATTR_NID, idstr);
8571                                 nla_nest_end(reply, nid_attr);
8572                         }
8573                         nla_nest_end(reply, nid_list);
8574
8575                         genlmsg_end(reply, hdr);
8576                 }
8577         }
8578
8579         if (dlists.lgpl_failed_count) {
8580                 int flags = NLM_F_CREATE | NLM_F_REPLACE | NLM_F_MULTI;
8581                 const struct ln_key_list *fail[] = {
8582                         &discover_err_props_list, NULL
8583                 };
8584
8585                 rc = lnet_genl_send_scalar_list(reply, info->snd_portid,
8586                                                 info->snd_seq, &lnet_family,
8587                                                 flags, LNET_CMD_PING, fail);
8588                 if (rc < 0) {
8589                         GENL_SET_ERR_MSG(info,
8590                                          "failed to send new key table");
8591                         GOTO(report_err, rc);
8592                 }
8593
8594                 for (i = 0; i < dlists.lgpl_failed_count; i++) {
8595                         struct lnet_fail_ping *fail;
8596
8597                         hdr = genlmsg_put(reply, info->snd_portid, info->snd_seq,
8598                                           &lnet_family, NLM_F_MULTI, LNET_CMD_PING);
8599                         if (!hdr) {
8600                                 GENL_SET_ERR_MSG(info,
8601                                                  "failed to send failed values");
8602                                 GOTO(report_err, rc = -ENOMSG);
8603                         }
8604
8605                         fail = genradix_ptr(&dlists.lgpl_failed, i);
8606                         if (i == 0)
8607                                 nla_put_string(reply, LNET_ERR_ATTR_HDR, "");
8608
8609                         nla_put_string(reply, LNET_ERR_ATTR_TYPE, "\n");
8610                         nla_put_s16(reply, LNET_ERR_ATTR_ERRNO,
8611                                     fail->lfp_errno);
8612                         nla_put_string(reply, LNET_ERR_ATTR_DESCR,
8613                                        fail->lfp_msg);
8614                         genlmsg_end(reply, hdr);
8615                 }
8616         }
8617
8618         nlh = nlmsg_put(reply, info->snd_portid, info->snd_seq, NLMSG_DONE, 0,
8619                         NLM_F_MULTI);
8620         if (!nlh) {
8621                 genlmsg_cancel(reply, hdr);
8622                 GENL_SET_ERR_MSG(info,
8623                                  "failed to finish message");
8624                 GOTO(report_err, rc = -EMSGSIZE);
8625         }
8626
8627 report_err:
8628         genradix_free(&dlists.lgpl_failed);
8629         genradix_free(&dlists.lgpl_list);
8630
8631         if (rc < 0) {
8632                 genlmsg_cancel(reply, hdr);
8633                 nlmsg_free(reply);
8634         } else {
8635                 rc = genlmsg_reply(reply, info);
8636         }
8637
8638         return rc;
8639 }
8640
8641 #define lnet_peer_dist_show_done        lnet_peer_ni_show_done
8642
8643 static int lnet_peer_dist_show_start(struct netlink_callback *cb)
8644 {
8645         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
8646 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8647         struct netlink_ext_ack *extack = NULL;
8648 #endif
8649         struct lnet_genl_processid_list *plist;
8650         int msg_len = genlmsg_len(gnlh);
8651         struct nlattr *params, *top;
8652         int rem, rc = 0;
8653
8654 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8655         extack = cb->extack;
8656 #endif
8657         mutex_lock(&the_lnet.ln_api_mutex);
8658         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
8659                 NL_SET_ERR_MSG(extack, "Network is down");
8660                 mutex_unlock(&the_lnet.ln_api_mutex);
8661                 return -ENETDOWN;
8662         }
8663
8664         msg_len = genlmsg_len(gnlh);
8665         if (!msg_len) {
8666                 NL_SET_ERR_MSG(extack, "Missing NID argument(s)");
8667                 mutex_unlock(&the_lnet.ln_api_mutex);
8668                 return -ENOENT;
8669         }
8670
8671         CFS_ALLOC_PTR(plist);
8672         if (!plist) {
8673                 NL_SET_ERR_MSG(extack, "No memory for peer NID list");
8674                 mutex_unlock(&the_lnet.ln_api_mutex);
8675                 return -ENOMEM;
8676         }
8677
8678         genradix_init(&plist->lgpl_list);
8679         plist->lgpl_count = 0;
8680         plist->lgpl_index = 0;
8681         cb->args[0] = (long)plist;
8682
8683         params = genlmsg_data(gnlh);
8684         nla_for_each_attr(top, params, msg_len, rem) {
8685                 struct nlattr *nids;
8686                 int rem2;
8687
8688                 if (nla_type(top) != LN_SCALAR_ATTR_LIST)
8689                         continue;
8690
8691                 nla_for_each_nested(nids, top, rem2) {
8692                         char nidstr[LNET_NIDSTR_SIZE + 1];
8693                         struct lnet_processid *id;
8694
8695                         if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8696                                 continue;
8697
8698                         memset(nidstr, 0, sizeof(nidstr));
8699                         rc = nla_strscpy(nidstr, nids, sizeof(nidstr));
8700                         if (rc < 0) {
8701                                 NL_SET_ERR_MSG(extack,
8702                                                "failed to get NID");
8703                                 GOTO(report_err, rc);
8704                         }
8705
8706                         id = genradix_ptr_alloc(&plist->lgpl_list,
8707                                                 plist->lgpl_count++,
8708                                                 GFP_KERNEL);
8709                         if (!id) {
8710                                 NL_SET_ERR_MSG(extack, "failed to allocate NID");
8711                                 GOTO(report_err, rc = -ENOMEM);
8712                         }
8713
8714                         rc = libcfs_strid(id, strim(nidstr));
8715                         if (rc < 0) {
8716                                 NL_SET_ERR_MSG(extack, "invalid NID");
8717                                 GOTO(report_err, rc);
8718                         }
8719                         rc = 0;
8720                 }
8721         }
8722 report_err:
8723         mutex_unlock(&the_lnet.ln_api_mutex);
8724
8725         if (rc < 0)
8726                 lnet_peer_dist_show_done(cb);
8727
8728         return rc;
8729 }
8730
8731 static const struct ln_key_list peer_dist_props_list = {
8732         .lkl_maxattr                    = LNET_PEER_DIST_ATTR_MAX,
8733         .lkl_list                       = {
8734                 [LNET_PEER_DIST_ATTR_HDR]       = {
8735                         .lkp_value              = "peer",
8736                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8737                         .lkp_data_type          = NLA_NUL_STRING,
8738                 },
8739                 [LNET_PEER_DIST_ATTR_NID]       = {
8740                         .lkp_value              = "nid",
8741                         .lkp_data_type          = NLA_STRING
8742                 },
8743                 [LNET_PEER_DIST_ATTR_DIST]      = {
8744                         .lkp_value              = "distance",
8745                         .lkp_data_type          = NLA_U32
8746                 },
8747                 [LNET_PEER_DIST_ATTR_ORDER]     = {
8748                         .lkp_value              = "order",
8749                         .lkp_data_type          = NLA_U32
8750                 },
8751         },
8752 };
8753
8754 static int lnet_peer_dist_show_dump(struct sk_buff *msg,
8755                                     struct netlink_callback *cb)
8756 {
8757         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
8758 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8759         struct netlink_ext_ack *extack = NULL;
8760 #endif
8761         int portid = NETLINK_CB(cb->skb).portid;
8762         int seq = cb->nlh->nlmsg_seq;
8763         int idx = plist->lgpl_index;
8764         int rc = 0;
8765
8766 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8767         extack = cb->extack;
8768 #endif
8769         if (!idx) {
8770                 const struct ln_key_list *all[] = {
8771                         &peer_dist_props_list, NULL
8772                 };
8773
8774                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
8775                                                 &lnet_family,
8776                                                 NLM_F_CREATE | NLM_F_MULTI,
8777                                                 LNET_CMD_PEER_DIST, all);
8778                 if (rc < 0) {
8779                         NL_SET_ERR_MSG(extack, "failed to send key table");
8780                         GOTO(send_error, rc);
8781                 }
8782         }
8783
8784         while (idx < plist->lgpl_count) {
8785                 struct lnet_processid *id;
8786                 void *hdr;
8787                 u32 order;
8788                 int dist;
8789
8790                 id = genradix_ptr(&plist->lgpl_list, idx++);
8791                 if (nid_is_lo0(&id->nid))
8792                         continue;
8793
8794                 dist = LNetDist(&id->nid, &id->nid, &order);
8795                 if (dist < 0) {
8796                         if (dist == -EHOSTUNREACH)
8797                                 continue;
8798
8799                         rc = dist;
8800                         return rc;
8801                 }
8802
8803                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8804                                   NLM_F_MULTI, LNET_CMD_PEER_DIST);
8805                 if (!hdr) {
8806                         NL_SET_ERR_MSG(extack, "failed to send values");
8807                         genlmsg_cancel(msg, hdr);
8808                         GOTO(send_error, rc = -EMSGSIZE);
8809                 }
8810
8811                 if (idx == 1)
8812                         nla_put_string(msg, LNET_PEER_DIST_ATTR_HDR, "");
8813
8814                 nla_put_string(msg, LNET_PEER_DIST_ATTR_NID,
8815                                libcfs_nidstr(&id->nid));
8816                 nla_put_u32(msg, LNET_PEER_DIST_ATTR_DIST, dist);
8817                 nla_put_u32(msg, LNET_PEER_DIST_ATTR_ORDER, order);
8818
8819                 genlmsg_end(msg, hdr);
8820         }
8821
8822         plist->lgpl_index = idx;
8823 send_error:
8824         return lnet_nl_send_error(cb->skb, portid, seq, rc);
8825 }
8826
8827 #ifndef HAVE_NETLINK_CALLBACK_START
8828 static int lnet_old_peer_dist_show_dump(struct sk_buff *msg,
8829                                         struct netlink_callback *cb)
8830 {
8831         if (!cb->args[0]) {
8832                 int rc = lnet_peer_dist_show_start(cb);
8833
8834                 if (rc < 0)
8835                         return lnet_nl_send_error(cb->skb,
8836                                                   NETLINK_CB(cb->skb).portid,
8837                                                   cb->nlh->nlmsg_seq,
8838                                                   rc);
8839         }
8840
8841         return lnet_peer_dist_show_dump(msg, cb);
8842 }
8843 #endif
8844
8845 static const struct genl_multicast_group lnet_mcast_grps[] = {
8846         { .name =       "ip2net",       },
8847         { .name =       "net",          },
8848         { .name =       "peer",         },
8849         { .name =       "route",        },
8850         { .name =       "ping",         },
8851         { .name =       "discover",     },
8852         { .name =       "cpt-of-nid",   },
8853 };
8854
8855 static const struct genl_ops lnet_genl_ops[] = {
8856         {
8857                 .cmd            = LNET_CMD_CONFIGURE,
8858                 .flags          = GENL_ADMIN_PERM,
8859                 .doit           = lnet_net_conf_cmd,
8860         },
8861         {
8862                 .cmd            = LNET_CMD_NETS,
8863                 .flags          = GENL_ADMIN_PERM,
8864 #ifdef HAVE_NETLINK_CALLBACK_START
8865                 .start          = lnet_net_show_start,
8866                 .dumpit         = lnet_net_show_dump,
8867 #else
8868                 .dumpit         = lnet_old_net_show_dump,
8869 #endif
8870                 .done           = lnet_net_show_done,
8871                 .doit           = lnet_net_cmd,
8872         },
8873         {
8874                 .cmd            = LNET_CMD_PEERS,
8875                 .flags          = GENL_ADMIN_PERM,
8876 #ifdef HAVE_NETLINK_CALLBACK_START
8877                 .start          = lnet_peer_ni_show_start,
8878                 .dumpit         = lnet_peer_ni_show_dump,
8879 #else
8880                 .dumpit         = lnet_old_peer_ni_show_dump,
8881 #endif
8882                 .done           = lnet_peer_ni_show_done,
8883                 .doit           = lnet_peer_ni_cmd,
8884         },
8885         {
8886                 .cmd            = LNET_CMD_ROUTES,
8887                 .flags          = GENL_ADMIN_PERM,
8888 #ifdef HAVE_NETLINK_CALLBACK_START
8889                 .start          = lnet_route_show_start,
8890                 .dumpit         = lnet_route_show_dump,
8891 #else
8892                 .dumpit         = lnet_old_route_show_dump,
8893 #endif
8894                 .done           = lnet_route_show_done,
8895                 .doit           = lnet_route_cmd,
8896         },
8897         {
8898                 .cmd            = LNET_CMD_PING,
8899                 .flags          = GENL_ADMIN_PERM,
8900 #ifdef HAVE_NETLINK_CALLBACK_START
8901                 .start          = lnet_ping_show_start,
8902                 .dumpit         = lnet_ping_show_dump,
8903 #else
8904                 .dumpit         = lnet_old_ping_show_dump,
8905 #endif
8906                 .done           = lnet_ping_show_done,
8907                 .doit           = lnet_ping_cmd,
8908         },
8909         {
8910                 .cmd            = LNET_CMD_CPT_OF_NID,
8911 #ifdef HAVE_NETLINK_CALLBACK_START
8912                 .start          = lnet_cpt_of_nid_show_start,
8913                 .dumpit         = lnet_cpt_of_nid_show_dump,
8914 #else
8915                 .dumpit         = lnet_old_cpt_of_nid_show_dump,
8916 #endif
8917                 .done           = lnet_cpt_of_nid_show_done,
8918         },
8919         {
8920                 .cmd            = LNET_CMD_PEER_DIST,
8921 #ifdef HAVE_NETLINK_CALLBACK_START
8922                 .start          = lnet_peer_dist_show_start,
8923                 .dumpit         = lnet_peer_dist_show_dump,
8924 #else
8925                 .dumpit         = lnet_old_peer_dist_show_dump,
8926 #endif
8927                 .done           = lnet_peer_dist_show_done,
8928         },
8929 };
8930
8931 static struct genl_family lnet_family = {
8932         .name           = LNET_GENL_NAME,
8933         .version        = LNET_GENL_VERSION,
8934         .module         = THIS_MODULE,
8935         .parallel_ops   = true,
8936         .netnsok        = true,
8937         .ops            = lnet_genl_ops,
8938         .n_ops          = ARRAY_SIZE(lnet_genl_ops),
8939         .mcgrps         = lnet_mcast_grps,
8940         .n_mcgrps       = ARRAY_SIZE(lnet_mcast_grps),
8941 #ifdef GENL_FAMILY_HAS_RESV_START_OP
8942         .resv_start_op  = __LNET_CMD_MAX_PLUS_ONE,
8943 #endif
8944 };
8945
8946 void LNetDebugPeer(struct lnet_processid *id)
8947 {
8948         lnet_debug_peer(&id->nid);
8949 }
8950 EXPORT_SYMBOL(LNetDebugPeer);
8951
8952 /**
8953  * Determine if the specified peer \a nid is on the local node.
8954  *
8955  * \param nid   peer nid to check
8956  *
8957  * \retval true         If peer NID is on the local node.
8958  * \retval false        If peer NID is not on the local node.
8959  */
8960 bool LNetIsPeerLocal(struct lnet_nid *nid)
8961 {
8962         struct lnet_net *net;
8963         struct lnet_ni *ni;
8964         int cpt;
8965
8966         cpt = lnet_net_lock_current();
8967         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
8968                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
8969                         if (nid_same(&ni->ni_nid, nid)) {
8970                                 lnet_net_unlock(cpt);
8971                                 return true;
8972                         }
8973                 }
8974         }
8975         lnet_net_unlock(cpt);
8976
8977         return false;
8978 }
8979 EXPORT_SYMBOL(LNetIsPeerLocal);
8980
8981 /**
8982  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
8983  * Note that all interfaces share a same PID, as requested by LNetNIInit().
8984  *
8985  * @index       Index of the interface to look up.
8986  * @id          On successful return, this location will hold the
8987  *              struct lnet_process_id ID of the interface.
8988  * @large_nids  Report large NIDs if this is true.
8989  *
8990  * RETURN       0 If an interface exists at \a index.
8991  *              -ENOENT If no interface has been found.
8992  */
8993 int
8994 LNetGetId(unsigned int index, struct lnet_processid *id, bool large_nids)
8995 {
8996         struct lnet_ni   *ni;
8997         struct lnet_net  *net;
8998         int               cpt;
8999         int               rc = -ENOENT;
9000
9001         LASSERT(the_lnet.ln_refcount > 0);
9002
9003         cpt = lnet_net_lock_current();
9004
9005         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
9006                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
9007                         if (!large_nids && !nid_is_nid4(&ni->ni_nid))
9008                                 continue;
9009
9010                         if (index-- != 0)
9011                                 continue;
9012
9013                         id->nid = ni->ni_nid;
9014                         id->pid = the_lnet.ln_pid;
9015                         rc = 0;
9016                         break;
9017                 }
9018         }
9019
9020         lnet_net_unlock(cpt);
9021         return rc;
9022 }
9023 EXPORT_SYMBOL(LNetGetId);
9024
9025 struct ping_data {
9026         int rc;
9027         int replied;
9028         int pd_unlinked;
9029         struct lnet_handle_md mdh;
9030         struct completion completion;
9031 };
9032
9033 static void
9034 lnet_ping_event_handler(struct lnet_event *event)
9035 {
9036         struct ping_data *pd = event->md_user_ptr;
9037
9038         CDEBUG(D_NET, "ping event (%d %d)%s\n",
9039                event->type, event->status,
9040                event->unlinked ? " unlinked" : "");
9041
9042         if (event->status) {
9043                 if (!pd->rc)
9044                         pd->rc = event->status;
9045         } else if (event->type == LNET_EVENT_REPLY) {
9046                 pd->replied = 1;
9047                 pd->rc = event->mlength;
9048         }
9049
9050         if (event->unlinked)
9051                 pd->pd_unlinked = 1;
9052
9053         if (event->unlinked ||
9054             (event->type == LNET_EVENT_SEND && event->status))
9055                 complete(&pd->completion);
9056 }
9057
9058 /* Max buffer we allow to be sent. Larger values will cause IB failures */
9059 #define LNET_PING_BUFFER_MAX    3960
9060
9061 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
9062                      signed long timeout, struct lnet_genl_ping_list *plist,
9063                      int n_ids)
9064 {
9065         int id_bytes = sizeof(struct lnet_ni_status); /* For 0@lo */
9066         struct lnet_md md = { NULL };
9067         struct ping_data pd = { 0 };
9068         struct lnet_ping_buffer *pbuf;
9069         struct lnet_processid pid;
9070         struct lnet_ping_iter pi;
9071         int i = 0;
9072         u32 *st;
9073         int nob;
9074         int rc;
9075         int rc2;
9076
9077         genradix_init(&plist->lgpl_list);
9078
9079         /* n_ids limit is arbitrary */
9080         if (n_ids <= 0 || LNET_NID_IS_ANY(&id->nid))
9081                 return -EINVAL;
9082
9083         /* if the user buffer has more space than the lnet_interfaces_max
9084          * then only fill it up to lnet_interfaces_max
9085          */
9086         if (n_ids > lnet_interfaces_max)
9087                 n_ids = lnet_interfaces_max;
9088
9089         if (id->pid == LNET_PID_ANY)
9090                 id->pid = LNET_PID_LUSTRE;
9091
9092         /* Allocate maximum possible NID size */
9093         id_bytes += lnet_ping_sts_size(&LNET_ANY_NID) * n_ids;
9094         if (id_bytes > LNET_PING_BUFFER_MAX)
9095                 id_bytes = LNET_PING_BUFFER_MAX;
9096
9097         pbuf = lnet_ping_buffer_alloc(id_bytes, GFP_NOFS);
9098         if (!pbuf)
9099                 return -ENOMEM;
9100
9101         /* initialize md content */
9102         md.start     = &pbuf->pb_info;
9103         md.length    = id_bytes;
9104         md.threshold = 2; /* GET/REPLY */
9105         md.max_size  = 0;
9106         md.options   = LNET_MD_TRUNCATE;
9107         md.user_ptr  = &pd;
9108         md.handler   = lnet_ping_event_handler;
9109
9110         init_completion(&pd.completion);
9111
9112         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
9113         if (rc != 0) {
9114                 CERROR("Can't bind MD: %d\n", rc);
9115                 goto fail_ping_buffer_decref;
9116         }
9117
9118         rc = LNetGet(src_nid, pd.mdh, id, LNET_RESERVED_PORTAL,
9119                      LNET_PROTO_PING_MATCHBITS, 0, false);
9120         if (rc != 0) {
9121                 /* Don't CERROR; this could be deliberate! */
9122                 rc2 = LNetMDUnlink(pd.mdh);
9123                 LASSERT(rc2 == 0);
9124
9125                 /* NB must wait for the UNLINK event below... */
9126         }
9127
9128         /* Ensure completion in finite time... */
9129         wait_for_completion_timeout(&pd.completion, timeout);
9130         if (!pd.pd_unlinked) {
9131                 LNetMDUnlink(pd.mdh);
9132                 wait_for_completion(&pd.completion);
9133         }
9134
9135         if (!pd.replied) {
9136                 rc = pd.rc ?: -EIO;
9137                 goto fail_ping_buffer_decref;
9138         }
9139
9140         nob = pd.rc;
9141         LASSERT(nob >= 0 && nob <= id_bytes);
9142
9143         rc = -EPROTO;           /* if I can't parse... */
9144
9145         if (nob < LNET_PING_INFO_HDR_SIZE) {
9146                 CERROR("%s: ping info too short %d\n",
9147                        libcfs_idstr(id), nob);
9148                 goto fail_ping_buffer_decref;
9149         }
9150
9151         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
9152                 lnet_swap_pinginfo(pbuf);
9153         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
9154                 CERROR("%s: Unexpected magic %08x\n",
9155                        libcfs_idstr(id), pbuf->pb_info.pi_magic);
9156                 goto fail_ping_buffer_decref;
9157         }
9158
9159         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
9160                 CERROR("%s: ping w/o NI status: 0x%x\n",
9161                        libcfs_idstr(id), pbuf->pb_info.pi_features);
9162                 goto fail_ping_buffer_decref;
9163         }
9164
9165         /* Test if smaller than lnet_pinginfo with just one pi_ni status info.
9166          * That one might contain size when large nids are used.
9167          */
9168         if (nob < offsetof(struct lnet_ping_info, pi_ni[1])) {
9169                 CERROR("%s: Short reply %d(%lu min)\n",
9170                        libcfs_idstr(id), nob,
9171                        offsetof(struct lnet_ping_info, pi_ni[1]));
9172                 goto fail_ping_buffer_decref;
9173         }
9174
9175         if (ping_info_count_entries(pbuf) < n_ids) {
9176                 n_ids = ping_info_count_entries(pbuf);
9177                 id_bytes = lnet_ping_info_size(&pbuf->pb_info);
9178         }
9179
9180         if (nob < id_bytes) {
9181                 CERROR("%s: Short reply %d(%d expected)\n",
9182                        libcfs_idstr(id), nob, id_bytes);
9183                 goto fail_ping_buffer_decref;
9184         }
9185
9186         for (st = ping_iter_first(&pi, pbuf, &pid.nid);
9187              st;
9188              st = ping_iter_next(&pi, &pid.nid)) {
9189                 id = genradix_ptr_alloc(&plist->lgpl_list, i++, GFP_KERNEL);
9190                 if (!id) {
9191                         rc = -ENOMEM;
9192                         goto fail_ping_buffer_decref;
9193                 }
9194
9195                 id->pid = pbuf->pb_info.pi_pid;
9196                 id->nid = pid.nid;
9197         }
9198         rc = i;
9199 fail_ping_buffer_decref:
9200         lnet_ping_buffer_decref(pbuf);
9201         return rc;
9202 }
9203
9204 static int
9205 lnet_discover(struct lnet_processid *pid, u32 force,
9206               struct lnet_genl_ping_list *dlist)
9207 {
9208         struct lnet_peer_ni *lpni;
9209         struct lnet_peer_ni *p;
9210         struct lnet_peer *lp;
9211         int cpt;
9212         int rc;
9213
9214         if (LNET_NID_IS_ANY(&pid->nid))
9215                 return -EINVAL;
9216
9217         if (pid->pid == LNET_PID_ANY)
9218                 pid->pid = LNET_PID_LUSTRE;
9219
9220         cpt = lnet_net_lock_current();
9221         lpni = lnet_peerni_by_nid_locked(&pid->nid, NULL, cpt);
9222         if (IS_ERR(lpni)) {
9223                 rc = PTR_ERR(lpni);
9224                 goto out;
9225         }
9226
9227         /*
9228          * Clearing the NIDS_UPTODATE flag ensures the peer will
9229          * be discovered, provided discovery has not been disabled.
9230          */
9231         lp = lpni->lpni_peer_net->lpn_peer;
9232         spin_lock(&lp->lp_lock);
9233         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
9234         /* If the force flag is set, force a PING and PUSH as well. */
9235         if (force)
9236                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
9237         spin_unlock(&lp->lp_lock);
9238         rc = lnet_discover_peer_locked(lpni, cpt, true);
9239         if (rc)
9240                 goto out_decref;
9241
9242         /* The lpni (or lp) for this NID may have changed and our ref is
9243          * the only thing keeping the old one around. Release the ref
9244          * and lookup the lpni again
9245          */
9246         lnet_peer_ni_decref_locked(lpni);
9247         lpni = lnet_peer_ni_find_locked(&pid->nid);
9248         if (!lpni) {
9249                 rc = -ENOENT;
9250                 goto out;
9251         }
9252         lp = lpni->lpni_peer_net->lpn_peer;
9253
9254         dlist->lgpl_list_count = 0;
9255         p = NULL;
9256         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
9257                 struct lnet_processid *id;
9258
9259                 id = genradix_ptr_alloc(&dlist->lgpl_list,
9260                                         dlist->lgpl_list_count++, GFP_ATOMIC);
9261                 if (!id) {
9262                         rc = -ENOMEM;
9263                         goto out_decref;
9264                 }
9265                 id->pid = pid->pid;
9266                 id->nid = p->lpni_nid;
9267         }
9268         rc = dlist->lgpl_list_count;
9269
9270 out_decref:
9271         lnet_peer_ni_decref_locked(lpni);
9272 out:
9273         lnet_net_unlock(cpt);
9274
9275         return rc;
9276 }
9277
9278 /**
9279  * Retrieve peer discovery status.
9280  *
9281  * \retval 1 if lnet_peer_discovery_disabled is 0
9282  * \retval 0 if lnet_peer_discovery_disabled is 1
9283  */
9284 int
9285 LNetGetPeerDiscoveryStatus(void)
9286 {
9287         return !lnet_peer_discovery_disabled;
9288 }
9289 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);