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