Whamcloud - gitweb
LU-6142 lnet: SPDX for lnet/lnet/
[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 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
3941         mutex_unlock(&the_lnet.ln_api_mutex);
3942 }
3943
3944
3945 void lnet_queue_ping_buffer_update(void)
3946 {
3947         /* don't queue pb update if it is not needed */
3948         if (atomic_dec_if_positive(&the_lnet.ln_update_ping_buf) < 0)
3949                 return;
3950
3951         /* don't queue pb update if already queued and not processed */
3952         if (atomic_dec_if_positive(&the_lnet.ln_pb_update_ready) < 0)
3953                 return;
3954
3955         INIT_WORK(&the_lnet.ln_pb_update_work, lnet_update_ping_buffer);
3956         queue_work(the_lnet.ln_pb_update_wq, &the_lnet.ln_pb_update_work);
3957 }
3958
3959 void lnet_incr_dlc_seq(void)
3960 {
3961         atomic_inc(&lnet_dlc_seq_no);
3962 }
3963
3964 __u32 lnet_get_dlc_seq_locked(void)
3965 {
3966         return atomic_read(&lnet_dlc_seq_no);
3967 }
3968
3969 static void
3970 lnet_ni_set_healthv(struct lnet_nid *nid, int value)
3971 {
3972         bool all = nid_same(nid, &LNET_ANY_NID);
3973         struct lnet_net *net;
3974         struct lnet_ni *ni;
3975
3976         lnet_net_lock(LNET_LOCK_EX);
3977         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3978                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3979                         if (!all && !nid_same(&ni->ni_nid, nid))
3980                                 continue;
3981
3982                         atomic_set(&ni->ni_healthv, value);
3983                         if (list_empty(&ni->ni_recovery) &&
3984                             value < LNET_MAX_HEALTH_VALUE) {
3985                                 CERROR("manually adding local NI %s to recovery\n",
3986                                        libcfs_nidstr(&ni->ni_nid));
3987                                 list_add_tail(&ni->ni_recovery,
3988                                               &the_lnet.ln_mt_localNIRecovq);
3989                                 lnet_ni_addref_locked(ni, 0);
3990                         }
3991                         if (!all) {
3992                                 lnet_net_unlock(LNET_LOCK_EX);
3993                                 return;
3994                         }
3995                 }
3996         }
3997         lnet_net_unlock(LNET_LOCK_EX);
3998 }
3999
4000 static void
4001 lnet_ni_set_conns_per_peer(lnet_nid_t nid, int value, bool all)
4002 {
4003         struct lnet_net *net;
4004         struct lnet_ni *ni;
4005
4006         lnet_net_lock(LNET_LOCK_EX);
4007         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4008                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4009                         if (lnet_nid_to_nid4(&ni->ni_nid) != nid && !all)
4010                                 continue;
4011                         if (LNET_NETTYP(net->net_id) == SOCKLND)
4012                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_sock.lnd_conns_per_peer = value;
4013                         else if (LNET_NETTYP(net->net_id) == O2IBLND)
4014                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib.lnd_conns_per_peer = value;
4015                         if (!all) {
4016                                 lnet_net_unlock(LNET_LOCK_EX);
4017                                 return;
4018                         }
4019                 }
4020         }
4021         lnet_net_unlock(LNET_LOCK_EX);
4022 }
4023
4024 static int
4025 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
4026 {
4027         int cpt, rc = 0;
4028         struct lnet_ni *ni;
4029         struct lnet_nid nid;
4030
4031         lnet_nid4_to_nid(stats->hlni_nid, &nid);
4032         cpt = lnet_net_lock_current();
4033         ni = lnet_nid_to_ni_locked(&nid, cpt);
4034         if (!ni) {
4035                 rc = -ENOENT;
4036                 goto unlock;
4037         }
4038
4039         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
4040         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
4041         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
4042         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
4043         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
4044         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
4045         stats->hlni_fatal_error = atomic_read(&ni->ni_fatal_error_on);
4046         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
4047         stats->hlni_ping_count = ni->ni_ping_count;
4048         stats->hlni_next_ping = ni->ni_next_ping;
4049
4050 unlock:
4051         lnet_net_unlock(cpt);
4052
4053         return rc;
4054 }
4055
4056 static int
4057 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4058 {
4059         struct lnet_ni *ni;
4060         int i = 0;
4061
4062         lnet_net_lock(LNET_LOCK_EX);
4063         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
4064                 if (!nid_is_nid4(&ni->ni_nid))
4065                         continue;
4066                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&ni->ni_nid);
4067                 i++;
4068                 if (i >= LNET_MAX_SHOW_NUM_NID)
4069                         break;
4070         }
4071         lnet_net_unlock(LNET_LOCK_EX);
4072         list->rlst_num_nids = i;
4073
4074         return 0;
4075 }
4076
4077 static int
4078 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4079 {
4080         struct lnet_peer_ni *lpni;
4081         int i = 0;
4082
4083         lnet_net_lock(LNET_LOCK_EX);
4084         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
4085                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&lpni->lpni_nid);
4086                 i++;
4087                 if (i >= LNET_MAX_SHOW_NUM_NID)
4088                         break;
4089         }
4090         lnet_net_unlock(LNET_LOCK_EX);
4091         list->rlst_num_nids = i;
4092
4093         return 0;
4094 }
4095
4096 /**
4097  * LNet ioctl handler.
4098  *
4099  */
4100 int
4101 LNetCtl(unsigned int cmd, void *arg)
4102 {
4103         struct libcfs_ioctl_data *data = arg;
4104         struct lnet_ioctl_config_data *config;
4105         struct lnet_ni           *ni;
4106         struct lnet_nid           nid;
4107         int                       rc;
4108
4109         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
4110                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
4111
4112         switch (cmd) {
4113         case IOC_LIBCFS_GET_NI: {
4114                 struct lnet_processid id = {};
4115
4116                 rc = LNetGetId(data->ioc_count, &id, false);
4117                 data->ioc_nid = lnet_nid_to_nid4(&id.nid);
4118                 return rc;
4119         }
4120         case IOC_LIBCFS_FAIL_NID:
4121                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
4122
4123         case IOC_LIBCFS_ADD_ROUTE: {
4124                 /* default router sensitivity to 1 */
4125                 unsigned int sensitivity = 1;
4126                 config = arg;
4127
4128                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4129                         return -EINVAL;
4130
4131                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
4132                         sensitivity =
4133                           config->cfg_config_u.cfg_route.rtr_sensitivity;
4134                 }
4135
4136                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4137                 mutex_lock(&the_lnet.ln_api_mutex);
4138                 rc = lnet_add_route(config->cfg_net,
4139                                     config->cfg_config_u.cfg_route.rtr_hop,
4140                                     &nid,
4141                                     config->cfg_config_u.cfg_route.
4142                                         rtr_priority, sensitivity);
4143                 mutex_unlock(&the_lnet.ln_api_mutex);
4144                 return rc;
4145         }
4146
4147         case IOC_LIBCFS_DEL_ROUTE:
4148                 config = arg;
4149
4150                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4151                         return -EINVAL;
4152
4153                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4154                 mutex_lock(&the_lnet.ln_api_mutex);
4155                 rc = lnet_del_route(config->cfg_net, &nid);
4156                 mutex_unlock(&the_lnet.ln_api_mutex);
4157                 return rc;
4158
4159         case IOC_LIBCFS_GET_ROUTE:
4160                 config = arg;
4161
4162                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4163                         return -EINVAL;
4164
4165                 mutex_lock(&the_lnet.ln_api_mutex);
4166                 rc = lnet_get_route(config->cfg_count,
4167                                     &config->cfg_net,
4168                                     &config->cfg_config_u.cfg_route.rtr_hop,
4169                                     &config->cfg_nid,
4170                                     &config->cfg_config_u.cfg_route.rtr_flags,
4171                                     &config->cfg_config_u.cfg_route.
4172                                         rtr_priority,
4173                                     &config->cfg_config_u.cfg_route.
4174                                         rtr_sensitivity);
4175                 mutex_unlock(&the_lnet.ln_api_mutex);
4176                 return rc;
4177
4178         case IOC_LIBCFS_GET_LOCAL_NI: {
4179                 struct lnet_ioctl_config_ni *cfg_ni;
4180                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
4181                 struct lnet_ioctl_element_stats *stats;
4182                 __u32 tun_size;
4183
4184                 cfg_ni = arg;
4185
4186                 /* get the tunables if they are available */
4187                 if (cfg_ni->lic_cfg_hdr.ioc_len <
4188                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
4189                         return -EINVAL;
4190
4191                 stats = (struct lnet_ioctl_element_stats *)
4192                         cfg_ni->lic_bulk;
4193                 tun = (struct lnet_ioctl_config_lnd_tunables *)
4194                                 (cfg_ni->lic_bulk + sizeof(*stats));
4195
4196                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
4197                         sizeof(*stats);
4198
4199                 mutex_lock(&the_lnet.ln_api_mutex);
4200                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
4201                 mutex_unlock(&the_lnet.ln_api_mutex);
4202                 return rc;
4203         }
4204
4205         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
4206                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
4207                 int cpt;
4208
4209                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
4210                         return -EINVAL;
4211
4212                 mutex_lock(&the_lnet.ln_api_mutex);
4213
4214                 cpt = lnet_net_lock_current();
4215                 rc = lnet_get_ni_stats(msg_stats);
4216                 lnet_net_unlock(cpt);
4217
4218                 mutex_unlock(&the_lnet.ln_api_mutex);
4219
4220                 return rc;
4221         }
4222
4223         case IOC_LIBCFS_GET_NET: {
4224                 size_t total = sizeof(*config) +
4225                                sizeof(struct lnet_ioctl_net_config);
4226                 config = arg;
4227
4228                 if (config->cfg_hdr.ioc_len < total)
4229                         return -EINVAL;
4230
4231                 mutex_lock(&the_lnet.ln_api_mutex);
4232                 rc = lnet_get_net_config(config);
4233                 mutex_unlock(&the_lnet.ln_api_mutex);
4234                 return rc;
4235         }
4236
4237         case IOC_LIBCFS_GET_LNET_STATS:
4238         {
4239                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
4240
4241                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
4242                         return -EINVAL;
4243
4244                 mutex_lock(&the_lnet.ln_api_mutex);
4245                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
4246                 mutex_unlock(&the_lnet.ln_api_mutex);
4247                 return rc;
4248         }
4249
4250         case IOC_LIBCFS_RESET_LNET_STATS:
4251         {
4252                 mutex_lock(&the_lnet.ln_api_mutex);
4253                 lnet_counters_reset();
4254                 mutex_unlock(&the_lnet.ln_api_mutex);
4255                 return 0;
4256         }
4257
4258         case IOC_LIBCFS_CONFIG_RTR:
4259                 config = arg;
4260
4261                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4262                         return -EINVAL;
4263
4264                 mutex_lock(&the_lnet.ln_api_mutex);
4265                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
4266                         rc = lnet_rtrpools_enable();
4267                         mutex_unlock(&the_lnet.ln_api_mutex);
4268                         return rc;
4269                 }
4270                 lnet_rtrpools_disable();
4271                 mutex_unlock(&the_lnet.ln_api_mutex);
4272                 return 0;
4273
4274         case IOC_LIBCFS_ADD_BUF:
4275                 config = arg;
4276
4277                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4278                         return -EINVAL;
4279
4280                 mutex_lock(&the_lnet.ln_api_mutex);
4281                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4282                                                 buf_tiny,
4283                                           config->cfg_config_u.cfg_buffers.
4284                                                 buf_small,
4285                                           config->cfg_config_u.cfg_buffers.
4286                                                 buf_large);
4287                 mutex_unlock(&the_lnet.ln_api_mutex);
4288                 return rc;
4289
4290         case IOC_LIBCFS_SET_NUMA_RANGE: {
4291                 struct lnet_ioctl_set_value *numa;
4292                 numa = arg;
4293                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4294                         return -EINVAL;
4295                 lnet_net_lock(LNET_LOCK_EX);
4296                 lnet_numa_range = numa->sv_value;
4297                 lnet_net_unlock(LNET_LOCK_EX);
4298                 return 0;
4299         }
4300
4301         case IOC_LIBCFS_GET_NUMA_RANGE: {
4302                 struct lnet_ioctl_set_value *numa;
4303                 numa = arg;
4304                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4305                         return -EINVAL;
4306                 numa->sv_value = lnet_numa_range;
4307                 return 0;
4308         }
4309
4310         case IOC_LIBCFS_GET_BUF: {
4311                 struct lnet_ioctl_pool_cfg *pool_cfg;
4312                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4313
4314                 config = arg;
4315
4316                 if (config->cfg_hdr.ioc_len < total)
4317                         return -EINVAL;
4318
4319                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4320
4321                 mutex_lock(&the_lnet.ln_api_mutex);
4322                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4323                 mutex_unlock(&the_lnet.ln_api_mutex);
4324                 return rc;
4325         }
4326
4327         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4328                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4329
4330                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4331                         return -EINVAL;
4332
4333                 mutex_lock(&the_lnet.ln_api_mutex);
4334                 rc = lnet_get_local_ni_hstats(stats);
4335                 mutex_unlock(&the_lnet.ln_api_mutex);
4336
4337                 return rc;
4338         }
4339
4340         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4341                 struct lnet_ioctl_recovery_list *list = arg;
4342                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4343                         return -EINVAL;
4344
4345                 mutex_lock(&the_lnet.ln_api_mutex);
4346                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4347                         rc = lnet_get_local_ni_recovery_list(list);
4348                 else
4349                         rc = lnet_get_peer_ni_recovery_list(list);
4350                 mutex_unlock(&the_lnet.ln_api_mutex);
4351                 return rc;
4352         }
4353
4354         case IOC_LIBCFS_ADD_PEER_NI: {
4355                 struct lnet_ioctl_peer_cfg *cfg = arg;
4356                 struct lnet_nid prim_nid;
4357
4358                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4359                         return -EINVAL;
4360
4361                 mutex_lock(&the_lnet.ln_api_mutex);
4362                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4363                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4364                 rc = lnet_user_add_peer_ni(&prim_nid, &nid, cfg->prcfg_mr,
4365                                            cfg->prcfg_count == 1);
4366                 mutex_unlock(&the_lnet.ln_api_mutex);
4367                 return rc;
4368         }
4369
4370         case IOC_LIBCFS_DEL_PEER_NI: {
4371                 struct lnet_ioctl_peer_cfg *cfg = arg;
4372                 struct lnet_nid prim_nid;
4373
4374                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4375                         return -EINVAL;
4376
4377                 mutex_lock(&the_lnet.ln_api_mutex);
4378                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4379                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4380                 rc = lnet_del_peer_ni(&prim_nid,
4381                                       &nid,
4382                                       cfg->prcfg_count);
4383                 mutex_unlock(&the_lnet.ln_api_mutex);
4384                 return rc;
4385         }
4386
4387         case IOC_LIBCFS_GET_PEER_INFO: {
4388                 struct lnet_ioctl_peer *peer_info = arg;
4389
4390                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4391                         return -EINVAL;
4392
4393                 mutex_lock(&the_lnet.ln_api_mutex);
4394                 rc = lnet_get_peer_ni_info(
4395                    peer_info->pr_count,
4396                    &peer_info->pr_nid,
4397                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4398                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4399                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4400                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4401                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4402                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4403                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4404                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4405                 mutex_unlock(&the_lnet.ln_api_mutex);
4406                 return rc;
4407         }
4408
4409         case IOC_LIBCFS_GET_PEER_NI: {
4410                 struct lnet_ioctl_peer_cfg *cfg = arg;
4411
4412                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4413                         return -EINVAL;
4414
4415                 mutex_lock(&the_lnet.ln_api_mutex);
4416                 rc = lnet_get_peer_info(cfg,
4417                                         (void __user *)cfg->prcfg_bulk);
4418                 mutex_unlock(&the_lnet.ln_api_mutex);
4419                 return rc;
4420         }
4421
4422         case IOC_LIBCFS_GET_PEER_LIST: {
4423                 struct lnet_ioctl_peer_cfg *cfg = arg;
4424
4425                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4426                         return -EINVAL;
4427
4428                 mutex_lock(&the_lnet.ln_api_mutex);
4429                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4430                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4431                 mutex_unlock(&the_lnet.ln_api_mutex);
4432                 return rc;
4433         }
4434
4435         case IOC_LIBCFS_SET_HEALHV: {
4436                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4437                 int value;
4438
4439                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4440                         return -EINVAL;
4441                 if (cfg->rh_value < 0 ||
4442                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4443                         value = LNET_MAX_HEALTH_VALUE;
4444                 else
4445                         value = cfg->rh_value;
4446                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4447                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4448                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4449                 lnet_nid4_to_nid(cfg->rh_nid, &nid);
4450                 mutex_lock(&the_lnet.ln_api_mutex);
4451                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) {
4452                         if (cfg->rh_all)
4453                                 nid = LNET_ANY_NID;
4454                         lnet_ni_set_healthv(&nid, value);
4455                 } else {
4456                         lnet_peer_ni_set_healthv(&nid, value, cfg->rh_all);
4457                 }
4458                 mutex_unlock(&the_lnet.ln_api_mutex);
4459                 return 0;
4460         }
4461
4462         case IOC_LIBCFS_SET_PEER: {
4463                 struct lnet_ioctl_peer_cfg *cfg = arg;
4464                 struct lnet_peer *lp;
4465
4466                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4467                         return -EINVAL;
4468
4469                 mutex_lock(&the_lnet.ln_api_mutex);
4470                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &nid);
4471                 lp = lnet_find_peer(&nid);
4472                 if (!lp) {
4473                         mutex_unlock(&the_lnet.ln_api_mutex);
4474                         return -ENOENT;
4475                 }
4476                 spin_lock(&lp->lp_lock);
4477                 lp->lp_state = cfg->prcfg_state;
4478                 spin_unlock(&lp->lp_lock);
4479                 lnet_peer_decref_locked(lp);
4480                 mutex_unlock(&the_lnet.ln_api_mutex);
4481                 CDEBUG(D_NET, "Set peer %s state to %u\n",
4482                        libcfs_nid2str(cfg->prcfg_prim_nid), cfg->prcfg_state);
4483                 return 0;
4484         }
4485
4486         case IOC_LIBCFS_SET_CONNS_PER_PEER: {
4487                 struct lnet_ioctl_reset_conns_per_peer_cfg *cfg = arg;
4488                 int value;
4489
4490                 if (cfg->rcpp_hdr.ioc_len < sizeof(*cfg))
4491                         return -EINVAL;
4492                 if (cfg->rcpp_value < 0)
4493                         value = 1;
4494                 else
4495                         value = cfg->rcpp_value;
4496                 CDEBUG(D_NET,
4497                        "Setting conns_per_peer to %d for %s. all = %d\n",
4498                        value, libcfs_nid2str(cfg->rcpp_nid), cfg->rcpp_all);
4499                 mutex_lock(&the_lnet.ln_api_mutex);
4500                 lnet_ni_set_conns_per_peer(cfg->rcpp_nid, value, cfg->rcpp_all);
4501                 mutex_unlock(&the_lnet.ln_api_mutex);
4502                 return 0;
4503         }
4504
4505         case IOC_LIBCFS_NOTIFY_ROUTER: {
4506                 /* Convert the user-supplied real time to monotonic.
4507                  * NB: "when" is always in the past
4508                  */
4509                 time64_t when = ktime_get_seconds() -
4510                                 (ktime_get_real_seconds() - data->ioc_u64[0]);
4511
4512                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4513                 return lnet_notify(NULL, &nid, data->ioc_flags, false, when);
4514         }
4515
4516         case IOC_LIBCFS_LNET_DIST:
4517                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4518                 rc = LNetDist(&nid, &nid, &data->ioc_u32[1]);
4519                 if (rc < 0 && rc != -EHOSTUNREACH)
4520                         return rc;
4521
4522                 data->ioc_nid = lnet_nid_to_nid4(&nid);
4523                 data->ioc_u32[0] = rc;
4524                 return 0;
4525
4526         case IOC_LIBCFS_TESTPROTOCOMPAT:
4527                 the_lnet.ln_testprotocompat = data->ioc_flags;
4528                 return 0;
4529
4530         case IOC_LIBCFS_LNET_FAULT:
4531                 return lnet_fault_ctl(data->ioc_flags, data);
4532
4533         case IOC_LIBCFS_PING_PEER: {
4534                 struct lnet_ioctl_ping_data *ping = arg;
4535                 struct lnet_process_id __user *ids = ping->ping_buf;
4536                 struct lnet_nid src_nid = LNET_ANY_NID;
4537                 struct lnet_genl_ping_list plist;
4538                 struct lnet_processid id;
4539                 struct lnet_peer *lp;
4540                 signed long timeout;
4541                 int count, i;
4542
4543                 /* Check if the supplied ping data supports source nid
4544                  * NB: This check is sufficient if lnet_ioctl_ping_data has
4545                  * additional fields added, but if they are re-ordered or
4546                  * fields removed then this will break. It is expected that
4547                  * these ioctls will be replaced with netlink implementation, so
4548                  * it is probably not worth coming up with a more robust version
4549                  * compatibility scheme.
4550                  */
4551                 if (ping->ping_hdr.ioc_len >= sizeof(struct lnet_ioctl_ping_data))
4552                         lnet_nid4_to_nid(ping->ping_src, &src_nid);
4553
4554                 /* If timeout is negative then set default of 3 minutes */
4555                 if (((s32)ping->op_param) <= 0 ||
4556                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4557                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4558                 else
4559                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4560
4561                 id.pid = ping->ping_id.pid;
4562                 lnet_nid4_to_nid(ping->ping_id.nid, &id.nid);
4563                 rc = lnet_ping(&id, &src_nid, timeout, &plist,
4564                                ping->ping_count);
4565                 if (rc < 0)
4566                         goto report_ping_err;
4567                 count = rc;
4568                 rc = 0;
4569
4570                 for (i = 0; i < count; i++) {
4571                         struct lnet_processid *result;
4572                         struct lnet_process_id tmpid;
4573
4574                         result = genradix_ptr(&plist.lgpl_list, i);
4575                         memset(&tmpid, 0, sizeof(tmpid));
4576                         tmpid.pid = result->pid;
4577                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4578                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4579                                 rc = -EFAULT;
4580                                 goto report_ping_err;
4581                         }
4582                 }
4583
4584                 mutex_lock(&the_lnet.ln_api_mutex);
4585                 lp = lnet_find_peer(&id.nid);
4586                 if (lp) {
4587                         ping->ping_id.nid =
4588                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4589                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4590                         lnet_peer_decref_locked(lp);
4591                 }
4592                 mutex_unlock(&the_lnet.ln_api_mutex);
4593
4594                 ping->ping_count = count;
4595 report_ping_err:
4596                 genradix_free(&plist.lgpl_list);
4597                 return rc;
4598         }
4599
4600         case IOC_LIBCFS_DISCOVER: {
4601                 struct lnet_ioctl_ping_data *discover = arg;
4602                 struct lnet_process_id __user *ids;
4603                 struct lnet_genl_ping_list dlists;
4604                 struct lnet_processid id;
4605                 struct lnet_peer *lp;
4606                 int count, i;
4607
4608                 if (discover->ping_count <= 0)
4609                         return -EINVAL;
4610
4611                 genradix_init(&dlists.lgpl_list);
4612                 /* If the user buffer has more space than the lnet_interfaces_max,
4613                  * then only fill it up to lnet_interfaces_max.
4614                  */
4615                 if (discover->ping_count > lnet_interfaces_max)
4616                         discover->ping_count = lnet_interfaces_max;
4617
4618                 id.pid = discover->ping_id.pid;
4619                 lnet_nid4_to_nid(discover->ping_id.nid, &id.nid);
4620                 rc = lnet_discover(&id, discover->op_param, &dlists);
4621                 if (rc < 0)
4622                         goto report_discover_err;
4623                 count = rc;
4624
4625                 ids = discover->ping_buf;
4626                 for (i = 0; i < count; i++) {
4627                         struct lnet_processid *result;
4628                         struct lnet_process_id tmpid;
4629
4630                         result = genradix_ptr(&dlists.lgpl_list, i);
4631                         memset(&tmpid, 0, sizeof(tmpid));
4632                         tmpid.pid = result->pid;
4633                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4634                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4635                                 rc = -EFAULT;
4636                                 goto report_discover_err;
4637                         }
4638
4639                         if (i >= discover->ping_count)
4640                                 break;
4641                 }
4642                 rc = 0;
4643
4644                 mutex_lock(&the_lnet.ln_api_mutex);
4645                 lp = lnet_find_peer(&id.nid);
4646                 if (lp) {
4647                         discover->ping_id.nid =
4648                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4649                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4650                         lnet_peer_decref_locked(lp);
4651                 }
4652                 mutex_unlock(&the_lnet.ln_api_mutex);
4653
4654                 discover->ping_count = count;
4655 report_discover_err:
4656                 genradix_free(&dlists.lgpl_list);
4657                 return rc;
4658         }
4659
4660         case IOC_LIBCFS_ADD_UDSP: {
4661                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4662                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4663
4664                 mutex_lock(&the_lnet.ln_api_mutex);
4665                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4666                 if (!rc) {
4667                         rc = lnet_udsp_apply_policies(NULL, false);
4668                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4669                         rc = 0;
4670                 }
4671                 mutex_unlock(&the_lnet.ln_api_mutex);
4672
4673                 return rc;
4674         }
4675
4676         case IOC_LIBCFS_DEL_UDSP: {
4677                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4678                 int idx = ioc_udsp->iou_idx;
4679
4680                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4681                         return -EINVAL;
4682
4683                 mutex_lock(&the_lnet.ln_api_mutex);
4684                 rc = lnet_udsp_del_policy(idx);
4685                 mutex_unlock(&the_lnet.ln_api_mutex);
4686
4687                 return rc;
4688         }
4689
4690         case IOC_LIBCFS_GET_UDSP_SIZE: {
4691                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4692                 struct lnet_udsp *udsp;
4693
4694                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4695                         return -EINVAL;
4696
4697                 rc = 0;
4698
4699                 mutex_lock(&the_lnet.ln_api_mutex);
4700                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4701                 if (!udsp) {
4702                         rc = -ENOENT;
4703                 } else {
4704                         /* coming in iou_idx will hold the idx of the udsp
4705                          * to get the size of. going out the iou_idx will
4706                          * hold the size of the UDSP found at the passed
4707                          * in index.
4708                          */
4709                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4710                         if (ioc_udsp->iou_idx < 0)
4711                                 rc = -EINVAL;
4712                 }
4713                 mutex_unlock(&the_lnet.ln_api_mutex);
4714
4715                 return rc;
4716         }
4717
4718         case IOC_LIBCFS_GET_UDSP: {
4719                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4720                 struct lnet_udsp *udsp;
4721
4722                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4723                         return -EINVAL;
4724
4725                 rc = 0;
4726
4727                 mutex_lock(&the_lnet.ln_api_mutex);
4728                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4729                 if (!udsp)
4730                         rc = -ENOENT;
4731                 else
4732                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4733                 mutex_unlock(&the_lnet.ln_api_mutex);
4734
4735                 return rc;
4736         }
4737
4738         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4739                 struct lnet_ioctl_construct_udsp_info *info = arg;
4740
4741                 if (info->cud_hdr.ioc_len < sizeof(*info))
4742                         return -EINVAL;
4743
4744                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4745                        libcfs_nid2str(info->cud_nid));
4746
4747                 lnet_nid4_to_nid(info->cud_nid, &nid);
4748                 mutex_lock(&the_lnet.ln_api_mutex);
4749                 lnet_net_lock(0);
4750                 lnet_udsp_get_construct_info(info, &nid);
4751                 lnet_net_unlock(0);
4752                 mutex_unlock(&the_lnet.ln_api_mutex);
4753
4754                 return 0;
4755         }
4756
4757         default:
4758                 ni = lnet_net2ni_addref(data->ioc_net);
4759                 if (ni == NULL)
4760                         return -EINVAL;
4761
4762                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4763                         rc = -EINVAL;
4764                 else
4765                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4766
4767                 lnet_ni_decref(ni);
4768                 return rc <= 0 ? rc : 0;
4769         }
4770         /* not reached */
4771 }
4772 EXPORT_SYMBOL(LNetCtl);
4773
4774 static int lnet_net_conf_cmd(struct sk_buff *skb, struct genl_info *info)
4775 {
4776         int rc = 0;
4777
4778         if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
4779                 /* NLM_F_EXCL means ignore module parameters */
4780                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
4781                         the_lnet.ln_nis_from_mod_params = true;
4782
4783                 rc = lnet_configure(NULL);
4784                 switch (rc) {
4785                 case -ENETDOWN:
4786                         GENL_SET_ERR_MSG(info,
4787                                          "Network is down");
4788                         break;
4789                 case -ENODEV:
4790                         GENL_SET_ERR_MSG(info,
4791                                          "LNET is currently not loaded");
4792                         break;
4793                 case -EBUSY:
4794                         GENL_SET_ERR_MSG(info, "LNET busy");
4795                         break;
4796                 default:
4797                         break;
4798                 }
4799         } else {
4800                 rc = lnet_unconfigure();
4801         }
4802
4803         return rc;
4804 };
4805
4806 struct lnet_nid_cpt {
4807         struct lnet_nid lnc_nid;
4808         unsigned int lnc_cpt;
4809 };
4810
4811 struct lnet_genl_nid_cpt_list {
4812         unsigned int lgncl_index;
4813         unsigned int lgncl_list_count;
4814         GENRADIX(struct lnet_nid_cpt) lgncl_lnc_list;
4815 };
4816
4817 static inline struct lnet_genl_nid_cpt_list *
4818 lnet_cpt_of_nid_dump_ctx(struct netlink_callback *cb)
4819 {
4820         return (struct lnet_genl_nid_cpt_list *)cb->args[0];
4821 }
4822
4823 static int lnet_cpt_of_nid_show_done(struct netlink_callback *cb)
4824 {
4825         struct lnet_genl_nid_cpt_list *lgncl;
4826
4827         lgncl = lnet_cpt_of_nid_dump_ctx(cb);
4828
4829         if (lgncl) {
4830                 genradix_free(&lgncl->lgncl_lnc_list);
4831                 LIBCFS_FREE(lgncl, sizeof(*lgncl));
4832                 cb->args[0] = 0;
4833         }
4834
4835         return 0;
4836 }
4837
4838 static int lnet_cpt_of_nid_show_start(struct netlink_callback *cb)
4839 {
4840         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
4841 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4842         struct netlink_ext_ack *extack = NULL;
4843 #endif
4844         struct lnet_genl_nid_cpt_list *lgncl;
4845         int msg_len = genlmsg_len(gnlh);
4846         struct nlattr *params, *top;
4847         int rem, rc = 0;
4848
4849 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4850         extack = cb->extack;
4851 #endif
4852
4853         mutex_lock(&the_lnet.ln_api_mutex);
4854         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
4855                 NL_SET_ERR_MSG(extack, "Network is down");
4856                 mutex_unlock(&the_lnet.ln_api_mutex);
4857                 return -ENETDOWN;
4858         }
4859
4860         msg_len = genlmsg_len(gnlh);
4861         if (!msg_len) {
4862                 NL_SET_ERR_MSG(extack, "Missing NID argument(s)");
4863                 mutex_unlock(&the_lnet.ln_api_mutex);
4864                 return -ENOENT;
4865         }
4866
4867         LIBCFS_ALLOC(lgncl, sizeof(*lgncl));
4868         if (!lgncl) {
4869                 mutex_unlock(&the_lnet.ln_api_mutex);
4870                 return -ENOMEM;
4871         }
4872
4873         genradix_init(&lgncl->lgncl_lnc_list);
4874         lgncl->lgncl_list_count = 0;
4875         cb->args[0] = (long)lgncl;
4876
4877         params = genlmsg_data(gnlh);
4878         nla_for_each_attr(top, params, msg_len, rem) {
4879                 struct nlattr *nids;
4880                 int rem2;
4881
4882                 switch (nla_type(top)) {
4883                 case LN_SCALAR_ATTR_LIST:
4884                         nla_for_each_nested(nids, top, rem2) {
4885                                 char nidstr[LNET_NIDSTR_SIZE + 1];
4886                                 struct lnet_nid_cpt *lnc;
4887
4888                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
4889                                         continue;
4890
4891                                 memset(nidstr, 0, sizeof(nidstr));
4892                                 rc = nla_strscpy(nidstr, nids, sizeof(nidstr));
4893                                 if (rc < 0) {
4894                                         NL_SET_ERR_MSG(extack,
4895                                                        "failed to get NID");
4896                                         GOTO(report_err, rc);
4897                                 }
4898
4899                                 lnc = genradix_ptr_alloc(&lgncl->lgncl_lnc_list,
4900                                                       lgncl->lgncl_list_count++,
4901                                                       GFP_KERNEL);
4902                                 if (!lnc) {
4903                                         NL_SET_ERR_MSG(extack,
4904                                                       "failed to allocate NID");
4905                                         GOTO(report_err, rc = -ENOMEM);
4906                                 }
4907
4908                                 rc = libcfs_strnid(&lnc->lnc_nid,
4909                                                    strim(nidstr));
4910                                 if (rc < 0) {
4911                                         NL_SET_ERR_MSG(extack, "invalid NID");
4912                                         GOTO(report_err, rc);
4913                                 }
4914                                 rc = 0;
4915                                 CDEBUG(D_NET, "nid: %s\n",
4916                                        libcfs_nidstr(&lnc->lnc_nid));
4917                         }
4918                         fallthrough;
4919                 default:
4920                         break;
4921                 }
4922         }
4923 report_err:
4924         mutex_unlock(&the_lnet.ln_api_mutex);
4925
4926         if (rc < 0)
4927                 lnet_cpt_of_nid_show_done(cb);
4928
4929         return rc;
4930 }
4931
4932 static const struct ln_key_list cpt_of_nid_props_list = {
4933         .lkl_maxattr                    = LNET_CPT_OF_NID_ATTR_MAX,
4934         .lkl_list                       = {
4935                 [LNET_CPT_OF_NID_ATTR_HDR]      = {
4936                         .lkp_value              = "cpt-of-nid",
4937                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4938                         .lkp_data_type          = NLA_NUL_STRING,
4939                 },
4940                 [LNET_CPT_OF_NID_ATTR_NID]      = {
4941                         .lkp_value              = "nid",
4942                         .lkp_data_type          = NLA_STRING,
4943                 },
4944                 [LNET_CPT_OF_NID_ATTR_CPT]      = {
4945                         .lkp_value              = "cpt",
4946                         .lkp_data_type          = NLA_U32,
4947                 },
4948         },
4949 };
4950
4951 static int lnet_cpt_of_nid_show_dump(struct sk_buff *msg,
4952                                      struct netlink_callback *cb)
4953 {
4954         struct lnet_genl_nid_cpt_list *lgncl;
4955 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4956         struct netlink_ext_ack *extack = NULL;
4957 #endif
4958         int portid = NETLINK_CB(cb->skb).portid;
4959         int seq = cb->nlh->nlmsg_seq;
4960         int idx;
4961         int rc = 0;
4962         bool need_hdr = true;
4963
4964 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4965         extack = cb->extack;
4966 #endif
4967
4968         mutex_lock(&the_lnet.ln_api_mutex);
4969         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
4970                 NL_SET_ERR_MSG(extack, "Network is down");
4971                 GOTO(send_error, rc = -ENETDOWN);
4972         }
4973
4974         lgncl = lnet_cpt_of_nid_dump_ctx(cb);
4975         idx = lgncl->lgncl_index;
4976
4977         if (!lgncl->lgncl_index) {
4978                 const struct ln_key_list *all[] = {
4979                         &cpt_of_nid_props_list, NULL, NULL
4980                 };
4981
4982                 rc = lnet_genl_send_scalar_list(msg, portid, seq, &lnet_family,
4983                                                 NLM_F_CREATE | NLM_F_MULTI,
4984                                                 LNET_CMD_CPT_OF_NID, all);
4985                 if (rc < 0) {
4986                         NL_SET_ERR_MSG(extack, "failed to send key table");
4987                         GOTO(send_error, rc);
4988                 }
4989         }
4990
4991         while (idx < lgncl->lgncl_list_count) {
4992                 struct lnet_nid_cpt *lnc;
4993                 void *hdr;
4994                 int cpt;
4995
4996                 lnc = genradix_ptr(&lgncl->lgncl_lnc_list, idx++);
4997
4998                 cpt = lnet_nid_cpt_hash(&lnc->lnc_nid, LNET_CPT_NUMBER);
4999
5000                 CDEBUG(D_NET, "nid: %s cpt: %d\n", libcfs_nidstr(&lnc->lnc_nid), cpt);
5001                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5002                                   NLM_F_MULTI, LNET_CMD_CPT_OF_NID);
5003                 if (!hdr) {
5004                         NL_SET_ERR_MSG(extack, "failed to send values");
5005                         genlmsg_cancel(msg, hdr);
5006                         GOTO(send_error, rc = -EMSGSIZE);
5007                 }
5008
5009                 if (need_hdr) {
5010                         nla_put_string(msg, LNET_CPT_OF_NID_ATTR_HDR, "");
5011                         need_hdr = false;
5012                 }
5013
5014                 nla_put_string(msg, LNET_CPT_OF_NID_ATTR_NID,
5015                                libcfs_nidstr(&lnc->lnc_nid));
5016                 nla_put_u32(msg, LNET_CPT_OF_NID_ATTR_CPT, cpt);
5017
5018                 genlmsg_end(msg, hdr);
5019         }
5020
5021         genradix_free(&lgncl->lgncl_lnc_list);
5022         rc = 0;
5023         lgncl->lgncl_index = idx;
5024
5025 send_error:
5026         mutex_unlock(&the_lnet.ln_api_mutex);
5027
5028         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5029 }
5030
5031 #ifndef HAVE_NETLINK_CALLBACK_START
5032 static int lnet_old_cpt_of_nid_show_dump(struct sk_buff *msg,
5033                                          struct netlink_callback *cb)
5034 {
5035         if (!cb->args[0]) {
5036                 int rc = lnet_cpt_of_nid_show_start(cb);
5037
5038                 if (rc < 0)
5039                         return lnet_nl_send_error(cb->skb,
5040                                                   NETLINK_CB(cb->skb).portid,
5041                                                   cb->nlh->nlmsg_seq,
5042                                                   rc);
5043         }
5044
5045         return lnet_cpt_of_nid_show_dump(msg, cb);
5046 }
5047 #endif
5048
5049 /* This is the keys for the UDSP info which is used by many
5050  * Netlink commands.
5051  */
5052 static const struct ln_key_list udsp_info_list = {
5053         .lkl_maxattr                    = LNET_UDSP_INFO_ATTR_MAX,
5054         .lkl_list                       = {
5055                 [LNET_UDSP_INFO_ATTR_NET_PRIORITY]              = {
5056                         .lkp_value      = "net priority",
5057                         .lkp_data_type  = NLA_S32
5058                 },
5059                 [LNET_UDSP_INFO_ATTR_NID_PRIORITY]              = {
5060                         .lkp_value      = "nid priority",
5061                         .lkp_data_type  = NLA_S32
5062                 },
5063                 [LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST]        = {
5064                         .lkp_value      = "Preferred gateway NIDs",
5065                         .lkp_key_format = LNKF_MAPPING,
5066                         .lkp_data_type  = NLA_NESTED,
5067                 },
5068                 [LNET_UDSP_INFO_ATTR_PREF_NIDS_LIST]            = {
5069                         .lkp_value      = "Preferred source NIDs",
5070                         .lkp_key_format = LNKF_MAPPING,
5071                         .lkp_data_type  = NLA_NESTED,
5072                 },
5073         },
5074 };
5075
5076 static const struct ln_key_list udsp_info_pref_nids_list = {
5077         .lkl_maxattr                    = LNET_UDSP_INFO_PREF_NIDS_ATTR_MAX,
5078         .lkl_list                       = {
5079                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX]           = {
5080                         .lkp_value      = "NID-0",
5081                         .lkp_data_type  = NLA_NUL_STRING,
5082                 },
5083                 [LNET_UDSP_INFO_PREF_NIDS_ATTR_NID]             = {
5084                         .lkp_value      = "0@lo",
5085                         .lkp_data_type  = NLA_STRING,
5086                 },
5087         },
5088 };
5089
5090 static int lnet_udsp_info_send(struct sk_buff *msg, int attr,
5091                                struct lnet_nid *nid, bool remote)
5092 {
5093         struct lnet_ioctl_construct_udsp_info *udsp;
5094         struct nlattr *udsp_attr, *udsp_info;
5095         struct nlattr *udsp_list_attr;
5096         struct nlattr *udsp_list_info;
5097         int i;
5098
5099         CFS_ALLOC_PTR(udsp);
5100         if (!udsp)
5101                 return -ENOMEM;
5102
5103         udsp->cud_peer = remote;
5104         lnet_udsp_get_construct_info(udsp, nid);
5105
5106         udsp_info = nla_nest_start(msg, attr);
5107         udsp_attr = nla_nest_start(msg, 0);
5108         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NET_PRIORITY,
5109                     udsp->cud_net_priority);
5110         nla_put_s32(msg, LNET_UDSP_INFO_ATTR_NID_PRIORITY,
5111                     udsp->cud_nid_priority);
5112
5113         if (udsp->cud_pref_rtr_nid[0] == 0)
5114                 goto skip_list;
5115
5116         udsp_list_info = nla_nest_start(msg,
5117                                         LNET_UDSP_INFO_ATTR_PREF_RTR_NIDS_LIST);
5118         for (i = 0; i < LNET_MAX_SHOW_NUM_NID; i++) {
5119                 char tmp[8]; /* NID-"3 number"\0 */
5120
5121                 if (udsp->cud_pref_rtr_nid[i] == 0)
5122                         break;
5123
5124                 udsp_list_attr = nla_nest_start(msg, i);
5125                 snprintf(tmp, sizeof(tmp), "NID-%d", i);
5126                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_INDEX,
5127                                tmp);
5128                 nla_put_string(msg, LNET_UDSP_INFO_PREF_NIDS_ATTR_NID,
5129                                libcfs_nid2str(udsp->cud_pref_rtr_nid[i]));
5130                 nla_nest_end(msg, udsp_list_attr);
5131         }
5132         nla_nest_end(msg, udsp_list_info);
5133 skip_list:
5134         nla_nest_end(msg, udsp_attr);
5135         nla_nest_end(msg, udsp_info);
5136         LIBCFS_FREE(udsp, sizeof(*udsp));
5137
5138         return 0;
5139 }
5140
5141 /* LNet NI handling */
5142 static const struct ln_key_list net_props_list = {
5143         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
5144         .lkl_list                       = {
5145                 [LNET_NET_ATTR_HDR]             = {
5146                         .lkp_value              = "net",
5147                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5148                         .lkp_data_type          = NLA_NUL_STRING,
5149                 },
5150                 [LNET_NET_ATTR_TYPE]            = {
5151                         .lkp_value              = "net type",
5152                         .lkp_data_type          = NLA_STRING
5153                 },
5154                 [LNET_NET_ATTR_LOCAL]           = {
5155                         .lkp_value              = "local NI(s)",
5156                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5157                         .lkp_data_type          = NLA_NESTED
5158                 },
5159         },
5160 };
5161
5162 static struct ln_key_list local_ni_list = {
5163         .lkl_maxattr                    = LNET_NET_LOCAL_NI_ATTR_MAX,
5164         .lkl_list                       = {
5165                 [LNET_NET_LOCAL_NI_ATTR_NID]            = {
5166                         .lkp_value              = "nid",
5167                         .lkp_data_type          = NLA_STRING
5168                 },
5169                 [LNET_NET_LOCAL_NI_ATTR_STATUS]         = {
5170                         .lkp_value              = "status",
5171                         .lkp_data_type          = NLA_STRING
5172                 },
5173                 [LNET_NET_LOCAL_NI_ATTR_INTERFACE]      = {
5174                         .lkp_value              = "interfaces",
5175                         .lkp_key_format         = LNKF_MAPPING,
5176                         .lkp_data_type          = NLA_NESTED
5177                 },
5178                 [LNET_NET_LOCAL_NI_ATTR_STATS]          = {
5179                         .lkp_value              = "statistics",
5180                         .lkp_key_format         = LNKF_MAPPING,
5181                         .lkp_data_type          = NLA_NESTED
5182                 },
5183                 [LNET_NET_LOCAL_NI_ATTR_UDSP_INFO]      = {
5184                         .lkp_value              = "udsp info",
5185                         .lkp_key_format         = LNKF_MAPPING,
5186                         .lkp_data_type          = NLA_NESTED
5187                 },
5188                 [LNET_NET_LOCAL_NI_ATTR_SEND_STATS]     = {
5189                         .lkp_value              = "sent_stats",
5190                         .lkp_key_format         = LNKF_MAPPING,
5191                         .lkp_data_type          = NLA_NESTED
5192                 },
5193                 [LNET_NET_LOCAL_NI_ATTR_RECV_STATS]     = {
5194                         .lkp_value              = "received_stats",
5195                         .lkp_key_format         = LNKF_MAPPING,
5196                         .lkp_data_type          = NLA_NESTED
5197                 },
5198                 [LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS]  = {
5199                         .lkp_value              = "dropped_stats",
5200                         .lkp_key_format         = LNKF_MAPPING,
5201                         .lkp_data_type          = NLA_NESTED
5202
5203                 },
5204                 [LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS]   = {
5205                         .lkp_value              = "health stats",
5206                         .lkp_key_format         = LNKF_MAPPING,
5207                         .lkp_data_type          = NLA_NESTED
5208                 },
5209                 [LNET_NET_LOCAL_NI_ATTR_TUNABLES]       = {
5210                         .lkp_value              = "tunables",
5211                         .lkp_key_format         = LNKF_MAPPING,
5212                         .lkp_data_type          = NLA_NESTED
5213                 },
5214                 [LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES]   = {
5215                         .lkp_value              = "lnd tunables",
5216                         .lkp_key_format         = LNKF_MAPPING,
5217                         .lkp_data_type          = NLA_NESTED
5218                 },
5219                 [LNET_NET_LOCAL_NI_DEV_CPT]             = {
5220                         .lkp_value              = "dev cpt",
5221                         .lkp_data_type          = NLA_S32,
5222                 },
5223                 [LNET_NET_LOCAL_NI_CPTS]                = {
5224                         .lkp_value              = "CPT",
5225                         .lkp_data_type          = NLA_STRING,
5226                 },
5227         },
5228 };
5229
5230 static const struct ln_key_list local_ni_interfaces_list = {
5231         .lkl_maxattr                    = LNET_NET_LOCAL_NI_INTF_ATTR_MAX,
5232         .lkl_list                       = {
5233                 [LNET_NET_LOCAL_NI_INTF_ATTR_TYPE] = {
5234                         .lkp_value      = "0",
5235                         .lkp_data_type  = NLA_STRING
5236                 },
5237         },
5238 };
5239
5240 static const struct ln_key_list local_ni_stats_list = {
5241         .lkl_maxattr                    = LNET_NET_LOCAL_NI_STATS_ATTR_MAX,
5242         .lkl_list                       = {
5243                 [LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT]       = {
5244                         .lkp_value      = "send_count",
5245                         .lkp_data_type  = NLA_U32
5246                 },
5247                 [LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT]       = {
5248                         .lkp_value      = "recv_count",
5249                         .lkp_data_type  = NLA_U32
5250                 },
5251                 [LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT]       = {
5252                         .lkp_value      = "drop_count",
5253                         .lkp_data_type  = NLA_U32
5254                 },
5255         },
5256 };
5257
5258 static const struct ln_key_list local_ni_msg_stats_list = {
5259         .lkl_maxattr                    = LNET_NET_LOCAL_NI_MSG_STATS_ATTR_MAX,
5260         .lkl_list                       = {
5261                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT]    = {
5262                         .lkp_value      = "put",
5263                         .lkp_data_type  = NLA_U32
5264                 },
5265                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT]    = {
5266                         .lkp_value      = "get",
5267                         .lkp_data_type  = NLA_U32
5268                 },
5269                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT]  = {
5270                         .lkp_value      = "reply",
5271                         .lkp_data_type  = NLA_U32
5272                 },
5273                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT]    = {
5274                         .lkp_value      = "ack",
5275                         .lkp_data_type  = NLA_U32
5276                 },
5277                 [LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT]  = {
5278                         .lkp_value      = "hello",
5279                         .lkp_data_type  = NLA_U32
5280                 },
5281         },
5282 };
5283
5284 static const struct ln_key_list local_ni_health_stats_list = {
5285         .lkl_maxattr                    = LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_MAX,
5286         .lkl_list                       = {
5287                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS] = {
5288                         .lkp_value      = "fatal_error",
5289                         .lkp_data_type  = NLA_S32
5290                 },
5291                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL] = {
5292                         .lkp_value      = "health value",
5293                         .lkp_data_type  = NLA_S32
5294                 },
5295                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS] = {
5296                         .lkp_value      = "interrupts",
5297                         .lkp_data_type  = NLA_U32
5298                 },
5299                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED] = {
5300                         .lkp_value      = "dropped",
5301                         .lkp_data_type  = NLA_U32
5302                 },
5303                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED] = {
5304                         .lkp_value      = "aborted",
5305                         .lkp_data_type  = NLA_U32
5306                 },
5307                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE] = {
5308                         .lkp_value      = "no route",
5309                         .lkp_data_type  = NLA_U32
5310                 },
5311                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS] = {
5312                         .lkp_value      = "timeouts",
5313                         .lkp_data_type  = NLA_U32
5314                 },
5315                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR] = {
5316                         .lkp_value      = "error",
5317                         .lkp_data_type  = NLA_U32
5318                 },
5319                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT] = {
5320                         .lkp_value      = "ping_count",
5321                         .lkp_data_type  = NLA_U32,
5322                 },
5323                 [LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING] = {
5324                         .lkp_value      = "next_ping",
5325                         .lkp_data_type  = NLA_U64
5326                 },
5327         },
5328 };
5329
5330 static const struct ln_key_list local_ni_tunables_list = {
5331         .lkl_maxattr                    = LNET_NET_LOCAL_NI_TUNABLES_ATTR_MAX,
5332         .lkl_list                       = {
5333                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT]  = {
5334                         .lkp_value      = "peer_timeout",
5335                         .lkp_data_type  = NLA_S32
5336                 },
5337                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS]  = {
5338                         .lkp_value      = "peer_credits",
5339                         .lkp_data_type  = NLA_S32
5340                 },
5341                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS] = {
5342                         .lkp_value      = "peer_buffer_credits",
5343                         .lkp_data_type  = NLA_S32
5344                 },
5345                 [LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS] = {
5346                         .lkp_value      = "credits",
5347                         .lkp_data_type  = NLA_S32
5348                 },
5349         },
5350 };
5351
5352 /* Use an index since the traversal is across LNet nets and ni collections */
5353 struct lnet_genl_net_list {
5354         unsigned int    lngl_net_id;
5355         unsigned int    lngl_idx;
5356 };
5357
5358 static inline struct lnet_genl_net_list *
5359 lnet_net_dump_ctx(struct netlink_callback *cb)
5360 {
5361         return (struct lnet_genl_net_list *)cb->args[0];
5362 }
5363
5364 static int lnet_net_show_done(struct netlink_callback *cb)
5365 {
5366         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5367
5368         if (nlist) {
5369                 LIBCFS_FREE(nlist, sizeof(*nlist));
5370                 cb->args[0] = 0;
5371         }
5372
5373         return 0;
5374 }
5375
5376 /* LNet net ->start() handler for GET requests */
5377 static int lnet_net_show_start(struct netlink_callback *cb)
5378 {
5379         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5380 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5381         struct netlink_ext_ack *extack = NULL;
5382 #endif
5383         struct lnet_genl_net_list *nlist;
5384         int msg_len = genlmsg_len(gnlh);
5385         struct nlattr *params, *top;
5386         int rem, rc = 0;
5387
5388 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5389         extack = cb->extack;
5390 #endif
5391         if (the_lnet.ln_refcount == 0) {
5392                 NL_SET_ERR_MSG(extack, "LNet stack down");
5393                 return -ENETDOWN;
5394         }
5395
5396         LIBCFS_ALLOC(nlist, sizeof(*nlist));
5397         if (!nlist)
5398                 return -ENOMEM;
5399
5400         nlist->lngl_net_id = LNET_NET_ANY;
5401         nlist->lngl_idx = 0;
5402         cb->args[0] = (long)nlist;
5403
5404         cb->min_dump_alloc = U16_MAX;
5405         if (!msg_len)
5406                 return 0;
5407
5408         params = genlmsg_data(gnlh);
5409         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
5410                 NL_SET_ERR_MSG(extack, "invalid configuration");
5411                 return -EINVAL;
5412         }
5413
5414         nla_for_each_nested(top, params, rem) {
5415                 struct nlattr *net;
5416                 int rem2;
5417
5418                 nla_for_each_nested(net, top, rem2) {
5419                         char filter[LNET_NIDSTR_SIZE];
5420
5421                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE ||
5422                             nla_strcmp(net, "net type") != 0)
5423                                 continue;
5424
5425                         net = nla_next(net, &rem2);
5426                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE) {
5427                                 NL_SET_ERR_MSG(extack, "invalid config param");
5428                                 GOTO(report_err, rc = -EINVAL);
5429                         }
5430
5431                         rc = nla_strscpy(filter, net, sizeof(filter));
5432                         if (rc < 0) {
5433                                 NL_SET_ERR_MSG(extack, "failed to get param");
5434                                 GOTO(report_err, rc);
5435                         }
5436                         rc = 0;
5437
5438                         nlist->lngl_net_id = libcfs_str2net(filter);
5439                         if (nlist->lngl_net_id == LNET_NET_ANY) {
5440                                 NL_SET_ERR_MSG(extack, "cannot parse net");
5441                                 GOTO(report_err, rc = -ENOENT);
5442                         }
5443                 }
5444         }
5445 report_err:
5446         if (rc < 0)
5447                 lnet_net_show_done(cb);
5448
5449         return rc;
5450 }
5451
5452 static const struct ln_key_list net_update_props_list = {
5453         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
5454         .lkl_list                       = {
5455                 [LNET_NET_ATTR_HDR]             = {
5456                         .lkp_value              = "",
5457                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5458                         .lkp_data_type          = NLA_NUL_STRING,
5459                 },
5460                 [LNET_NET_ATTR_TYPE]            = {
5461                         .lkp_value              = "net type",
5462                         .lkp_data_type          = NLA_STRING
5463                 },
5464                 [LNET_NET_ATTR_LOCAL]           = {
5465                         .lkp_value              = "local NI(s)",
5466                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5467                         .lkp_data_type          = NLA_NESTED
5468                 },
5469         },
5470 };
5471
5472 static int lnet_net_show_dump(struct sk_buff *msg,
5473                               struct netlink_callback *cb)
5474 {
5475         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
5476 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5477         struct netlink_ext_ack *extack = NULL;
5478 #endif
5479         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5480         int portid = NETLINK_CB(cb->skb).portid;
5481         bool found = false, started = false;
5482         const struct lnet_lnd *lnd = NULL;
5483         int idx = nlist->lngl_idx, rc = 0;
5484         int seq = cb->nlh->nlmsg_seq;
5485         struct lnet_net *net;
5486         void *hdr = NULL;
5487
5488 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5489         extack = cb->extack;
5490 #endif
5491         lnet_net_lock(LNET_LOCK_EX);
5492
5493         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
5494                 struct nlattr *local_ni, *ni_attr;
5495                 struct lnet_ni *ni;
5496                 int dev = 0;
5497
5498                 if (nlist->lngl_net_id != LNET_NET_ANY &&
5499                     nlist->lngl_net_id != net->net_id)
5500                         continue;
5501
5502                 if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED &&
5503                     LNET_NETTYP(net->net_id) == LOLND)
5504                         continue;
5505
5506                 if (gnlh->version && LNET_NETTYP(net->net_id) != LOLND) {
5507                         if (!net->net_lnd) {
5508                                 NL_SET_ERR_MSG(extack,
5509                                                "LND not setup for NI");
5510                                 GOTO(net_unlock, rc = -ENODEV);
5511                         }
5512                         if (net->net_lnd != lnd)
5513                                 lnd = net->net_lnd;
5514                         else
5515                                 lnd = NULL;
5516                 }
5517
5518                 /* We need to resend the key table every time the base LND
5519                  * changed.
5520                  */
5521                 if (!idx || lnd) {
5522                         const struct ln_key_list *all[] = {
5523                                 &net_props_list, &local_ni_list,
5524                                 &local_ni_interfaces_list,
5525                                 &local_ni_stats_list,
5526                                 &udsp_info_list,
5527                                 &udsp_info_pref_nids_list,
5528                                 &udsp_info_pref_nids_list,
5529                                 &local_ni_msg_stats_list,
5530                                 &local_ni_msg_stats_list,
5531                                 &local_ni_msg_stats_list,
5532                                 &local_ni_health_stats_list,
5533                                 &local_ni_tunables_list,
5534                                 NULL, /* lnd tunables */
5535                                 NULL
5536                         };
5537                         int flags = NLM_F_CREATE | NLM_F_MULTI;
5538
5539                         if (lnd) {
5540                                 all[ARRAY_SIZE(all) - 2] = lnd->lnd_keys;
5541                                 if (idx) {
5542                                         all[0] = &net_update_props_list;
5543                                         flags |= NLM_F_REPLACE;
5544                                 }
5545                         }
5546
5547                         rc = lnet_genl_send_scalar_list(msg, portid, seq,
5548                                                         &lnet_family, flags,
5549                                                         LNET_CMD_NETS, all);
5550                         if (rc < 0) {
5551                                 NL_SET_ERR_MSG(extack, "failed to send key table");
5552                                 GOTO(net_unlock, rc);
5553                         }
5554                         started = true;
5555                 }
5556
5557                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5558                                   NLM_F_MULTI, LNET_CMD_NETS);
5559                 if (!hdr) {
5560                         NL_SET_ERR_MSG(extack, "failed to send values");
5561                         GOTO(net_unlock, rc = -EMSGSIZE);
5562                 }
5563
5564                 if (started) {
5565                         nla_put_string(msg, LNET_NET_ATTR_HDR, "");
5566                         started = false;
5567                 }
5568
5569                 nla_put_string(msg, LNET_NET_ATTR_TYPE,
5570                                libcfs_net2str(net->net_id));
5571
5572                 local_ni = nla_nest_start(msg, LNET_NET_ATTR_LOCAL);
5573                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
5574                         char *status = "up";
5575
5576                         if (idx++ < nlist->lngl_idx)
5577                                 continue;
5578
5579                         ni_attr = nla_nest_start(msg, dev++);
5580                         found = true;
5581                         lnet_ni_lock(ni);
5582                         if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)) {
5583                                 nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_NID,
5584                                                libcfs_nidstr(&ni->ni_nid));
5585                                 if (!nid_is_lo0(&ni->ni_nid) &&
5586                                     lnet_ni_get_status_locked(ni) != LNET_NI_STATUS_UP)
5587                                         status = "down";
5588                                 nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_STATUS,
5589                                                status);
5590                         }
5591
5592                         if (!nid_is_lo0(&ni->ni_nid) && ni->ni_interface) {
5593                                 struct nlattr *intf_nest, *intf_attr;
5594
5595                                 intf_nest = nla_nest_start(msg,
5596                                                            LNET_NET_LOCAL_NI_ATTR_INTERFACE);
5597                                 intf_attr = nla_nest_start(msg, 0);
5598                                 nla_put_string(msg,
5599                                                LNET_NET_LOCAL_NI_INTF_ATTR_TYPE,
5600                                                ni->ni_interface);
5601                                 nla_nest_end(msg, intf_attr);
5602                                 nla_nest_end(msg, intf_nest);
5603                         }
5604
5605                         if (gnlh->version) {
5606                                 char cpts[LNET_MAX_SHOW_NUM_CPT * 4 + 4], *cpt;
5607                                 struct lnet_ioctl_element_msg_stats msg_stats;
5608                                 struct lnet_ioctl_element_stats stats;
5609                                 size_t buf_len = sizeof(cpts), len;
5610                                 struct nlattr *health_attr, *health_stats;
5611                                 struct nlattr *send_attr, *send_stats;
5612                                 struct nlattr *recv_attr, *recv_stats;
5613                                 struct nlattr *drop_attr, *drop_stats;
5614                                 struct nlattr *stats_attr, *ni_stats;
5615                                 struct nlattr *tun_attr, *ni_tun;
5616                                 int j;
5617
5618                                 if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED) {
5619                                         lnet_ni_unlock(ni);
5620                                         goto skip_msg_stats;
5621                                 }
5622
5623                                 stats.iel_send_count = lnet_sum_stats(&ni->ni_stats,
5624                                                                       LNET_STATS_TYPE_SEND);
5625                                 stats.iel_recv_count = lnet_sum_stats(&ni->ni_stats,
5626                                                                       LNET_STATS_TYPE_RECV);
5627                                 stats.iel_drop_count = lnet_sum_stats(&ni->ni_stats,
5628                                                                       LNET_STATS_TYPE_DROP);
5629                                 lnet_ni_unlock(ni);
5630
5631                                 stats_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_STATS);
5632                                 ni_stats = nla_nest_start(msg, 0);
5633                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_SEND_COUNT,
5634                                             stats.iel_send_count);
5635                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_RECV_COUNT,
5636                                             stats.iel_recv_count);
5637                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_STATS_ATTR_DROP_COUNT,
5638                                             stats.iel_drop_count);
5639                                 nla_nest_end(msg, ni_stats);
5640                                 nla_nest_end(msg, stats_attr);
5641
5642                                 if (gnlh->version < 4)
5643                                         goto skip_udsp;
5644
5645                                 /* UDSP info */
5646                                 rc = lnet_udsp_info_send(msg, LNET_NET_LOCAL_NI_ATTR_UDSP_INFO,
5647                                                          &ni->ni_nid, false);
5648                                 if (rc < 0) {
5649                                         NL_SET_ERR_MSG(extack,
5650                                                        "Failed to get udsp info");
5651                                         genlmsg_cancel(msg, hdr);
5652                                         GOTO(net_unlock, rc = -ENOMEM);
5653                                 }
5654 skip_udsp:
5655                                 if (gnlh->version < 2)
5656                                         goto skip_msg_stats;
5657
5658                                 msg_stats.im_idx = idx - 1;
5659                                 rc = lnet_get_ni_stats(&msg_stats);
5660                                 if (rc < 0) {
5661                                         NL_SET_ERR_MSG(extack,
5662                                                        "failed to get msg stats");
5663                                         genlmsg_cancel(msg, hdr);
5664                                         GOTO(net_unlock, rc = -ENOMEM);
5665                                 }
5666
5667                                 send_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_SEND_STATS);
5668                                 send_attr = nla_nest_start(msg, 0);
5669                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5670                                             msg_stats.im_send_stats.ico_get_count);
5671                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5672                                             msg_stats.im_send_stats.ico_put_count);
5673                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5674                                             msg_stats.im_send_stats.ico_reply_count);
5675                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5676                                             msg_stats.im_send_stats.ico_ack_count);
5677                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5678                                             msg_stats.im_send_stats.ico_hello_count);
5679                                 nla_nest_end(msg, send_attr);
5680                                 nla_nest_end(msg, send_stats);
5681
5682                                 recv_stats = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_RECV_STATS);
5683                                 recv_attr = nla_nest_start(msg, 0);
5684                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5685                                             msg_stats.im_recv_stats.ico_get_count);
5686                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5687                                             msg_stats.im_recv_stats.ico_put_count);
5688                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5689                                             msg_stats.im_recv_stats.ico_reply_count);
5690                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5691                                             msg_stats.im_recv_stats.ico_ack_count);
5692                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5693                                             msg_stats.im_recv_stats.ico_hello_count);
5694                                 nla_nest_end(msg, recv_attr);
5695                                 nla_nest_end(msg, recv_stats);
5696
5697                                 drop_stats = nla_nest_start(msg,
5698                                                             LNET_NET_LOCAL_NI_ATTR_DROPPED_STATS);
5699                                 drop_attr = nla_nest_start(msg, 0);
5700                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_PUT_COUNT,
5701                                             msg_stats.im_drop_stats.ico_get_count);
5702                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_GET_COUNT,
5703                                             msg_stats.im_drop_stats.ico_put_count);
5704                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_REPLY_COUNT,
5705                                             msg_stats.im_drop_stats.ico_reply_count);
5706                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_ACK_COUNT,
5707                                             msg_stats.im_drop_stats.ico_ack_count);
5708                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_MSG_STATS_ATTR_HELLO_COUNT,
5709                                             msg_stats.im_drop_stats.ico_hello_count);
5710                                 nla_nest_end(msg, drop_attr);
5711                                 nla_nest_end(msg, drop_stats);
5712
5713                                 /* health stats */
5714                                 health_stats = nla_nest_start(msg,
5715                                                               LNET_NET_LOCAL_NI_ATTR_HEALTH_STATS);
5716                                 health_attr = nla_nest_start(msg, 0);
5717                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_FATAL_ERRORS,
5718                                             atomic_read(&ni->ni_fatal_error_on));
5719                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_LEVEL,
5720                                             atomic_read(&ni->ni_healthv));
5721                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_INTERRUPTS,
5722                                             atomic_read(&ni->ni_hstats.hlt_local_interrupt));
5723                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_DROPPED,
5724                                             atomic_read(&ni->ni_hstats.hlt_local_dropped));
5725                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ABORTED,
5726                                             atomic_read(&ni->ni_hstats.hlt_local_aborted));
5727                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NO_ROUTE,
5728                                             atomic_read(&ni->ni_hstats.hlt_local_no_route));
5729                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_TIMEOUTS,
5730                                             atomic_read(&ni->ni_hstats.hlt_local_timeout));
5731                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_ERROR,
5732                                             atomic_read(&ni->ni_hstats.hlt_local_error));
5733                                 nla_put_u32(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PING_COUNT,
5734                                             ni->ni_ping_count);
5735                                 nla_put_u64_64bit(msg, LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_NEXT_PING,
5736                                                   ni->ni_next_ping,
5737                                                   LNET_NET_LOCAL_NI_HEALTH_STATS_ATTR_PAD);
5738                                 nla_nest_end(msg, health_attr);
5739                                 nla_nest_end(msg, health_stats);
5740 skip_msg_stats:
5741                                 /* Report net tunables */
5742                                 tun_attr = nla_nest_start(msg, LNET_NET_LOCAL_NI_ATTR_TUNABLES);
5743                                 ni_tun = nla_nest_start(msg, 0);
5744                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT,
5745                                             ni->ni_net->net_tunables.lct_peer_timeout);
5746                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS,
5747                                             ni->ni_net->net_tunables.lct_peer_tx_credits);
5748                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS,
5749                                             ni->ni_net->net_tunables.lct_peer_rtr_credits);
5750                                 nla_put_s32(msg, LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS,
5751                                             ni->ni_net->net_tunables.lct_max_tx_credits);
5752                                 nla_nest_end(msg, ni_tun);
5753
5754                                 nla_nest_end(msg, tun_attr);
5755
5756                                 if (lnd && lnd->lnd_nl_get && lnd->lnd_keys) {
5757                                         struct nlattr *lnd_tun_attr, *lnd_ni_tun;
5758
5759                                         lnd_tun_attr = nla_nest_start(msg,
5760                                                                       LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES);
5761                                         lnd_ni_tun = nla_nest_start(msg, 0);
5762                                         rc = lnd->lnd_nl_get(LNET_CMD_NETS, msg,
5763                                                              LNET_NET_LOCAL_NI_ATTR_LND_TUNABLES,
5764                                                              ni);
5765                                         if (rc < 0) {
5766                                                 NL_SET_ERR_MSG(extack,
5767                                                                "failed to get lnd tunables");
5768                                                 genlmsg_cancel(msg, hdr);
5769                                                 GOTO(net_unlock, rc);
5770                                         }
5771                                         nla_nest_end(msg, lnd_ni_tun);
5772                                         nla_nest_end(msg, lnd_tun_attr);
5773                                 }
5774
5775                                 if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED))
5776                                         nla_put_s32(msg, LNET_NET_LOCAL_NI_DEV_CPT,
5777                                                     ni->ni_dev_cpt);
5778
5779                                 /* Report cpts. We could send this as a nested list
5780                                  * of integers but older versions of the tools
5781                                  * except a string. The new versions can handle
5782                                  * both formats so in the future we can change
5783                                  * this to a nested list.
5784                                  */
5785                                 len = snprintf(cpts, buf_len, "\"[");
5786                                 cpt = cpts + len;
5787                                 buf_len -= len;
5788
5789                                 if (ni->ni_ncpts == LNET_CPT_NUMBER && !ni->ni_cpts)  {
5790                                         for (j = 0; j < ni->ni_ncpts; j++) {
5791                                                 len = snprintf(cpt, buf_len, "%d,", j);
5792                                                 buf_len -= len;
5793                                                 cpt += len;
5794                                         }
5795                                 } else {
5796                                         for (j = 0;
5797                                              ni->ni_cpts && j < ni->ni_ncpts &&
5798                                              j < LNET_MAX_SHOW_NUM_CPT; j++) {
5799                                                 len = snprintf(cpt, buf_len, "%d,",
5800                                                                ni->ni_cpts[j]);
5801                                                 buf_len -= len;
5802                                                 cpt += len;
5803                                         }
5804                                 }
5805                                 snprintf(cpt - 1, sizeof(cpts), "]\"");
5806
5807                                 nla_put_string(msg, LNET_NET_LOCAL_NI_CPTS, cpts);
5808                         } else {
5809                                 lnet_ni_unlock(ni);
5810                         }
5811                         nla_nest_end(msg, ni_attr);
5812                 }
5813                 nla_nest_end(msg, local_ni);
5814
5815                 genlmsg_end(msg, hdr);
5816         }
5817
5818         if (!found) {
5819                 struct nlmsghdr *nlh = nlmsg_hdr(msg);
5820
5821                 nlmsg_cancel(msg, nlh);
5822                 NL_SET_ERR_MSG(extack, "Network is down");
5823                 rc = -ESRCH;
5824         }
5825         nlist->lngl_idx = idx;
5826 net_unlock:
5827         lnet_net_unlock(LNET_LOCK_EX);
5828
5829         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5830 }
5831
5832 #ifndef HAVE_NETLINK_CALLBACK_START
5833 static int lnet_old_net_show_dump(struct sk_buff *msg,
5834                                    struct netlink_callback *cb)
5835 {
5836         if (!cb->args[0]) {
5837                 int rc = lnet_net_show_start(cb);
5838
5839                 if (rc < 0)
5840                         return lnet_nl_send_error(cb->skb,
5841                                                   NETLINK_CB(cb->skb).portid,
5842                                                   cb->nlh->nlmsg_seq,
5843                                                   rc);
5844         }
5845
5846         return lnet_net_show_dump(msg, cb);
5847 }
5848 #endif
5849
5850 static int lnet_genl_parse_tunables(struct nlattr *settings,
5851                                     struct lnet_ioctl_config_lnd_tunables *tun)
5852 {
5853         struct nlattr *param;
5854         int rem, rc = 0;
5855
5856         nla_for_each_nested(param, settings, rem) {
5857                 int type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_UNSPEC;
5858                 s64 num;
5859
5860                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5861                         continue;
5862
5863                 if (nla_strcmp(param, "peer_timeout") == 0)
5864                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT;
5865                 else if (nla_strcmp(param, "peer_credits") == 0)
5866                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS;
5867                 else if (nla_strcmp(param, "peer_buffer_credits") == 0)
5868                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS;
5869                 else if (nla_strcmp(param, "credits") == 0)
5870                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS;
5871
5872                 param = nla_next(param, &rem);
5873                 if (nla_type(param) != LN_SCALAR_ATTR_INT_VALUE)
5874                         return -EINVAL;
5875
5876                 num = nla_get_s64(param);
5877                 switch (type) {
5878                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT:
5879                         if (num >= 0)
5880                                 tun->lt_cmn.lct_peer_timeout = num;
5881                         break;
5882                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS:
5883                         if (num > 0)
5884                                 tun->lt_cmn.lct_peer_tx_credits = num;
5885                         break;
5886                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS:
5887                         if (num > 0)
5888                                 tun->lt_cmn.lct_peer_rtr_credits = num;
5889                         break;
5890                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS:
5891                         if (num > 0)
5892                                 tun->lt_cmn.lct_max_tx_credits = num;
5893                         break;
5894                 default:
5895                         rc = -EINVAL;
5896                         break;
5897                 }
5898         }
5899         return rc;
5900 }
5901
5902 static int lnet_genl_parse_lnd_tunables(struct nlattr *settings,
5903                                         struct lnet_lnd_tunables *tun,
5904                                         const struct lnet_lnd *lnd)
5905 {
5906         const struct ln_key_list *list = lnd->lnd_keys;
5907         struct nlattr *param;
5908         int rem, rc = 0;
5909         int i = 1;
5910
5911         /* silently ignore these setting if the LND driver doesn't
5912          * support any LND tunables
5913          */
5914         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5915                 return 0;
5916
5917         nla_for_each_nested(param, settings, rem) {
5918                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5919                         continue;
5920
5921                 for (i = 1; i <= list->lkl_maxattr; i++) {
5922                         if (!list->lkl_list[i].lkp_value ||
5923                             nla_strcmp(param, list->lkl_list[i].lkp_value) != 0)
5924                                 continue;
5925
5926                         param = nla_next(param, &rem);
5927                         rc = lnd->lnd_nl_set(LNET_CMD_NETS, param, i, tun);
5928                         if (rc < 0)
5929                                 return rc;
5930                 }
5931         }
5932
5933         return rc;
5934 }
5935
5936 static inline void
5937 lnet_genl_init_tunables(const struct lnet_lnd *lnd,
5938                         struct lnet_ioctl_config_lnd_tunables *tun)
5939 {
5940         const struct ln_key_list *list = lnd ? lnd->lnd_keys : NULL;
5941         int i;
5942
5943         tun->lt_cmn.lct_peer_timeout = -1;
5944         tun->lt_cmn.lct_peer_tx_credits = -1;
5945         tun->lt_cmn.lct_peer_rtr_credits = -1;
5946         tun->lt_cmn.lct_max_tx_credits = -1;
5947
5948         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5949                 return;
5950
5951         /* init lnd tunables with default values */
5952         for (i = 1; i <= list->lkl_maxattr; i++)
5953                 lnd->lnd_nl_set(LNET_CMD_NETS, NULL, i, &tun->lt_tun);
5954 }
5955
5956 static int
5957 lnet_genl_parse_local_ni(struct nlattr *entry, struct genl_info *info,
5958                          int net_id, struct lnet_ioctl_config_ni *conf,
5959                          bool *ni_list)
5960 {
5961         struct lnet_ioctl_config_lnd_tunables *tun;
5962         struct lnet_nid nid = LNET_ANY_NID;
5963         const struct lnet_lnd *lnd = NULL;
5964         struct nlattr *settings;
5965         int healthv = -1;
5966         int rem3, rc = 0;
5967
5968         if (net_id != LNET_NET_ANY) {
5969                 lnd = lnet_load_lnd(LNET_NETTYP(net_id));
5970                 if (IS_ERR(lnd)) {
5971                         GENL_SET_ERR_MSG(info, "LND type not supported");
5972                         RETURN(PTR_ERR(lnd));
5973                 }
5974         }
5975
5976         LIBCFS_ALLOC(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5977         if (!tun) {
5978                 GENL_SET_ERR_MSG(info, "cannot allocate memory for tunables");
5979                 GOTO(out, rc = -ENOMEM);
5980         }
5981
5982         /* Use LND defaults */
5983         lnet_genl_init_tunables(lnd, tun);
5984         conf->lic_ncpts = 0;
5985
5986         nla_for_each_nested(settings, entry, rem3) {
5987                 if (nla_type(settings) != LN_SCALAR_ATTR_VALUE)
5988                         continue;
5989
5990                 if (nla_strcmp(settings, "interfaces") == 0) {
5991                         struct nlattr *intf;
5992                         int rem4;
5993
5994                         settings = nla_next(settings, &rem3);
5995                         if (nla_type(settings) !=
5996                             LN_SCALAR_ATTR_LIST) {
5997                                 GENL_SET_ERR_MSG(info,
5998                                                  "invalid interfaces");
5999                                 GOTO(out, rc = -EINVAL);
6000                         }
6001
6002                         nla_for_each_nested(intf, settings, rem4) {
6003                                 intf = nla_next(intf, &rem4);
6004                                 if (nla_type(intf) !=
6005                                     LN_SCALAR_ATTR_VALUE) {
6006                                         GENL_SET_ERR_MSG(info,
6007                                                          "cannot parse interface");
6008                                         GOTO(out, rc = -EINVAL);
6009                                 }
6010
6011                                 rc = nla_strscpy(conf->lic_ni_intf, intf,
6012                                                  sizeof(conf->lic_ni_intf));
6013                                 if (rc < 0) {
6014                                         GENL_SET_ERR_MSG(info,
6015                                                          "failed to parse interfaces");
6016                                         GOTO(out, rc);
6017                                 }
6018                         }
6019                         *ni_list = true;
6020                 } else if (nla_strcmp(settings, "nid") == 0 &&
6021                            net_id != LNET_NET_ANY) {
6022                         char nidstr[LNET_NIDSTR_SIZE];
6023
6024                         settings = nla_next(settings, &rem3);
6025                         if (nla_type(settings) != LN_SCALAR_ATTR_VALUE) {
6026                                 GENL_SET_ERR_MSG(info, "cannot parse NID");
6027                                 GOTO(out, rc = -EINVAL);
6028                         }
6029
6030                         rc = nla_strscpy(nidstr, settings, sizeof(nidstr));
6031                         if (rc < 0) {
6032                                 GENL_SET_ERR_MSG(info,
6033                                                  "failed to parse NID");
6034                                 GOTO(out, rc);
6035                         }
6036
6037                         CDEBUG(D_NET, "Requested NID %s\n", nidstr);
6038                         rc = libcfs_strnid(&nid, strim(nidstr));
6039                         if (rc < 0) {
6040                                 GENL_SET_ERR_MSG(info, "unsupported NID");
6041                                 GOTO(out, rc);
6042                         }
6043
6044                         if (!(info->nlhdr->nlmsg_flags & NLM_F_REPLACE) &&
6045                              nid_same(&nid, &LNET_ANY_NID)) {
6046                                 GENL_SET_ERR_MSG(info, "any NID not supported");
6047                                 GOTO(out, rc = -EINVAL);
6048                         }
6049                         *ni_list = true;
6050                 } else if (nla_strcmp(settings, "health stats") == 0 &&
6051                            info->nlhdr->nlmsg_flags & NLM_F_REPLACE) {
6052                         struct nlattr *health;
6053                         int rem4;
6054
6055                         settings = nla_next(settings, &rem3);
6056                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
6057                                 GENL_SET_ERR_MSG(info,
6058                                                  "cannot parse health stats");
6059                                 GOTO(out, rc = -EINVAL);
6060                         }
6061
6062                         nla_for_each_nested(health, settings, rem4) {
6063                                 if (nla_type(health) != LN_SCALAR_ATTR_VALUE ||
6064                                     nla_strcmp(health, "health value") != 0) {
6065                                         GENL_SET_ERR_MSG(info,
6066                                                          "wrong health config format");
6067                                         GOTO(out, rc = -EINVAL);
6068                                 }
6069
6070                                 health = nla_next(health, &rem4);
6071                                 if (nla_type(health) !=
6072                                     LN_SCALAR_ATTR_INT_VALUE) {
6073                                         GENL_SET_ERR_MSG(info,
6074                                                          "invalid health config format");
6075                                         GOTO(out, rc = -EINVAL);
6076                                 }
6077
6078                                 healthv = nla_get_s64(health);
6079                                 clamp_t(s64, healthv, 0, LNET_MAX_HEALTH_VALUE);
6080                         }
6081                 } else if (nla_strcmp(settings, "tunables") == 0) {
6082                         settings = nla_next(settings, &rem3);
6083                         if (nla_type(settings) !=
6084                             LN_SCALAR_ATTR_LIST) {
6085                                 GENL_SET_ERR_MSG(info,
6086                                                  "invalid tunables");
6087                                 GOTO(out, rc = -EINVAL);
6088                         }
6089
6090                         rc = lnet_genl_parse_tunables(settings, tun);
6091                         if (rc < 0) {
6092                                 GENL_SET_ERR_MSG(info,
6093                                                  "failed to parse tunables");
6094                                 GOTO(out, rc);
6095                         }
6096                 } else if ((nla_strcmp(settings, "lnd tunables") == 0)) {
6097                         settings = nla_next(settings, &rem3);
6098                         if (nla_type(settings) !=
6099                             LN_SCALAR_ATTR_LIST) {
6100                                 GENL_SET_ERR_MSG(info,
6101                                                  "lnd tunables should be list\n");
6102                                 GOTO(out, rc = -EINVAL);
6103                         }
6104
6105                         if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE &&
6106                             net_id == LNET_NET_ANY) {
6107                                 struct lnet_net *net;
6108
6109                                 lnet_net_lock(LNET_LOCK_EX);
6110                                 list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6111                                         struct lnet_ni *ni;
6112
6113                                         if (!net->net_lnd)
6114                                                 continue;
6115
6116                                         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6117                                                 if (!nid_same(&nid, &LNET_ANY_NID) &&
6118                                                     !nid_same(&nid, &ni->ni_nid))
6119                                                         continue;
6120
6121                                                 rc = lnet_genl_parse_lnd_tunables(settings,
6122                                                                                   &ni->ni_lnd_tunables,
6123                                                                                   net->net_lnd);
6124                                                 if (rc < 0) {
6125                                                         GENL_SET_ERR_MSG(info,
6126                                                                          "failed to parse lnd tunables");
6127                                                         lnet_net_unlock(LNET_LOCK_EX);
6128                                                         GOTO(out, rc);
6129                                                 }
6130                                         }
6131                                 }
6132                                 lnet_net_unlock(LNET_LOCK_EX);
6133                         } else {
6134                                 lnd = lnet_load_lnd(LNET_NETTYP(net_id));
6135                                 if (IS_ERR(lnd)) {
6136                                         GENL_SET_ERR_MSG(info,
6137                                                          "LND type not supported");
6138                                         GOTO(out, rc = PTR_ERR(lnd));
6139                                 }
6140
6141                                 rc = lnet_genl_parse_lnd_tunables(settings,
6142                                                                   &tun->lt_tun, lnd);
6143                                 if (rc < 0) {
6144                                         GENL_SET_ERR_MSG(info,
6145                                                          "failed to parse lnd tunables");
6146                                         GOTO(out, rc);
6147                                 }
6148                         }
6149                 } else if (nla_strcmp(settings, "CPT") == 0) {
6150                         struct nlattr *cpt;
6151                         int rem4;
6152
6153                         settings = nla_next(settings, &rem3);
6154                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
6155                                 GENL_SET_ERR_MSG(info,
6156                                                  "CPT should be list");
6157                                 GOTO(out, rc = -EINVAL);
6158                         }
6159
6160                         nla_for_each_nested(cpt, settings, rem4) {
6161                                 s64 core;
6162
6163                                 if (nla_type(cpt) !=
6164                                     LN_SCALAR_ATTR_INT_VALUE) {
6165                                         GENL_SET_ERR_MSG(info,
6166                                                          "invalid CPT config");
6167                                         GOTO(out, rc = -EINVAL);
6168                                 }
6169
6170                                 core = nla_get_s64(cpt);
6171                                 if (core >= LNET_CPT_NUMBER) {
6172                                         GENL_SET_ERR_MSG(info,
6173                                                          "invalid CPT value");
6174                                         GOTO(out, rc = -ERANGE);
6175                                 }
6176
6177                                 conf->lic_cpts[conf->lic_ncpts] = core;
6178                                 conf->lic_ncpts++;
6179                         }
6180                 }
6181         }
6182
6183         if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6184                 if (nid_same(&nid, &LNET_ANY_NID) &&
6185                     !strlen(conf->lic_ni_intf)) {
6186                         GENL_SET_ERR_MSG(info,
6187                                          "interface / NID is missing");
6188                         GOTO(out, rc);
6189                 }
6190
6191                 rc = lnet_dyn_add_ni(conf, net_id, &nid, tun);
6192                 switch (rc) {
6193                 case -ENOENT:
6194                         GENL_SET_ERR_MSG(info,
6195                                          "cannot parse net");
6196                         break;
6197                 case -ERANGE:
6198                         GENL_SET_ERR_MSG(info,
6199                                          "invalid CPT set");
6200                         break;
6201                 default:
6202                         GENL_SET_ERR_MSG(info,
6203                                          "cannot add LNet NI");
6204                 case 0:
6205                         break;
6206                 }
6207         } else if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE && healthv != -1) {
6208                 lnet_ni_set_healthv(&nid, healthv);
6209         } else if (!(info->nlhdr->nlmsg_flags & (NLM_F_CREATE | NLM_F_REPLACE))) {
6210                 struct lnet_ni *ni;
6211
6212                 /* delete case */
6213                 rc = -ENODEV;
6214                 if (!strlen(conf->lic_ni_intf) &&
6215                     nid_same(&nid, &LNET_ANY_NID)) {
6216                         GENL_SET_ERR_MSG(info,
6217                                          "interface / NID is missing");
6218                         GOTO(out, rc);
6219                 }
6220
6221                 if (nid_same(&nid, &LNET_ANY_NID)) {
6222                         struct lnet_net *net;
6223                         bool found = false;
6224
6225                         lnet_net_lock(LNET_LOCK_EX);
6226                         net = lnet_get_net_locked(net_id);
6227                         if (!net) {
6228                                 GENL_SET_ERR_MSG(info,
6229                                                  "LNet net doesn't exist");
6230                                 lnet_net_unlock(LNET_LOCK_EX);
6231                                 GOTO(out, rc);
6232                         }
6233
6234                         list_for_each_entry(ni, &net->net_ni_list,
6235                                             ni_netlist) {
6236                                 if (!ni->ni_interface ||
6237                                     strcmp(ni->ni_interface,
6238                                           conf->lic_ni_intf) != 0)
6239                                         continue;
6240
6241                                 found = true;
6242                                 lnet_net_unlock(LNET_LOCK_EX);
6243                                 rc = lnet_dyn_del_ni(&ni->ni_nid);
6244                                 break;
6245                         }
6246
6247                         if (rc < 0 && !found) { /* will be -ENODEV */
6248                                 GENL_SET_ERR_MSG(info,
6249                                                  "interface invalid for deleting LNet NI");
6250                                 lnet_net_unlock(LNET_LOCK_EX);
6251                         }
6252                 } else {
6253                         rc = lnet_dyn_del_ni(&nid);
6254                 }
6255
6256                 if (rc < 0) {
6257                         GENL_SET_ERR_MSG(info,
6258                                          "cannot del LNet NI");
6259                         GOTO(out, rc);
6260                 }
6261         }
6262 out:
6263         if (tun)
6264                 LIBCFS_FREE(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
6265
6266         return rc;
6267 }
6268
6269 static int lnet_net_cmd(struct sk_buff *skb, struct genl_info *info)
6270 {
6271         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6272         struct genlmsghdr *gnlh = nlmsg_data(nlh);
6273         struct nlattr *params = genlmsg_data(gnlh);
6274         int msg_len, rem, rc = 0;
6275         struct nlattr *attr;
6276
6277         msg_len = genlmsg_len(gnlh);
6278         if (!msg_len) {
6279                 GENL_SET_ERR_MSG(info, "no configuration");
6280                 return -ENOMSG;
6281         }
6282
6283         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
6284                 GENL_SET_ERR_MSG(info, "invalid configuration");
6285                 return -EINVAL;
6286         }
6287
6288         nla_for_each_nested(attr, params, rem) {
6289                 bool ni_list = false, ipnets = false;
6290                 struct lnet_ioctl_config_ni conf;
6291                 u32 net_id = LNET_NET_ANY;
6292                 struct nlattr *entry;
6293                 int rem2;
6294
6295                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6296                         continue;
6297
6298                 nla_for_each_nested(entry, attr, rem2) {
6299                         switch (nla_type(entry)) {
6300                         case LN_SCALAR_ATTR_VALUE: {
6301                                 ssize_t len;
6302
6303                                 memset(&conf, 0, sizeof(conf));
6304                                 if (nla_strcmp(entry, "ip2net") == 0) {
6305                                         entry = nla_next(entry, &rem2);
6306                                         if (nla_type(entry) !=
6307                                             LN_SCALAR_ATTR_VALUE) {
6308                                                 GENL_SET_ERR_MSG(info,
6309                                                                  "ip2net has invalid key");
6310                                                 GOTO(out, rc = -EINVAL);
6311                                         }
6312
6313                                         len = nla_strscpy(conf.lic_legacy_ip2nets,
6314                                                           entry,
6315                                                           sizeof(conf.lic_legacy_ip2nets));
6316                                         if (len < 0) {
6317                                                 GENL_SET_ERR_MSG(info,
6318                                                                  "ip2net key string is invalid");
6319                                                 GOTO(out, rc = len);
6320                                         }
6321                                         ni_list = true;
6322                                         ipnets = true;
6323                                 } else if (nla_strcmp(entry, "net type") == 0) {
6324                                         char tmp[LNET_NIDSTR_SIZE];
6325
6326                                         entry = nla_next(entry, &rem2);
6327                                         if (nla_type(entry) !=
6328                                             LN_SCALAR_ATTR_VALUE) {
6329                                                 GENL_SET_ERR_MSG(info,
6330                                                                  "net type has invalid key");
6331                                                 GOTO(out, rc = -EINVAL);
6332                                         }
6333
6334                                         len = nla_strscpy(tmp, entry,
6335                                                           sizeof(tmp));
6336                                         if (len < 0) {
6337                                                 GENL_SET_ERR_MSG(info,
6338                                                                  "net type key string is invalid");
6339                                                 GOTO(out, rc = len);
6340                                         }
6341
6342                                         net_id = libcfs_str2net(tmp);
6343                                         if (!net_id) {
6344                                                 GENL_SET_ERR_MSG(info,
6345                                                                  "cannot parse net");
6346                                                 GOTO(out, rc = -ENODEV);
6347                                         }
6348                                         if (LNET_NETTYP(net_id) == LOLND) {
6349                                                 GENL_SET_ERR_MSG(info,
6350                                                                  "setting @lo not allowed");
6351                                                 GOTO(out, rc = -ENODEV);
6352                                         }
6353                                         conf.lic_legacy_ip2nets[0] = '\0';
6354                                         conf.lic_ni_intf[0] = '\0';
6355                                         ni_list = false;
6356                                 }
6357                                 if (rc < 0)
6358                                         GOTO(out, rc);
6359                                 break;
6360                         }
6361                         case LN_SCALAR_ATTR_LIST: {
6362                                 struct nlattr *interface;
6363                                 int rem3;
6364
6365                                 ipnets = false;
6366                                 nla_for_each_nested(interface, entry, rem3) {
6367                                         rc = lnet_genl_parse_local_ni(interface, info,
6368                                                                       net_id, &conf,
6369                                                                       &ni_list);
6370                                         if (rc < 0)
6371                                                 GOTO(out, rc);
6372                                 }
6373                                 break;
6374                         }
6375                         /* it is possible a newer version of the user land send
6376                          * values older kernels doesn't handle. So silently
6377                          * ignore these values
6378                          */
6379                         default:
6380                                 break;
6381                         }
6382                 }
6383
6384                 /* Handle case of just sent NET with no list of NIDs */
6385                 if (!(info->nlhdr->nlmsg_flags & (NLM_F_CREATE | NLM_F_REPLACE)) &&
6386                     !ni_list) {
6387                         rc = lnet_dyn_del_net(net_id);
6388                         if (rc < 0) {
6389                                 GENL_SET_ERR_MSG(info,
6390                                                  "cannot del network");
6391                         }
6392                 } else if ((info->nlhdr->nlmsg_flags & NLM_F_CREATE) &&
6393                            ipnets && ni_list) {
6394                         rc = lnet_handle_legacy_ip2nets(conf.lic_legacy_ip2nets,
6395                                                         NULL);
6396                         if (rc < 0)
6397                                 GENL_SET_ERR_MSG(info,
6398                                                  "cannot setup ip2nets");
6399                 }
6400         }
6401 out:
6402         return rc;
6403 }
6404
6405 /* Called with ln_api_mutex */
6406 static int lnet_parse_peer_nis(struct nlattr *rlist, struct genl_info *info,
6407                                struct lnet_nid *pnid, bool mr,
6408                                bool *create_some)
6409 {
6410         struct lnet_nid snid = LNET_ANY_NID;
6411         struct nlattr *props;
6412         int rem, rc = 0;
6413         s64 num = -1;
6414
6415         nla_for_each_nested(props, rlist, rem) {
6416                 if (nla_type(props) != LN_SCALAR_ATTR_VALUE)
6417                         continue;
6418
6419                 if (nla_strcmp(props, "nid") == 0) {
6420                         char nidstr[LNET_NIDSTR_SIZE];
6421
6422                         props = nla_next(props, &rem);
6423                         if (nla_type(props) != LN_SCALAR_ATTR_VALUE) {
6424                                 GENL_SET_ERR_MSG(info,
6425                                                  "invalid secondary NID");
6426                                 GOTO(report_err, rc = -EINVAL);
6427                         }
6428
6429                         rc = nla_strscpy(nidstr, props, sizeof(nidstr));
6430                         if (rc < 0) {
6431                                 GENL_SET_ERR_MSG(info,
6432                                                  "failed to get secondary NID");
6433                                 GOTO(report_err, rc);
6434                         }
6435
6436                         rc = libcfs_strnid(&snid, strim(nidstr));
6437                         if (rc < 0) {
6438                                 GENL_SET_ERR_MSG(info, "unsupported secondary NID");
6439                                 GOTO(report_err, rc);
6440                         }
6441
6442                         if (LNET_NID_IS_ANY(&snid) || nid_same(&snid, pnid))
6443                                 *create_some = false;
6444                 } else if (nla_strcmp(props, "health stats") == 0) {
6445                         struct nlattr *health;
6446                         int rem2;
6447
6448                         props = nla_next(props, &rem);
6449                         if (nla_type(props) !=
6450                               LN_SCALAR_ATTR_LIST) {
6451                                 GENL_SET_ERR_MSG(info,
6452                                                  "invalid health configuration");
6453                                 GOTO(report_err, rc = -EINVAL);
6454                         }
6455
6456                         nla_for_each_nested(health, props, rem2) {
6457                                 if (nla_type(health) != LN_SCALAR_ATTR_VALUE ||
6458                                     nla_strcmp(health, "health value") != 0) {
6459                                         GENL_SET_ERR_MSG(info,
6460                                                          "wrong health config format");
6461                                         GOTO(report_err, rc = -EINVAL);
6462                                 }
6463
6464                                 health = nla_next(health, &rem2);
6465                                 if (nla_type(health) !=
6466                                     LN_SCALAR_ATTR_INT_VALUE) {
6467                                         GENL_SET_ERR_MSG(info,
6468                                                          "invalid health config format");
6469                                         GOTO(report_err, rc = -EINVAL);
6470                                 }
6471
6472                                 num = nla_get_s64(health);
6473                                 clamp_t(s64, num, 0, LNET_MAX_HEALTH_VALUE);
6474                         }
6475                 }
6476         }
6477
6478         if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE && num != -1) {
6479                 lnet_peer_ni_set_healthv(pnid, num, !*create_some);
6480         } else if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6481                 bool lock_prim = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6482
6483                 rc = lnet_user_add_peer_ni(pnid, &snid, mr, lock_prim);
6484                 if (rc < 0)
6485                         GENL_SET_ERR_MSG(info,
6486                                          "failed to add peer");
6487         } else if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE) && *create_some) {
6488                 bool force = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6489
6490                 rc = lnet_del_peer_ni(pnid, &snid, force);
6491                 if (rc < 0)
6492                         GENL_SET_ERR_MSG(info,
6493                                          "failed to del peer");
6494         }
6495 report_err:
6496         return rc;
6497 }
6498
6499 static int lnet_peer_ni_cmd(struct sk_buff *skb, struct genl_info *info)
6500 {
6501         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6502         struct genlmsghdr *gnlh = nlmsg_data(nlh);
6503         struct nlattr *params = genlmsg_data(gnlh);
6504         int msg_len, rem, rc = 0;
6505         struct lnet_nid pnid;
6506         struct nlattr *attr;
6507
6508         mutex_lock(&the_lnet.ln_api_mutex);
6509         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
6510                 GENL_SET_ERR_MSG(info, "Network is down");
6511                 mutex_unlock(&the_lnet.ln_api_mutex);
6512                 return -ENETDOWN;
6513         }
6514
6515         msg_len = genlmsg_len(gnlh);
6516         if (!msg_len) {
6517                 GENL_SET_ERR_MSG(info, "no configuration");
6518                 mutex_unlock(&the_lnet.ln_api_mutex);
6519                 return -ENOMSG;
6520         }
6521
6522         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
6523                 GENL_SET_ERR_MSG(info, "invalid configuration");
6524                 mutex_unlock(&the_lnet.ln_api_mutex);
6525                 return -EINVAL;
6526         }
6527
6528         nla_for_each_nested(attr, params, rem) {
6529                 bool parse_peer_nis = false;
6530                 struct nlattr *pnid_prop;
6531                 int rem2;
6532
6533                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6534                         continue;
6535
6536                 pnid = LNET_ANY_NID;
6537                 nla_for_each_nested(pnid_prop, attr, rem2) {
6538                         bool mr = true;
6539
6540                         if (nla_type(pnid_prop) != LN_SCALAR_ATTR_VALUE)
6541                                 continue;
6542
6543                         if (nla_strcmp(pnid_prop, "primary nid") == 0) {
6544                                 char nidstr[LNET_NIDSTR_SIZE];
6545
6546                                 pnid_prop = nla_next(pnid_prop, &rem2);
6547                                 if (nla_type(pnid_prop) !=
6548                                     LN_SCALAR_ATTR_VALUE) {
6549                                         GENL_SET_ERR_MSG(info,
6550                                                           "invalid primary NID type");
6551                                         GOTO(report_err, rc = -EINVAL);
6552                                 }
6553
6554                                 rc = nla_strscpy(nidstr, pnid_prop,
6555                                                  sizeof(nidstr));
6556                                 if (rc < 0) {
6557                                         GENL_SET_ERR_MSG(info,
6558                                                          "failed to get primary NID");
6559                                         GOTO(report_err, rc);
6560                                 }
6561
6562                                 rc = libcfs_strnid(&pnid, strim(nidstr));
6563                                 if (rc < 0) {
6564                                         GENL_SET_ERR_MSG(info,
6565                                                          "unsupported primary NID");
6566                                         GOTO(report_err, rc);
6567                                 }
6568
6569                                 /* we must create primary NID for peer ni
6570                                  * creation
6571                                  */
6572                                 if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
6573                                         bool lock_prim;
6574
6575                                         lock_prim = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6576                                         rc = lnet_user_add_peer_ni(&pnid,
6577                                                                    &LNET_ANY_NID,
6578                                                                    true, lock_prim);
6579                                         if (rc < 0) {
6580                                                 GENL_SET_ERR_MSG(info,
6581                                                                  "failed to add primary peer");
6582                                                 GOTO(report_err, rc);
6583                                         }
6584                                 }
6585                         } else if (nla_strcmp(pnid_prop, "Multi-Rail") == 0) {
6586                                 pnid_prop = nla_next(pnid_prop, &rem2);
6587                                 if (nla_type(pnid_prop) !=
6588                                     LN_SCALAR_ATTR_INT_VALUE) {
6589                                         GENL_SET_ERR_MSG(info,
6590                                                           "invalid MR flag param");
6591                                         GOTO(report_err, rc = -EINVAL);
6592                                 }
6593
6594                                 if (nla_get_s64(pnid_prop) == 0)
6595                                         mr = false;
6596                         } else if (nla_strcmp(pnid_prop, "peer state") == 0) {
6597                                 struct lnet_peer_ni *lpni;
6598                                 struct lnet_peer *lp;
6599
6600                                 pnid_prop = nla_next(pnid_prop, &rem2);
6601                                 if (nla_type(pnid_prop) !=
6602                                     LN_SCALAR_ATTR_INT_VALUE) {
6603                                         GENL_SET_ERR_MSG(info,
6604                                                           "invalid peer state param");
6605                                         GOTO(report_err, rc = -EINVAL);
6606                                 }
6607
6608                                 lpni = lnet_peer_ni_find_locked(&pnid);
6609                                 if (!lpni) {
6610                                         GENL_SET_ERR_MSG(info,
6611                                                           "invalid peer state param");
6612                                         GOTO(report_err, rc = -ENOENT);
6613                                 }
6614                                 lnet_peer_ni_decref_locked(lpni);
6615                                 lp = lpni->lpni_peer_net->lpn_peer;
6616                                 lp->lp_state = nla_get_s64(pnid_prop);
6617                         } else if (nla_strcmp(pnid_prop, "peer ni") == 0) {
6618                                 struct nlattr *rlist;
6619                                 int rem3;
6620
6621                                 if (!(info->nlhdr->nlmsg_flags & NLM_F_REPLACE) &&
6622                                     LNET_NID_IS_ANY(&pnid)) {
6623                                         GENL_SET_ERR_MSG(info,
6624                                                          "missing required primary NID");
6625                                         GOTO(report_err, rc);
6626                                 }
6627
6628                                 pnid_prop = nla_next(pnid_prop, &rem2);
6629                                 if (nla_type(pnid_prop) !=
6630                                     LN_SCALAR_ATTR_LIST) {
6631                                         GENL_SET_ERR_MSG(info,
6632                                                           "invalid NIDs list");
6633                                         GOTO(report_err, rc = -EINVAL);
6634                                 }
6635
6636                                 parse_peer_nis = true;
6637                                 nla_for_each_nested(rlist, pnid_prop, rem3) {
6638                                         rc = lnet_parse_peer_nis(rlist, info,
6639                                                                  &pnid, mr,
6640                                                                  &parse_peer_nis);
6641                                         if (rc < 0)
6642                                                 GOTO(report_err, rc);
6643                                 }
6644                         }
6645                 }
6646
6647                 /* If we have remote peer ni's we already add /del peers */
6648                 if (parse_peer_nis)
6649                         continue;
6650
6651                 if (LNET_NID_IS_ANY(&pnid)) {
6652                         GENL_SET_ERR_MSG(info, "missing primary NID");
6653                         GOTO(report_err, rc);
6654                 }
6655
6656                 if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
6657                         bool force = info->nlhdr->nlmsg_flags & NLM_F_EXCL;
6658
6659                         rc = lnet_del_peer_ni(&pnid, &LNET_ANY_NID,
6660                                               force);
6661                         if (rc < 0) {
6662                                 GENL_SET_ERR_MSG(info,
6663                                                  "failed to del primary peer");
6664                                 GOTO(report_err, rc);
6665                         }
6666                 }
6667         }
6668 report_err:
6669         /* If we failed on creation and encounter a latter error then
6670          * delete the primary nid.
6671          */
6672         if (rc < 0 && info->nlhdr->nlmsg_flags & NLM_F_CREATE &&
6673             !LNET_NID_IS_ANY(&pnid))
6674                 lnet_del_peer_ni(&pnid, &LNET_ANY_NID,
6675                                  info->nlhdr->nlmsg_flags & NLM_F_EXCL);
6676         mutex_unlock(&the_lnet.ln_api_mutex);
6677
6678         return rc;
6679 }
6680
6681 /** LNet route handling */
6682
6683 /* We can't use struct lnet_ioctl_config_data since it lacks
6684  * support for large NIDS
6685  */
6686 struct lnet_route_properties {
6687         struct lnet_nid         lrp_gateway;
6688         u32                     lrp_net;
6689         s32                     lrp_hop;
6690         u32                     lrp_flags;
6691         u32                     lrp_priority;
6692         u32                     lrp_sensitivity;
6693 };
6694
6695 struct lnet_genl_route_list {
6696         unsigned int                            lgrl_index;
6697         unsigned int                            lgrl_count;
6698         GENRADIX(struct lnet_route_properties)  lgrl_list;
6699 };
6700
6701 static inline struct lnet_genl_route_list *
6702 lnet_route_dump_ctx(struct netlink_callback *cb)
6703 {
6704         return (struct lnet_genl_route_list *)cb->args[0];
6705 }
6706
6707 static int lnet_route_show_done(struct netlink_callback *cb)
6708 {
6709         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
6710
6711         if (rlist) {
6712                 genradix_free(&rlist->lgrl_list);
6713                 CFS_FREE_PTR(rlist);
6714         }
6715         cb->args[0] = 0;
6716
6717         return 0;
6718 }
6719
6720 static int lnet_scan_route(struct lnet_genl_route_list *rlist,
6721                     struct lnet_route_properties *settings)
6722 {
6723         struct lnet_remotenet *rnet;
6724         struct list_head *rn_list;
6725         struct lnet_route *route;
6726         int cpt, i, rc = 0;
6727
6728         cpt = lnet_net_lock_current();
6729
6730         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
6731                 rn_list = &the_lnet.ln_remote_nets_hash[i];
6732                 list_for_each_entry(rnet, rn_list, lrn_list) {
6733                         if (settings->lrp_net != LNET_NET_ANY &&
6734                             settings->lrp_net != rnet->lrn_net)
6735                                 continue;
6736
6737                         list_for_each_entry(route, &rnet->lrn_routes,
6738                                             lr_list) {
6739                                 struct lnet_route_properties *prop;
6740
6741                                 if (!LNET_NID_IS_ANY(&settings->lrp_gateway) &&
6742                                     !nid_same(&settings->lrp_gateway,
6743                                               &route->lr_nid)) {
6744                                         continue;
6745                                 }
6746
6747                                 if (settings->lrp_hop != -1 &&
6748                                     settings->lrp_hop != route->lr_hops)
6749                                         continue;
6750
6751                                 if (settings->lrp_priority != -1 &&
6752                                     settings->lrp_priority != route->lr_priority)
6753                                         continue;
6754
6755                                 if (settings->lrp_sensitivity != -1 &&
6756                                     settings->lrp_sensitivity !=
6757                                     route->lr_gateway->lp_health_sensitivity)
6758                                         continue;
6759
6760                                 prop = genradix_ptr_alloc(&rlist->lgrl_list,
6761                                                           rlist->lgrl_count++,
6762                                                           GFP_ATOMIC);
6763                                 if (!prop)
6764                                         GOTO(failed_alloc, rc = -ENOMEM);
6765
6766                                 prop->lrp_net = rnet->lrn_net;
6767                                 prop->lrp_gateway = route->lr_nid;
6768                                 prop->lrp_hop = route->lr_hops;
6769                                 prop->lrp_priority = route->lr_priority;
6770                                 prop->lrp_sensitivity =
6771                                         route->lr_gateway->lp_health_sensitivity;
6772                                 if (lnet_is_route_alive(route))
6773                                         prop->lrp_flags |= LNET_RT_ALIVE;
6774                                 else
6775                                         prop->lrp_flags &= ~LNET_RT_ALIVE;
6776                                 if (route->lr_single_hop)
6777                                         prop->lrp_flags &= ~LNET_RT_MULTI_HOP;
6778                                 else
6779                                         prop->lrp_flags |= LNET_RT_MULTI_HOP;
6780                         }
6781                 }
6782         }
6783
6784 failed_alloc:
6785         lnet_net_unlock(cpt);
6786         return rc;
6787 }
6788
6789 /* LNet route ->start() handler for GET requests */
6790 static int lnet_route_show_start(struct netlink_callback *cb)
6791 {
6792         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6793 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6794         struct netlink_ext_ack *extack = NULL;
6795 #endif
6796         struct lnet_genl_route_list *rlist;
6797         int msg_len = genlmsg_len(gnlh);
6798         int rc = 0;
6799
6800 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6801         extack = cb->extack;
6802 #endif
6803         if (the_lnet.ln_refcount == 0 ||
6804             the_lnet.ln_state != LNET_STATE_RUNNING) {
6805                 NL_SET_ERR_MSG(extack, "Network is down");
6806                 return -ENETDOWN;
6807         }
6808
6809         CFS_ALLOC_PTR(rlist);
6810         if (!rlist) {
6811                 NL_SET_ERR_MSG(extack, "No memory for route list");
6812                 return -ENOMEM;
6813         }
6814
6815         genradix_init(&rlist->lgrl_list);
6816         rlist->lgrl_count = 0;
6817         rlist->lgrl_index = 0;
6818         cb->args[0] = (long)rlist;
6819
6820         mutex_lock(&the_lnet.ln_api_mutex);
6821         if (!msg_len) {
6822                 struct lnet_route_properties tmp = {
6823                         .lrp_gateway            = LNET_ANY_NID,
6824                         .lrp_net                = LNET_NET_ANY,
6825                         .lrp_hop                = -1,
6826                         .lrp_priority           = -1,
6827                         .lrp_sensitivity        = -1,
6828                 };
6829
6830                 rc = lnet_scan_route(rlist, &tmp);
6831                 if (rc < 0) {
6832                         NL_SET_ERR_MSG(extack,
6833                                        "failed to allocate router data");
6834                         GOTO(report_err, rc);
6835                 }
6836         } else {
6837                 struct nlattr *params = genlmsg_data(gnlh);
6838                 struct nlattr *attr;
6839                 int rem;
6840
6841                 nla_for_each_nested(attr, params, rem) {
6842                         struct lnet_route_properties tmp = {
6843                                 .lrp_gateway            = LNET_ANY_NID,
6844                                 .lrp_net                = LNET_NET_ANY,
6845                                 .lrp_hop                = -1,
6846                                 .lrp_priority           = -1,
6847                                 .lrp_sensitivity        = -1,
6848                         };
6849                         struct nlattr *route;
6850                         int rem2;
6851
6852                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
6853                                 continue;
6854
6855                         nla_for_each_nested(route, attr, rem2) {
6856                                 if (nla_type(route) != LN_SCALAR_ATTR_VALUE)
6857                                         continue;
6858
6859                                 if (nla_strcmp(route, "net") == 0) {
6860                                         char nw[LNET_NIDSTR_SIZE];
6861
6862                                         route = nla_next(route, &rem2);
6863                                         if (nla_type(route) !=
6864                                             LN_SCALAR_ATTR_VALUE) {
6865                                                 NL_SET_ERR_MSG(extack,
6866                                                                "invalid net param");
6867                                                 GOTO(report_err, rc = -EINVAL);
6868                                         }
6869
6870                                         rc = nla_strscpy(nw, route, sizeof(nw));
6871                                         if (rc < 0) {
6872                                                 NL_SET_ERR_MSG(extack,
6873                                                                "failed to get route param");
6874                                                 GOTO(report_err, rc);
6875                                         }
6876                                         rc = 0;
6877                                         tmp.lrp_net = libcfs_str2net(strim(nw));
6878                                 } else if (nla_strcmp(route, "gateway") == 0) {
6879                                         char gw[LNET_NIDSTR_SIZE];
6880
6881                                         route = nla_next(route, &rem2);
6882                                         if (nla_type(route) !=
6883                                             LN_SCALAR_ATTR_VALUE) {
6884                                                 NL_SET_ERR_MSG(extack,
6885                                                                "invalid gateway param");
6886                                                 GOTO(report_err, rc = -EINVAL);
6887                                         }
6888
6889                                         rc = nla_strscpy(gw, route, sizeof(gw));
6890                                         if (rc < 0) {
6891                                                 NL_SET_ERR_MSG(extack,
6892                                                                "failed to get route param");
6893                                                 GOTO(report_err, rc);
6894                                         }
6895
6896                                         rc = libcfs_strnid(&tmp.lrp_gateway, strim(gw));
6897                                         if (rc < 0) {
6898                                                 NL_SET_ERR_MSG(extack,
6899                                                                "cannot parse gateway");
6900                                                 GOTO(report_err, rc = -ENODEV);
6901                                         }
6902                                         rc = 0;
6903                                 } else if (nla_strcmp(route, "hop") == 0) {
6904                                         route = nla_next(route, &rem2);
6905                                         if (nla_type(route) !=
6906                                             LN_SCALAR_ATTR_INT_VALUE) {
6907                                                 NL_SET_ERR_MSG(extack,
6908                                                                "invalid hop param");
6909                                                 GOTO(report_err, rc = -EINVAL);
6910                                         }
6911
6912                                         tmp.lrp_hop = nla_get_s64(route);
6913                                         if (tmp.lrp_hop != -1)
6914                                                 clamp_t(s32, tmp.lrp_hop, 1, 127);
6915                                 } else if (nla_strcmp(route, "priority") == 0) {
6916                                         route = nla_next(route, &rem2);
6917                                         if (nla_type(route) !=
6918                                             LN_SCALAR_ATTR_INT_VALUE) {
6919                                                 NL_SET_ERR_MSG(extack,
6920                                                                "invalid priority param");
6921                                                 GOTO(report_err, rc = -EINVAL);
6922                                         }
6923
6924                                         tmp.lrp_priority = nla_get_s64(route);
6925                                 }
6926                         }
6927
6928                         rc = lnet_scan_route(rlist, &tmp);
6929                         if (rc < 0) {
6930                                 NL_SET_ERR_MSG(extack,
6931                                                "failed to allocate router data");
6932                                 GOTO(report_err, rc);
6933                         }
6934                 }
6935         }
6936 report_err:
6937         mutex_unlock(&the_lnet.ln_api_mutex);
6938
6939         if (rc < 0)
6940                 lnet_route_show_done(cb);
6941
6942         return rc;
6943 }
6944
6945 static const struct ln_key_list route_props_list = {
6946         .lkl_maxattr                    = LNET_ROUTE_ATTR_MAX,
6947         .lkl_list                       = {
6948                 [LNET_ROUTE_ATTR_HDR]                   = {
6949                         .lkp_value                      = "route",
6950                         .lkp_key_format                 = LNKF_SEQUENCE | LNKF_MAPPING,
6951                         .lkp_data_type                  = NLA_NUL_STRING,
6952                 },
6953                 [LNET_ROUTE_ATTR_NET]                   = {
6954                         .lkp_value                      = "net",
6955                         .lkp_data_type                  = NLA_STRING
6956                 },
6957                 [LNET_ROUTE_ATTR_GATEWAY]               = {
6958                         .lkp_value                      = "gateway",
6959                         .lkp_data_type                  = NLA_STRING
6960                 },
6961                 [LNET_ROUTE_ATTR_HOP]                   = {
6962                         .lkp_value                      = "hop",
6963                         .lkp_data_type                  = NLA_S32
6964                 },
6965                 [LNET_ROUTE_ATTR_PRIORITY]              = {
6966                         .lkp_value                      = "priority",
6967                         .lkp_data_type                  = NLA_U32
6968                 },
6969                 [LNET_ROUTE_ATTR_HEALTH_SENSITIVITY]    = {
6970                         .lkp_value                      = "health_sensitivity",
6971                         .lkp_data_type                  = NLA_U32
6972                 },
6973                 [LNET_ROUTE_ATTR_STATE] = {
6974                         .lkp_value                      = "state",
6975                         .lkp_data_type                  = NLA_STRING,
6976                 },
6977                 [LNET_ROUTE_ATTR_TYPE]  = {
6978                         .lkp_value                      = "type",
6979                         .lkp_data_type                  = NLA_STRING,
6980                 },
6981         },
6982 };
6983
6984
6985 static int lnet_route_show_dump(struct sk_buff *msg,
6986                                 struct netlink_callback *cb)
6987 {
6988         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
6989         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6990 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6991         struct netlink_ext_ack *extack = NULL;
6992 #endif
6993         int portid = NETLINK_CB(cb->skb).portid;
6994         int seq = cb->nlh->nlmsg_seq;
6995         int idx = rlist->lgrl_index;
6996         int msg_len = genlmsg_len(gnlh);
6997         int rc = 0;
6998
6999 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7000         extack = cb->extack;
7001 #endif
7002         if (!rlist->lgrl_count) {
7003                 NL_SET_ERR_MSG(extack, "No routes found");
7004                 GOTO(send_error, rc = msg_len ? -ENOENT : 0);
7005         }
7006
7007         if (!idx) {
7008                 const struct ln_key_list *all[] = {
7009                         &route_props_list, NULL
7010                 };
7011
7012                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
7013                                                 &lnet_family,
7014                                                 NLM_F_CREATE | NLM_F_MULTI,
7015                                                 LNET_CMD_ROUTES, all);
7016                 if (rc < 0) {
7017                         NL_SET_ERR_MSG(extack, "failed to send key table");
7018                         GOTO(send_error, rc);
7019                 }
7020         }
7021
7022         while (idx < rlist->lgrl_count) {
7023                 struct lnet_route_properties *prop;
7024                 void *hdr;
7025
7026                 prop = genradix_ptr(&rlist->lgrl_list, idx++);
7027
7028                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
7029                                   NLM_F_MULTI, LNET_CMD_ROUTES);
7030                 if (!hdr) {
7031                         NL_SET_ERR_MSG(extack, "failed to send values");
7032                         genlmsg_cancel(msg, hdr);
7033                         GOTO(send_error, rc = -EMSGSIZE);
7034                 }
7035
7036                 if (idx == 1)
7037                         nla_put_string(msg, LNET_ROUTE_ATTR_HDR, "");
7038
7039                 nla_put_string(msg, LNET_ROUTE_ATTR_NET,
7040                                libcfs_net2str(prop->lrp_net));
7041                 nla_put_string(msg, LNET_ROUTE_ATTR_GATEWAY,
7042                                libcfs_nidstr(&prop->lrp_gateway));
7043                 if (gnlh->version) {
7044                         nla_put_s32(msg, LNET_ROUTE_ATTR_HOP, prop->lrp_hop);
7045                         nla_put_u32(msg, LNET_ROUTE_ATTR_PRIORITY, prop->lrp_priority);
7046                         nla_put_u32(msg, LNET_ROUTE_ATTR_HEALTH_SENSITIVITY,
7047                                     prop->lrp_sensitivity);
7048
7049                         if (!(cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)) {
7050                                 nla_put_string(msg, LNET_ROUTE_ATTR_STATE,
7051                                                prop->lrp_flags & LNET_RT_ALIVE ?
7052                                                "up" : "down");
7053                                 nla_put_string(msg, LNET_ROUTE_ATTR_TYPE,
7054                                                prop->lrp_flags & LNET_RT_MULTI_HOP ?
7055                                                "multi-hop" : "single-hop");
7056                         }
7057                 }
7058                 genlmsg_end(msg, hdr);
7059         }
7060         rlist->lgrl_index = idx;
7061 send_error:
7062         return lnet_nl_send_error(cb->skb, portid, seq, rc);
7063 };
7064
7065 #ifndef HAVE_NETLINK_CALLBACK_START
7066 static int lnet_old_route_show_dump(struct sk_buff *msg,
7067                                     struct netlink_callback *cb)
7068 {
7069         if (!cb->args[0]) {
7070                 int rc = lnet_route_show_start(cb);
7071
7072                 if (rc < 0)
7073                         return lnet_nl_send_error(cb->skb,
7074                                                   NETLINK_CB(cb->skb).portid,
7075                                                   cb->nlh->nlmsg_seq,
7076                                                   rc);
7077         }
7078
7079         return lnet_route_show_dump(msg, cb);
7080 }
7081 #endif /* !HAVE_NETLINK_CALLBACK_START */
7082
7083 /** LNet peer handling */
7084 struct lnet_genl_processid_list {
7085         unsigned int                    lgpl_index;
7086         unsigned int                    lgpl_count;
7087         GENRADIX(struct lnet_processid) lgpl_list;
7088 };
7089
7090 static inline struct lnet_genl_processid_list *
7091 lnet_peer_dump_ctx(struct netlink_callback *cb)
7092 {
7093         return (struct lnet_genl_processid_list *)cb->args[0];
7094 }
7095
7096 static int lnet_peer_ni_show_done(struct netlink_callback *cb)
7097 {
7098         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
7099
7100         if (plist) {
7101                 genradix_free(&plist->lgpl_list);
7102                 CFS_FREE_PTR(plist);
7103         }
7104         cb->args[0] = 0;
7105
7106         return 0;
7107 }
7108
7109 /* LNet peer ->start() handler for GET requests */
7110 static int lnet_peer_ni_show_start(struct netlink_callback *cb)
7111 {
7112         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7113 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7114         struct netlink_ext_ack *extack = NULL;
7115 #endif
7116         struct lnet_genl_processid_list *plist;
7117         int msg_len = genlmsg_len(gnlh);
7118         int rc = 0;
7119
7120 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7121         extack = cb->extack;
7122 #endif
7123         mutex_lock(&the_lnet.ln_api_mutex);
7124         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7125                 NL_SET_ERR_MSG(extack, "Network is down");
7126                 mutex_unlock(&the_lnet.ln_api_mutex);
7127                 return -ENETDOWN;
7128         }
7129
7130         CFS_ALLOC_PTR(plist);
7131         if (!plist) {
7132                 NL_SET_ERR_MSG(extack, "No memory for peer list");
7133                 mutex_unlock(&the_lnet.ln_api_mutex);
7134                 return -ENOMEM;
7135         }
7136
7137         genradix_init(&plist->lgpl_list);
7138         plist->lgpl_count = 0;
7139         plist->lgpl_index = 0;
7140         cb->args[0] = (long)plist;
7141
7142         if (!msg_len) {
7143                 struct lnet_peer_table *ptable;
7144                 int cpt;
7145
7146                 cfs_percpt_for_each(ptable, cpt, the_lnet.ln_peer_tables) {
7147                         struct lnet_peer *lp;
7148
7149                         list_for_each_entry(lp, &ptable->pt_peer_list,
7150                                             lp_peer_list) {
7151                                 struct lnet_processid *lpi;
7152
7153                                 lpi = genradix_ptr_alloc(&plist->lgpl_list,
7154                                                          plist->lgpl_count++,
7155                                                          GFP_KERNEL);
7156                                 if (!lpi) {
7157                                         NL_SET_ERR_MSG(extack,
7158                                                       "failed to allocate NID");
7159                                         GOTO(report_err, rc = -ENOMEM);
7160                                 }
7161
7162                                 lpi->pid = LNET_PID_LUSTRE;
7163                                 lpi->nid = lp->lp_primary_nid;
7164                         }
7165                 }
7166         } else {
7167                 struct nlattr *params = genlmsg_data(gnlh);
7168                 struct nlattr *attr;
7169                 int rem;
7170
7171                 nla_for_each_nested(attr, params, rem) {
7172                         struct nlattr *nid;
7173                         int rem2;
7174
7175                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
7176                                 continue;
7177
7178                         nla_for_each_nested(nid, attr, rem2) {
7179                                 char addr[LNET_NIDSTR_SIZE];
7180                                 struct lnet_processid *id;
7181
7182                                 if (nla_type(nid) != LN_SCALAR_ATTR_VALUE ||
7183                                     nla_strcmp(nid, "primary nid") != 0)
7184                                         continue;
7185
7186                                 nid = nla_next(nid, &rem2);
7187                                 if (nla_type(nid) != LN_SCALAR_ATTR_VALUE) {
7188                                         NL_SET_ERR_MSG(extack,
7189                                                        "invalid primary nid param");
7190                                         GOTO(report_err, rc = -EINVAL);
7191                                 }
7192
7193                                 rc = nla_strscpy(addr, nid, sizeof(addr));
7194                                 if (rc < 0) {
7195                                         NL_SET_ERR_MSG(extack,
7196                                                        "failed to get primary nid param");
7197                                         GOTO(report_err, rc);
7198                                 }
7199
7200                                 id = genradix_ptr_alloc(&plist->lgpl_list,
7201                                                         plist->lgpl_count++,
7202                                                         GFP_KERNEL);
7203                                 if (!id) {
7204                                         NL_SET_ERR_MSG(extack, "failed to allocate NID");
7205                                         GOTO(report_err, rc = -ENOMEM);
7206                                 }
7207
7208                                 rc = libcfs_strid(id, strim(addr));
7209                                 if (rc < 0) {
7210                                         NL_SET_ERR_MSG(extack, "invalid NID");
7211                                         GOTO(report_err, rc);
7212                                 }
7213                                 rc = 0;
7214                         }
7215                 }
7216         }
7217 report_err:
7218         mutex_unlock(&the_lnet.ln_api_mutex);
7219
7220         if (rc < 0)
7221                 lnet_peer_ni_show_done(cb);
7222
7223         return rc;
7224 }
7225
7226 static const struct ln_key_list lnet_peer_ni_keys = {
7227         .lkl_maxattr                    = LNET_PEER_NI_ATTR_MAX,
7228         .lkl_list                       = {
7229                 [LNET_PEER_NI_ATTR_HDR]  = {
7230                         .lkp_value              = "peer",
7231                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
7232                         .lkp_data_type          = NLA_NUL_STRING,
7233                 },
7234                 [LNET_PEER_NI_ATTR_PRIMARY_NID] = {
7235                         .lkp_value              = "primary nid",
7236                         .lkp_data_type          = NLA_STRING,
7237                 },
7238                 [LNET_PEER_NI_ATTR_MULTIRAIL]   = {
7239                         .lkp_value              = "Multi-Rail",
7240                         .lkp_data_type          = NLA_FLAG
7241                 },
7242                 [LNET_PEER_NI_ATTR_STATE]       = {
7243                         .lkp_value              = "peer state",
7244                         .lkp_data_type          = NLA_U32
7245                 },
7246                 [LNET_PEER_NI_ATTR_PEER_NI_LIST] = {
7247                         .lkp_value              = "peer ni",
7248                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
7249                         .lkp_data_type          = NLA_NESTED,
7250                 },
7251         },
7252 };
7253
7254 static const struct ln_key_list lnet_peer_ni_list = {
7255         .lkl_maxattr                    = LNET_PEER_NI_LIST_ATTR_MAX,
7256         .lkl_list                       = {
7257                 [LNET_PEER_NI_LIST_ATTR_NID]            = {
7258                         .lkp_value                      = "nid",
7259                         .lkp_data_type                  = NLA_STRING,
7260                 },
7261                 [LNET_PEER_NI_LIST_ATTR_UDSP_INFO]      = {
7262                         .lkp_value                      = "udsp info",
7263                         .lkp_key_format                 = LNKF_MAPPING,
7264                         .lkp_data_type                  = NLA_NESTED,
7265                 },
7266                 [LNET_PEER_NI_LIST_ATTR_STATE]          = {
7267                         .lkp_value                      = "state",
7268                         .lkp_data_type                  = NLA_STRING,
7269                 },
7270                 [LNET_PEER_NI_LIST_ATTR_MAX_TX_CREDITS] = {
7271                         .lkp_value                      = "max_ni_tx_credits",
7272                         .lkp_data_type                  = NLA_U32,
7273                 },
7274                 [LNET_PEER_NI_LIST_ATTR_CUR_TX_CREDITS] = {
7275                         .lkp_value                      = "available_tx_credits",
7276                         .lkp_data_type                  = NLA_U32,
7277                 },
7278                 [LNET_PEER_NI_LIST_ATTR_MIN_TX_CREDITS] = {
7279                         .lkp_value                      = "min_tx_credits",
7280                         .lkp_data_type                  = NLA_U32,
7281                 },
7282                 [LNET_PEER_NI_LIST_ATTR_QUEUE_BUF_COUNT] = {
7283                         .lkp_value                      = "tx_q_num_of_buf",
7284                         .lkp_data_type                  = NLA_U32,
7285                 },
7286                 [LNET_PEER_NI_LIST_ATTR_CUR_RTR_CREDITS] = {
7287                         .lkp_value                      = "available_rtr_credits",
7288                         .lkp_data_type                  = NLA_U32,
7289                 },
7290                 [LNET_PEER_NI_LIST_ATTR_MIN_RTR_CREDITS] = {
7291                         .lkp_value                      = "min_rtr_credits",
7292                         .lkp_data_type                  = NLA_U32,
7293                 },
7294                 [LNET_PEER_NI_LIST_ATTR_REFCOUNT]       = {
7295                         .lkp_value                      = "refcount",
7296                         .lkp_data_type                  = NLA_U32,
7297                 },
7298                 [LNET_PEER_NI_LIST_ATTR_STATS_COUNT]    = {
7299                         .lkp_value                      = "statistics",
7300                         .lkp_key_format                 = LNKF_MAPPING,
7301                         .lkp_data_type                  = NLA_NESTED
7302                 },
7303                 [LNET_PEER_NI_LIST_ATTR_SENT_STATS]     = {
7304                         .lkp_value                      = "sent_stats",
7305                         .lkp_key_format                 = LNKF_MAPPING,
7306                         .lkp_data_type                  = NLA_NESTED
7307                 },
7308                 [LNET_PEER_NI_LIST_ATTR_RECV_STATS]     = {
7309                         .lkp_value                      = "received_stats",
7310                         .lkp_key_format                 = LNKF_MAPPING,
7311                         .lkp_data_type                  = NLA_NESTED
7312                 },
7313                 [LNET_PEER_NI_LIST_ATTR_DROP_STATS]     = {
7314                         .lkp_value                      = "dropped_stats",
7315                         .lkp_key_format                 = LNKF_MAPPING,
7316                         .lkp_data_type                  = NLA_NESTED
7317                 },
7318                 [LNET_PEER_NI_LIST_ATTR_HEALTH_STATS]   = {
7319                         .lkp_value                      = "health stats",
7320                         .lkp_key_format                 = LNKF_MAPPING,
7321                         .lkp_data_type                  = NLA_NESTED
7322                 },
7323         },
7324 };
7325
7326 static const struct ln_key_list lnet_peer_ni_list_stats_count = {
7327         .lkl_maxattr                    = LNET_PEER_NI_LIST_STATS_COUNT_ATTR_MAX,
7328         .lkl_list                       = {
7329                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_SEND_COUNT] = {
7330                         .lkp_value                              = "send_count",
7331                         .lkp_data_type                          = NLA_U32,
7332                 },
7333                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_RECV_COUNT] = {
7334                         .lkp_value                              = "recv_count",
7335                         .lkp_data_type                          = NLA_U32,
7336                 },
7337                 [LNET_PEER_NI_LIST_STATS_COUNT_ATTR_DROP_COUNT] = {
7338                         .lkp_value                              = "drop_count",
7339                         .lkp_data_type                          = NLA_U32,
7340                 },
7341         },
7342 };
7343
7344 static const struct ln_key_list lnet_peer_ni_list_stats = {
7345         .lkl_maxattr                    = LNET_PEER_NI_LIST_STATS_ATTR_MAX,
7346         .lkl_list                       = {
7347                 [LNET_PEER_NI_LIST_STATS_ATTR_PUT]      = {
7348                         .lkp_value                      = "put",
7349                         .lkp_data_type                  = NLA_U32,
7350                 },
7351                 [LNET_PEER_NI_LIST_STATS_ATTR_GET]      = {
7352                         .lkp_value                      = "get",
7353                         .lkp_data_type                  = NLA_U32,
7354                 },
7355                 [LNET_PEER_NI_LIST_STATS_ATTR_REPLY]    = {
7356                         .lkp_value                      = "reply",
7357                         .lkp_data_type                  = NLA_U32,
7358                 },
7359                 [LNET_PEER_NI_LIST_STATS_ATTR_ACK]      = {
7360                         .lkp_value                      = "ack",
7361                         .lkp_data_type                  = NLA_U32,
7362                 },
7363                 [LNET_PEER_NI_LIST_STATS_ATTR_HELLO]    = {
7364                         .lkp_value                      = "hello",
7365                         .lkp_data_type                  = NLA_U32,
7366                 },
7367         },
7368 };
7369
7370 static const struct ln_key_list lnet_peer_ni_list_health = {
7371         .lkl_maxattr                    = LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_MAX,
7372         .lkl_list                       = {
7373                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_VALUE]     = {
7374                         .lkp_value                      = "health value",
7375                         .lkp_data_type                  = NLA_S32,
7376                 },
7377                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_DROPPED]   = {
7378                         .lkp_value                      = "dropped",
7379                         .lkp_data_type                  = NLA_U32,
7380                 },
7381                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_TIMEOUT]   = {
7382                         .lkp_value                      = "timeout",
7383                         .lkp_data_type                  = NLA_U32,
7384                 },
7385                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_ERROR]     = {
7386                         .lkp_value                      = "error",
7387                         .lkp_data_type                  = NLA_U32,
7388                 },
7389                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NETWORK_TIMEOUT] = {
7390                         .lkp_value                      = "network timeout",
7391                         .lkp_data_type                  = NLA_U32,
7392                 },
7393                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PING_COUNT] = {
7394                         .lkp_value                      = "ping_count",
7395                         .lkp_data_type                  = NLA_U32,
7396                 },
7397                 [LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NEXT_PING] = {
7398                         .lkp_value                      = "next_ping",
7399                         .lkp_data_type                  = NLA_S64,
7400                 },
7401         },
7402 };
7403
7404 static int lnet_peer_ni_show_dump(struct sk_buff *msg,
7405                                   struct netlink_callback *cb)
7406 {
7407         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
7408         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7409 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7410         struct netlink_ext_ack *extack = NULL;
7411 #endif
7412         int portid = NETLINK_CB(cb->skb).portid;
7413         int seq = cb->nlh->nlmsg_seq;
7414         int idx = plist->lgpl_index;
7415         int msg_len = genlmsg_len(gnlh);
7416         int rc = 0;
7417
7418 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7419         extack = cb->extack;
7420 #endif
7421         if (!plist->lgpl_count) {
7422                 NL_SET_ERR_MSG(extack, "No peers found");
7423                 GOTO(send_error, rc = msg_len ? -ENOENT : 0);
7424         }
7425
7426         if (!idx) {
7427                 const struct ln_key_list *all[] = {
7428                         &lnet_peer_ni_keys, &lnet_peer_ni_list,
7429                         &udsp_info_list, &udsp_info_pref_nids_list,
7430                         &udsp_info_pref_nids_list,
7431                         &lnet_peer_ni_list_stats_count,
7432                         &lnet_peer_ni_list_stats, /* send_stats */
7433                         &lnet_peer_ni_list_stats, /* recv_stats */
7434                         &lnet_peer_ni_list_stats, /* drop stats */
7435                         &lnet_peer_ni_list_health,
7436                         NULL
7437                 };
7438
7439                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
7440                                                 &lnet_family,
7441                                                 NLM_F_CREATE | NLM_F_MULTI,
7442                                                 LNET_CMD_PEERS, all);
7443                 if (rc < 0) {
7444                         NL_SET_ERR_MSG(extack, "failed to send key table");
7445                         GOTO(send_error, rc);
7446                 }
7447         }
7448
7449         mutex_lock(&the_lnet.ln_api_mutex);
7450         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7451                 NL_SET_ERR_MSG(extack, "Network is down");
7452                 GOTO(unlock_api_mutex, rc = -ENETDOWN);
7453         }
7454
7455         while (idx < plist->lgpl_count) {
7456                 struct lnet_processid *id;
7457                 struct lnet_peer_ni *lpni = NULL;
7458                 struct nlattr *nid_list;
7459                 struct lnet_peer *lp;
7460                 int count = 1;
7461                 void *hdr;
7462
7463                 id = genradix_ptr(&plist->lgpl_list, idx++);
7464                 if (nid_is_lo0(&id->nid))
7465                         continue;
7466
7467                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
7468                                   NLM_F_MULTI, LNET_CMD_PEERS);
7469                 if (!hdr) {
7470                         NL_SET_ERR_MSG(extack, "failed to send values");
7471                         genlmsg_cancel(msg, hdr);
7472                         GOTO(unlock_api_mutex, rc = -EMSGSIZE);
7473                 }
7474
7475                 lp = lnet_find_peer(&id->nid);
7476                 if (!lp) {
7477                         NL_SET_ERR_MSG(extack, "cannot find peer");
7478                         GOTO(unlock_api_mutex, rc = -ENOENT);
7479                 }
7480
7481                 if (idx == 1)
7482                         nla_put_string(msg, LNET_PEER_NI_ATTR_HDR, "");
7483
7484                 nla_put_string(msg, LNET_PEER_NI_ATTR_PRIMARY_NID,
7485                                libcfs_nidstr(&lp->lp_primary_nid));
7486                 if (lnet_peer_is_multi_rail(lp))
7487                         nla_put_flag(msg, LNET_PEER_NI_ATTR_MULTIRAIL);
7488
7489                 if (gnlh->version >= 3)
7490                         nla_put_u32(msg, LNET_PEER_NI_ATTR_STATE, lp->lp_state);
7491
7492                 nid_list = nla_nest_start(msg, LNET_PEER_NI_ATTR_PEER_NI_LIST);
7493                 while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
7494                         struct nlattr *peer_nid = nla_nest_start(msg, count++);
7495
7496                         nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_NID,
7497                                        libcfs_nidstr(&lpni->lpni_nid));
7498
7499                         if (gnlh->version >= 4) {
7500                                 rc = lnet_udsp_info_send(msg,
7501                                                          LNET_PEER_NI_LIST_ATTR_UDSP_INFO,
7502                                                          &lpni->lpni_nid, true);
7503                                 if (rc < 0) {
7504                                         lnet_peer_decref_locked(lp);
7505                                         NL_SET_ERR_MSG(extack,
7506                                                        "failed to get UDSP info");
7507                                         GOTO(unlock_api_mutex, rc);
7508                                 }
7509                         }
7510
7511                         if (cb->nlh->nlmsg_flags & NLM_F_DUMP_FILTERED)
7512                                 goto skip_state;
7513
7514                         if (lnet_isrouter(lpni) ||
7515                             lnet_peer_aliveness_enabled(lpni)) {
7516                                 nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_STATE,
7517                                                lnet_is_peer_ni_alive(lpni) ?
7518                                                "up" : "down");
7519                         } else {
7520                                 nla_put_string(msg, LNET_PEER_NI_LIST_ATTR_STATE,
7521                                                "NA");
7522                         }
7523 skip_state:
7524                         if (gnlh->version) {
7525                                 struct lnet_ioctl_element_msg_stats lpni_msg_stats;
7526                                 struct nlattr *send_stats_list, *send_stats;
7527                                 struct nlattr *recv_stats_list, *recv_stats;
7528                                 struct nlattr *drop_stats_list, *drop_stats;
7529                                 struct nlattr *health_list, *health_stats;
7530                                 struct lnet_ioctl_element_stats stats;
7531                                 struct nlattr *stats_attr, *ni_stats;
7532
7533                                 nla_put_u32(msg,
7534                                             LNET_PEER_NI_LIST_ATTR_MAX_TX_CREDITS,
7535                                             lpni->lpni_net ?
7536                                                 lpni->lpni_net->net_tunables.lct_peer_tx_credits : 0);
7537                                 nla_put_u32(msg,
7538                                             LNET_PEER_NI_LIST_ATTR_CUR_TX_CREDITS,
7539                                             lpni->lpni_txcredits);
7540                                 nla_put_u32(msg,
7541                                             LNET_PEER_NI_LIST_ATTR_MIN_TX_CREDITS,
7542                                             lpni->lpni_mintxcredits);
7543                                 nla_put_u32(msg,
7544                                             LNET_PEER_NI_LIST_ATTR_QUEUE_BUF_COUNT,
7545                                             lpni->lpni_txqnob);
7546                                 nla_put_u32(msg,
7547                                             LNET_PEER_NI_LIST_ATTR_CUR_RTR_CREDITS,
7548                                             lpni->lpni_rtrcredits);
7549                                 nla_put_u32(msg,
7550                                             LNET_PEER_NI_LIST_ATTR_MIN_RTR_CREDITS,
7551                                             lpni->lpni_minrtrcredits);
7552                                 nla_put_u32(msg,
7553                                             LNET_PEER_NI_LIST_ATTR_REFCOUNT,
7554                                             kref_read(&lpni->lpni_kref));
7555
7556                                 memset(&stats, 0, sizeof(stats));
7557                                 stats.iel_send_count = lnet_sum_stats(&lpni->lpni_stats,
7558                                                                       LNET_STATS_TYPE_SEND);
7559                                 stats.iel_recv_count = lnet_sum_stats(&lpni->lpni_stats,
7560                                                                       LNET_STATS_TYPE_RECV);
7561                                 stats.iel_drop_count = lnet_sum_stats(&lpni->lpni_stats,
7562                                                                       LNET_STATS_TYPE_DROP);
7563
7564                                 stats_attr = nla_nest_start(msg,
7565                                                             LNET_PEER_NI_LIST_ATTR_STATS_COUNT);
7566                                 ni_stats = nla_nest_start(msg, 0);
7567                                 nla_put_u32(msg,
7568                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_SEND_COUNT,
7569                                             stats.iel_send_count);
7570                                 nla_put_u32(msg,
7571                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_RECV_COUNT,
7572                                             stats.iel_recv_count);
7573                                 nla_put_u32(msg,
7574                                             LNET_PEER_NI_LIST_STATS_COUNT_ATTR_DROP_COUNT,
7575                                             stats.iel_drop_count);
7576                                 nla_nest_end(msg, ni_stats);
7577                                 nla_nest_end(msg, stats_attr);
7578
7579                                 if (gnlh->version < 2)
7580                                         goto skip_msg_stats;
7581
7582                                 lnet_usr_translate_stats(&lpni_msg_stats, &lpni->lpni_stats);
7583
7584                                 send_stats_list = nla_nest_start(msg,
7585                                                                  LNET_PEER_NI_LIST_ATTR_SENT_STATS);
7586                                 send_stats = nla_nest_start(msg, 0);
7587                                 nla_put_u32(msg,
7588                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7589                                             lpni_msg_stats.im_send_stats.ico_put_count);
7590                                 nla_put_u32(msg,
7591                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7592                                             lpni_msg_stats.im_send_stats.ico_get_count);
7593                                 nla_put_u32(msg,
7594                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7595                                             lpni_msg_stats.im_send_stats.ico_reply_count);
7596                                 nla_put_u32(msg,
7597                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7598                                             lpni_msg_stats.im_send_stats.ico_ack_count);
7599                                 nla_put_u32(msg,
7600                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7601                                             lpni_msg_stats.im_send_stats.ico_hello_count);
7602                                 nla_nest_end(msg, send_stats);
7603                                 nla_nest_end(msg, send_stats_list);
7604
7605                                 recv_stats_list = nla_nest_start(msg,
7606                                                                  LNET_PEER_NI_LIST_ATTR_RECV_STATS);
7607                                 recv_stats = nla_nest_start(msg, 0);
7608                                 nla_put_u32(msg,
7609                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7610                                             lpni_msg_stats.im_recv_stats.ico_put_count);
7611                                 nla_put_u32(msg,
7612                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7613                                             lpni_msg_stats.im_recv_stats.ico_get_count);
7614                                 nla_put_u32(msg,
7615                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7616                                             lpni_msg_stats.im_recv_stats.ico_reply_count);
7617                                 nla_put_u32(msg,
7618                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7619                                             lpni_msg_stats.im_recv_stats.ico_ack_count);
7620                                 nla_put_u32(msg,
7621                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7622                                             lpni_msg_stats.im_recv_stats.ico_hello_count);
7623                                 nla_nest_end(msg, recv_stats);
7624                                 nla_nest_end(msg, recv_stats_list);
7625
7626                                 drop_stats_list = nla_nest_start(msg,
7627                                                                  LNET_PEER_NI_LIST_ATTR_DROP_STATS);
7628                                 drop_stats = nla_nest_start(msg, 0);
7629                                 nla_put_u32(msg,
7630                                             LNET_PEER_NI_LIST_STATS_ATTR_PUT,
7631                                             lpni_msg_stats.im_drop_stats.ico_put_count);
7632                                 nla_put_u32(msg,
7633                                             LNET_PEER_NI_LIST_STATS_ATTR_GET,
7634                                             lpni_msg_stats.im_drop_stats.ico_get_count);
7635                                 nla_put_u32(msg,
7636                                             LNET_PEER_NI_LIST_STATS_ATTR_REPLY,
7637                                             lpni_msg_stats.im_drop_stats.ico_reply_count);
7638                                 nla_put_u32(msg,
7639                                             LNET_PEER_NI_LIST_STATS_ATTR_ACK,
7640                                             lpni_msg_stats.im_drop_stats.ico_ack_count);
7641                                 nla_put_u32(msg,
7642                                             LNET_PEER_NI_LIST_STATS_ATTR_HELLO,
7643                                             lpni_msg_stats.im_drop_stats.ico_hello_count);
7644                                 nla_nest_end(msg, drop_stats);
7645                                 nla_nest_end(msg, drop_stats_list);
7646
7647                                 health_list = nla_nest_start(msg,
7648                                                              LNET_PEER_NI_LIST_ATTR_HEALTH_STATS);
7649                                 health_stats = nla_nest_start(msg, 0);
7650                                 nla_put_s32(msg,
7651                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_VALUE,
7652                                             atomic_read(&lpni->lpni_healthv));
7653                                 nla_put_u32(msg,
7654                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_DROPPED,
7655                                             atomic_read(&lpni->lpni_hstats.hlt_remote_dropped));
7656                                 nla_put_u32(msg,
7657                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_TIMEOUT,
7658                                             atomic_read(&lpni->lpni_hstats.hlt_remote_timeout));
7659                                 nla_put_u32(msg,
7660                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_ERROR,
7661                                             atomic_read(&lpni->lpni_hstats.hlt_remote_error));
7662                                 nla_put_u32(msg,
7663                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NETWORK_TIMEOUT,
7664                                             atomic_read(&lpni->lpni_hstats.hlt_network_timeout));
7665                                 nla_put_u32(msg,
7666                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PING_COUNT,
7667                                             lpni->lpni_ping_count);
7668                                 nla_put_s64(msg,
7669                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_NEXT_PING,
7670                                             lpni->lpni_next_ping,
7671                                             LNET_PEER_NI_LIST_HEALTH_STATS_ATTR_PAD);
7672                                 nla_nest_end(msg, health_stats);
7673                                 nla_nest_end(msg, health_list);
7674                         }
7675 skip_msg_stats:
7676                         nla_nest_end(msg, peer_nid);
7677                 }
7678                 nla_nest_end(msg, nid_list);
7679
7680                 genlmsg_end(msg, hdr);
7681                 lnet_peer_decref_locked(lp);
7682         }
7683         plist->lgpl_index = idx;
7684 unlock_api_mutex:
7685         mutex_unlock(&the_lnet.ln_api_mutex);
7686 send_error:
7687         return lnet_nl_send_error(cb->skb, portid, seq, rc);
7688 };
7689
7690 #ifndef HAVE_NETLINK_CALLBACK_START
7691 static int lnet_old_peer_ni_show_dump(struct sk_buff *msg,
7692                                       struct netlink_callback *cb)
7693 {
7694         if (!cb->args[0]) {
7695                 int rc = lnet_peer_ni_show_start(cb);
7696
7697                 if (rc < 0)
7698                         return lnet_nl_send_error(cb->skb,
7699                                                   NETLINK_CB(cb->skb).portid,
7700                                                   cb->nlh->nlmsg_seq,
7701                                                   rc);
7702         }
7703
7704         return lnet_peer_ni_show_dump(msg, cb);
7705 }
7706 #endif
7707
7708 static int lnet_route_cmd(struct sk_buff *skb, struct genl_info *info)
7709 {
7710         struct nlmsghdr *nlh = nlmsg_hdr(skb);
7711         struct genlmsghdr *gnlh = nlmsg_data(nlh);
7712         struct nlattr *params = genlmsg_data(gnlh);
7713         int msg_len, rem, rc = 0;
7714         struct nlattr *attr;
7715
7716         mutex_lock(&the_lnet.ln_api_mutex);
7717         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
7718                 GENL_SET_ERR_MSG(info, "Network is down");
7719                 mutex_unlock(&the_lnet.ln_api_mutex);
7720                 return -ENETDOWN;
7721         }
7722
7723         msg_len = genlmsg_len(gnlh);
7724         if (!msg_len) {
7725                 GENL_SET_ERR_MSG(info, "no configuration");
7726                 mutex_unlock(&the_lnet.ln_api_mutex);
7727                 return -ENOMSG;
7728         }
7729
7730         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
7731                 GENL_SET_ERR_MSG(info, "invalid configuration");
7732                 mutex_unlock(&the_lnet.ln_api_mutex);
7733                 return -EINVAL;
7734         }
7735
7736         nla_for_each_nested(attr, params, rem) {
7737                 u32 net_id = LNET_NET_ANY, hops = LNET_UNDEFINED_HOPS;
7738                 u32 priority = 0, sensitivity = 1;
7739                 struct lnet_nid gw_nid = LNET_ANY_NID;
7740                 struct nlattr *route_prop;
7741                 bool alive = true;
7742                 s64 when = 0;
7743                 int rem2;
7744
7745                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
7746                         continue;
7747
7748                 nla_for_each_nested(route_prop, attr, rem2) {
7749                         char tmp[LNET_NIDSTR_SIZE];
7750                         ssize_t len;
7751                         s64 num;
7752
7753                         if (nla_type(route_prop) != LN_SCALAR_ATTR_VALUE)
7754                                 continue;
7755
7756                         if (nla_strcmp(route_prop, "net") == 0) {
7757                                 route_prop = nla_next(route_prop, &rem2);
7758                                 if (nla_type(route_prop) !=
7759                                     LN_SCALAR_ATTR_VALUE) {
7760                                         GENL_SET_ERR_MSG(info,
7761                                                          "net is invalid key");
7762                                         GOTO(report_err, rc = -EINVAL);
7763                                 }
7764
7765                                 len = nla_strscpy(tmp, route_prop, sizeof(tmp));
7766                                 if (len < 0) {
7767                                         GENL_SET_ERR_MSG(info,
7768                                                          "net key string is invalid");
7769                                         GOTO(report_err, rc = len);
7770                                 }
7771
7772                                 net_id = libcfs_str2net(tmp);
7773                                 if (!net_id) {
7774                                         GENL_SET_ERR_MSG(info,
7775                                                          "cannot parse remote net");
7776                                         GOTO(report_err, rc = -ENODEV);
7777                                 }
7778
7779                                 if (LNET_NETTYP(net_id) == LOLND) {
7780                                         GENL_SET_ERR_MSG(info,
7781                                                          "setting @lo not allowed");
7782                                         GOTO(report_err, rc = -EACCES);
7783                                 }
7784
7785                                 if (net_id == LNET_NET_ANY) {
7786                                         GENL_SET_ERR_MSG(info,
7787                                                          "setting LNET_NET_ANY not allowed");
7788                                         GOTO(report_err, rc = -ENXIO);
7789                                 }
7790                         } else if (nla_strcmp(route_prop, "gateway") == 0) {
7791                                 route_prop = nla_next(route_prop, &rem2);
7792                                 if (nla_type(route_prop) !=
7793                                     LN_SCALAR_ATTR_VALUE) {
7794                                         GENL_SET_ERR_MSG(info,
7795                                                          "gateway is invalid key");
7796                                         GOTO(report_err, rc = -EINVAL);
7797                                 }
7798
7799                                 len = nla_strscpy(tmp, route_prop, sizeof(tmp));
7800                                 if (len < 0) {
7801                                         GENL_SET_ERR_MSG(info,
7802                                                          "gateway string is invalid");
7803                                         GOTO(report_err, rc = len);
7804                                 }
7805
7806                                 rc = libcfs_strnid(&gw_nid, strim(tmp));
7807                                 if (rc < 0) {
7808                                         GENL_SET_ERR_MSG(info,
7809                                                          "cannot parse gateway");
7810                                         GOTO(report_err, rc = -ENODEV);
7811                                 }
7812                         } else if (nla_strcmp(route_prop, "state") == 0) {
7813                                 route_prop = nla_next(route_prop, &rem2);
7814                                 if (nla_type(route_prop) !=
7815                                     LN_SCALAR_ATTR_VALUE) {
7816                                         GENL_SET_ERR_MSG(info,
7817                                                          "state is invalid key");
7818                                         GOTO(report_err, rc = -EINVAL);
7819                                 }
7820
7821                                 if (nla_strcmp(route_prop, "down") == 0) {
7822                                         alive = false;
7823                                 } else if (nla_strcmp(route_prop, "up") == 0) {
7824                                         alive = true;
7825                                 } else {
7826                                         GENL_SET_ERR_MSG(info,
7827                                                          "status string bad value");
7828                                         GOTO(report_err, rc = -EINVAL);
7829                                 }
7830                         } else if (nla_strcmp(route_prop, "notify_time") == 0) {
7831                                 route_prop = nla_next(route_prop, &rem2);
7832                                 if (nla_type(route_prop) !=
7833                                     LN_SCALAR_ATTR_INT_VALUE) {
7834                                         GENL_SET_ERR_MSG(info,
7835                                                          "notify_time is invalid key");
7836                                         GOTO(report_err, rc = -EINVAL);
7837                                 }
7838
7839                                 when = nla_get_s64(route_prop);
7840                                 if (ktime_get_real_seconds() < when) {
7841                                         GENL_SET_ERR_MSG(info,
7842                                                          "notify_time is in the future");
7843                                         GOTO(report_err, rc = -EINVAL);
7844                                 }
7845                         } else if (nla_strcmp(route_prop, "hop") == 0) {
7846                                 route_prop = nla_next(route_prop, &rem2);
7847                                 if (nla_type(route_prop) !=
7848                                     LN_SCALAR_ATTR_INT_VALUE) {
7849                                         GENL_SET_ERR_MSG(info,
7850                                                          "hop has invalid key");
7851                                         GOTO(report_err, rc = -EINVAL);
7852                                 }
7853
7854                                 hops = nla_get_s64(route_prop);
7855                                 if ((hops < 1 || hops > 255) && hops != -1) {
7856                                         GENL_SET_ERR_MSG(info,
7857                                                          "invalid hop count must be between 1 and 255");
7858                                         GOTO(report_err, rc = -EINVAL);
7859                                 }
7860                         } else if (nla_strcmp(route_prop, "priority") == 0) {
7861                                 route_prop = nla_next(route_prop, &rem2);
7862                                 if (nla_type(route_prop) !=
7863                                     LN_SCALAR_ATTR_INT_VALUE) {
7864                                         GENL_SET_ERR_MSG(info,
7865                                                          "priority has invalid key");
7866                                         GOTO(report_err, rc = -EINVAL);
7867                                 }
7868
7869                                 num = nla_get_s64(route_prop);
7870                                 if (num < 0) {
7871                                         GENL_SET_ERR_MSG(info,
7872                                                          "invalid priority, must not be negative");
7873                                         GOTO(report_err, rc = -EINVAL);
7874                                 }
7875                                 priority = num;
7876                         } else if (nla_strcmp(route_prop,
7877                                               "health_sensitivity") == 0) {
7878                                 route_prop = nla_next(route_prop, &rem2);
7879                                 if (nla_type(route_prop) !=
7880                                     LN_SCALAR_ATTR_INT_VALUE) {
7881                                         GENL_SET_ERR_MSG(info,
7882                                                          "sensitivity has invalid key");
7883                                         GOTO(report_err, rc = -EINVAL);
7884                                 }
7885
7886                                 num = nla_get_s64(route_prop);
7887                                 if (num < 1) {
7888                                         GENL_SET_ERR_MSG(info,
7889                                                          "invalid health sensitivity, must be 1 or greater");
7890                                         GOTO(report_err, rc = -EINVAL);
7891                                 }
7892                                 sensitivity = num;
7893                         }
7894                 }
7895
7896                 if (net_id == LNET_NET_ANY) {
7897                         GENL_SET_ERR_MSG(info,
7898                                          "missing mandatory parameter: network");
7899                         GOTO(report_err, rc = -ENODEV);
7900                 }
7901
7902                 if (LNET_NID_IS_ANY(&gw_nid)) {
7903                         GENL_SET_ERR_MSG(info,
7904                                          "missing mandatory parameter: gateway");
7905                         GOTO(report_err, rc = -ENODEV);
7906                 }
7907
7908                 if (info->nlhdr->nlmsg_flags & NLM_F_REPLACE) {
7909                         /* Convert the user-supplied real time to monotonic.
7910                          * NB: "when" is always in the past
7911                          */
7912                         when = ktime_get_seconds() -
7913                                 (ktime_get_real_seconds() - when);
7914
7915                         mutex_unlock(&the_lnet.ln_api_mutex);
7916                         rc = lnet_notify(NULL, &gw_nid, alive, false, when);
7917                         mutex_lock(&the_lnet.ln_api_mutex);
7918                         if (rc < 0)
7919                                 GOTO(report_err, rc);
7920                         else if (the_lnet.ln_state != LNET_STATE_RUNNING)
7921                                 GOTO(report_err, rc = -ENETDOWN);
7922                 } else if (info->nlhdr->nlmsg_flags & NLM_F_CREATE) {
7923                         rc = lnet_add_route(net_id, hops, &gw_nid, priority,
7924                                             sensitivity);
7925                         if (rc < 0) {
7926                                 switch (rc) {
7927                                 case -EINVAL:
7928                                         GENL_SET_ERR_MSG(info,
7929                                                          "invalid settings for route creation");
7930                                         break;
7931                                 case -EHOSTUNREACH:
7932                                         GENL_SET_ERR_MSG(info,
7933                                                          "No interface configured on the same net as gateway");
7934                                         break;
7935                                 case -ESHUTDOWN:
7936                                         GENL_SET_ERR_MSG(info,
7937                                                          "Network is down");
7938                                         break;
7939                                 case -EEXIST:
7940                                         GENL_SET_ERR_MSG(info,
7941                                                          "Route already exists or the specified network is local");
7942                                         break;
7943                                 default:
7944                                         GENL_SET_ERR_MSG(info,
7945                                                          "failed to create route");
7946                                         break;
7947                                 }
7948                                 GOTO(report_err, rc);
7949                         }
7950                 } else if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
7951                         rc = lnet_del_route(net_id, &gw_nid);
7952                         if (rc < 0) {
7953                                 GENL_SET_ERR_MSG(info,
7954                                                  "failed to delete route");
7955                                 GOTO(report_err, rc);
7956                         }
7957                 }
7958         }
7959 report_err:
7960         mutex_unlock(&the_lnet.ln_api_mutex);
7961
7962         return rc;
7963 }
7964
7965 static inline struct lnet_genl_ping_list *
7966 lnet_ping_dump_ctx(struct netlink_callback *cb)
7967 {
7968         return (struct lnet_genl_ping_list *)cb->args[0];
7969 }
7970
7971 static int lnet_ping_show_done(struct netlink_callback *cb)
7972 {
7973         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
7974
7975         if (plist) {
7976                 genradix_free(&plist->lgpl_failed);
7977                 genradix_free(&plist->lgpl_list);
7978                 LIBCFS_FREE(plist, sizeof(*plist));
7979                 cb->args[0] = 0;
7980         }
7981
7982         return 0;
7983 }
7984
7985 /* LNet ping ->start() handler for GET requests */
7986 static int lnet_ping_show_start(struct netlink_callback *cb)
7987 {
7988         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
7989 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
7990         struct netlink_ext_ack *extack = NULL;
7991 #endif
7992         struct lnet_genl_ping_list *plist;
7993         int msg_len = genlmsg_len(gnlh);
7994         struct nlattr *params, *top;
7995         int rem, rc = 0;
7996
7997 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
7998         extack = cb->extack;
7999 #endif
8000         if (the_lnet.ln_refcount == 0) {
8001                 NL_SET_ERR_MSG(extack, "Network is down");
8002                 return -ENETDOWN;
8003         }
8004
8005         if (!msg_len) {
8006                 NL_SET_ERR_MSG(extack, "Ping needs NID targets");
8007                 return -ENOENT;
8008         }
8009
8010         LIBCFS_ALLOC(plist, sizeof(*plist));
8011         if (!plist) {
8012                 NL_SET_ERR_MSG(extack, "failed to setup ping list");
8013                 return -ENOMEM;
8014         }
8015         genradix_init(&plist->lgpl_list);
8016         plist->lgpl_timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
8017         plist->lgpl_src_nid = LNET_ANY_NID;
8018         plist->lgpl_index = 0;
8019         plist->lgpl_list_count = 0;
8020         cb->args[0] = (long)plist;
8021
8022         params = genlmsg_data(gnlh);
8023         nla_for_each_attr(top, params, msg_len, rem) {
8024                 struct nlattr *nids;
8025                 int rem2;
8026
8027                 switch (nla_type(top)) {
8028                 case LN_SCALAR_ATTR_VALUE:
8029                         if (nla_strcmp(top, "timeout") == 0) {
8030                                 s64 timeout;
8031
8032                                 top = nla_next(top, &rem);
8033                                 if (nla_type(top) != LN_SCALAR_ATTR_INT_VALUE) {
8034                                         NL_SET_ERR_MSG(extack,
8035                                                        "invalid timeout param");
8036                                         GOTO(report_err, rc = -EINVAL);
8037                                 }
8038
8039                                 /* If timeout is negative then set default of
8040                                  * 3 minutes
8041                                  */
8042                                 timeout = nla_get_s64(top);
8043                                 if (timeout > 0 &&
8044                                     timeout < (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
8045                                         plist->lgpl_timeout =
8046                                                 nsecs_to_jiffies(timeout * NSEC_PER_MSEC);
8047                         } else if (nla_strcmp(top, "source") == 0) {
8048                                 char nidstr[LNET_NIDSTR_SIZE + 1];
8049
8050                                 top = nla_next(top, &rem);
8051                                 if (nla_type(top) != LN_SCALAR_ATTR_VALUE) {
8052                                         NL_SET_ERR_MSG(extack,
8053                                                        "invalid source param");
8054                                         GOTO(report_err, rc = -EINVAL);
8055                                 }
8056
8057                                 rc = nla_strscpy(nidstr, top, sizeof(nidstr));
8058                                 if (rc < 0) {
8059                                         NL_SET_ERR_MSG(extack,
8060                                                        "failed to parse source nid");
8061                                         GOTO(report_err, rc);
8062                                 }
8063
8064                                 rc = libcfs_strnid(&plist->lgpl_src_nid,
8065                                                    strim(nidstr));
8066                                 if (rc < 0) {
8067                                         NL_SET_ERR_MSG(extack,
8068                                                        "invalid source nid");
8069                                         GOTO(report_err, rc);
8070                                 }
8071                                 rc = 0;
8072                         }
8073                         break;
8074                 case LN_SCALAR_ATTR_LIST:
8075                         nla_for_each_nested(nids, top, rem2) {
8076                                 char nid[LNET_NIDSTR_SIZE + 1];
8077                                 struct lnet_processid *id;
8078
8079                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8080                                         continue;
8081
8082                                 memset(nid, 0, sizeof(nid));
8083                                 rc = nla_strscpy(nid, nids, sizeof(nid));
8084                                 if (rc < 0) {
8085                                         NL_SET_ERR_MSG(extack,
8086                                                        "failed to get NID");
8087                                         GOTO(report_err, rc);
8088                                 }
8089
8090                                 id = genradix_ptr_alloc(&plist->lgpl_list,
8091                                                         plist->lgpl_list_count++,
8092                                                         GFP_KERNEL);
8093                                 if (!id) {
8094                                         NL_SET_ERR_MSG(extack,
8095                                                        "failed to allocate NID");
8096                                         GOTO(report_err, rc = -ENOMEM);
8097                                 }
8098
8099                                 rc = libcfs_strid(id, strim(nid));
8100                                 if (rc < 0) {
8101                                         NL_SET_ERR_MSG(extack, "cannot parse NID");
8102                                         GOTO(report_err, rc);
8103                                 }
8104                                 rc = 0;
8105                         }
8106                         fallthrough;
8107                 default:
8108                         break;
8109                 }
8110         }
8111 report_err:
8112         if (rc < 0)
8113                 lnet_ping_show_done(cb);
8114
8115         return rc;
8116 }
8117
8118 static const struct ln_key_list ping_err_props_list = {
8119         .lkl_maxattr                    = LNET_ERR_ATTR_MAX,
8120         .lkl_list                       = {
8121                 [LNET_ERR_ATTR_HDR]             = {
8122                         .lkp_value              = "manage",
8123                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8124                         .lkp_data_type          = NLA_NUL_STRING,
8125                 },
8126                 [LNET_ERR_ATTR_TYPE]            = {
8127                         .lkp_value              = "ping",
8128                         .lkp_data_type          = NLA_STRING,
8129                 },
8130                 [LNET_ERR_ATTR_ERRNO]           = {
8131                         .lkp_value              = "errno",
8132                         .lkp_data_type          = NLA_S16,
8133                 },
8134                 [LNET_ERR_ATTR_DESCR]           = {
8135                         .lkp_value              = "descr",
8136                         .lkp_data_type          = NLA_STRING,
8137                 },
8138         },
8139 };
8140
8141 static const struct ln_key_list ping_props_list = {
8142         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
8143         .lkl_list                       = {
8144                 [LNET_PING_ATTR_HDR]            = {
8145                         .lkp_value              = "ping",
8146                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8147                         .lkp_data_type          = NLA_NUL_STRING,
8148                 },
8149                 [LNET_PING_ATTR_PRIMARY_NID]    = {
8150                         .lkp_value              = "primary nid",
8151                         .lkp_data_type          = NLA_STRING
8152                 },
8153                 [LNET_PING_ATTR_ERRNO]          = {
8154                         .lkp_value              = "errno",
8155                         .lkp_data_type          = NLA_S16
8156                 },
8157                 [LNET_PING_ATTR_MULTIRAIL]      = {
8158                         .lkp_value              = "Multi-Rail",
8159                         .lkp_data_type          = NLA_FLAG
8160                 },
8161                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
8162                         .lkp_value              = "peer_ni",
8163                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8164                         .lkp_data_type          = NLA_NESTED
8165                 },
8166         },
8167 };
8168
8169 static const struct ln_key_list ping_peer_ni_list = {
8170         .lkl_maxattr                    = LNET_PING_PEER_NI_ATTR_MAX,
8171         .lkl_list                       = {
8172                 [LNET_PING_PEER_NI_ATTR_NID]    = {
8173                         .lkp_value              = "nid",
8174                         .lkp_data_type          = NLA_STRING
8175                 },
8176         },
8177 };
8178
8179 static int lnet_ping_show_dump(struct sk_buff *msg,
8180                                struct netlink_callback *cb)
8181 {
8182         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
8183 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8184         struct netlink_ext_ack *extack = NULL;
8185 #endif
8186         int portid = NETLINK_CB(cb->skb).portid;
8187         int seq = cb->nlh->nlmsg_seq;
8188         int idx = plist->lgpl_index;
8189         int rc = 0, i = 0;
8190
8191 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8192         extack = cb->extack;
8193 #endif
8194         if (!plist->lgpl_index) {
8195                 const struct ln_key_list *all[] = {
8196                         &ping_props_list, &ping_peer_ni_list, NULL
8197                 };
8198
8199                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
8200                                                 &lnet_family,
8201                                                 NLM_F_CREATE | NLM_F_MULTI,
8202                                                 LNET_CMD_PING, all);
8203                 if (rc < 0) {
8204                         NL_SET_ERR_MSG(extack, "failed to send key table");
8205                         GOTO(send_error, rc);
8206                 }
8207
8208                 genradix_init(&plist->lgpl_failed);
8209         }
8210
8211         while (idx < plist->lgpl_list_count) {
8212                 struct lnet_nid primary_nid = LNET_ANY_NID;
8213                 struct lnet_genl_ping_list peers;
8214                 struct lnet_processid *id;
8215                 struct nlattr *nid_list;
8216                 struct lnet_peer *lp;
8217                 bool mr_flag = false;
8218                 unsigned int count;
8219                 void *hdr = NULL;
8220
8221                 id = genradix_ptr(&plist->lgpl_list, idx++);
8222
8223                 rc = lnet_ping(id, &plist->lgpl_src_nid, plist->lgpl_timeout,
8224                                &peers, lnet_interfaces_max);
8225                 if (rc < 0) {
8226                         struct lnet_fail_ping *fail;
8227
8228                         fail = genradix_ptr_alloc(&plist->lgpl_failed,
8229                                                   plist->lgpl_failed_count++,
8230                                                   GFP_KERNEL);
8231                         if (!fail) {
8232                                 NL_SET_ERR_MSG(extack,
8233                                                "failed to allocate failed NID");
8234                                 GOTO(send_error, rc);
8235                         }
8236                         memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8237                         snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8238                                  "failed to ping %s",
8239                                  libcfs_nidstr(&id->nid));
8240                         fail->lfp_id = *id;
8241                         fail->lfp_errno = rc;
8242                         goto cant_reach;
8243                 }
8244
8245                 mutex_lock(&the_lnet.ln_api_mutex);
8246                 lp = lnet_find_peer(&id->nid);
8247                 if (lp) {
8248                         primary_nid = lp->lp_primary_nid;
8249                         mr_flag = lnet_peer_is_multi_rail(lp);
8250                         lnet_peer_decref_locked(lp);
8251                 }
8252                 mutex_unlock(&the_lnet.ln_api_mutex);
8253
8254                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8255                                   NLM_F_MULTI, LNET_CMD_PING);
8256                 if (!hdr) {
8257                         NL_SET_ERR_MSG(extack, "failed to send values");
8258                         genlmsg_cancel(msg, hdr);
8259                         GOTO(send_error, rc = -EMSGSIZE);
8260                 }
8261
8262                 if (i++ == 0)
8263                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
8264
8265                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
8266                                libcfs_nidstr(&primary_nid));
8267                 if (mr_flag)
8268                         nla_put_flag(msg, LNET_PING_ATTR_MULTIRAIL);
8269
8270                 nid_list = nla_nest_start(msg, LNET_PING_ATTR_PEER_NI_LIST);
8271                 for (count = 0; count < rc; count++) {
8272                         struct lnet_processid *result;
8273                         struct nlattr *nid_attr;
8274                         char *idstr;
8275
8276                         result = genradix_ptr(&peers.lgpl_list, count);
8277                         if (nid_is_lo0(&result->nid))
8278                                 continue;
8279
8280                         nid_attr = nla_nest_start(msg, count + 1);
8281                         if (id->pid == LNET_PID_LUSTRE)
8282                                 idstr = libcfs_nidstr(&result->nid);
8283                         else
8284                                 idstr = libcfs_idstr(result);
8285                         nla_put_string(msg, LNET_PING_PEER_NI_ATTR_NID, idstr);
8286                         nla_nest_end(msg, nid_attr);
8287                 }
8288                 nla_nest_end(msg, nid_list);
8289                 genlmsg_end(msg, hdr);
8290 cant_reach:
8291                 genradix_free(&peers.lgpl_list);
8292         }
8293
8294         if (plist->lgpl_failed_count) {
8295                 int flags = NLM_F_CREATE | NLM_F_REPLACE | NLM_F_MULTI;
8296                 const struct ln_key_list *fail[] = {
8297                         &ping_err_props_list, NULL
8298                 };
8299
8300                 rc = lnet_genl_send_scalar_list(msg, portid, seq, &lnet_family,
8301                                                 flags, LNET_CMD_PING, fail);
8302                 if (rc < 0) {
8303                         NL_SET_ERR_MSG(extack,
8304                                        "failed to send new key table");
8305                         GOTO(send_error, rc);
8306                 }
8307
8308                 for (i = 0; i < plist->lgpl_failed_count; i++) {
8309                         struct lnet_fail_ping *fail;
8310                         void *hdr;
8311
8312                         fail = genradix_ptr(&plist->lgpl_failed, i);
8313
8314                         hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8315                                           NLM_F_MULTI, LNET_CMD_PING);
8316                         if (!hdr) {
8317                                 NL_SET_ERR_MSG(extack,
8318                                                "failed to send failed values");
8319                                 genlmsg_cancel(msg, hdr);
8320                                 GOTO(send_error, rc = -EMSGSIZE);
8321                         }
8322
8323                         if (i == 0)
8324                                 nla_put_string(msg, LNET_ERR_ATTR_HDR, "");
8325
8326                         nla_put_string(msg, LNET_ERR_ATTR_TYPE, "\n");
8327                         nla_put_s16(msg, LNET_ERR_ATTR_ERRNO,
8328                                     fail->lfp_errno);
8329                         nla_put_string(msg, LNET_ERR_ATTR_DESCR,
8330                                        fail->lfp_msg);
8331                         genlmsg_end(msg, hdr);
8332                 }
8333         }
8334         genradix_free(&plist->lgpl_list);
8335         rc = 0; /* don't treat it as an error */
8336
8337         plist->lgpl_index = idx;
8338 send_error:
8339         return lnet_nl_send_error(cb->skb, portid, seq, rc);
8340 }
8341
8342 #ifndef HAVE_NETLINK_CALLBACK_START
8343 static int lnet_old_ping_show_dump(struct sk_buff *msg,
8344                                    struct netlink_callback *cb)
8345 {
8346         if (!cb->args[0]) {
8347                 int rc = lnet_ping_show_start(cb);
8348
8349                 if (rc < 0)
8350                         return lnet_nl_send_error(cb->skb,
8351                                                   NETLINK_CB(cb->skb).portid,
8352                                                   cb->nlh->nlmsg_seq,
8353                                                   rc);
8354         }
8355
8356         return lnet_ping_show_dump(msg, cb);
8357 }
8358 #endif
8359
8360 static const struct ln_key_list discover_err_props_list = {
8361         .lkl_maxattr                    = LNET_ERR_ATTR_MAX,
8362         .lkl_list                       = {
8363                 [LNET_ERR_ATTR_HDR]             = {
8364                         .lkp_value              = "manage",
8365                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8366                         .lkp_data_type          = NLA_NUL_STRING,
8367                 },
8368                 [LNET_ERR_ATTR_TYPE]            = {
8369                         .lkp_value              = "discover",
8370                         .lkp_data_type          = NLA_STRING,
8371                 },
8372                 [LNET_ERR_ATTR_ERRNO]           = {
8373                         .lkp_value              = "errno",
8374                         .lkp_data_type          = NLA_S16,
8375                 },
8376                 [LNET_ERR_ATTR_DESCR]           = {
8377                         .lkp_value              = "descr",
8378                         .lkp_data_type          = NLA_STRING,
8379                 },
8380         },
8381 };
8382
8383 static const struct ln_key_list discover_props_list = {
8384         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
8385         .lkl_list                       = {
8386                 [LNET_PING_ATTR_HDR]            = {
8387                         .lkp_value              = "discover",
8388                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8389                         .lkp_data_type          = NLA_NUL_STRING,
8390                 },
8391                 [LNET_PING_ATTR_PRIMARY_NID]    = {
8392                         .lkp_value              = "primary nid",
8393                         .lkp_data_type          = NLA_STRING
8394                 },
8395                 [LNET_PING_ATTR_ERRNO]          = {
8396                         .lkp_value              = "errno",
8397                         .lkp_data_type          = NLA_S16
8398                 },
8399                 [LNET_PING_ATTR_MULTIRAIL]      = {
8400                         .lkp_value              = "Multi-Rail",
8401                         .lkp_data_type          = NLA_FLAG
8402                 },
8403                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
8404                         .lkp_value              = "peer_ni",
8405                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8406                         .lkp_data_type          = NLA_NESTED
8407                 },
8408         },
8409 };
8410
8411 static int lnet_ping_cmd(struct sk_buff *skb, struct genl_info *info)
8412 {
8413         const struct ln_key_list *all[] = {
8414                 &discover_props_list, &ping_peer_ni_list, NULL
8415         };
8416         struct nlmsghdr *nlh = nlmsg_hdr(skb);
8417         struct genlmsghdr *gnlh = nlmsg_data(nlh);
8418         struct nlattr *params = genlmsg_data(gnlh);
8419         struct lnet_genl_ping_list dlists;
8420         int msg_len, rem, rc = 0, i;
8421         bool clear_hdr = false;
8422         struct sk_buff *reply;
8423         struct nlattr *attr;
8424         void *hdr = NULL;
8425
8426         msg_len = genlmsg_len(gnlh);
8427         if (!msg_len) {
8428                 GENL_SET_ERR_MSG(info, "no configuration");
8429                 return -ENOMSG;
8430         }
8431
8432         if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE)) {
8433                 GENL_SET_ERR_MSG(info, "only NLM_F_CREATE setting is allowed");
8434                 return -EINVAL;
8435         }
8436
8437         reply = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
8438         if (!reply) {
8439                 GENL_SET_ERR_MSG(info,
8440                                  "fail to allocate reply");
8441                 return -ENOMEM;
8442         }
8443
8444         genradix_init(&dlists.lgpl_failed);
8445         dlists.lgpl_failed_count = 0;
8446         genradix_init(&dlists.lgpl_list);
8447         dlists.lgpl_list_count = 0;
8448
8449         rc = lnet_genl_send_scalar_list(reply, info->snd_portid,
8450                                         info->snd_seq, &lnet_family,
8451                                         NLM_F_CREATE | NLM_F_MULTI,
8452                                         LNET_CMD_PING, all);
8453         if (rc < 0) {
8454                 GENL_SET_ERR_MSG(info,
8455                                  "failed to send key table");
8456                 GOTO(report_err, rc);
8457         }
8458
8459         nla_for_each_attr(attr, params, msg_len, rem) {
8460                 struct nlattr *nids;
8461                 int rem2;
8462
8463                 /* We only care about the NID list to discover with */
8464                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
8465                         continue;
8466
8467                 nla_for_each_nested(nids, attr, rem2) {
8468                         char nid[LNET_NIDSTR_SIZE + 1];
8469                         struct lnet_processid id;
8470                         struct nlattr *nid_list;
8471                         struct lnet_peer *lp;
8472                         ssize_t len;
8473
8474                         if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8475                                 continue;
8476
8477                         memset(nid, 0, sizeof(nid));
8478                         rc = nla_strscpy(nid, nids, sizeof(nid));
8479                         if (rc < 0) {
8480                                 GENL_SET_ERR_MSG(info,
8481                                                  "failed to get NID");
8482                                 GOTO(report_err, rc);
8483                         }
8484
8485                         len = libcfs_strid(&id, strim(nid));
8486                         if (len < 0) {
8487                                 struct lnet_fail_ping *fail;
8488
8489                                 fail = genradix_ptr_alloc(&dlists.lgpl_failed,
8490                                                           dlists.lgpl_failed_count++,
8491                                                           GFP_KERNEL);
8492                                 if (!fail) {
8493                                         GENL_SET_ERR_MSG(info,
8494                                                          "failed to allocate improper NID");
8495                                         GOTO(report_err, rc = -ENOMEM);
8496                                 }
8497                                 memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8498                                 snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8499                                          "cannot parse NID '%s'", strim(nid));
8500                                 fail->lfp_id = id;
8501                                 fail->lfp_errno = len;
8502                                 continue;
8503                         }
8504
8505                         if (LNET_NID_IS_ANY(&id.nid))
8506                                 continue;
8507
8508                         rc = lnet_discover(&id,
8509                                            info->nlhdr->nlmsg_flags & NLM_F_EXCL,
8510                                            &dlists);
8511                         if (rc < 0) {
8512                                 struct lnet_fail_ping *fail;
8513
8514                                 fail = genradix_ptr_alloc(&dlists.lgpl_failed,
8515                                                           dlists.lgpl_failed_count++,
8516                                                           GFP_KERNEL);
8517                                 if (!fail) {
8518                                         GENL_SET_ERR_MSG(info,
8519                                                          "failed to allocate failed NID");
8520                                         GOTO(report_err, rc = -ENOMEM);
8521                                 }
8522                                 memset(fail->lfp_msg, '\0', sizeof(fail->lfp_msg));
8523                                 snprintf(fail->lfp_msg, sizeof(fail->lfp_msg),
8524                                          "failed to discover %s",
8525                                          libcfs_nidstr(&id.nid));
8526                                 fail->lfp_id = id;
8527                                 fail->lfp_errno = rc;
8528                                 continue;
8529                         }
8530
8531                         /* create the genetlink message header */
8532                         hdr = genlmsg_put(reply, info->snd_portid, info->snd_seq,
8533                                           &lnet_family, NLM_F_MULTI, LNET_CMD_PING);
8534                         if (!hdr) {
8535                                 GENL_SET_ERR_MSG(info,
8536                                                  "failed to allocate hdr");
8537                                 GOTO(report_err, rc = -ENOMEM);
8538                         }
8539
8540                         if (!clear_hdr) {
8541                                 nla_put_string(reply, LNET_PING_ATTR_HDR, "");
8542                                 clear_hdr = true;
8543                         }
8544
8545                         lp = lnet_find_peer(&id.nid);
8546                         if (lp) {
8547                                 nla_put_string(reply, LNET_PING_ATTR_PRIMARY_NID,
8548                                                libcfs_nidstr(&lp->lp_primary_nid));
8549                                 if (lnet_peer_is_multi_rail(lp))
8550                                         nla_put_flag(reply, LNET_PING_ATTR_MULTIRAIL);
8551                                 lnet_peer_decref_locked(lp);
8552                         }
8553
8554                         nid_list = nla_nest_start(reply, LNET_PING_ATTR_PEER_NI_LIST);
8555                         for (i = 0; i < dlists.lgpl_list_count; i++) {
8556                                 struct lnet_processid *found;
8557                                 struct nlattr *nid_attr;
8558                                 char *idstr;
8559
8560                                 found = genradix_ptr(&dlists.lgpl_list, i);
8561                                 if (nid_is_lo0(&found->nid))
8562                                         continue;
8563
8564                                 nid_attr = nla_nest_start(reply, i + 1);
8565                                 if (id.pid == LNET_PID_LUSTRE)
8566                                         idstr = libcfs_nidstr(&found->nid);
8567                                 else
8568                                         idstr = libcfs_idstr(found);
8569                                 nla_put_string(reply, LNET_PING_PEER_NI_ATTR_NID, idstr);
8570                                 nla_nest_end(reply, nid_attr);
8571                         }
8572                         nla_nest_end(reply, nid_list);
8573
8574                         genlmsg_end(reply, hdr);
8575                 }
8576         }
8577
8578         if (dlists.lgpl_failed_count) {
8579                 int flags = NLM_F_CREATE | NLM_F_REPLACE | NLM_F_MULTI;
8580                 const struct ln_key_list *fail[] = {
8581                         &discover_err_props_list, NULL
8582                 };
8583
8584                 rc = lnet_genl_send_scalar_list(reply, info->snd_portid,
8585                                                 info->snd_seq, &lnet_family,
8586                                                 flags, LNET_CMD_PING, fail);
8587                 if (rc < 0) {
8588                         GENL_SET_ERR_MSG(info,
8589                                          "failed to send new key table");
8590                         GOTO(report_err, rc);
8591                 }
8592
8593                 for (i = 0; i < dlists.lgpl_failed_count; i++) {
8594                         struct lnet_fail_ping *fail;
8595
8596                         hdr = genlmsg_put(reply, info->snd_portid, info->snd_seq,
8597                                           &lnet_family, NLM_F_MULTI, LNET_CMD_PING);
8598                         if (!hdr) {
8599                                 GENL_SET_ERR_MSG(info,
8600                                                  "failed to send failed values");
8601                                 GOTO(report_err, rc = -ENOMSG);
8602                         }
8603
8604                         fail = genradix_ptr(&dlists.lgpl_failed, i);
8605                         if (i == 0)
8606                                 nla_put_string(reply, LNET_ERR_ATTR_HDR, "");
8607
8608                         nla_put_string(reply, LNET_ERR_ATTR_TYPE, "\n");
8609                         nla_put_s16(reply, LNET_ERR_ATTR_ERRNO,
8610                                     fail->lfp_errno);
8611                         nla_put_string(reply, LNET_ERR_ATTR_DESCR,
8612                                        fail->lfp_msg);
8613                         genlmsg_end(reply, hdr);
8614                 }
8615         }
8616
8617         nlh = nlmsg_put(reply, info->snd_portid, info->snd_seq, NLMSG_DONE, 0,
8618                         NLM_F_MULTI);
8619         if (!nlh) {
8620                 genlmsg_cancel(reply, hdr);
8621                 GENL_SET_ERR_MSG(info,
8622                                  "failed to finish message");
8623                 GOTO(report_err, rc = -EMSGSIZE);
8624         }
8625
8626 report_err:
8627         genradix_free(&dlists.lgpl_failed);
8628         genradix_free(&dlists.lgpl_list);
8629
8630         if (rc < 0) {
8631                 genlmsg_cancel(reply, hdr);
8632                 nlmsg_free(reply);
8633         } else {
8634                 rc = genlmsg_reply(reply, info);
8635         }
8636
8637         return rc;
8638 }
8639
8640 #define lnet_peer_dist_show_done        lnet_peer_ni_show_done
8641
8642 static int lnet_peer_dist_show_start(struct netlink_callback *cb)
8643 {
8644         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
8645 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8646         struct netlink_ext_ack *extack = NULL;
8647 #endif
8648         struct lnet_genl_processid_list *plist;
8649         int msg_len = genlmsg_len(gnlh);
8650         struct nlattr *params, *top;
8651         int rem, rc = 0;
8652
8653 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8654         extack = cb->extack;
8655 #endif
8656         mutex_lock(&the_lnet.ln_api_mutex);
8657         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
8658                 NL_SET_ERR_MSG(extack, "Network is down");
8659                 mutex_unlock(&the_lnet.ln_api_mutex);
8660                 return -ENETDOWN;
8661         }
8662
8663         msg_len = genlmsg_len(gnlh);
8664         if (!msg_len) {
8665                 NL_SET_ERR_MSG(extack, "Missing NID argument(s)");
8666                 mutex_unlock(&the_lnet.ln_api_mutex);
8667                 return -ENOENT;
8668         }
8669
8670         CFS_ALLOC_PTR(plist);
8671         if (!plist) {
8672                 NL_SET_ERR_MSG(extack, "No memory for peer NID list");
8673                 mutex_unlock(&the_lnet.ln_api_mutex);
8674                 return -ENOMEM;
8675         }
8676
8677         genradix_init(&plist->lgpl_list);
8678         plist->lgpl_count = 0;
8679         plist->lgpl_index = 0;
8680         cb->args[0] = (long)plist;
8681
8682         params = genlmsg_data(gnlh);
8683         nla_for_each_attr(top, params, msg_len, rem) {
8684                 struct nlattr *nids;
8685                 int rem2;
8686
8687                 if (nla_type(top) != LN_SCALAR_ATTR_LIST)
8688                         continue;
8689
8690                 nla_for_each_nested(nids, top, rem2) {
8691                         char nidstr[LNET_NIDSTR_SIZE + 1];
8692                         struct lnet_processid *id;
8693
8694                         if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
8695                                 continue;
8696
8697                         memset(nidstr, 0, sizeof(nidstr));
8698                         rc = nla_strscpy(nidstr, nids, sizeof(nidstr));
8699                         if (rc < 0) {
8700                                 NL_SET_ERR_MSG(extack,
8701                                                "failed to get NID");
8702                                 GOTO(report_err, rc);
8703                         }
8704
8705                         id = genradix_ptr_alloc(&plist->lgpl_list,
8706                                                 plist->lgpl_count++,
8707                                                 GFP_KERNEL);
8708                         if (!id) {
8709                                 NL_SET_ERR_MSG(extack, "failed to allocate NID");
8710                                 GOTO(report_err, rc = -ENOMEM);
8711                         }
8712
8713                         rc = libcfs_strid(id, strim(nidstr));
8714                         if (rc < 0) {
8715                                 NL_SET_ERR_MSG(extack, "invalid NID");
8716                                 GOTO(report_err, rc);
8717                         }
8718                         rc = 0;
8719                 }
8720         }
8721 report_err:
8722         mutex_unlock(&the_lnet.ln_api_mutex);
8723
8724         if (rc < 0)
8725                 lnet_peer_dist_show_done(cb);
8726
8727         return rc;
8728 }
8729
8730 static const struct ln_key_list peer_dist_props_list = {
8731         .lkl_maxattr                    = LNET_PEER_DIST_ATTR_MAX,
8732         .lkl_list                       = {
8733                 [LNET_PEER_DIST_ATTR_HDR]       = {
8734                         .lkp_value              = "peer",
8735                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
8736                         .lkp_data_type          = NLA_NUL_STRING,
8737                 },
8738                 [LNET_PEER_DIST_ATTR_NID]       = {
8739                         .lkp_value              = "nid",
8740                         .lkp_data_type          = NLA_STRING
8741                 },
8742                 [LNET_PEER_DIST_ATTR_DIST]      = {
8743                         .lkp_value              = "distance",
8744                         .lkp_data_type          = NLA_U32
8745                 },
8746                 [LNET_PEER_DIST_ATTR_ORDER]     = {
8747                         .lkp_value              = "order",
8748                         .lkp_data_type          = NLA_U32
8749                 },
8750         },
8751 };
8752
8753 static int lnet_peer_dist_show_dump(struct sk_buff *msg,
8754                                     struct netlink_callback *cb)
8755 {
8756         struct lnet_genl_processid_list *plist = lnet_peer_dump_ctx(cb);
8757 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
8758         struct netlink_ext_ack *extack = NULL;
8759 #endif
8760         int portid = NETLINK_CB(cb->skb).portid;
8761         int seq = cb->nlh->nlmsg_seq;
8762         int idx = plist->lgpl_index;
8763         int rc = 0;
8764
8765 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
8766         extack = cb->extack;
8767 #endif
8768         if (!idx) {
8769                 const struct ln_key_list *all[] = {
8770                         &peer_dist_props_list, NULL
8771                 };
8772
8773                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
8774                                                 &lnet_family,
8775                                                 NLM_F_CREATE | NLM_F_MULTI,
8776                                                 LNET_CMD_PEER_DIST, all);
8777                 if (rc < 0) {
8778                         NL_SET_ERR_MSG(extack, "failed to send key table");
8779                         GOTO(send_error, rc);
8780                 }
8781         }
8782
8783         while (idx < plist->lgpl_count) {
8784                 struct lnet_processid *id;
8785                 void *hdr;
8786                 u32 order;
8787                 int dist;
8788
8789                 id = genradix_ptr(&plist->lgpl_list, idx++);
8790                 if (nid_is_lo0(&id->nid))
8791                         continue;
8792
8793                 dist = LNetDist(&id->nid, &id->nid, &order);
8794                 if (dist < 0) {
8795                         if (dist == -EHOSTUNREACH)
8796                                 continue;
8797
8798                         rc = dist;
8799                         return rc;
8800                 }
8801
8802                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
8803                                   NLM_F_MULTI, LNET_CMD_PEER_DIST);
8804                 if (!hdr) {
8805                         NL_SET_ERR_MSG(extack, "failed to send values");
8806                         genlmsg_cancel(msg, hdr);
8807                         GOTO(send_error, rc = -EMSGSIZE);
8808                 }
8809
8810                 if (idx == 1)
8811                         nla_put_string(msg, LNET_PEER_DIST_ATTR_HDR, "");
8812
8813                 nla_put_string(msg, LNET_PEER_DIST_ATTR_NID,
8814                                libcfs_nidstr(&id->nid));
8815                 nla_put_u32(msg, LNET_PEER_DIST_ATTR_DIST, dist);
8816                 nla_put_u32(msg, LNET_PEER_DIST_ATTR_ORDER, order);
8817
8818                 genlmsg_end(msg, hdr);
8819         }
8820
8821         plist->lgpl_index = idx;
8822 send_error:
8823         return lnet_nl_send_error(cb->skb, portid, seq, rc);
8824 }
8825
8826 #ifndef HAVE_NETLINK_CALLBACK_START
8827 static int lnet_old_peer_dist_show_dump(struct sk_buff *msg,
8828                                         struct netlink_callback *cb)
8829 {
8830         if (!cb->args[0]) {
8831                 int rc = lnet_peer_dist_show_start(cb);
8832
8833                 if (rc < 0)
8834                         return lnet_nl_send_error(cb->skb,
8835                                                   NETLINK_CB(cb->skb).portid,
8836                                                   cb->nlh->nlmsg_seq,
8837                                                   rc);
8838         }
8839
8840         return lnet_peer_dist_show_dump(msg, cb);
8841 }
8842 #endif
8843
8844 static const struct genl_multicast_group lnet_mcast_grps[] = {
8845         { .name =       "ip2net",       },
8846         { .name =       "net",          },
8847         { .name =       "peer",         },
8848         { .name =       "route",        },
8849         { .name =       "ping",         },
8850         { .name =       "discover",     },
8851         { .name =       "cpt-of-nid",   },
8852 };
8853
8854 static const struct genl_ops lnet_genl_ops[] = {
8855         {
8856                 .cmd            = LNET_CMD_CONFIGURE,
8857                 .flags          = GENL_ADMIN_PERM,
8858                 .doit           = lnet_net_conf_cmd,
8859         },
8860         {
8861                 .cmd            = LNET_CMD_NETS,
8862                 .flags          = GENL_ADMIN_PERM,
8863 #ifdef HAVE_NETLINK_CALLBACK_START
8864                 .start          = lnet_net_show_start,
8865                 .dumpit         = lnet_net_show_dump,
8866 #else
8867                 .dumpit         = lnet_old_net_show_dump,
8868 #endif
8869                 .done           = lnet_net_show_done,
8870                 .doit           = lnet_net_cmd,
8871         },
8872         {
8873                 .cmd            = LNET_CMD_PEERS,
8874                 .flags          = GENL_ADMIN_PERM,
8875 #ifdef HAVE_NETLINK_CALLBACK_START
8876                 .start          = lnet_peer_ni_show_start,
8877                 .dumpit         = lnet_peer_ni_show_dump,
8878 #else
8879                 .dumpit         = lnet_old_peer_ni_show_dump,
8880 #endif
8881                 .done           = lnet_peer_ni_show_done,
8882                 .doit           = lnet_peer_ni_cmd,
8883         },
8884         {
8885                 .cmd            = LNET_CMD_ROUTES,
8886                 .flags          = GENL_ADMIN_PERM,
8887 #ifdef HAVE_NETLINK_CALLBACK_START
8888                 .start          = lnet_route_show_start,
8889                 .dumpit         = lnet_route_show_dump,
8890 #else
8891                 .dumpit         = lnet_old_route_show_dump,
8892 #endif
8893                 .done           = lnet_route_show_done,
8894                 .doit           = lnet_route_cmd,
8895         },
8896         {
8897                 .cmd            = LNET_CMD_PING,
8898                 .flags          = GENL_ADMIN_PERM,
8899 #ifdef HAVE_NETLINK_CALLBACK_START
8900                 .start          = lnet_ping_show_start,
8901                 .dumpit         = lnet_ping_show_dump,
8902 #else
8903                 .dumpit         = lnet_old_ping_show_dump,
8904 #endif
8905                 .done           = lnet_ping_show_done,
8906                 .doit           = lnet_ping_cmd,
8907         },
8908         {
8909                 .cmd            = LNET_CMD_CPT_OF_NID,
8910 #ifdef HAVE_NETLINK_CALLBACK_START
8911                 .start          = lnet_cpt_of_nid_show_start,
8912                 .dumpit         = lnet_cpt_of_nid_show_dump,
8913 #else
8914                 .dumpit         = lnet_old_cpt_of_nid_show_dump,
8915 #endif
8916                 .done           = lnet_cpt_of_nid_show_done,
8917         },
8918         {
8919                 .cmd            = LNET_CMD_PEER_DIST,
8920 #ifdef HAVE_NETLINK_CALLBACK_START
8921                 .start          = lnet_peer_dist_show_start,
8922                 .dumpit         = lnet_peer_dist_show_dump,
8923 #else
8924                 .dumpit         = lnet_old_peer_dist_show_dump,
8925 #endif
8926                 .done           = lnet_peer_dist_show_done,
8927         },
8928 };
8929
8930 static struct genl_family lnet_family = {
8931         .name           = LNET_GENL_NAME,
8932         .version        = LNET_GENL_VERSION,
8933         .module         = THIS_MODULE,
8934         .parallel_ops   = true,
8935         .netnsok        = true,
8936         .ops            = lnet_genl_ops,
8937         .n_ops          = ARRAY_SIZE(lnet_genl_ops),
8938         .mcgrps         = lnet_mcast_grps,
8939         .n_mcgrps       = ARRAY_SIZE(lnet_mcast_grps),
8940 #ifdef GENL_FAMILY_HAS_RESV_START_OP
8941         .resv_start_op  = __LNET_CMD_MAX_PLUS_ONE,
8942 #endif
8943 };
8944
8945 void LNetDebugPeer(struct lnet_processid *id)
8946 {
8947         lnet_debug_peer(&id->nid);
8948 }
8949 EXPORT_SYMBOL(LNetDebugPeer);
8950
8951 /**
8952  * Determine if the specified peer \a nid is on the local node.
8953  *
8954  * \param nid   peer nid to check
8955  *
8956  * \retval true         If peer NID is on the local node.
8957  * \retval false        If peer NID is not on the local node.
8958  */
8959 bool LNetIsPeerLocal(struct lnet_nid *nid)
8960 {
8961         struct lnet_net *net;
8962         struct lnet_ni *ni;
8963         int cpt;
8964
8965         cpt = lnet_net_lock_current();
8966         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
8967                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
8968                         if (nid_same(&ni->ni_nid, nid)) {
8969                                 lnet_net_unlock(cpt);
8970                                 return true;
8971                         }
8972                 }
8973         }
8974         lnet_net_unlock(cpt);
8975
8976         return false;
8977 }
8978 EXPORT_SYMBOL(LNetIsPeerLocal);
8979
8980 /**
8981  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
8982  * Note that all interfaces share a same PID, as requested by LNetNIInit().
8983  *
8984  * @index       Index of the interface to look up.
8985  * @id          On successful return, this location will hold the
8986  *              struct lnet_process_id ID of the interface.
8987  * @large_nids  Report large NIDs if this is true.
8988  *
8989  * RETURN       0 If an interface exists at \a index.
8990  *              -ENOENT If no interface has been found.
8991  */
8992 int
8993 LNetGetId(unsigned int index, struct lnet_processid *id, bool large_nids)
8994 {
8995         struct lnet_ni   *ni;
8996         struct lnet_net  *net;
8997         int               cpt;
8998         int               rc = -ENOENT;
8999
9000         LASSERT(the_lnet.ln_refcount > 0);
9001
9002         cpt = lnet_net_lock_current();
9003
9004         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
9005                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
9006                         if (!large_nids && !nid_is_nid4(&ni->ni_nid))
9007                                 continue;
9008
9009                         if (index-- != 0)
9010                                 continue;
9011
9012                         id->nid = ni->ni_nid;
9013                         id->pid = the_lnet.ln_pid;
9014                         rc = 0;
9015                         break;
9016                 }
9017         }
9018
9019         lnet_net_unlock(cpt);
9020         return rc;
9021 }
9022 EXPORT_SYMBOL(LNetGetId);
9023
9024 struct ping_data {
9025         int rc;
9026         int replied;
9027         int pd_unlinked;
9028         struct lnet_handle_md mdh;
9029         struct completion completion;
9030 };
9031
9032 static void
9033 lnet_ping_event_handler(struct lnet_event *event)
9034 {
9035         struct ping_data *pd = event->md_user_ptr;
9036
9037         CDEBUG(D_NET, "ping event (%d %d)%s\n",
9038                event->type, event->status,
9039                event->unlinked ? " unlinked" : "");
9040
9041         if (event->status) {
9042                 if (!pd->rc)
9043                         pd->rc = event->status;
9044         } else if (event->type == LNET_EVENT_REPLY) {
9045                 pd->replied = 1;
9046                 pd->rc = event->mlength;
9047         }
9048
9049         if (event->unlinked)
9050                 pd->pd_unlinked = 1;
9051
9052         if (event->unlinked ||
9053             (event->type == LNET_EVENT_SEND && event->status))
9054                 complete(&pd->completion);
9055 }
9056
9057 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
9058                      signed long timeout, struct lnet_genl_ping_list *plist,
9059                      int n_ids)
9060 {
9061         int id_bytes = sizeof(struct lnet_ni_status); /* For 0@lo */
9062         struct lnet_md md = { NULL };
9063         struct ping_data pd = { 0 };
9064         struct lnet_ping_buffer *pbuf;
9065         struct lnet_processid pid;
9066         struct lnet_ping_iter pi;
9067         int i = 0;
9068         u32 *st;
9069         int nob;
9070         int rc;
9071         int rc2;
9072
9073         genradix_init(&plist->lgpl_list);
9074
9075         /* n_ids limit is arbitrary */
9076         if (n_ids <= 0 || LNET_NID_IS_ANY(&id->nid))
9077                 return -EINVAL;
9078
9079         /* if the user buffer has more space than the lnet_interfaces_max
9080          * then only fill it up to lnet_interfaces_max
9081          */
9082         if (n_ids > lnet_interfaces_max)
9083                 n_ids = lnet_interfaces_max;
9084
9085         if (id->pid == LNET_PID_ANY)
9086                 id->pid = LNET_PID_LUSTRE;
9087
9088         id_bytes += n_ids * sizeof(struct lnet_nid);
9089         pbuf = lnet_ping_buffer_alloc(id_bytes, GFP_NOFS);
9090         if (!pbuf)
9091                 return -ENOMEM;
9092
9093         /* initialize md content */
9094         md.start     = &pbuf->pb_info;
9095         md.length    = id_bytes;
9096         md.threshold = 2; /* GET/REPLY */
9097         md.max_size  = 0;
9098         md.options   = LNET_MD_TRUNCATE;
9099         md.user_ptr  = &pd;
9100         md.handler   = lnet_ping_event_handler;
9101
9102         init_completion(&pd.completion);
9103
9104         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
9105         if (rc != 0) {
9106                 CERROR("Can't bind MD: %d\n", rc);
9107                 goto fail_ping_buffer_decref;
9108         }
9109
9110         rc = LNetGet(src_nid, pd.mdh, id, LNET_RESERVED_PORTAL,
9111                      LNET_PROTO_PING_MATCHBITS, 0, false);
9112         if (rc != 0) {
9113                 /* Don't CERROR; this could be deliberate! */
9114                 rc2 = LNetMDUnlink(pd.mdh);
9115                 LASSERT(rc2 == 0);
9116
9117                 /* NB must wait for the UNLINK event below... */
9118         }
9119
9120         /* Ensure completion in finite time... */
9121         wait_for_completion_timeout(&pd.completion, timeout);
9122         if (!pd.pd_unlinked) {
9123                 LNetMDUnlink(pd.mdh);
9124                 wait_for_completion(&pd.completion);
9125         }
9126
9127         if (!pd.replied) {
9128                 rc = pd.rc ?: -EIO;
9129                 goto fail_ping_buffer_decref;
9130         }
9131
9132         nob = pd.rc;
9133         LASSERT(nob >= 0 && nob <= id_bytes);
9134
9135         rc = -EPROTO;           /* if I can't parse... */
9136
9137         if (nob < LNET_PING_INFO_HDR_SIZE) {
9138                 CERROR("%s: ping info too short %d\n",
9139                        libcfs_idstr(id), nob);
9140                 goto fail_ping_buffer_decref;
9141         }
9142
9143         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
9144                 lnet_swap_pinginfo(pbuf);
9145         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
9146                 CERROR("%s: Unexpected magic %08x\n",
9147                        libcfs_idstr(id), pbuf->pb_info.pi_magic);
9148                 goto fail_ping_buffer_decref;
9149         }
9150
9151         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
9152                 CERROR("%s: ping w/o NI status: 0x%x\n",
9153                        libcfs_idstr(id), pbuf->pb_info.pi_features);
9154                 goto fail_ping_buffer_decref;
9155         }
9156
9157         /* Test if smaller than lnet_pinginfo with just one pi_ni status info.
9158          * That one might contain size when large nids are used.
9159          */
9160         if (nob < offsetof(struct lnet_ping_info, pi_ni[1])) {
9161                 CERROR("%s: Short reply %d(%lu min)\n",
9162                        libcfs_idstr(id), nob,
9163                        offsetof(struct lnet_ping_info, pi_ni[1]));
9164                 goto fail_ping_buffer_decref;
9165         }
9166
9167         if (ping_info_count_entries(pbuf) < n_ids) {
9168                 n_ids = ping_info_count_entries(pbuf);
9169                 id_bytes = lnet_ping_info_size(&pbuf->pb_info);
9170         }
9171
9172         if (nob < id_bytes) {
9173                 CERROR("%s: Short reply %d(%d expected)\n",
9174                        libcfs_idstr(id), nob, id_bytes);
9175                 goto fail_ping_buffer_decref;
9176         }
9177
9178         for (st = ping_iter_first(&pi, pbuf, &pid.nid);
9179              st;
9180              st = ping_iter_next(&pi, &pid.nid)) {
9181                 id = genradix_ptr_alloc(&plist->lgpl_list, i++, GFP_KERNEL);
9182                 if (!id) {
9183                         rc = -ENOMEM;
9184                         goto fail_ping_buffer_decref;
9185                 }
9186
9187                 id->pid = pbuf->pb_info.pi_pid;
9188                 id->nid = pid.nid;
9189         }
9190         rc = i;
9191 fail_ping_buffer_decref:
9192         lnet_ping_buffer_decref(pbuf);
9193         return rc;
9194 }
9195
9196 static int
9197 lnet_discover(struct lnet_processid *pid, u32 force,
9198               struct lnet_genl_ping_list *dlist)
9199 {
9200         struct lnet_peer_ni *lpni;
9201         struct lnet_peer_ni *p;
9202         struct lnet_peer *lp;
9203         int cpt;
9204         int rc;
9205
9206         if (LNET_NID_IS_ANY(&pid->nid))
9207                 return -EINVAL;
9208
9209         if (pid->pid == LNET_PID_ANY)
9210                 pid->pid = LNET_PID_LUSTRE;
9211
9212         cpt = lnet_net_lock_current();
9213         lpni = lnet_peerni_by_nid_locked(&pid->nid, NULL, cpt);
9214         if (IS_ERR(lpni)) {
9215                 rc = PTR_ERR(lpni);
9216                 goto out;
9217         }
9218
9219         /*
9220          * Clearing the NIDS_UPTODATE flag ensures the peer will
9221          * be discovered, provided discovery has not been disabled.
9222          */
9223         lp = lpni->lpni_peer_net->lpn_peer;
9224         spin_lock(&lp->lp_lock);
9225         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
9226         /* If the force flag is set, force a PING and PUSH as well. */
9227         if (force)
9228                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
9229         spin_unlock(&lp->lp_lock);
9230         rc = lnet_discover_peer_locked(lpni, cpt, true);
9231         if (rc)
9232                 goto out_decref;
9233
9234         /* The lpni (or lp) for this NID may have changed and our ref is
9235          * the only thing keeping the old one around. Release the ref
9236          * and lookup the lpni again
9237          */
9238         lnet_peer_ni_decref_locked(lpni);
9239         lpni = lnet_peer_ni_find_locked(&pid->nid);
9240         if (!lpni) {
9241                 rc = -ENOENT;
9242                 goto out;
9243         }
9244         lp = lpni->lpni_peer_net->lpn_peer;
9245
9246         dlist->lgpl_list_count = 0;
9247         p = NULL;
9248         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
9249                 struct lnet_processid *id;
9250
9251                 id = genradix_ptr_alloc(&dlist->lgpl_list,
9252                                         dlist->lgpl_list_count++, GFP_ATOMIC);
9253                 if (!id) {
9254                         rc = -ENOMEM;
9255                         goto out_decref;
9256                 }
9257                 id->pid = pid->pid;
9258                 id->nid = p->lpni_nid;
9259         }
9260         rc = dlist->lgpl_list_count;
9261
9262 out_decref:
9263         lnet_peer_ni_decref_locked(lpni);
9264 out:
9265         lnet_net_unlock(cpt);
9266
9267         return rc;
9268 }
9269
9270 /**
9271  * Retrieve peer discovery status.
9272  *
9273  * \retval 1 if lnet_peer_discovery_disabled is 0
9274  * \retval 0 if lnet_peer_discovery_disabled is 1
9275  */
9276 int
9277 LNetGetPeerDiscoveryStatus(void)
9278 {
9279         return !lnet_peer_discovery_disabled;
9280 }
9281 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);