Whamcloud - gitweb
LU-16949 lnet: get monitor thread to update 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 {
2106         struct lnet_ping_buffer *old_pbuf = NULL;
2107         struct lnet_handle_md old_ping_md;
2108
2109         /* switch the NIs to point to the new ping info created */
2110         lnet_net_lock(LNET_LOCK_EX);
2111
2112         if (!the_lnet.ln_routing)
2113                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
2114         if (!lnet_peer_discovery_disabled)
2115                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
2116
2117         /* Ensure only known feature bits have been set. */
2118         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
2119         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
2120
2121         lnet_ping_target_install_locked(pbuf);
2122
2123         if (the_lnet.ln_ping_target) {
2124                 old_pbuf = the_lnet.ln_ping_target;
2125                 old_ping_md = the_lnet.ln_ping_target_md;
2126         }
2127         the_lnet.ln_ping_target_md = ping_mdh;
2128         the_lnet.ln_ping_target = pbuf;
2129
2130         lnet_net_unlock(LNET_LOCK_EX);
2131
2132         if (old_pbuf) {
2133                 /* unlink and free the old ping info */
2134                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
2135                 lnet_ping_buffer_decref(old_pbuf);
2136         }
2137
2138         lnet_push_update_to_peers(0);
2139 }
2140
2141 static void
2142 lnet_ping_target_fini(void)
2143 {
2144         lnet_ping_md_unlink(the_lnet.ln_ping_target,
2145                             &the_lnet.ln_ping_target_md);
2146
2147         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
2148         lnet_ping_target_destroy();
2149 }
2150
2151 /* Resize the push target. */
2152 int lnet_push_target_resize(void)
2153 {
2154         struct lnet_handle_md mdh;
2155         struct lnet_handle_md old_mdh;
2156         struct lnet_ping_buffer *pbuf;
2157         struct lnet_ping_buffer *old_pbuf;
2158         int nbytes;
2159         int rc;
2160
2161 again:
2162         nbytes = the_lnet.ln_push_target_nbytes;
2163         if (nbytes <= 0) {
2164                 CDEBUG(D_NET, "Invalid nbytes %d\n", nbytes);
2165                 return -EINVAL;
2166         }
2167
2168         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
2169          * dropped when we need to resize again (see "old_pbuf" below) or when
2170          * LNet is shutdown (see lnet_push_target_fini())
2171          */
2172         pbuf = lnet_ping_buffer_alloc(nbytes, GFP_NOFS);
2173         if (!pbuf) {
2174                 CDEBUG(D_NET, "Can't allocate pbuf for nbytes %d\n", nbytes);
2175                 return -ENOMEM;
2176         }
2177
2178         rc = lnet_push_target_post(pbuf, &mdh);
2179         if (rc) {
2180                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
2181                 lnet_ping_buffer_decref(pbuf);
2182                 return rc;
2183         }
2184
2185         lnet_net_lock(LNET_LOCK_EX);
2186         old_pbuf = the_lnet.ln_push_target;
2187         old_mdh = the_lnet.ln_push_target_md;
2188         the_lnet.ln_push_target = pbuf;
2189         the_lnet.ln_push_target_md = mdh;
2190         lnet_net_unlock(LNET_LOCK_EX);
2191
2192         if (old_pbuf) {
2193                 LNetMDUnlink(old_mdh);
2194                 /* Drop ref set by lnet_ping_buffer_alloc() */
2195                 lnet_ping_buffer_decref(old_pbuf);
2196         }
2197
2198         /* Received another push or reply that requires a larger buffer */
2199         if (nbytes < the_lnet.ln_push_target_nbytes)
2200                 goto again;
2201
2202         CDEBUG(D_NET, "nbytes %d success\n", nbytes);
2203         return 0;
2204 }
2205
2206 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
2207                           struct lnet_handle_md *mdhp)
2208 {
2209         struct lnet_processid id = { LNET_ANY_NID, LNET_PID_ANY };
2210         struct lnet_md md = { NULL };
2211         struct lnet_me *me;
2212         int rc;
2213
2214         me = LNetMEAttach(LNET_RESERVED_PORTAL, &id,
2215                           LNET_PROTO_PING_MATCHBITS, 0,
2216                           LNET_UNLINK, LNET_INS_AFTER);
2217         if (IS_ERR(me)) {
2218                 rc = PTR_ERR(me);
2219                 CERROR("Can't create push target ME: %d\n", rc);
2220                 return rc;
2221         }
2222
2223         pbuf->pb_needs_post = false;
2224
2225         /* This reference is dropped by lnet_push_target_event_handler() */
2226         lnet_ping_buffer_addref(pbuf);
2227
2228         /* initialize md content */
2229         md.start     = &pbuf->pb_info;
2230         md.length    = pbuf->pb_nbytes;
2231         md.threshold = 1;
2232         md.max_size  = 0;
2233         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
2234         md.user_ptr  = pbuf;
2235         md.handler   = the_lnet.ln_push_target_handler;
2236
2237         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
2238         if (rc) {
2239                 CERROR("Can't attach push MD: %d\n", rc);
2240                 lnet_ping_buffer_decref(pbuf);
2241                 pbuf->pb_needs_post = true;
2242                 return rc;
2243         }
2244
2245         CDEBUG(D_NET, "posted push target %p\n", pbuf);
2246
2247         return 0;
2248 }
2249
2250 static void lnet_push_target_event_handler(struct lnet_event *ev)
2251 {
2252         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
2253
2254         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
2255                ev->unlinked);
2256
2257         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2258                 lnet_swap_pinginfo(pbuf);
2259
2260         if (ev->type == LNET_EVENT_UNLINK) {
2261                 /* Drop ref added by lnet_push_target_post() */
2262                 lnet_ping_buffer_decref(pbuf);
2263                 return;
2264         }
2265
2266         lnet_peer_push_event(ev);
2267         if (ev->unlinked)
2268                 /* Drop ref added by lnet_push_target_post */
2269                 lnet_ping_buffer_decref(pbuf);
2270 }
2271
2272 /* Initialize the push target. */
2273 static int lnet_push_target_init(void)
2274 {
2275         int rc;
2276
2277         if (the_lnet.ln_push_target)
2278                 return -EALREADY;
2279
2280         the_lnet.ln_push_target_handler =
2281                 lnet_push_target_event_handler;
2282
2283         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2284         LASSERT(rc == 0);
2285
2286         /* Start at the required minimum, we'll enlarge if required. */
2287         the_lnet.ln_push_target_nbytes = LNET_PING_INFO_MIN_SIZE;
2288
2289         rc = lnet_push_target_resize();
2290         if (rc) {
2291                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2292                 the_lnet.ln_push_target_handler = NULL;
2293         }
2294
2295         return rc;
2296 }
2297
2298 /* Clean up the push target. */
2299 static void lnet_push_target_fini(void)
2300 {
2301         if (!the_lnet.ln_push_target)
2302                 return;
2303
2304         /* Unlink and invalidate to prevent new references. */
2305         LNetMDUnlink(the_lnet.ln_push_target_md);
2306         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2307
2308         /* Wait for the unlink to complete. */
2309         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2310                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2311                                "Still waiting for ping data MD to unlink\n");
2312
2313         /* Drop ref set by lnet_ping_buffer_alloc() */
2314         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2315         the_lnet.ln_push_target = NULL;
2316         the_lnet.ln_push_target_nbytes = 0;
2317
2318         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2319         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2320         the_lnet.ln_push_target_handler = NULL;
2321 }
2322
2323 static int
2324 lnet_ni_tq_credits(struct lnet_ni *ni)
2325 {
2326         int     credits;
2327
2328         LASSERT(ni->ni_ncpts >= 1);
2329
2330         if (ni->ni_ncpts == 1)
2331                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2332
2333         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2334         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2335         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2336
2337         return credits;
2338 }
2339
2340 static void
2341 lnet_ni_unlink_locked(struct lnet_ni *ni)
2342 {
2343         /* move it to zombie list and nobody can find it anymore */
2344         LASSERT(!list_empty(&ni->ni_netlist));
2345         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2346         lnet_ni_decref_locked(ni, 0);
2347 }
2348
2349 static void
2350 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2351 {
2352         int             i;
2353         int             islo;
2354         struct lnet_ni  *ni;
2355         struct list_head *zombie_list = &net->net_ni_zombie;
2356
2357         /*
2358          * Now wait for the NIs I just nuked to show up on the zombie
2359          * list and shut them down in guaranteed thread context
2360          */
2361         i = 2;
2362         while ((ni = list_first_entry_or_null(zombie_list,
2363                                               struct lnet_ni,
2364                                               ni_netlist)) != NULL) {
2365                 int *ref;
2366                 int j;
2367
2368                 list_del_init(&ni->ni_netlist);
2369                 /* the ni should be in deleting state. If it's not it's
2370                  * a bug */
2371                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2372                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2373                         if (*ref == 0)
2374                                 continue;
2375                         /* still busy, add it back to zombie list */
2376                         list_add(&ni->ni_netlist, zombie_list);
2377                         break;
2378                 }
2379
2380                 if (!list_empty(&ni->ni_netlist)) {
2381                         /* Unlock mutex while waiting to allow other
2382                          * threads to read the LNet state and fall through
2383                          * to avoid deadlock
2384                          */
2385                         lnet_net_unlock(LNET_LOCK_EX);
2386                         mutex_unlock(&the_lnet.ln_api_mutex);
2387
2388                         ++i;
2389                         if ((i & (-i)) == i) {
2390                                 CDEBUG(D_WARNING,
2391                                        "Waiting for zombie LNI %s\n",
2392                                        libcfs_nidstr(&ni->ni_nid));
2393                         }
2394                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2395
2396                         mutex_lock(&the_lnet.ln_api_mutex);
2397                         lnet_net_lock(LNET_LOCK_EX);
2398                         continue;
2399                 }
2400
2401                 lnet_net_unlock(LNET_LOCK_EX);
2402
2403                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2404
2405                 LASSERT(!in_interrupt());
2406                 /* Holding the LND mutex makes it safe for lnd_shutdown
2407                  * to call module_put(). Module unload cannot finish
2408                  * until lnet_unregister_lnd() completes, and that
2409                  * requires the LND mutex.
2410                  */
2411                 mutex_unlock(&the_lnet.ln_api_mutex);
2412                 mutex_lock(&the_lnet.ln_lnd_mutex);
2413                 (net->net_lnd->lnd_shutdown)(ni);
2414                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2415                 mutex_lock(&the_lnet.ln_api_mutex);
2416
2417                 if (!islo)
2418                         CDEBUG(D_LNI, "Removed LNI %s\n",
2419                               libcfs_nidstr(&ni->ni_nid));
2420
2421                 lnet_ni_free(ni);
2422                 i = 2;
2423                 lnet_net_lock(LNET_LOCK_EX);
2424         }
2425 }
2426
2427 /* shutdown down the NI and release refcount */
2428 static void
2429 lnet_shutdown_lndni(struct lnet_ni *ni)
2430 {
2431         int i;
2432         struct lnet_net *net = ni->ni_net;
2433
2434         lnet_net_lock(LNET_LOCK_EX);
2435         lnet_ni_lock(ni);
2436         ni->ni_state = LNET_NI_STATE_DELETING;
2437         lnet_ni_unlock(ni);
2438         lnet_ni_unlink_locked(ni);
2439         lnet_incr_dlc_seq();
2440         lnet_net_unlock(LNET_LOCK_EX);
2441
2442         /* clear messages for this NI on the lazy portal */
2443         for (i = 0; i < the_lnet.ln_nportals; i++)
2444                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2445
2446         lnet_net_lock(LNET_LOCK_EX);
2447         lnet_clear_zombies_nis_locked(net);
2448         lnet_net_unlock(LNET_LOCK_EX);
2449 }
2450
2451 static void
2452 lnet_shutdown_lndnet(struct lnet_net *net)
2453 {
2454         struct lnet_ni *ni;
2455
2456         lnet_net_lock(LNET_LOCK_EX);
2457
2458         list_del_init(&net->net_list);
2459
2460         while ((ni = list_first_entry_or_null(&net->net_ni_list,
2461                                               struct lnet_ni,
2462                                               ni_netlist)) != NULL) {
2463                 lnet_net_unlock(LNET_LOCK_EX);
2464                 lnet_shutdown_lndni(ni);
2465                 lnet_net_lock(LNET_LOCK_EX);
2466         }
2467
2468         lnet_net_unlock(LNET_LOCK_EX);
2469
2470         /* Do peer table cleanup for this net */
2471         lnet_peer_tables_cleanup(net);
2472
2473         lnet_net_free(net);
2474 }
2475
2476 static void
2477 lnet_shutdown_lndnets(void)
2478 {
2479         struct lnet_net *net;
2480         LIST_HEAD(resend);
2481         struct lnet_msg *msg, *tmp;
2482
2483         /* NB called holding the global mutex */
2484
2485         /* All quiet on the API front */
2486         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING ||
2487                 the_lnet.ln_state == LNET_STATE_STOPPING);
2488         LASSERT(the_lnet.ln_refcount == 0);
2489
2490         lnet_net_lock(LNET_LOCK_EX);
2491         the_lnet.ln_state = LNET_STATE_STOPPING;
2492
2493         /*
2494          * move the nets to the zombie list to avoid them being
2495          * picked up for new work. LONET is also included in the
2496          * Nets that will be moved to the zombie list
2497          */
2498         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2499
2500         /* Drop the cached loopback Net. */
2501         if (the_lnet.ln_loni != NULL) {
2502                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2503                 the_lnet.ln_loni = NULL;
2504         }
2505         lnet_net_unlock(LNET_LOCK_EX);
2506
2507         /* iterate through the net zombie list and delete each net */
2508         while ((net = list_first_entry_or_null(&the_lnet.ln_net_zombie,
2509                                                struct lnet_net,
2510                                                net_list)) != NULL)
2511                 lnet_shutdown_lndnet(net);
2512
2513         spin_lock(&the_lnet.ln_msg_resend_lock);
2514         list_splice(&the_lnet.ln_msg_resend, &resend);
2515         spin_unlock(&the_lnet.ln_msg_resend_lock);
2516
2517         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2518                 list_del_init(&msg->msg_list);
2519                 msg->msg_no_resend = true;
2520                 lnet_finalize(msg, -ECANCELED);
2521         }
2522
2523         lnet_net_lock(LNET_LOCK_EX);
2524         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2525         lnet_net_unlock(LNET_LOCK_EX);
2526 }
2527
2528 static int
2529 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2530 {
2531         int                     rc = -EINVAL;
2532         struct lnet_tx_queue    *tq;
2533         int                     i;
2534         struct lnet_net         *net = ni->ni_net;
2535
2536         mutex_lock(&the_lnet.ln_lnd_mutex);
2537
2538         if (tun) {
2539                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2540                 ni->ni_lnd_tunables_set = true;
2541         }
2542
2543         rc = (net->net_lnd->lnd_startup)(ni);
2544
2545         mutex_unlock(&the_lnet.ln_lnd_mutex);
2546
2547         if (rc != 0) {
2548                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2549                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2550                 goto failed0;
2551         }
2552
2553         lnet_ni_lock(ni);
2554         ni->ni_state = LNET_NI_STATE_ACTIVE;
2555         lnet_ni_unlock(ni);
2556
2557         /* We keep a reference on the loopback net through the loopback NI */
2558         if (net->net_lnd->lnd_type == LOLND) {
2559                 lnet_ni_addref(ni);
2560                 LASSERT(the_lnet.ln_loni == NULL);
2561                 the_lnet.ln_loni = ni;
2562                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2563                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2564                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2565                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2566                 return 0;
2567         }
2568
2569         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2570             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2571                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2572                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2573                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2574                                         "" : "per-peer ");
2575                 /* shutdown the NI since if we get here then it must've already
2576                  * been started
2577                  */
2578                 lnet_shutdown_lndni(ni);
2579                 return -EINVAL;
2580         }
2581
2582         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2583                 tq->tq_credits_min =
2584                 tq->tq_credits_max =
2585                 tq->tq_credits = lnet_ni_tq_credits(ni);
2586         }
2587
2588         atomic_set(&ni->ni_tx_credits,
2589                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2590         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2591
2592         /* Nodes with small feet have little entropy. The NID for this
2593          * node gives the most entropy in the low bits.
2594          */
2595         add_device_randomness(&ni->ni_nid, sizeof(ni->ni_nid));
2596
2597         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2598                 libcfs_nidstr(&ni->ni_nid),
2599                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2600                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2601                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2602                 ni->ni_net->net_tunables.lct_peer_timeout);
2603
2604         return 0;
2605 failed0:
2606         lnet_ni_free(ni);
2607         return rc;
2608 }
2609
2610 static const struct lnet_lnd *lnet_load_lnd(u32 lnd_type)
2611 {
2612         const struct lnet_lnd *lnd;
2613         int rc = 0;
2614
2615         mutex_lock(&the_lnet.ln_lnd_mutex);
2616         lnd = lnet_find_lnd_by_type(lnd_type);
2617         if (!lnd) {
2618                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2619                 rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2620                 mutex_lock(&the_lnet.ln_lnd_mutex);
2621
2622                 lnd = lnet_find_lnd_by_type(lnd_type);
2623                 if (!lnd) {
2624                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2625                         CERROR("Can't load LND %s, module %s, rc=%d\n",
2626                         libcfs_lnd2str(lnd_type),
2627                         libcfs_lnd2modname(lnd_type), rc);
2628 #ifndef HAVE_MODULE_LOADING_SUPPORT
2629                         LCONSOLE_ERROR_MSG(0x104,
2630                                            "Your kernel must be compiled with kernel module loading support.");
2631 #endif
2632                         return ERR_PTR(-EINVAL);
2633                 }
2634         }
2635         mutex_unlock(&the_lnet.ln_lnd_mutex);
2636
2637         return lnd;
2638 }
2639
2640 static int
2641 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2642 {
2643         struct lnet_ni *ni;
2644         struct lnet_net *net_l = NULL;
2645         LIST_HEAD(local_ni_list);
2646         int rc;
2647         int ni_count = 0;
2648         __u32 lnd_type;
2649         const struct lnet_lnd  *lnd;
2650         int peer_timeout =
2651                 net->net_tunables.lct_peer_timeout;
2652         int maxtxcredits =
2653                 net->net_tunables.lct_max_tx_credits;
2654         int peerrtrcredits =
2655                 net->net_tunables.lct_peer_rtr_credits;
2656
2657         /*
2658          * make sure that this net is unique. If it isn't then
2659          * we are adding interfaces to an already existing network, and
2660          * 'net' is just a convenient way to pass in the list.
2661          * if it is unique we need to find the LND and load it if
2662          * necessary.
2663          */
2664         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2665                 lnd_type = LNET_NETTYP(net->net_id);
2666
2667                 lnd = lnet_load_lnd(lnd_type);
2668                 if (IS_ERR(lnd)) {
2669                         rc = PTR_ERR(lnd);
2670                         goto failed0;
2671                 }
2672
2673                 mutex_lock(&the_lnet.ln_lnd_mutex);
2674                 net->net_lnd = lnd;
2675                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2676
2677                 net_l = net;
2678         }
2679
2680         /*
2681          * net_l: if the network being added is unique then net_l
2682          *        will point to that network
2683          *        if the network being added is not unique then
2684          *        net_l points to the existing network.
2685          *
2686          * When we enter the loop below, we'll pick NIs off he
2687          * network beign added and start them up, then add them to
2688          * a local ni list. Once we've successfully started all
2689          * the NIs then we join the local NI list (of started up
2690          * networks) with the net_l->net_ni_list, which should
2691          * point to the correct network to add the new ni list to
2692          *
2693          * If any of the new NIs fail to start up, then we want to
2694          * iterate through the local ni list, which should include
2695          * any NIs which were successfully started up, and shut
2696          * them down.
2697          *
2698          * After than we want to delete the network being added,
2699          * to avoid a memory leak.
2700          */
2701         while ((ni = list_first_entry_or_null(&net->net_ni_added,
2702                                               struct lnet_ni,
2703                                               ni_netlist)) != NULL) {
2704                 list_del_init(&ni->ni_netlist);
2705
2706                 /* make sure that the the NI we're about to start
2707                  * up is actually unique. if it's not fail. */
2708                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2709                                         ni->ni_interface)) {
2710                         rc = -EEXIST;
2711                         goto failed1;
2712                 }
2713
2714                 /* adjust the pointer the parent network, just in case it
2715                  * the net is a duplicate */
2716                 ni->ni_net = net_l;
2717
2718                 rc = lnet_startup_lndni(ni, tun);
2719
2720                 if (rc < 0)
2721                         goto failed1;
2722
2723                 lnet_ni_addref(ni);
2724                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2725
2726                 ni_count++;
2727         }
2728
2729         lnet_net_lock(LNET_LOCK_EX);
2730         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2731         lnet_incr_dlc_seq();
2732         lnet_net_unlock(LNET_LOCK_EX);
2733
2734         /* if the network is not unique then we don't want to keep
2735          * it around after we're done. Free it. Otherwise add that
2736          * net to the global the_lnet.ln_nets */
2737         if (net_l != net && net_l != NULL) {
2738                 /*
2739                  * TODO - note. currently the tunables can not be updated
2740                  * once added
2741                  */
2742                 lnet_net_free(net);
2743         } else {
2744                 /*
2745                  * restore tunables after it has been overwitten by the
2746                  * lnd
2747                  */
2748                 if (peer_timeout != -1)
2749                         net->net_tunables.lct_peer_timeout = peer_timeout;
2750                 if (maxtxcredits != -1)
2751                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2752                 if (peerrtrcredits != -1)
2753                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2754
2755                 lnet_net_lock(LNET_LOCK_EX);
2756                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2757                 lnet_net_unlock(LNET_LOCK_EX);
2758         }
2759
2760         return ni_count;
2761
2762 failed1:
2763         /*
2764          * shutdown the new NIs that are being started up
2765          * free the NET being started
2766          */
2767         while ((ni = list_first_entry_or_null(&local_ni_list,
2768                                               struct lnet_ni,
2769                                               ni_netlist)) != NULL)
2770                 lnet_shutdown_lndni(ni);
2771
2772 failed0:
2773         lnet_net_free(net);
2774
2775         return rc;
2776 }
2777
2778 static int
2779 lnet_startup_lndnets(struct list_head *netlist)
2780 {
2781         struct lnet_net         *net;
2782         int                     rc;
2783         int                     ni_count = 0;
2784
2785         /*
2786          * Change to running state before bringing up the LNDs. This
2787          * allows lnet_shutdown_lndnets() to assert that we've passed
2788          * through here.
2789          */
2790         lnet_net_lock(LNET_LOCK_EX);
2791         the_lnet.ln_state = LNET_STATE_RUNNING;
2792         lnet_net_unlock(LNET_LOCK_EX);
2793
2794         while ((net = list_first_entry_or_null(netlist,
2795                                                struct lnet_net,
2796                                                net_list)) != NULL) {
2797                 list_del_init(&net->net_list);
2798
2799                 rc = lnet_startup_lndnet(net, NULL);
2800
2801                 if (rc < 0)
2802                         goto failed;
2803
2804                 ni_count += rc;
2805         }
2806
2807         return ni_count;
2808 failed:
2809         lnet_shutdown_lndnets();
2810
2811         return rc;
2812 }
2813
2814 static int lnet_genl_parse_list(struct sk_buff *msg,
2815                                 const struct ln_key_list *data[], u16 idx)
2816 {
2817         const struct ln_key_list *list = data[idx];
2818         const struct ln_key_props *props;
2819         struct nlattr *node;
2820         u16 count;
2821
2822         if (!list)
2823                 return 0;
2824
2825         if (!list->lkl_maxattr)
2826                 return -ERANGE;
2827
2828         props = list->lkl_list;
2829         if (!props)
2830                 return -EINVAL;
2831
2832         node = nla_nest_start(msg, LN_SCALAR_ATTR_LIST);
2833         if (!node)
2834                 return -ENOBUFS;
2835
2836         for (count = 1; count <= list->lkl_maxattr; count++) {
2837                 struct nlattr *key = nla_nest_start(msg, count);
2838
2839                 if (count == 1)
2840                         nla_put_u16(msg, LN_SCALAR_ATTR_LIST_SIZE,
2841                                     list->lkl_maxattr);
2842
2843                 nla_put_u16(msg, LN_SCALAR_ATTR_INDEX, count);
2844                 if (props[count].lkp_value)
2845                         nla_put_string(msg, LN_SCALAR_ATTR_VALUE,
2846                                        props[count].lkp_value);
2847                 if (props[count].lkp_key_format)
2848                         nla_put_u16(msg, LN_SCALAR_ATTR_KEY_FORMAT,
2849                                     props[count].lkp_key_format);
2850                 nla_put_u16(msg, LN_SCALAR_ATTR_NLA_TYPE,
2851                             props[count].lkp_data_type);
2852                 if (props[count].lkp_data_type == NLA_NESTED) {
2853                         int rc;
2854
2855                         rc = lnet_genl_parse_list(msg, data, ++idx);
2856                         if (rc < 0)
2857                                 return rc;
2858                         idx = rc;
2859                 }
2860
2861                 nla_nest_end(msg, key);
2862         }
2863
2864         nla_nest_end(msg, node);
2865         return idx;
2866 }
2867
2868 int lnet_genl_send_scalar_list(struct sk_buff *msg, u32 portid, u32 seq,
2869                                const struct genl_family *family, int flags,
2870                                u8 cmd, const struct ln_key_list *data[])
2871 {
2872         int rc = 0;
2873         void *hdr;
2874
2875         if (!data[0])
2876                 return -EINVAL;
2877
2878         hdr = genlmsg_put(msg, portid, seq, family, flags, cmd);
2879         if (!hdr)
2880                 GOTO(canceled, rc = -EMSGSIZE);
2881
2882         rc = lnet_genl_parse_list(msg, data, 0);
2883         if (rc < 0)
2884                 GOTO(canceled, rc);
2885
2886         genlmsg_end(msg, hdr);
2887 canceled:
2888         if (rc < 0)
2889                 genlmsg_cancel(msg, hdr);
2890         return rc > 0 ? 0 : rc;
2891 }
2892 EXPORT_SYMBOL(lnet_genl_send_scalar_list);
2893
2894 static struct genl_family lnet_family;
2895
2896 /**
2897  * Initialize LNet library.
2898  *
2899  * Automatically called at module loading time. Caller has to call
2900  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2901  * latter returned 0. It must be called exactly once.
2902  *
2903  * \retval 0 on success
2904  * \retval -ve on failures.
2905  */
2906 int lnet_lib_init(void)
2907 {
2908         int rc;
2909
2910         lnet_assert_wire_constants();
2911
2912         /* refer to global cfs_cpt_table for now */
2913         the_lnet.ln_cpt_table = cfs_cpt_tab;
2914         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2915
2916         LASSERT(the_lnet.ln_cpt_number > 0);
2917         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2918                 /* we are under risk of consuming all lh_cookie */
2919                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2920                        "please change setting of CPT-table and retry\n",
2921                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2922                 return -E2BIG;
2923         }
2924
2925         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2926                 the_lnet.ln_cpt_bits++;
2927
2928         rc = lnet_create_locks();
2929         if (rc != 0) {
2930                 CERROR("Can't create LNet global locks: %d\n", rc);
2931                 return rc;
2932         }
2933
2934         rc = genl_register_family(&lnet_family);
2935         if (rc != 0) {
2936                 lnet_destroy_locks();
2937                 CERROR("Can't register LNet netlink family: %d\n", rc);
2938                 return rc;
2939         }
2940
2941         the_lnet.ln_refcount = 0;
2942         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2943         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2944
2945         /* The hash table size is the number of bits it takes to express the set
2946          * ln_num_routes, minus 1 (better to under estimate than over so we
2947          * don't waste memory). */
2948         if (rnet_htable_size <= 0)
2949                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2950         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2951                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2952         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2953                                            order_base_2(rnet_htable_size) - 1);
2954
2955         /* All LNDs apart from the LOLND are in separate modules.  They
2956          * register themselves when their module loads, and unregister
2957          * themselves when their module is unloaded. */
2958         lnet_register_lnd(&the_lolnd);
2959         return 0;
2960 }
2961
2962 /**
2963  * Finalize LNet library.
2964  *
2965  * \pre lnet_lib_init() called with success.
2966  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2967  *
2968  * As this happens at module-unload, all lnds must already be unloaded,
2969  * so they must already be unregistered.
2970  */
2971 void lnet_lib_exit(void)
2972 {
2973         int i;
2974
2975         LASSERT(the_lnet.ln_refcount == 0);
2976         lnet_unregister_lnd(&the_lolnd);
2977         for (i = 0; i < NUM_LNDS; i++)
2978                 LASSERT(!the_lnet.ln_lnds[i]);
2979         lnet_destroy_locks();
2980         genl_unregister_family(&lnet_family);
2981 }
2982
2983 /**
2984  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2985  *
2986  * Users must call this function at least once before any other functions.
2987  * For each successful call there must be a corresponding call to
2988  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2989  * ignored.
2990  *
2991  * The PID used by LNet may be different from the one requested.
2992  * See LNetGetId().
2993  *
2994  * \param requested_pid PID requested by the caller.
2995  *
2996  * \return >= 0 on success, and < 0 error code on failures.
2997  */
2998 int
2999 LNetNIInit(lnet_pid_t requested_pid)
3000 {
3001         int im_a_router = 0;
3002         int rc;
3003         int ni_bytes;
3004         struct lnet_ping_buffer *pbuf;
3005         struct lnet_handle_md ping_mdh;
3006         LIST_HEAD(net_head);
3007         struct lnet_net *net;
3008
3009         mutex_lock(&the_lnet.ln_api_mutex);
3010
3011         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
3012
3013         if (the_lnet.ln_state == LNET_STATE_STOPPING) {
3014                 mutex_unlock(&the_lnet.ln_api_mutex);
3015                 return -ESHUTDOWN;
3016         }
3017
3018         if (the_lnet.ln_refcount > 0) {
3019                 rc = the_lnet.ln_refcount++;
3020                 mutex_unlock(&the_lnet.ln_api_mutex);
3021                 return rc;
3022         }
3023
3024         rc = lnet_prepare(requested_pid);
3025         if (rc != 0) {
3026                 mutex_unlock(&the_lnet.ln_api_mutex);
3027                 return rc;
3028         }
3029
3030         /* create a network for Loopback network */
3031         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
3032         if (net == NULL) {
3033                 rc = -ENOMEM;
3034                 goto err_empty_list;
3035         }
3036
3037         /* Add in the loopback NI */
3038         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
3039                 rc = -ENOMEM;
3040                 goto err_empty_list;
3041         }
3042
3043         if (use_tcp_bonding)
3044                 CWARN("use_tcp_bonding has been removed. Use Multi-Rail and Dynamic Discovery instead, see LU-13641\n");
3045
3046         /* If LNet is being initialized via DLC it is possible
3047          * that the user requests not to load module parameters (ones which
3048          * are supported by DLC) on initialization.  Therefore, make sure not
3049          * to load networks, routes and forwarding from module parameters
3050          * in this case.  On cleanup in case of failure only clean up
3051          * routes if it has been loaded */
3052         if (!the_lnet.ln_nis_from_mod_params) {
3053                 rc = lnet_parse_networks(&net_head, lnet_get_networks());
3054                 if (rc < 0)
3055                         goto err_empty_list;
3056         }
3057
3058         rc = lnet_startup_lndnets(&net_head);
3059         if (rc < 0)
3060                 goto err_empty_list;
3061
3062         if (!the_lnet.ln_nis_from_mod_params) {
3063                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
3064                 if (rc != 0)
3065                         goto err_shutdown_lndnis;
3066
3067                 rc = lnet_rtrpools_alloc(im_a_router);
3068                 if (rc != 0)
3069                         goto err_destroy_routes;
3070         }
3071
3072         rc = lnet_acceptor_start();
3073         if (rc != 0)
3074                 goto err_destroy_routes;
3075
3076         the_lnet.ln_refcount = 1;
3077         /* Now I may use my own API functions... */
3078
3079         ni_bytes = LNET_PING_INFO_HDR_SIZE;
3080         list_for_each_entry(net, &the_lnet.ln_nets, net_list)
3081                 ni_bytes += lnet_get_net_ni_bytes_locked(net);
3082
3083         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_bytes, true);
3084         if (rc != 0)
3085                 goto err_acceptor_stop;
3086
3087         lnet_ping_target_update(pbuf, ping_mdh);
3088
3089         the_lnet.ln_mt_handler = lnet_mt_event_handler;
3090
3091         rc = lnet_push_target_init();
3092         if (rc != 0)
3093                 goto err_stop_ping;
3094
3095         rc = lnet_peer_discovery_start();
3096         if (rc != 0)
3097                 goto err_destroy_push_target;
3098
3099         rc = lnet_monitor_thr_start();
3100         if (rc != 0)
3101                 goto err_stop_discovery_thr;
3102
3103         lnet_fault_init();
3104         lnet_router_debugfs_init();
3105
3106         mutex_unlock(&the_lnet.ln_api_mutex);
3107
3108         complete_all(&the_lnet.ln_started);
3109
3110         /* wait for all routers to start */
3111         lnet_wait_router_start();
3112
3113         return 0;
3114
3115 err_stop_discovery_thr:
3116         lnet_peer_discovery_stop();
3117 err_destroy_push_target:
3118         lnet_push_target_fini();
3119 err_stop_ping:
3120         lnet_ping_target_fini();
3121 err_acceptor_stop:
3122         the_lnet.ln_refcount = 0;
3123         lnet_acceptor_stop();
3124 err_destroy_routes:
3125         if (!the_lnet.ln_nis_from_mod_params)
3126                 lnet_destroy_routes();
3127 err_shutdown_lndnis:
3128         lnet_shutdown_lndnets();
3129 err_empty_list:
3130         lnet_unprepare();
3131         LASSERT(rc < 0);
3132         mutex_unlock(&the_lnet.ln_api_mutex);
3133         while ((net = list_first_entry_or_null(&net_head,
3134                                                struct lnet_net,
3135                                                net_list)) != NULL) {
3136                 list_del_init(&net->net_list);
3137                 lnet_net_free(net);
3138         }
3139         return rc;
3140 }
3141 EXPORT_SYMBOL(LNetNIInit);
3142
3143 /**
3144  * Stop LNet interfaces, routing, and forwarding.
3145  *
3146  * Users must call this function once for each successful call to LNetNIInit().
3147  * Once the LNetNIFini() operation has been started, the results of pending
3148  * API operations are undefined.
3149  *
3150  * \return always 0 for current implementation.
3151  */
3152 int
3153 LNetNIFini(void)
3154 {
3155         mutex_lock(&the_lnet.ln_api_mutex);
3156
3157         LASSERT(the_lnet.ln_refcount > 0);
3158
3159         if (the_lnet.ln_refcount != 1) {
3160                 the_lnet.ln_refcount--;
3161         } else {
3162                 LASSERT(!the_lnet.ln_niinit_self);
3163
3164                 lnet_net_lock(LNET_LOCK_EX);
3165                 the_lnet.ln_state = LNET_STATE_STOPPING;
3166                 lnet_net_unlock(LNET_LOCK_EX);
3167
3168                 lnet_fault_fini();
3169
3170                 lnet_router_debugfs_fini();
3171                 lnet_monitor_thr_stop();
3172                 lnet_peer_discovery_stop();
3173                 lnet_push_target_fini();
3174                 lnet_ping_target_fini();
3175
3176                 /* Teardown fns that use my own API functions BEFORE here */
3177                 the_lnet.ln_refcount = 0;
3178
3179                 lnet_acceptor_stop();
3180                 lnet_destroy_routes();
3181                 lnet_shutdown_lndnets();
3182                 lnet_unprepare();
3183         }
3184
3185         mutex_unlock(&the_lnet.ln_api_mutex);
3186         return 0;
3187 }
3188 EXPORT_SYMBOL(LNetNIFini);
3189
3190 /**
3191  * Grabs the ni data from the ni structure and fills the out
3192  * parameters
3193  *
3194  * \param[in] ni network        interface structure
3195  * \param[out] cfg_ni           NI config information
3196  * \param[out] tun              network and LND tunables
3197  */
3198 static void
3199 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
3200                    struct lnet_ioctl_config_lnd_tunables *tun,
3201                    struct lnet_ioctl_element_stats *stats,
3202                    __u32 tun_size)
3203 {
3204         size_t min_size = 0;
3205         int i;
3206
3207         if (!ni || !cfg_ni || !tun || !nid_is_nid4(&ni->ni_nid))
3208                 return;
3209
3210         if (ni->ni_interface != NULL) {
3211                 strncpy(cfg_ni->lic_ni_intf,
3212                         ni->ni_interface,
3213                         sizeof(cfg_ni->lic_ni_intf));
3214         }
3215
3216         cfg_ni->lic_nid = lnet_nid_to_nid4(&ni->ni_nid);
3217         cfg_ni->lic_status = lnet_ni_get_status_locked(ni);
3218         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
3219
3220         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
3221
3222         if (stats) {
3223                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
3224                                                        LNET_STATS_TYPE_SEND);
3225                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
3226                                                        LNET_STATS_TYPE_RECV);
3227                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
3228                                                        LNET_STATS_TYPE_DROP);
3229         }
3230
3231         /*
3232          * tun->lt_tun will always be present, but in order to be
3233          * backwards compatible, we need to deal with the cases when
3234          * tun->lt_tun is smaller than what the kernel has, because it
3235          * comes from an older version of a userspace program, then we'll
3236          * need to copy as much information as we have available space.
3237          */
3238         min_size = tun_size - sizeof(tun->lt_cmn);
3239         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
3240
3241         /* copy over the cpts */
3242         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
3243             ni->ni_cpts == NULL)  {
3244                 for (i = 0; i < ni->ni_ncpts; i++)
3245                         cfg_ni->lic_cpts[i] = i;
3246         } else {
3247                 for (i = 0;
3248                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
3249                      i < LNET_MAX_SHOW_NUM_CPT;
3250                      i++)
3251                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
3252         }
3253         cfg_ni->lic_ncpts = ni->ni_ncpts;
3254 }
3255
3256 /**
3257  * NOTE: This is a legacy function left in the code to be backwards
3258  * compatible with older userspace programs. It should eventually be
3259  * removed.
3260  *
3261  * Grabs the ni data from the ni structure and fills the out
3262  * parameters
3263  *
3264  * \param[in] ni network        interface structure
3265  * \param[out] config           config information
3266  */
3267 static void
3268 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
3269                          struct lnet_ioctl_config_data *config)
3270 {
3271         struct lnet_ioctl_net_config *net_config;
3272         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
3273         size_t min_size, tunable_size = 0;
3274         int i;
3275
3276         if (!ni || !config || !nid_is_nid4(&ni->ni_nid))
3277                 return;
3278
3279         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
3280         if (!net_config)
3281                 return;
3282
3283         if (!ni->ni_interface)
3284                 return;
3285
3286         strncpy(net_config->ni_interface,
3287                 ni->ni_interface,
3288                 sizeof(net_config->ni_interface));
3289
3290         config->cfg_nid = lnet_nid_to_nid4(&ni->ni_nid);
3291         config->cfg_config_u.cfg_net.net_peer_timeout =
3292                 ni->ni_net->net_tunables.lct_peer_timeout;
3293         config->cfg_config_u.cfg_net.net_max_tx_credits =
3294                 ni->ni_net->net_tunables.lct_max_tx_credits;
3295         config->cfg_config_u.cfg_net.net_peer_tx_credits =
3296                 ni->ni_net->net_tunables.lct_peer_tx_credits;
3297         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
3298                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
3299
3300         net_config->ni_status = lnet_ni_get_status_locked(ni);
3301
3302         if (ni->ni_cpts) {
3303                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
3304
3305                 for (i = 0; i < num_cpts; i++)
3306                         net_config->ni_cpts[i] = ni->ni_cpts[i];
3307
3308                 config->cfg_ncpts = num_cpts;
3309         }
3310
3311         /*
3312          * See if user land tools sent in a newer and larger version
3313          * of struct lnet_tunables than what the kernel uses.
3314          */
3315         min_size = sizeof(*config) + sizeof(*net_config);
3316
3317         if (config->cfg_hdr.ioc_len > min_size)
3318                 tunable_size = config->cfg_hdr.ioc_len - min_size;
3319
3320         /* Don't copy too much data to user space */
3321         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
3322         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
3323
3324         if (lnd_cfg && min_size) {
3325                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
3326                 config->cfg_config_u.cfg_net.net_interface_count = 1;
3327
3328                 /* Tell user land that kernel side has less data */
3329                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
3330                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
3331                         config->cfg_hdr.ioc_len -= min_size;
3332                 }
3333         }
3334 }
3335
3336 struct lnet_ni *
3337 lnet_get_ni_idx_locked(int idx)
3338 {
3339         struct lnet_ni          *ni;
3340         struct lnet_net         *net;
3341
3342         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3343                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3344                         if (idx-- == 0)
3345                                 return ni;
3346                 }
3347         }
3348
3349         return NULL;
3350 }
3351
3352 int lnet_get_net_healthv_locked(struct lnet_net *net)
3353 {
3354         struct lnet_ni *ni;
3355         int best_healthv = 0;
3356         int healthv, ni_fatal;
3357
3358         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3359                 healthv = atomic_read(&ni->ni_healthv);
3360                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3361                 if (!ni_fatal && healthv > best_healthv)
3362                         best_healthv = healthv;
3363         }
3364
3365         return best_healthv;
3366 }
3367
3368 struct lnet_ni *
3369 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3370 {
3371         struct lnet_ni          *ni;
3372         struct lnet_net         *net = mynet;
3373
3374         /*
3375          * It is possible that the net has been cleaned out while there is
3376          * a message being sent. This function accessed the net without
3377          * checking if the list is empty
3378          */
3379         if (!prev) {
3380                 if (!net)
3381                         net = list_first_entry(&the_lnet.ln_nets,
3382                                                struct lnet_net,
3383                                                net_list);
3384                 if (list_empty(&net->net_ni_list))
3385                         return NULL;
3386                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3387                                       ni_netlist);
3388
3389                 return ni;
3390         }
3391
3392         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3393                 /* if you reached the end of the ni list and the net is
3394                  * specified, then there are no more nis in that net */
3395                 if (net != NULL)
3396                         return NULL;
3397
3398                 /* we reached the end of this net ni list. move to the
3399                  * next net */
3400                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3401                         /* no more nets and no more NIs. */
3402                         return NULL;
3403
3404                 /* get the next net */
3405                 net = list_first_entry(&prev->ni_net->net_list, struct lnet_net,
3406                                        net_list);
3407                 if (list_empty(&net->net_ni_list))
3408                         return NULL;
3409                 /* get the ni on it */
3410                 ni = list_first_entry(&net->net_ni_list, struct lnet_ni,
3411                                       ni_netlist);
3412
3413                 return ni;
3414         }
3415
3416         if (list_empty(&prev->ni_netlist))
3417                 return NULL;
3418
3419         /* there are more nis left */
3420         ni = list_first_entry(&prev->ni_netlist, struct lnet_ni, ni_netlist);
3421
3422         return ni;
3423 }
3424
3425 static int
3426 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3427 {
3428         struct lnet_ni *ni;
3429         int cpt;
3430         int rc = -ENOENT;
3431         int idx = config->cfg_count;
3432
3433         cpt = lnet_net_lock_current();
3434
3435         ni = lnet_get_ni_idx_locked(idx);
3436
3437         if (ni != NULL) {
3438                 rc = 0;
3439                 lnet_ni_lock(ni);
3440                 lnet_fill_ni_info_legacy(ni, config);
3441                 lnet_ni_unlock(ni);
3442         }
3443
3444         lnet_net_unlock(cpt);
3445         return rc;
3446 }
3447
3448 static int
3449 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3450                    struct lnet_ioctl_config_lnd_tunables *tun,
3451                    struct lnet_ioctl_element_stats *stats,
3452                    __u32 tun_size)
3453 {
3454         struct lnet_ni          *ni;
3455         int                     cpt;
3456         int                     rc = -ENOENT;
3457
3458         if (!cfg_ni || !tun || !stats)
3459                 return -EINVAL;
3460
3461         cpt = lnet_net_lock_current();
3462
3463         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3464
3465         if (ni) {
3466                 rc = 0;
3467                 lnet_ni_lock(ni);
3468                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3469                 lnet_ni_unlock(ni);
3470         }
3471
3472         lnet_net_unlock(cpt);
3473         return rc;
3474 }
3475
3476 static int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3477 {
3478         struct lnet_ni *ni;
3479         int cpt;
3480         int rc = -ENOENT;
3481
3482         if (!msg_stats)
3483                 return -EINVAL;
3484
3485         cpt = lnet_net_lock_current();
3486
3487         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3488
3489         if (ni) {
3490                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3491                 rc = 0;
3492         }
3493
3494         lnet_net_unlock(cpt);
3495
3496         return rc;
3497 }
3498
3499 static int lnet_add_net_common(struct lnet_net *net,
3500                                struct lnet_ioctl_config_lnd_tunables *tun)
3501 {
3502         struct lnet_handle_md ping_mdh;
3503         struct lnet_ping_buffer *pbuf;
3504         struct lnet_remotenet *rnet;
3505         struct lnet_ni *ni;
3506         u32 net_id;
3507         int rc;
3508
3509         lnet_net_lock(LNET_LOCK_EX);
3510         rnet = lnet_find_rnet_locked(net->net_id);
3511         lnet_net_unlock(LNET_LOCK_EX);
3512         /*
3513          * make sure that the net added doesn't invalidate the current
3514          * configuration LNet is keeping
3515          */
3516         if (rnet) {
3517                 CERROR("Adding net %s will invalidate routing configuration\n",
3518                        libcfs_net2str(net->net_id));
3519                 lnet_net_free(net);
3520                 return -EUSERS;
3521         }
3522
3523         if (tun)
3524                 memcpy(&net->net_tunables,
3525                        &tun->lt_cmn, sizeof(net->net_tunables));
3526         else
3527                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3528
3529         net_id = net->net_id;
3530
3531         rc = lnet_startup_lndnet(net,
3532                                  (tun) ? &tun->lt_tun : NULL);
3533         if (rc < 0)
3534                 return rc;
3535
3536         /* make sure you calculate the correct number of slots in the ping
3537          * buffer. Since the ping info is a flattened list of all the NIs,
3538          * we should allocate enough slots to accomodate the number of NIs
3539          * which will be added.
3540          */
3541         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3542                                     LNET_PING_INFO_HDR_SIZE +
3543                                     lnet_get_ni_bytes(),
3544                                     false);
3545         if (rc < 0) {
3546                 lnet_shutdown_lndnet(net);
3547                 return rc;
3548         }
3549
3550         lnet_net_lock(LNET_LOCK_EX);
3551         net = lnet_get_net_locked(net_id);
3552         LASSERT(net);
3553
3554         /* apply the UDSPs */
3555         rc = lnet_udsp_apply_policies_on_net(net);
3556         if (rc)
3557                 CERROR("Failed to apply UDSPs on local net %s\n",
3558                        libcfs_net2str(net->net_id));
3559
3560         /* At this point we lost track of which NI was just added, so we
3561          * just re-apply the policies on all of the NIs on this net
3562          */
3563         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3564                 rc = lnet_udsp_apply_policies_on_ni(ni);
3565                 if (rc)
3566                         CERROR("Failed to apply UDSPs on ni %s\n",
3567                                libcfs_nidstr(&ni->ni_nid));
3568         }
3569         lnet_net_unlock(LNET_LOCK_EX);
3570
3571         /*
3572          * Start the acceptor thread if this is the first network
3573          * being added that requires the thread.
3574          */
3575         if (net->net_lnd->lnd_accept) {
3576                 rc = lnet_acceptor_start();
3577                 if (rc < 0) {
3578                         /* shutdown the net that we just started */
3579                         CERROR("Failed to start up acceptor thread\n");
3580                         lnet_shutdown_lndnet(net);
3581                         goto failed;
3582                 }
3583         }
3584
3585         lnet_net_lock(LNET_LOCK_EX);
3586         lnet_peer_net_added(net);
3587         lnet_net_unlock(LNET_LOCK_EX);
3588
3589         lnet_ping_target_update(pbuf, ping_mdh);
3590
3591         return 0;
3592
3593 failed:
3594         lnet_ping_md_unlink(pbuf, &ping_mdh);
3595         lnet_ping_buffer_decref(pbuf);
3596         return rc;
3597 }
3598
3599 static void
3600 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3601 {
3602         if (tun) {
3603                 if (tun->lt_cmn.lct_peer_timeout < 0)
3604                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3605                 if (!tun->lt_cmn.lct_peer_tx_credits)
3606                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3607                 if (!tun->lt_cmn.lct_max_tx_credits)
3608                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3609         }
3610 }
3611
3612 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3613                                       struct lnet_ioctl_config_lnd_tunables *tun)
3614 {
3615         struct lnet_net *net;
3616         const char *nets;
3617         int rc;
3618         LIST_HEAD(net_head);
3619
3620         rc = lnet_parse_ip2nets(&nets, ip2nets);
3621         if (rc < 0)
3622                 return rc;
3623
3624         rc = lnet_parse_networks(&net_head, nets);
3625         if (rc < 0)
3626                 return rc;
3627
3628         lnet_set_tune_defaults(tun);
3629
3630         mutex_lock(&the_lnet.ln_api_mutex);
3631         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3632                 rc = -ESHUTDOWN;
3633                 goto out;
3634         }
3635
3636         while ((net = list_first_entry_or_null(&net_head,
3637                                                struct lnet_net,
3638                                                net_list)) != NULL) {
3639                 list_del_init(&net->net_list);
3640                 rc = lnet_add_net_common(net, tun);
3641                 if (rc < 0)
3642                         goto out;
3643         }
3644
3645 out:
3646         mutex_unlock(&the_lnet.ln_api_mutex);
3647
3648         while ((net = list_first_entry_or_null(&net_head,
3649                                                struct lnet_net,
3650                                                net_list)) != NULL) {
3651                 list_del_init(&net->net_list);
3652                 lnet_net_free(net);
3653         }
3654         return rc;
3655 }
3656
3657 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf, u32 net_id,
3658                     struct lnet_ioctl_config_lnd_tunables *tun)
3659 {
3660         struct lnet_net *net;
3661         struct lnet_ni *ni;
3662         int rc, i;
3663         u32 lnd_type;
3664
3665         /* handle legacy ip2nets from DLC */
3666         if (conf->lic_legacy_ip2nets[0] != '\0')
3667                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3668                                                   tun);
3669
3670         lnd_type = LNET_NETTYP(net_id);
3671
3672         if (!libcfs_isknown_lnd(lnd_type)) {
3673                 CERROR("No valid net and lnd information provided\n");
3674                 return -ENOENT;
3675         }
3676
3677         net = lnet_net_alloc(net_id, NULL);
3678         if (!net)
3679                 return -ENOMEM;
3680
3681         for (i = 0; i < conf->lic_ncpts; i++) {
3682                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER) {
3683                         lnet_net_free(net);
3684                         return -ERANGE;
3685                 }
3686         }
3687
3688         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3689                                        conf->lic_ni_intf);
3690         if (!ni) {
3691                 lnet_net_free(net);
3692                 return -ENOMEM;
3693         }
3694
3695         lnet_set_tune_defaults(tun);
3696
3697         mutex_lock(&the_lnet.ln_api_mutex);
3698         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3699                 lnet_net_free(net);
3700                 rc = -ESHUTDOWN;
3701         } else {
3702                 rc = lnet_add_net_common(net, tun);
3703         }
3704
3705         mutex_unlock(&the_lnet.ln_api_mutex);
3706
3707         /* If NI already exist delete this new unused copy */
3708         if (rc == -EEXIST)
3709                 lnet_ni_free(ni);
3710
3711         return rc;
3712 }
3713
3714 int lnet_dyn_del_ni(struct lnet_nid *nid)
3715 {
3716         struct lnet_net *net;
3717         struct lnet_ni *ni;
3718         u32 net_id = LNET_NID_NET(nid);
3719         struct lnet_ping_buffer *pbuf;
3720         struct lnet_handle_md ping_mdh;
3721         int net_bytes, rc;
3722         bool net_empty;
3723
3724         /* don't allow userspace to shutdown the LOLND */
3725         if (LNET_NETTYP(net_id) == LOLND)
3726                 return -EINVAL;
3727
3728         mutex_lock(&the_lnet.ln_api_mutex);
3729         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3730                 rc = -ESHUTDOWN;
3731                 goto unlock_api_mutex;
3732         }
3733
3734         lnet_net_lock(0);
3735
3736         net = lnet_get_net_locked(net_id);
3737         if (!net) {
3738                 CERROR("net %s not found\n",
3739                        libcfs_net2str(net_id));
3740                 rc = -ENOENT;
3741                 goto unlock_net;
3742         }
3743
3744         if (!nid_addr_is_set(nid)) {
3745                 /* remove the entire net */
3746                 net_bytes = lnet_get_net_ni_bytes_locked(net);
3747
3748                 lnet_net_unlock(0);
3749
3750                 /* create and link a new ping info, before removing the old one */
3751                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3752                                             LNET_PING_INFO_HDR_SIZE +
3753                                             lnet_get_ni_bytes() - net_bytes,
3754                                             false);
3755                 if (rc != 0)
3756                         goto unlock_api_mutex;
3757
3758                 lnet_shutdown_lndnet(net);
3759
3760                 lnet_acceptor_stop();
3761
3762                 lnet_ping_target_update(pbuf, ping_mdh);
3763
3764                 goto unlock_api_mutex;
3765         }
3766
3767         ni = lnet_nid_to_ni_locked(nid, 0);
3768         if (!ni) {
3769                 CERROR("nid %s not found\n", libcfs_nidstr(nid));
3770                 rc = -ENOENT;
3771                 goto unlock_net;
3772         }
3773
3774         net_bytes = lnet_get_net_ni_bytes_locked(net);
3775         net_empty = list_is_singular(&net->net_ni_list);
3776
3777         lnet_net_unlock(0);
3778
3779         /* create and link a new ping info, before removing the old one */
3780         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3781                                     (LNET_PING_INFO_HDR_SIZE +
3782                                      lnet_get_ni_bytes() -
3783                                      lnet_ping_sts_size(&ni->ni_nid)),
3784                                     false);
3785         if (rc != 0)
3786                 goto unlock_api_mutex;
3787
3788         lnet_shutdown_lndni(ni);
3789
3790         lnet_acceptor_stop();
3791
3792         lnet_ping_target_update(pbuf, ping_mdh);
3793
3794         /* check if the net is empty and remove it if it is */
3795         if (net_empty)
3796                 lnet_shutdown_lndnet(net);
3797
3798         goto unlock_api_mutex;
3799
3800 unlock_net:
3801         lnet_net_unlock(0);
3802 unlock_api_mutex:
3803         mutex_unlock(&the_lnet.ln_api_mutex);
3804
3805         return rc;
3806 }
3807
3808 /*
3809  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3810  * They are only expected to be called for unique networks.
3811  * That can be as a result of older DLC library
3812  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3813  */
3814 int
3815 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3816 {
3817         struct lnet_net *net;
3818         LIST_HEAD(net_head);
3819         int rc;
3820         struct lnet_ioctl_config_lnd_tunables tun;
3821         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3822
3823         /* Create a net/ni structures for the network string */
3824         rc = lnet_parse_networks(&net_head, nets);
3825         if (rc <= 0)
3826                 return rc == 0 ? -EINVAL : rc;
3827
3828         mutex_lock(&the_lnet.ln_api_mutex);
3829         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3830                 rc = -ESHUTDOWN;
3831                 goto out_unlock_clean;
3832         }
3833
3834         if (rc > 1) {
3835                 rc = -EINVAL; /* only add one network per call */
3836                 goto out_unlock_clean;
3837         }
3838
3839         net = list_first_entry(&net_head, struct lnet_net, net_list);
3840         list_del_init(&net->net_list);
3841
3842         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3843
3844         memset(&tun, 0, sizeof(tun));
3845
3846         tun.lt_cmn.lct_peer_timeout =
3847           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3848                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3849         tun.lt_cmn.lct_peer_tx_credits =
3850           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3851                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3852         tun.lt_cmn.lct_peer_rtr_credits =
3853           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3854         tun.lt_cmn.lct_max_tx_credits =
3855           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3856                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3857
3858         rc = lnet_add_net_common(net, &tun);
3859
3860 out_unlock_clean:
3861         mutex_unlock(&the_lnet.ln_api_mutex);
3862         /* net_head list is empty in success case */
3863         while ((net = list_first_entry_or_null(&net_head,
3864                                                struct lnet_net,
3865                                                net_list)) != NULL) {
3866                 list_del_init(&net->net_list);
3867                 lnet_net_free(net);
3868         }
3869         return rc;
3870 }
3871
3872 int
3873 lnet_dyn_del_net(u32 net_id)
3874 {
3875         struct lnet_net *net;
3876         struct lnet_ping_buffer *pbuf;
3877         struct lnet_handle_md ping_mdh;
3878         int net_ni_bytes, rc;
3879
3880         /* don't allow userspace to shutdown the LOLND */
3881         if (LNET_NETTYP(net_id) == LOLND)
3882                 return -EINVAL;
3883
3884         mutex_lock(&the_lnet.ln_api_mutex);
3885         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3886                 rc = -ESHUTDOWN;
3887                 goto out;
3888         }
3889
3890         lnet_net_lock(0);
3891
3892         net = lnet_get_net_locked(net_id);
3893         if (net == NULL) {
3894                 lnet_net_unlock(0);
3895                 rc = -EINVAL;
3896                 goto out;
3897         }
3898
3899         net_ni_bytes = lnet_get_net_ni_bytes_locked(net);
3900
3901         lnet_net_unlock(0);
3902
3903         /* create and link a new ping info, before removing the old one */
3904         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3905                                     LNET_PING_INFO_HDR_SIZE +
3906                                     lnet_get_ni_bytes() - net_ni_bytes,
3907                                     false);
3908         if (rc != 0)
3909                 goto out;
3910
3911         lnet_shutdown_lndnet(net);
3912
3913         lnet_acceptor_stop();
3914
3915         lnet_ping_target_update(pbuf, ping_mdh);
3916
3917 out:
3918         mutex_unlock(&the_lnet.ln_api_mutex);
3919
3920         return rc;
3921 }
3922
3923 void lnet_mark_ping_buffer_for_update(void)
3924 {
3925         if (the_lnet.ln_routing)
3926                 return;
3927
3928         atomic_set(&the_lnet.ln_update_ping_buf, 1);
3929         complete(&the_lnet.ln_mt_wait_complete);
3930 }
3931 EXPORT_SYMBOL(lnet_mark_ping_buffer_for_update);
3932
3933 void lnet_update_ping_buffer(void)
3934 {
3935         struct lnet_ping_buffer *pbuf;
3936         struct lnet_handle_md ping_mdh;
3937
3938         if (atomic_dec_if_positive(&the_lnet.ln_update_ping_buf) < 0)
3939                 return;
3940
3941         mutex_lock(&the_lnet.ln_api_mutex);
3942
3943         if (!lnet_ping_target_setup(&pbuf, &ping_mdh,
3944                                     LNET_PING_INFO_HDR_SIZE +
3945                                     lnet_get_ni_bytes(),
3946                                     false))
3947                 lnet_ping_target_update(pbuf, ping_mdh);
3948
3949         mutex_unlock(&the_lnet.ln_api_mutex);
3950 }
3951
3952 void lnet_incr_dlc_seq(void)
3953 {
3954         atomic_inc(&lnet_dlc_seq_no);
3955 }
3956
3957 __u32 lnet_get_dlc_seq_locked(void)
3958 {
3959         return atomic_read(&lnet_dlc_seq_no);
3960 }
3961
3962 static void
3963 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3964 {
3965         struct lnet_net *net;
3966         struct lnet_ni *ni;
3967
3968         lnet_net_lock(LNET_LOCK_EX);
3969         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3970                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3971                         if (all || (nid_is_nid4(&ni->ni_nid) &&
3972                                     lnet_nid_to_nid4(&ni->ni_nid) == nid)) {
3973                                 atomic_set(&ni->ni_healthv, value);
3974                                 if (list_empty(&ni->ni_recovery) &&
3975                                     value < LNET_MAX_HEALTH_VALUE) {
3976                                         CERROR("manually adding local NI %s to recovery\n",
3977                                                libcfs_nidstr(&ni->ni_nid));
3978                                         list_add_tail(&ni->ni_recovery,
3979                                                       &the_lnet.ln_mt_localNIRecovq);
3980                                         lnet_ni_addref_locked(ni, 0);
3981                                 }
3982                                 if (!all) {
3983                                         lnet_net_unlock(LNET_LOCK_EX);
3984                                         return;
3985                                 }
3986                         }
3987                 }
3988         }
3989         lnet_net_unlock(LNET_LOCK_EX);
3990 }
3991
3992 static void
3993 lnet_ni_set_conns_per_peer(lnet_nid_t nid, int value, bool all)
3994 {
3995         struct lnet_net *net;
3996         struct lnet_ni *ni;
3997
3998         lnet_net_lock(LNET_LOCK_EX);
3999         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4000                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4001                         if (lnet_nid_to_nid4(&ni->ni_nid) != nid && !all)
4002                                 continue;
4003                         if (LNET_NETTYP(net->net_id) == SOCKLND)
4004                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_sock.lnd_conns_per_peer = value;
4005                         else if (LNET_NETTYP(net->net_id) == O2IBLND)
4006                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib.lnd_conns_per_peer = value;
4007                         if (!all) {
4008                                 lnet_net_unlock(LNET_LOCK_EX);
4009                                 return;
4010                         }
4011                 }
4012         }
4013         lnet_net_unlock(LNET_LOCK_EX);
4014 }
4015
4016 static int
4017 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
4018 {
4019         int cpt, rc = 0;
4020         struct lnet_ni *ni;
4021         struct lnet_nid nid;
4022
4023         lnet_nid4_to_nid(stats->hlni_nid, &nid);
4024         cpt = lnet_net_lock_current();
4025         ni = lnet_nid_to_ni_locked(&nid, cpt);
4026         if (!ni) {
4027                 rc = -ENOENT;
4028                 goto unlock;
4029         }
4030
4031         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
4032         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
4033         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
4034         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
4035         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
4036         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
4037         stats->hlni_fatal_error = atomic_read(&ni->ni_fatal_error_on);
4038         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
4039         stats->hlni_ping_count = ni->ni_ping_count;
4040         stats->hlni_next_ping = ni->ni_next_ping;
4041
4042 unlock:
4043         lnet_net_unlock(cpt);
4044
4045         return rc;
4046 }
4047
4048 static int
4049 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4050 {
4051         struct lnet_ni *ni;
4052         int i = 0;
4053
4054         lnet_net_lock(LNET_LOCK_EX);
4055         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
4056                 if (!nid_is_nid4(&ni->ni_nid))
4057                         continue;
4058                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&ni->ni_nid);
4059                 i++;
4060                 if (i >= LNET_MAX_SHOW_NUM_NID)
4061                         break;
4062         }
4063         lnet_net_unlock(LNET_LOCK_EX);
4064         list->rlst_num_nids = i;
4065
4066         return 0;
4067 }
4068
4069 static int
4070 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
4071 {
4072         struct lnet_peer_ni *lpni;
4073         int i = 0;
4074
4075         lnet_net_lock(LNET_LOCK_EX);
4076         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
4077                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&lpni->lpni_nid);
4078                 i++;
4079                 if (i >= LNET_MAX_SHOW_NUM_NID)
4080                         break;
4081         }
4082         lnet_net_unlock(LNET_LOCK_EX);
4083         list->rlst_num_nids = i;
4084
4085         return 0;
4086 }
4087
4088 /**
4089  * LNet ioctl handler.
4090  *
4091  */
4092 int
4093 LNetCtl(unsigned int cmd, void *arg)
4094 {
4095         struct libcfs_ioctl_data *data = arg;
4096         struct lnet_ioctl_config_data *config;
4097         struct lnet_ni           *ni;
4098         struct lnet_nid           nid;
4099         int                       rc;
4100
4101         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
4102                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
4103
4104         switch (cmd) {
4105         case IOC_LIBCFS_GET_NI: {
4106                 struct lnet_processid id = {};
4107
4108                 rc = LNetGetId(data->ioc_count, &id);
4109                 data->ioc_nid = lnet_nid_to_nid4(&id.nid);
4110                 return rc;
4111         }
4112         case IOC_LIBCFS_FAIL_NID:
4113                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
4114
4115         case IOC_LIBCFS_ADD_ROUTE: {
4116                 /* default router sensitivity to 1 */
4117                 unsigned int sensitivity = 1;
4118                 config = arg;
4119
4120                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4121                         return -EINVAL;
4122
4123                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
4124                         sensitivity =
4125                           config->cfg_config_u.cfg_route.rtr_sensitivity;
4126                 }
4127
4128                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4129                 mutex_lock(&the_lnet.ln_api_mutex);
4130                 rc = lnet_add_route(config->cfg_net,
4131                                     config->cfg_config_u.cfg_route.rtr_hop,
4132                                     &nid,
4133                                     config->cfg_config_u.cfg_route.
4134                                         rtr_priority, sensitivity);
4135                 mutex_unlock(&the_lnet.ln_api_mutex);
4136                 return rc;
4137         }
4138
4139         case IOC_LIBCFS_DEL_ROUTE:
4140                 config = arg;
4141
4142                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4143                         return -EINVAL;
4144
4145                 lnet_nid4_to_nid(config->cfg_nid, &nid);
4146                 mutex_lock(&the_lnet.ln_api_mutex);
4147                 rc = lnet_del_route(config->cfg_net, &nid);
4148                 mutex_unlock(&the_lnet.ln_api_mutex);
4149                 return rc;
4150
4151         case IOC_LIBCFS_GET_ROUTE:
4152                 config = arg;
4153
4154                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4155                         return -EINVAL;
4156
4157                 mutex_lock(&the_lnet.ln_api_mutex);
4158                 rc = lnet_get_route(config->cfg_count,
4159                                     &config->cfg_net,
4160                                     &config->cfg_config_u.cfg_route.rtr_hop,
4161                                     &config->cfg_nid,
4162                                     &config->cfg_config_u.cfg_route.rtr_flags,
4163                                     &config->cfg_config_u.cfg_route.
4164                                         rtr_priority,
4165                                     &config->cfg_config_u.cfg_route.
4166                                         rtr_sensitivity);
4167                 mutex_unlock(&the_lnet.ln_api_mutex);
4168                 return rc;
4169
4170         case IOC_LIBCFS_GET_LOCAL_NI: {
4171                 struct lnet_ioctl_config_ni *cfg_ni;
4172                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
4173                 struct lnet_ioctl_element_stats *stats;
4174                 __u32 tun_size;
4175
4176                 cfg_ni = arg;
4177
4178                 /* get the tunables if they are available */
4179                 if (cfg_ni->lic_cfg_hdr.ioc_len <
4180                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
4181                         return -EINVAL;
4182
4183                 stats = (struct lnet_ioctl_element_stats *)
4184                         cfg_ni->lic_bulk;
4185                 tun = (struct lnet_ioctl_config_lnd_tunables *)
4186                                 (cfg_ni->lic_bulk + sizeof(*stats));
4187
4188                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
4189                         sizeof(*stats);
4190
4191                 mutex_lock(&the_lnet.ln_api_mutex);
4192                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
4193                 mutex_unlock(&the_lnet.ln_api_mutex);
4194                 return rc;
4195         }
4196
4197         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
4198                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
4199
4200                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
4201                         return -EINVAL;
4202
4203                 mutex_lock(&the_lnet.ln_api_mutex);
4204                 rc = lnet_get_ni_stats(msg_stats);
4205                 mutex_unlock(&the_lnet.ln_api_mutex);
4206
4207                 return rc;
4208         }
4209
4210         case IOC_LIBCFS_GET_NET: {
4211                 size_t total = sizeof(*config) +
4212                                sizeof(struct lnet_ioctl_net_config);
4213                 config = arg;
4214
4215                 if (config->cfg_hdr.ioc_len < total)
4216                         return -EINVAL;
4217
4218                 mutex_lock(&the_lnet.ln_api_mutex);
4219                 rc = lnet_get_net_config(config);
4220                 mutex_unlock(&the_lnet.ln_api_mutex);
4221                 return rc;
4222         }
4223
4224         case IOC_LIBCFS_GET_LNET_STATS:
4225         {
4226                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
4227
4228                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
4229                         return -EINVAL;
4230
4231                 mutex_lock(&the_lnet.ln_api_mutex);
4232                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
4233                 mutex_unlock(&the_lnet.ln_api_mutex);
4234                 return rc;
4235         }
4236
4237         case IOC_LIBCFS_RESET_LNET_STATS:
4238         {
4239                 mutex_lock(&the_lnet.ln_api_mutex);
4240                 lnet_counters_reset();
4241                 mutex_unlock(&the_lnet.ln_api_mutex);
4242                 return 0;
4243         }
4244
4245         case IOC_LIBCFS_CONFIG_RTR:
4246                 config = arg;
4247
4248                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4249                         return -EINVAL;
4250
4251                 mutex_lock(&the_lnet.ln_api_mutex);
4252                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
4253                         rc = lnet_rtrpools_enable();
4254                         mutex_unlock(&the_lnet.ln_api_mutex);
4255                         return rc;
4256                 }
4257                 lnet_rtrpools_disable();
4258                 mutex_unlock(&the_lnet.ln_api_mutex);
4259                 return 0;
4260
4261         case IOC_LIBCFS_ADD_BUF:
4262                 config = arg;
4263
4264                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4265                         return -EINVAL;
4266
4267                 mutex_lock(&the_lnet.ln_api_mutex);
4268                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4269                                                 buf_tiny,
4270                                           config->cfg_config_u.cfg_buffers.
4271                                                 buf_small,
4272                                           config->cfg_config_u.cfg_buffers.
4273                                                 buf_large);
4274                 mutex_unlock(&the_lnet.ln_api_mutex);
4275                 return rc;
4276
4277         case IOC_LIBCFS_SET_NUMA_RANGE: {
4278                 struct lnet_ioctl_set_value *numa;
4279                 numa = arg;
4280                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4281                         return -EINVAL;
4282                 lnet_net_lock(LNET_LOCK_EX);
4283                 lnet_numa_range = numa->sv_value;
4284                 lnet_net_unlock(LNET_LOCK_EX);
4285                 return 0;
4286         }
4287
4288         case IOC_LIBCFS_GET_NUMA_RANGE: {
4289                 struct lnet_ioctl_set_value *numa;
4290                 numa = arg;
4291                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4292                         return -EINVAL;
4293                 numa->sv_value = lnet_numa_range;
4294                 return 0;
4295         }
4296
4297         case IOC_LIBCFS_GET_BUF: {
4298                 struct lnet_ioctl_pool_cfg *pool_cfg;
4299                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4300
4301                 config = arg;
4302
4303                 if (config->cfg_hdr.ioc_len < total)
4304                         return -EINVAL;
4305
4306                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4307
4308                 mutex_lock(&the_lnet.ln_api_mutex);
4309                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4310                 mutex_unlock(&the_lnet.ln_api_mutex);
4311                 return rc;
4312         }
4313
4314         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4315                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4316
4317                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4318                         return -EINVAL;
4319
4320                 mutex_lock(&the_lnet.ln_api_mutex);
4321                 rc = lnet_get_local_ni_hstats(stats);
4322                 mutex_unlock(&the_lnet.ln_api_mutex);
4323
4324                 return rc;
4325         }
4326
4327         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4328                 struct lnet_ioctl_recovery_list *list = arg;
4329                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4330                         return -EINVAL;
4331
4332                 mutex_lock(&the_lnet.ln_api_mutex);
4333                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4334                         rc = lnet_get_local_ni_recovery_list(list);
4335                 else
4336                         rc = lnet_get_peer_ni_recovery_list(list);
4337                 mutex_unlock(&the_lnet.ln_api_mutex);
4338                 return rc;
4339         }
4340
4341         case IOC_LIBCFS_ADD_PEER_NI: {
4342                 struct lnet_ioctl_peer_cfg *cfg = arg;
4343                 struct lnet_nid prim_nid;
4344
4345                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4346                         return -EINVAL;
4347
4348                 mutex_lock(&the_lnet.ln_api_mutex);
4349                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4350                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4351                 rc = lnet_user_add_peer_ni(&prim_nid, &nid, cfg->prcfg_mr,
4352                                            cfg->prcfg_count == 1);
4353                 mutex_unlock(&the_lnet.ln_api_mutex);
4354                 return rc;
4355         }
4356
4357         case IOC_LIBCFS_DEL_PEER_NI: {
4358                 struct lnet_ioctl_peer_cfg *cfg = arg;
4359                 struct lnet_nid prim_nid;
4360
4361                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4362                         return -EINVAL;
4363
4364                 mutex_lock(&the_lnet.ln_api_mutex);
4365                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &prim_nid);
4366                 lnet_nid4_to_nid(cfg->prcfg_cfg_nid, &nid);
4367                 rc = lnet_del_peer_ni(&prim_nid,
4368                                       &nid,
4369                                       cfg->prcfg_count);
4370                 mutex_unlock(&the_lnet.ln_api_mutex);
4371                 return rc;
4372         }
4373
4374         case IOC_LIBCFS_GET_PEER_INFO: {
4375                 struct lnet_ioctl_peer *peer_info = arg;
4376
4377                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4378                         return -EINVAL;
4379
4380                 mutex_lock(&the_lnet.ln_api_mutex);
4381                 rc = lnet_get_peer_ni_info(
4382                    peer_info->pr_count,
4383                    &peer_info->pr_nid,
4384                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4385                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4386                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4387                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4388                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4389                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4390                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4391                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4392                 mutex_unlock(&the_lnet.ln_api_mutex);
4393                 return rc;
4394         }
4395
4396         case IOC_LIBCFS_GET_PEER_NI: {
4397                 struct lnet_ioctl_peer_cfg *cfg = arg;
4398
4399                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4400                         return -EINVAL;
4401
4402                 mutex_lock(&the_lnet.ln_api_mutex);
4403                 rc = lnet_get_peer_info(cfg,
4404                                         (void __user *)cfg->prcfg_bulk);
4405                 mutex_unlock(&the_lnet.ln_api_mutex);
4406                 return rc;
4407         }
4408
4409         case IOC_LIBCFS_GET_PEER_LIST: {
4410                 struct lnet_ioctl_peer_cfg *cfg = arg;
4411
4412                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4413                         return -EINVAL;
4414
4415                 mutex_lock(&the_lnet.ln_api_mutex);
4416                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4417                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4418                 mutex_unlock(&the_lnet.ln_api_mutex);
4419                 return rc;
4420         }
4421
4422         case IOC_LIBCFS_SET_HEALHV: {
4423                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4424                 int value;
4425                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4426                         return -EINVAL;
4427                 if (cfg->rh_value < 0 ||
4428                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4429                         value = LNET_MAX_HEALTH_VALUE;
4430                 else
4431                         value = cfg->rh_value;
4432                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4433                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4434                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4435                 mutex_lock(&the_lnet.ln_api_mutex);
4436                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
4437                         lnet_ni_set_healthv(cfg->rh_nid, value,
4438                                              cfg->rh_all);
4439                 else
4440                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
4441                                                   cfg->rh_all);
4442                 mutex_unlock(&the_lnet.ln_api_mutex);
4443                 return 0;
4444         }
4445
4446         case IOC_LIBCFS_SET_PEER: {
4447                 struct lnet_ioctl_peer_cfg *cfg = arg;
4448                 struct lnet_peer *lp;
4449
4450                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4451                         return -EINVAL;
4452
4453                 mutex_lock(&the_lnet.ln_api_mutex);
4454                 lnet_nid4_to_nid(cfg->prcfg_prim_nid, &nid);
4455                 lp = lnet_find_peer(&nid);
4456                 if (!lp) {
4457                         mutex_unlock(&the_lnet.ln_api_mutex);
4458                         return -ENOENT;
4459                 }
4460                 spin_lock(&lp->lp_lock);
4461                 lp->lp_state = cfg->prcfg_state;
4462                 spin_unlock(&lp->lp_lock);
4463                 lnet_peer_decref_locked(lp);
4464                 mutex_unlock(&the_lnet.ln_api_mutex);
4465                 CDEBUG(D_NET, "Set peer %s state to %u\n",
4466                        libcfs_nid2str(cfg->prcfg_prim_nid), cfg->prcfg_state);
4467                 return 0;
4468         }
4469
4470         case IOC_LIBCFS_SET_CONNS_PER_PEER: {
4471                 struct lnet_ioctl_reset_conns_per_peer_cfg *cfg = arg;
4472                 int value;
4473
4474                 if (cfg->rcpp_hdr.ioc_len < sizeof(*cfg))
4475                         return -EINVAL;
4476                 if (cfg->rcpp_value < 0)
4477                         value = 1;
4478                 else
4479                         value = cfg->rcpp_value;
4480                 CDEBUG(D_NET,
4481                        "Setting conns_per_peer to %d for %s. all = %d\n",
4482                        value, libcfs_nid2str(cfg->rcpp_nid), cfg->rcpp_all);
4483                 mutex_lock(&the_lnet.ln_api_mutex);
4484                 lnet_ni_set_conns_per_peer(cfg->rcpp_nid, value, cfg->rcpp_all);
4485                 mutex_unlock(&the_lnet.ln_api_mutex);
4486                 return 0;
4487         }
4488
4489         case IOC_LIBCFS_NOTIFY_ROUTER: {
4490                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
4491
4492                 /* The deadline passed in by the user should be some time in
4493                  * seconds in the future since the UNIX epoch. We have to map
4494                  * that deadline to the wall clock.
4495                  */
4496                 deadline += ktime_get_seconds();
4497                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4498                 return lnet_notify(NULL, &nid, data->ioc_flags, false,
4499                                    deadline);
4500         }
4501
4502         case IOC_LIBCFS_LNET_DIST:
4503                 lnet_nid4_to_nid(data->ioc_nid, &nid);
4504                 rc = LNetDist(&nid, &nid, &data->ioc_u32[1]);
4505                 if (rc < 0 && rc != -EHOSTUNREACH)
4506                         return rc;
4507
4508                 data->ioc_nid = lnet_nid_to_nid4(&nid);
4509                 data->ioc_u32[0] = rc;
4510                 return 0;
4511
4512         case IOC_LIBCFS_TESTPROTOCOMPAT:
4513                 the_lnet.ln_testprotocompat = data->ioc_flags;
4514                 return 0;
4515
4516         case IOC_LIBCFS_LNET_FAULT:
4517                 return lnet_fault_ctl(data->ioc_flags, data);
4518
4519         case IOC_LIBCFS_PING_PEER: {
4520                 struct lnet_ioctl_ping_data *ping = arg;
4521                 struct lnet_process_id __user *ids = ping->ping_buf;
4522                 struct lnet_nid src_nid = LNET_ANY_NID;
4523                 struct lnet_genl_ping_list plist;
4524                 struct lnet_processid id;
4525                 struct lnet_peer *lp;
4526                 signed long timeout;
4527                 int count, i;
4528
4529                 /* Check if the supplied ping data supports source nid
4530                  * NB: This check is sufficient if lnet_ioctl_ping_data has
4531                  * additional fields added, but if they are re-ordered or
4532                  * fields removed then this will break. It is expected that
4533                  * these ioctls will be replaced with netlink implementation, so
4534                  * it is probably not worth coming up with a more robust version
4535                  * compatibility scheme.
4536                  */
4537                 if (ping->ping_hdr.ioc_len >= sizeof(struct lnet_ioctl_ping_data))
4538                         lnet_nid4_to_nid(ping->ping_src, &src_nid);
4539
4540                 /* If timeout is negative then set default of 3 minutes */
4541                 if (((s32)ping->op_param) <= 0 ||
4542                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4543                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4544                 else
4545                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4546
4547                 id.pid = ping->ping_id.pid;
4548                 lnet_nid4_to_nid(ping->ping_id.nid, &id.nid);
4549                 rc = lnet_ping(&id, &src_nid, timeout, &plist,
4550                                ping->ping_count);
4551                 if (rc < 0)
4552                         goto report_ping_err;
4553                 count = rc;
4554                 rc = 0;
4555
4556                 for (i = 0; i < count; i++) {
4557                         struct lnet_processid *result;
4558                         struct lnet_process_id tmpid;
4559
4560                         result = genradix_ptr(&plist.lgpl_list, i);
4561                         memset(&tmpid, 0, sizeof(tmpid));
4562                         tmpid.pid = result->pid;
4563                         tmpid.nid = lnet_nid_to_nid4(&result->nid);
4564                         if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid))) {
4565                                 rc = -EFAULT;
4566                                 goto report_ping_err;
4567                         }
4568                 }
4569
4570                 mutex_lock(&the_lnet.ln_api_mutex);
4571                 lp = lnet_find_peer(&id.nid);
4572                 if (lp) {
4573                         ping->ping_id.nid =
4574                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4575                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4576                         lnet_peer_decref_locked(lp);
4577                 }
4578                 mutex_unlock(&the_lnet.ln_api_mutex);
4579
4580                 ping->ping_count = count;
4581 report_ping_err:
4582                 genradix_free(&plist.lgpl_list);
4583                 return rc;
4584         }
4585
4586         case IOC_LIBCFS_DISCOVER: {
4587                 struct lnet_ioctl_ping_data *discover = arg;
4588                 struct lnet_peer *lp;
4589
4590                 rc = lnet_discover(discover->ping_id, discover->op_param,
4591                                    discover->ping_buf,
4592                                    discover->ping_count);
4593                 if (rc < 0)
4594                         return rc;
4595
4596                 mutex_lock(&the_lnet.ln_api_mutex);
4597                 lnet_nid4_to_nid(discover->ping_id.nid, &nid);
4598                 lp = lnet_find_peer(&nid);
4599                 if (lp) {
4600                         discover->ping_id.nid =
4601                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4602                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4603                         lnet_peer_decref_locked(lp);
4604                 }
4605                 mutex_unlock(&the_lnet.ln_api_mutex);
4606
4607                 discover->ping_count = rc;
4608                 return 0;
4609         }
4610
4611         case IOC_LIBCFS_ADD_UDSP: {
4612                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4613                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4614
4615                 mutex_lock(&the_lnet.ln_api_mutex);
4616                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4617                 if (!rc) {
4618                         rc = lnet_udsp_apply_policies(NULL, false);
4619                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4620                         rc = 0;
4621                 }
4622                 mutex_unlock(&the_lnet.ln_api_mutex);
4623
4624                 return rc;
4625         }
4626
4627         case IOC_LIBCFS_DEL_UDSP: {
4628                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4629                 int idx = ioc_udsp->iou_idx;
4630
4631                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4632                         return -EINVAL;
4633
4634                 mutex_lock(&the_lnet.ln_api_mutex);
4635                 rc = lnet_udsp_del_policy(idx);
4636                 mutex_unlock(&the_lnet.ln_api_mutex);
4637
4638                 return rc;
4639         }
4640
4641         case IOC_LIBCFS_GET_UDSP_SIZE: {
4642                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4643                 struct lnet_udsp *udsp;
4644
4645                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4646                         return -EINVAL;
4647
4648                 rc = 0;
4649
4650                 mutex_lock(&the_lnet.ln_api_mutex);
4651                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4652                 if (!udsp) {
4653                         rc = -ENOENT;
4654                 } else {
4655                         /* coming in iou_idx will hold the idx of the udsp
4656                          * to get the size of. going out the iou_idx will
4657                          * hold the size of the UDSP found at the passed
4658                          * in index.
4659                          */
4660                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4661                         if (ioc_udsp->iou_idx < 0)
4662                                 rc = -EINVAL;
4663                 }
4664                 mutex_unlock(&the_lnet.ln_api_mutex);
4665
4666                 return rc;
4667         }
4668
4669         case IOC_LIBCFS_GET_UDSP: {
4670                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4671                 struct lnet_udsp *udsp;
4672
4673                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4674                         return -EINVAL;
4675
4676                 rc = 0;
4677
4678                 mutex_lock(&the_lnet.ln_api_mutex);
4679                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4680                 if (!udsp)
4681                         rc = -ENOENT;
4682                 else
4683                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4684                 mutex_unlock(&the_lnet.ln_api_mutex);
4685
4686                 return rc;
4687         }
4688
4689         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4690                 struct lnet_ioctl_construct_udsp_info *info = arg;
4691
4692                 if (info->cud_hdr.ioc_len < sizeof(*info))
4693                         return -EINVAL;
4694
4695                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4696                        libcfs_nid2str(info->cud_nid));
4697
4698                 mutex_lock(&the_lnet.ln_api_mutex);
4699                 lnet_udsp_get_construct_info(info);
4700                 mutex_unlock(&the_lnet.ln_api_mutex);
4701
4702                 return 0;
4703         }
4704
4705         default:
4706                 ni = lnet_net2ni_addref(data->ioc_net);
4707                 if (ni == NULL)
4708                         return -EINVAL;
4709
4710                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4711                         rc = -EINVAL;
4712                 else
4713                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4714
4715                 lnet_ni_decref(ni);
4716                 return rc <= 0 ? rc : 0;
4717         }
4718         /* not reached */
4719 }
4720 EXPORT_SYMBOL(LNetCtl);
4721
4722 static const struct ln_key_list net_props_list = {
4723         .lkl_maxattr                    = LNET_NET_ATTR_MAX,
4724         .lkl_list                       = {
4725                 [LNET_NET_ATTR_HDR]             = {
4726                         .lkp_value              = "net",
4727                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4728                         .lkp_data_type          = NLA_NUL_STRING,
4729                 },
4730                 [LNET_NET_ATTR_TYPE]            = {
4731                         .lkp_value              = "net type",
4732                         .lkp_data_type          = NLA_STRING
4733                 },
4734                 [LNET_NET_ATTR_LOCAL]           = {
4735                         .lkp_value              = "local NI(s)",
4736                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
4737                         .lkp_data_type          = NLA_NESTED
4738                 },
4739         },
4740 };
4741
4742 static struct ln_key_list local_ni_list = {
4743         .lkl_maxattr                    = LNET_NET_LOCAL_NI_ATTR_MAX,
4744         .lkl_list                       = {
4745                 [LNET_NET_LOCAL_NI_ATTR_NID]    = {
4746                         .lkp_value              = "nid",
4747                         .lkp_data_type          = NLA_STRING
4748                 },
4749                 [LNET_NET_LOCAL_NI_ATTR_STATUS] = {
4750                         .lkp_value              = "status",
4751                         .lkp_data_type          = NLA_STRING
4752                 },
4753                 [LNET_NET_LOCAL_NI_ATTR_INTERFACE] = {
4754                         .lkp_value              = "interfaces",
4755                         .lkp_key_format         = LNKF_MAPPING,
4756                         .lkp_data_type          = NLA_NESTED
4757                 },
4758         },
4759 };
4760
4761 static const struct ln_key_list local_ni_interfaces_list = {
4762         .lkl_maxattr                    = LNET_NET_LOCAL_NI_INTF_ATTR_MAX,
4763         .lkl_list                       = {
4764                 [LNET_NET_LOCAL_NI_INTF_ATTR_TYPE] = {
4765                         .lkp_value      = "0",
4766                         .lkp_data_type  = NLA_STRING
4767                 },
4768         },
4769 };
4770
4771 /* Use an index since the traversal is across LNet nets and ni collections */
4772 struct lnet_genl_net_list {
4773         unsigned int    lngl_net_id;
4774         unsigned int    lngl_idx;
4775 };
4776
4777 static inline struct lnet_genl_net_list *
4778 lnet_net_dump_ctx(struct netlink_callback *cb)
4779 {
4780         return (struct lnet_genl_net_list *)cb->args[0];
4781 }
4782
4783 static int lnet_net_show_done(struct netlink_callback *cb)
4784 {
4785         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
4786
4787         if (nlist) {
4788                 LIBCFS_FREE(nlist, sizeof(*nlist));
4789                 cb->args[0] = 0;
4790         }
4791
4792         return 0;
4793 }
4794
4795 /* LNet net ->start() handler for GET requests */
4796 static int lnet_net_show_start(struct netlink_callback *cb)
4797 {
4798         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
4799 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4800         struct netlink_ext_ack *extack = NULL;
4801 #endif
4802         struct lnet_genl_net_list *nlist;
4803         int msg_len = genlmsg_len(gnlh);
4804         struct nlattr *params, *top;
4805         int rem, rc = 0;
4806
4807 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4808         extack = cb->extack;
4809 #endif
4810         if (the_lnet.ln_refcount == 0) {
4811                 NL_SET_ERR_MSG(extack, "LNet stack down");
4812                 return -ENETDOWN;
4813         }
4814
4815         LIBCFS_ALLOC(nlist, sizeof(*nlist));
4816         if (!nlist)
4817                 return -ENOMEM;
4818
4819         nlist->lngl_net_id = LNET_NET_ANY;
4820         nlist->lngl_idx = 0;
4821         cb->args[0] = (long)nlist;
4822
4823         if (!msg_len)
4824                 return 0;
4825
4826         params = genlmsg_data(gnlh);
4827         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
4828                 NL_SET_ERR_MSG(extack, "invalid configuration");
4829                 return -EINVAL;
4830         }
4831
4832         nla_for_each_nested(top, params, rem) {
4833                 struct nlattr *net;
4834                 int rem2;
4835
4836                 nla_for_each_nested(net, top, rem2) {
4837                         char filter[LNET_NIDSTR_SIZE];
4838
4839                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE ||
4840                             nla_strcmp(net, "net type") != 0)
4841                                 continue;
4842
4843                         net = nla_next(net, &rem2);
4844                         if (nla_type(net) != LN_SCALAR_ATTR_VALUE) {
4845                                 NL_SET_ERR_MSG(extack, "invalid config param");
4846                                 GOTO(report_err, rc = -EINVAL);
4847                         }
4848
4849                         rc = nla_strscpy(filter, net, sizeof(filter));
4850                         if (rc < 0) {
4851                                 NL_SET_ERR_MSG(extack, "failed to get param");
4852                                 GOTO(report_err, rc);
4853                         }
4854                         rc = 0;
4855
4856                         nlist->lngl_net_id = libcfs_str2net(filter);
4857                         if (nlist->lngl_net_id == LNET_NET_ANY) {
4858                                 NL_SET_ERR_MSG(extack, "cannot parse net");
4859                                 GOTO(report_err, rc = -ENOENT);
4860                         }
4861                 }
4862         }
4863 report_err:
4864         if (rc < 0)
4865                 lnet_net_show_done(cb);
4866
4867         return rc;
4868 }
4869
4870 static int lnet_net_show_dump(struct sk_buff *msg,
4871                               struct netlink_callback *cb)
4872 {
4873         struct lnet_genl_net_list *nlist = lnet_net_dump_ctx(cb);
4874 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
4875         struct netlink_ext_ack *extack = NULL;
4876 #endif
4877         int portid = NETLINK_CB(cb->skb).portid;
4878         int seq = cb->nlh->nlmsg_seq;
4879         struct lnet_net *net;
4880         int idx = 0, rc = 0;
4881         bool found = false;
4882         void *hdr = NULL;
4883
4884 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
4885         extack = cb->extack;
4886 #endif
4887         if (!nlist->lngl_idx) {
4888                 const struct ln_key_list *all[] = {
4889                         &net_props_list, &local_ni_list,
4890                         &local_ni_interfaces_list,
4891                         NULL
4892                 };
4893
4894                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
4895                                                 &lnet_family,
4896                                                 NLM_F_CREATE | NLM_F_MULTI,
4897                                                 LNET_CMD_NETS, all);
4898                 if (rc < 0) {
4899                         NL_SET_ERR_MSG(extack, "failed to send key table");
4900                         GOTO(send_error, rc);
4901                 }
4902         }
4903
4904         lnet_net_lock(LNET_LOCK_EX);
4905
4906         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4907                 struct lnet_ni *ni;
4908
4909                 if (nlist->lngl_net_id != LNET_NET_ANY &&
4910                     nlist->lngl_net_id != net->net_id)
4911                         continue;
4912
4913                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4914                         struct nlattr *local_ni, *ni_attr;
4915                         char *status = "up";
4916
4917                         if (idx++ < nlist->lngl_idx)
4918                                 continue;
4919
4920                         hdr = genlmsg_put(msg, portid, seq, &lnet_family,
4921                                           NLM_F_MULTI, LNET_CMD_NETS);
4922                         if (!hdr) {
4923                                 NL_SET_ERR_MSG(extack, "failed to send values");
4924                                 GOTO(net_unlock, rc = -EMSGSIZE);
4925                         }
4926
4927                         if (idx == 1)
4928                                 nla_put_string(msg, LNET_NET_ATTR_HDR, "");
4929
4930                         nla_put_string(msg, LNET_NET_ATTR_TYPE,
4931                                        libcfs_net2str(net->net_id));
4932                         found = true;
4933
4934                         local_ni = nla_nest_start(msg, LNET_NET_ATTR_LOCAL);
4935                         ni_attr = nla_nest_start(msg, idx - 1);
4936
4937                         lnet_ni_lock(ni);
4938                         nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_NID,
4939                                        libcfs_nidstr(&ni->ni_nid));
4940                         if (nid_is_lo0(&ni->ni_nid) &&
4941                             *ni->ni_status != LNET_NI_STATUS_UP)
4942                                 status = "down";
4943                         nla_put_string(msg, LNET_NET_LOCAL_NI_ATTR_STATUS, "up");
4944
4945                         if (!nid_is_lo0(&ni->ni_nid) && ni->ni_interface) {
4946                                 struct nlattr *intf_nest, *intf_attr;
4947
4948                                 intf_nest = nla_nest_start(msg,
4949                                                            LNET_NET_LOCAL_NI_ATTR_INTERFACE);
4950                                 intf_attr = nla_nest_start(msg, 0);
4951                                 nla_put_string(msg,
4952                                                LNET_NET_LOCAL_NI_INTF_ATTR_TYPE,
4953                                                ni->ni_interface);
4954                                 nla_nest_end(msg, intf_attr);
4955                                 nla_nest_end(msg, intf_nest);
4956                         }
4957
4958                         lnet_ni_unlock(ni);
4959                         nla_nest_end(msg, ni_attr);
4960                         nla_nest_end(msg, local_ni);
4961
4962                         genlmsg_end(msg, hdr);
4963                 }
4964         }
4965
4966         if (!found) {
4967                 struct nlmsghdr *nlh = nlmsg_hdr(msg);
4968
4969                 nlmsg_cancel(msg, nlh);
4970                 NL_SET_ERR_MSG(extack, "Network is down");
4971                 rc = -ESRCH;
4972         }
4973 net_unlock:
4974         lnet_net_unlock(LNET_LOCK_EX);
4975 send_error:
4976         nlist->lngl_idx = idx;
4977
4978         return lnet_nl_send_error(cb->skb, portid, seq, rc);
4979 }
4980
4981 #ifndef HAVE_NETLINK_CALLBACK_START
4982 static int lnet_old_net_show_dump(struct sk_buff *msg,
4983                                    struct netlink_callback *cb)
4984 {
4985         if (!cb->args[0]) {
4986                 int rc = lnet_net_show_start(cb);
4987
4988                 if (rc < 0)
4989                         return rc;
4990         }
4991
4992         return lnet_net_show_dump(msg, cb);
4993 }
4994 #endif
4995
4996 static int lnet_genl_parse_tunables(struct nlattr *settings,
4997                                     struct lnet_ioctl_config_lnd_tunables *tun)
4998 {
4999         struct nlattr *param;
5000         int rem, rc = 0;
5001
5002         nla_for_each_nested(param, settings, rem) {
5003                 int type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_UNSPEC;
5004                 s64 num;
5005
5006                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5007                         continue;
5008
5009                 if (nla_strcmp(param, "peer_timeout") == 0)
5010                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT;
5011                 else if (nla_strcmp(param, "peer_credits") == 0)
5012                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS;
5013                 else if (nla_strcmp(param, "peer_buffer_credits") == 0)
5014                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS;
5015                 else if (nla_strcmp(param, "credits") == 0)
5016                         type = LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS;
5017
5018                 param = nla_next(param, &rem);
5019                 if (nla_type(param) != LN_SCALAR_ATTR_INT_VALUE)
5020                         return -EINVAL;
5021
5022                 num = nla_get_s64(param);
5023                 switch (type) {
5024                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_TIMEOUT:
5025                         if (num >= 0)
5026                                 tun->lt_cmn.lct_peer_timeout = num;
5027                         break;
5028                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_CREDITS:
5029                         if (num > 0)
5030                                 tun->lt_cmn.lct_peer_tx_credits = num;
5031                         break;
5032                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_PEER_BUFFER_CREDITS:
5033                         if (num > 0)
5034                                 tun->lt_cmn.lct_peer_rtr_credits = num;
5035                         break;
5036                 case LNET_NET_LOCAL_NI_TUNABLES_ATTR_CREDITS:
5037                         if (num > 0)
5038                                 tun->lt_cmn.lct_max_tx_credits = num;
5039                         break;
5040                 default:
5041                         rc = -EINVAL;
5042                         break;
5043                 }
5044         }
5045         return rc;
5046 }
5047
5048 static int lnet_genl_parse_lnd_tunables(struct nlattr *settings,
5049                                         struct lnet_lnd_tunables *tun,
5050                                         const struct lnet_lnd *lnd)
5051 {
5052         const struct ln_key_list *list = lnd->lnd_keys;
5053         struct nlattr *param;
5054         int rem, rc = 0;
5055         int i = 1;
5056
5057         /* silently ignore these setting if the LND driver doesn't
5058          * support any LND tunables
5059          */
5060         if (!list || !lnd->lnd_nl_set || !list->lkl_maxattr)
5061                 return 0;
5062
5063         nla_for_each_nested(param, settings, rem) {
5064                 if (nla_type(param) != LN_SCALAR_ATTR_VALUE)
5065                         continue;
5066
5067                 for (i = 1; i <= list->lkl_maxattr; i++) {
5068                         if (!list->lkl_list[i].lkp_value ||
5069                             nla_strcmp(param, list->lkl_list[i].lkp_value) != 0)
5070                                 continue;
5071
5072                         param = nla_next(param, &rem);
5073                         rc = lnd->lnd_nl_set(LNET_CMD_NETS, param, i, tun);
5074                         if (rc < 0)
5075                                 return rc;
5076                 }
5077         }
5078
5079         return rc;
5080 }
5081
5082 static int
5083 lnet_genl_parse_local_ni(struct nlattr *entry, struct genl_info *info,
5084                          int net_id, struct lnet_ioctl_config_ni *conf,
5085                          bool *ni_list)
5086 {
5087         bool create = info->nlhdr->nlmsg_flags & NLM_F_CREATE;
5088         struct lnet_ioctl_config_lnd_tunables *tun;
5089         struct nlattr *settings;
5090         int rem3, rc = 0;
5091
5092         LIBCFS_ALLOC(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5093         if (!tun) {
5094                 GENL_SET_ERR_MSG(info, "cannot allocate memory for tunables");
5095                 GOTO(out, rc = -ENOMEM);
5096         }
5097
5098         /* Use LND defaults */
5099         tun->lt_cmn.lct_peer_timeout = -1;
5100         tun->lt_cmn.lct_peer_tx_credits = -1;
5101         tun->lt_cmn.lct_peer_rtr_credits = -1;
5102         tun->lt_cmn.lct_max_tx_credits = -1;
5103         conf->lic_ncpts = 0;
5104
5105         nla_for_each_nested(settings, entry, rem3) {
5106                 if (nla_type(settings) != LN_SCALAR_ATTR_VALUE)
5107                         continue;
5108
5109                 if (nla_strcmp(settings, "interfaces") == 0) {
5110                         struct nlattr *intf;
5111                         int rem4;
5112
5113                         settings = nla_next(settings, &rem3);
5114                         if (nla_type(settings) !=
5115                             LN_SCALAR_ATTR_LIST) {
5116                                 GENL_SET_ERR_MSG(info,
5117                                                  "invalid interfaces");
5118                                 GOTO(out, rc = -EINVAL);
5119                         }
5120
5121                         nla_for_each_nested(intf, settings, rem4) {
5122                                 intf = nla_next(intf, &rem4);
5123                                 if (nla_type(intf) !=
5124                                     LN_SCALAR_ATTR_VALUE) {
5125                                         GENL_SET_ERR_MSG(info,
5126                                                          "0 key is invalid");
5127                                         GOTO(out, rc = -EINVAL);
5128                                 }
5129
5130                                 rc = nla_strscpy(conf->lic_ni_intf, intf,
5131                                                  sizeof(conf->lic_ni_intf));
5132                                 if (rc < 0) {
5133                                         GENL_SET_ERR_MSG(info,
5134                                                          "failed to parse interfaces");
5135                                         GOTO(out, rc);
5136                                 }
5137                         }
5138                         *ni_list = true;
5139                 } else if (nla_strcmp(settings, "tunables") == 0) {
5140                         settings = nla_next(settings, &rem3);
5141                         if (nla_type(settings) !=
5142                             LN_SCALAR_ATTR_LIST) {
5143                                 GENL_SET_ERR_MSG(info,
5144                                                  "invalid tunables");
5145                                 GOTO(out, rc = -EINVAL);
5146                         }
5147
5148                         rc = lnet_genl_parse_tunables(settings, tun);
5149                         if (rc < 0) {
5150                                 GENL_SET_ERR_MSG(info,
5151                                                  "failed to parse tunables");
5152                                 GOTO(out, rc);
5153                         }
5154                 } else if ((nla_strcmp(settings, "lnd tunables") == 0)) {
5155                         const struct lnet_lnd *lnd;
5156
5157                         lnd = lnet_load_lnd(LNET_NETTYP(net_id));
5158                         if (IS_ERR(lnd)) {
5159                                 GENL_SET_ERR_MSG(info,
5160                                                  "LND type not supported");
5161                                 GOTO(out, rc = PTR_ERR(lnd));
5162                         }
5163
5164                         settings = nla_next(settings, &rem3);
5165                         if (nla_type(settings) !=
5166                             LN_SCALAR_ATTR_LIST) {
5167                                 GENL_SET_ERR_MSG(info,
5168                                                  "lnd tunables should be list\n");
5169                                 GOTO(out, rc = -EINVAL);
5170                         }
5171
5172                         rc = lnet_genl_parse_lnd_tunables(settings,
5173                                                           &tun->lt_tun, lnd);
5174                         if (rc < 0) {
5175                                 GENL_SET_ERR_MSG(info,
5176                                                  "failed to parse lnd tunables");
5177                                 GOTO(out, rc);
5178                         }
5179                 } else if (nla_strcmp(settings, "CPT") == 0) {
5180                         struct nlattr *cpt;
5181                         int rem4;
5182
5183                         settings = nla_next(settings, &rem3);
5184                         if (nla_type(settings) != LN_SCALAR_ATTR_LIST) {
5185                                 GENL_SET_ERR_MSG(info,
5186                                                  "CPT should be list");
5187                                 GOTO(out, rc = -EINVAL);
5188                         }
5189
5190                         nla_for_each_nested(cpt, settings, rem4) {
5191                                 s64 core;
5192
5193                                 if (nla_type(cpt) !=
5194                                     LN_SCALAR_ATTR_INT_VALUE) {
5195                                         GENL_SET_ERR_MSG(info,
5196                                                          "invalid CPT config");
5197                                         GOTO(out, rc = -EINVAL);
5198                                 }
5199
5200                                 core = nla_get_s64(cpt);
5201                                 if (core >= LNET_CPT_NUMBER) {
5202                                         GENL_SET_ERR_MSG(info,
5203                                                          "invalid CPT value");
5204                                         GOTO(out, rc = -ERANGE);
5205                                 }
5206
5207                                 conf->lic_cpts[conf->lic_ncpts] = core;
5208                                 conf->lic_ncpts++;
5209                         }
5210                 }
5211         }
5212
5213         if (!create) {
5214                 struct lnet_net *net;
5215                 struct lnet_ni *ni;
5216
5217                 rc = -ENODEV;
5218                 if (!strlen(conf->lic_ni_intf)) {
5219                         GENL_SET_ERR_MSG(info,
5220                                          "interface is missing");
5221                         GOTO(out, rc);
5222                 }
5223
5224                 lnet_net_lock(LNET_LOCK_EX);
5225                 net = lnet_get_net_locked(net_id);
5226                 if (!net) {
5227                         GENL_SET_ERR_MSG(info,
5228                                          "LNet net doesn't exist");
5229                         lnet_net_unlock(LNET_LOCK_EX);
5230                         GOTO(out, rc);
5231                 }
5232
5233                 list_for_each_entry(ni, &net->net_ni_list,
5234                                     ni_netlist) {
5235                         if (!ni->ni_interface ||
5236                             strcmp(ni->ni_interface,
5237                                   conf->lic_ni_intf) != 0)
5238                                 continue;
5239
5240                         lnet_net_unlock(LNET_LOCK_EX);
5241                         rc = lnet_dyn_del_ni(&ni->ni_nid);
5242                         if (rc < 0) {
5243                                 GENL_SET_ERR_MSG(info,
5244                                                  "cannot del LNet NI");
5245                                 GOTO(out, rc);
5246                         }
5247                         break;
5248                 }
5249
5250                 if (rc < 0) { /* will be -ENODEV */
5251                         GENL_SET_ERR_MSG(info,
5252                                          "interface invalid for deleting LNet NI");
5253                         lnet_net_unlock(LNET_LOCK_EX);
5254                 }
5255         } else {
5256                 if (!strlen(conf->lic_ni_intf)) {
5257                         GENL_SET_ERR_MSG(info,
5258                                          "interface is missing");
5259                         GOTO(out, rc);
5260                 }
5261
5262                 rc = lnet_dyn_add_ni(conf, net_id, tun);
5263                 switch (rc) {
5264                 case -ENOENT:
5265                         GENL_SET_ERR_MSG(info,
5266                                          "cannot parse net");
5267                         break;
5268                 case -ERANGE:
5269                         GENL_SET_ERR_MSG(info,
5270                                          "invalid CPT set");
5271                         break;
5272                 default:
5273                         GENL_SET_ERR_MSG(info,
5274                                          "cannot add LNet NI");
5275                 case 0:
5276                         break;
5277                 }
5278         }
5279 out:
5280         if (tun)
5281                 LIBCFS_FREE(tun, sizeof(struct lnet_ioctl_config_lnd_tunables));
5282
5283         return rc;
5284 }
5285
5286 static int lnet_net_cmd(struct sk_buff *skb, struct genl_info *info)
5287 {
5288         struct nlmsghdr *nlh = nlmsg_hdr(skb);
5289         struct genlmsghdr *gnlh = nlmsg_data(nlh);
5290         struct nlattr *params = genlmsg_data(gnlh);
5291         int msg_len, rem, rc = 0;
5292         struct nlattr *attr;
5293
5294         msg_len = genlmsg_len(gnlh);
5295         if (!msg_len) {
5296                 GENL_SET_ERR_MSG(info, "no configuration");
5297                 return -ENOMSG;
5298         }
5299
5300         if (!(nla_type(params) & LN_SCALAR_ATTR_LIST)) {
5301                 GENL_SET_ERR_MSG(info, "invalid configuration");
5302                 return -EINVAL;
5303         }
5304
5305         nla_for_each_nested(attr, params, rem) {
5306                 struct lnet_ioctl_config_ni conf;
5307                 u32 net_id = LNET_NET_ANY;
5308                 struct nlattr *entry;
5309                 bool ni_list = false;
5310                 int rem2;
5311
5312                 if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
5313                         continue;
5314
5315                 nla_for_each_nested(entry, attr, rem2) {
5316                         switch (nla_type(entry)) {
5317                         case LN_SCALAR_ATTR_VALUE: {
5318                                 ssize_t len;
5319
5320                                 memset(&conf, 0, sizeof(conf));
5321                                 if (nla_strcmp(entry, "ip2net") == 0) {
5322                                         entry = nla_next(entry, &rem2);
5323                                         if (nla_type(entry) !=
5324                                             LN_SCALAR_ATTR_VALUE) {
5325                                                 GENL_SET_ERR_MSG(info,
5326                                                                  "ip2net has invalid key");
5327                                                 GOTO(out, rc = -EINVAL);
5328                                         }
5329
5330                                         len = nla_strscpy(conf.lic_legacy_ip2nets,
5331                                                           entry,
5332                                                           sizeof(conf.lic_legacy_ip2nets));
5333                                         if (len < 0) {
5334                                                 GENL_SET_ERR_MSG(info,
5335                                                                  "ip2net key string is invalid");
5336                                                 GOTO(out, rc = len);
5337                                         }
5338                                         ni_list = true;
5339                                 } else if (nla_strcmp(entry, "net type") == 0) {
5340                                         char tmp[LNET_NIDSTR_SIZE];
5341
5342                                         entry = nla_next(entry, &rem2);
5343                                         if (nla_type(entry) !=
5344                                             LN_SCALAR_ATTR_VALUE) {
5345                                                 GENL_SET_ERR_MSG(info,
5346                                                                  "net type has invalid key");
5347                                                 GOTO(out, rc = -EINVAL);
5348                                         }
5349
5350                                         len = nla_strscpy(tmp, entry,
5351                                                           sizeof(tmp));
5352                                         if (len < 0) {
5353                                                 GENL_SET_ERR_MSG(info,
5354                                                                  "net type key string is invalid");
5355                                                 GOTO(out, rc = len);
5356                                         }
5357
5358                                         net_id = libcfs_str2net(tmp);
5359                                         if (!net_id) {
5360                                                 GENL_SET_ERR_MSG(info,
5361                                                                  "cannot parse net");
5362                                                 GOTO(out, rc = -ENODEV);
5363                                         }
5364                                         if (LNET_NETTYP(net_id) == LOLND) {
5365                                                 GENL_SET_ERR_MSG(info,
5366                                                                  "setting @lo not allowed");
5367                                                 GOTO(out, rc = -ENODEV);
5368                                         }
5369                                         conf.lic_legacy_ip2nets[0] = '\0';
5370                                         conf.lic_ni_intf[0] = '\0';
5371                                         ni_list = false;
5372                                 }
5373                                 if (rc < 0)
5374                                         GOTO(out, rc);
5375                                 break;
5376                         }
5377                         case LN_SCALAR_ATTR_LIST: {
5378                                 struct nlattr *interface;
5379                                 int rem3;
5380
5381                                 nla_for_each_nested(interface, entry, rem3) {
5382                                         rc = lnet_genl_parse_local_ni(interface, info,
5383                                                                       net_id, &conf,
5384                                                                       &ni_list);
5385                                         if (rc < 0)
5386                                                 GOTO(out, rc);
5387                                 }
5388                                 break;
5389                         }
5390                         /* it is possible a newer version of the user land send
5391                          * values older kernels doesn't handle. So silently
5392                          * ignore these values
5393                          */
5394                         default:
5395                                 break;
5396                         }
5397                 }
5398
5399                 /* Handle case of just sent NET with no list of NIDs */
5400                 if (!(info->nlhdr->nlmsg_flags & NLM_F_CREATE) && !ni_list) {
5401                         rc = lnet_dyn_del_net(net_id);
5402                         if (rc < 0) {
5403                                 GENL_SET_ERR_MSG(info,
5404                                                  "cannot del network");
5405                         }
5406                 }
5407         }
5408 out:
5409         return rc;
5410 }
5411
5412 /** LNet route handling */
5413
5414 /* We can't use struct lnet_ioctl_config_data since it lacks
5415  * support for large NIDS
5416  */
5417 struct lnet_route_properties {
5418         struct lnet_nid         lrp_gateway;
5419         u32                     lrp_net;
5420         s32                     lrp_hop;
5421         u32                     lrp_flags;
5422         u32                     lrp_priority;
5423         u32                     lrp_sensitivity;
5424 };
5425
5426 struct lnet_genl_route_list {
5427         unsigned int                            lgrl_index;
5428         unsigned int                            lgrl_count;
5429         GENRADIX(struct lnet_route_properties)  lgrl_list;
5430 };
5431
5432 static inline struct lnet_genl_route_list *
5433 lnet_route_dump_ctx(struct netlink_callback *cb)
5434 {
5435         return (struct lnet_genl_route_list *)cb->args[0];
5436 }
5437
5438 static int lnet_route_show_done(struct netlink_callback *cb)
5439 {
5440         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
5441
5442         if (rlist) {
5443                 genradix_free(&rlist->lgrl_list);
5444                 CFS_FREE_PTR(rlist);
5445         }
5446         cb->args[0] = 0;
5447
5448         return 0;
5449 }
5450
5451 static int lnet_scan_route(struct lnet_genl_route_list *rlist,
5452                     struct lnet_route_properties *settings)
5453 {
5454         struct lnet_remotenet *rnet;
5455         struct list_head *rn_list;
5456         struct lnet_route *route;
5457         int cpt, i, rc = 0;
5458
5459         cpt = lnet_net_lock_current();
5460
5461         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++) {
5462                 rn_list = &the_lnet.ln_remote_nets_hash[i];
5463                 list_for_each_entry(rnet, rn_list, lrn_list) {
5464                         if (settings->lrp_net != LNET_NET_ANY &&
5465                             settings->lrp_net != rnet->lrn_net)
5466                                 continue;
5467
5468                         list_for_each_entry(route, &rnet->lrn_routes,
5469                                             lr_list) {
5470                                 struct lnet_route_properties *prop;
5471
5472                                 if (!LNET_NID_IS_ANY(&settings->lrp_gateway) &&
5473                                     !nid_same(&settings->lrp_gateway,
5474                                               &route->lr_nid)) {
5475                                         continue;
5476                                 }
5477
5478                                 if (settings->lrp_hop != -1 &&
5479                                     settings->lrp_hop != route->lr_hops)
5480                                         continue;
5481
5482                                 if (settings->lrp_priority != -1 &&
5483                                     settings->lrp_priority != route->lr_priority)
5484                                         continue;
5485
5486                                 if (settings->lrp_sensitivity != -1 &&
5487                                     settings->lrp_sensitivity !=
5488                                     route->lr_gateway->lp_health_sensitivity)
5489                                         continue;
5490
5491                                 prop = genradix_ptr_alloc(&rlist->lgrl_list,
5492                                                           rlist->lgrl_count++,
5493                                                           GFP_KERNEL);
5494                                 if (!prop)
5495                                         GOTO(failed_alloc, rc = -ENOMEM);
5496
5497                                 prop->lrp_net = rnet->lrn_net;
5498                                 prop->lrp_gateway = route->lr_nid;
5499                                 prop->lrp_hop = route->lr_hops;
5500                                 prop->lrp_priority = route->lr_priority;
5501                                 prop->lrp_sensitivity =
5502                                         route->lr_gateway->lp_health_sensitivity;
5503                                 if (lnet_is_route_alive(route))
5504                                         prop->lrp_flags |= LNET_RT_ALIVE;
5505                                 else
5506                                         prop->lrp_flags &= ~LNET_RT_ALIVE;
5507                                 if (route->lr_single_hop)
5508                                         prop->lrp_flags &= ~LNET_RT_MULTI_HOP;
5509                                 else
5510                                         prop->lrp_flags |= LNET_RT_MULTI_HOP;
5511                         }
5512                 }
5513         }
5514
5515 failed_alloc:
5516         lnet_net_unlock(cpt);
5517         return rc;
5518 }
5519
5520 /* LNet route ->start() handler for GET requests */
5521 static int lnet_route_show_start(struct netlink_callback *cb)
5522 {
5523         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5524 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5525         struct netlink_ext_ack *extack = NULL;
5526 #endif
5527         struct lnet_genl_route_list *rlist;
5528         int msg_len = genlmsg_len(gnlh);
5529         int rc = 0;
5530
5531 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5532         extack = cb->extack;
5533 #endif
5534         if (the_lnet.ln_refcount == 0 ||
5535             the_lnet.ln_state != LNET_STATE_RUNNING) {
5536                 NL_SET_ERR_MSG(extack, "Network is down");
5537                 return -ENETDOWN;
5538         }
5539
5540         CFS_ALLOC_PTR(rlist);
5541         if (!rlist) {
5542                 NL_SET_ERR_MSG(extack, "No memory for route list");
5543                 return -ENOMEM;
5544         }
5545
5546         genradix_init(&rlist->lgrl_list);
5547         rlist->lgrl_count = 0;
5548         rlist->lgrl_index = 0;
5549         cb->args[0] = (long)rlist;
5550
5551         mutex_lock(&the_lnet.ln_api_mutex);
5552         if (!msg_len) {
5553                 struct lnet_route_properties tmp = {
5554                         .lrp_gateway            = LNET_ANY_NID,
5555                         .lrp_net                = LNET_NET_ANY,
5556                         .lrp_hop                = -1,
5557                         .lrp_priority           = -1,
5558                         .lrp_sensitivity        = -1,
5559                 };
5560
5561                 rc = lnet_scan_route(rlist, &tmp);
5562                 if (rc < 0) {
5563                         NL_SET_ERR_MSG(extack,
5564                                        "failed to allocate router data");
5565                         GOTO(report_err, rc);
5566                 }
5567         } else {
5568                 struct nlattr *params = genlmsg_data(gnlh);
5569                 struct nlattr *attr;
5570                 int rem;
5571
5572                 nla_for_each_nested(attr, params, rem) {
5573                         struct lnet_route_properties tmp = {
5574                                 .lrp_gateway            = LNET_ANY_NID,
5575                                 .lrp_net                = LNET_NET_ANY,
5576                                 .lrp_hop                = -1,
5577                                 .lrp_priority           = -1,
5578                                 .lrp_sensitivity        = -1,
5579                         };
5580                         struct nlattr *route;
5581                         int rem2;
5582
5583                         if (nla_type(attr) != LN_SCALAR_ATTR_LIST)
5584                                 continue;
5585
5586                         nla_for_each_nested(route, attr, rem2) {
5587                                 if (nla_type(route) != LN_SCALAR_ATTR_VALUE)
5588                                         continue;
5589
5590                                 if (nla_strcmp(route, "net") == 0) {
5591                                         char nw[LNET_NIDSTR_SIZE];
5592
5593                                         route = nla_next(route, &rem2);
5594                                         if (nla_type(route) !=
5595                                             LN_SCALAR_ATTR_VALUE) {
5596                                                 NL_SET_ERR_MSG(extack,
5597                                                                "invalid net param");
5598                                                 GOTO(report_err, rc = -EINVAL);
5599                                         }
5600
5601                                         rc = nla_strscpy(nw, route, sizeof(nw));
5602                                         if (rc < 0) {
5603                                                 NL_SET_ERR_MSG(extack,
5604                                                                "failed to get route param");
5605                                                 GOTO(report_err, rc);
5606                                         }
5607                                         rc = 0;
5608                                         tmp.lrp_net = libcfs_str2net(strim(nw));
5609                                 } else if (nla_strcmp(route, "gateway") == 0) {
5610                                         char gw[LNET_NIDSTR_SIZE];
5611
5612                                         route = nla_next(route, &rem2);
5613                                         if (nla_type(route) !=
5614                                             LN_SCALAR_ATTR_VALUE) {
5615                                                 NL_SET_ERR_MSG(extack,
5616                                                                "invalid gateway param");
5617                                                 GOTO(report_err, rc = -EINVAL);
5618                                         }
5619
5620                                         rc = nla_strscpy(gw, route, sizeof(gw));
5621                                         if (rc < 0) {
5622                                                 NL_SET_ERR_MSG(extack,
5623                                                                "failed to get route param");
5624                                                 GOTO(report_err, rc);
5625                                         }
5626                                         rc = 0;
5627                                         libcfs_strnid(&tmp.lrp_gateway, strim(gw));
5628                                 } else if (nla_strcmp(route, "hop") == 0) {
5629                                         route = nla_next(route, &rem2);
5630                                         if (nla_type(route) !=
5631                                             LN_SCALAR_ATTR_INT_VALUE) {
5632                                                 NL_SET_ERR_MSG(extack,
5633                                                                "invalid hop param");
5634                                                 GOTO(report_err, rc = -EINVAL);
5635                                         }
5636
5637                                         tmp.lrp_hop = nla_get_s64(route);
5638                                         if (tmp.lrp_hop != -1)
5639                                                 clamp_t(s32, tmp.lrp_hop, 1, 127);
5640                                 } else if (nla_strcmp(route, "priority") == 0) {
5641                                         route = nla_next(route, &rem2);
5642                                         if (nla_type(route) !=
5643                                             LN_SCALAR_ATTR_INT_VALUE) {
5644                                                 NL_SET_ERR_MSG(extack,
5645                                                                "invalid priority param");
5646                                                 GOTO(report_err, rc = -EINVAL);
5647                                         }
5648
5649                                         tmp.lrp_priority = nla_get_s64(route);
5650                                 }
5651                         }
5652
5653                         rc = lnet_scan_route(rlist, &tmp);
5654                         if (rc < 0) {
5655                                 NL_SET_ERR_MSG(extack,
5656                                                "failed to allocate router data");
5657                                 GOTO(report_err, rc);
5658                         }
5659                 }
5660         }
5661 report_err:
5662         mutex_unlock(&the_lnet.ln_api_mutex);
5663
5664         if (rc < 0)
5665                 lnet_route_show_done(cb);
5666
5667         return rc;
5668 }
5669
5670 static const struct ln_key_list route_props_list = {
5671         .lkl_maxattr                    = LNET_ROUTE_ATTR_MAX,
5672         .lkl_list                       = {
5673                 [LNET_ROUTE_ATTR_HDR]                   = {
5674                         .lkp_value                      = "route",
5675                         .lkp_key_format                 = LNKF_SEQUENCE | LNKF_MAPPING,
5676                         .lkp_data_type                  = NLA_NUL_STRING,
5677                 },
5678                 [LNET_ROUTE_ATTR_NET]                   = {
5679                         .lkp_value                      = "net",
5680                         .lkp_data_type                  = NLA_STRING
5681                 },
5682                 [LNET_ROUTE_ATTR_GATEWAY]               = {
5683                         .lkp_value                      = "gateway",
5684                         .lkp_data_type                  = NLA_STRING
5685                 },
5686                 [LNET_ROUTE_ATTR_HOP]                   = {
5687                         .lkp_value                      = "hop",
5688                         .lkp_data_type                  = NLA_S32
5689                 },
5690                 [LNET_ROUTE_ATTR_PRIORITY]              = {
5691                         .lkp_value                      = "priority",
5692                         .lkp_data_type                  = NLA_U32
5693                 },
5694                 [LNET_ROUTE_ATTR_HEALTH_SENSITIVITY]    = {
5695                         .lkp_value                      = "health_sensitivity",
5696                         .lkp_data_type                  = NLA_U32
5697                 },
5698                 [LNET_ROUTE_ATTR_STATE] = {
5699                         .lkp_value                      = "state",
5700                         .lkp_data_type                  = NLA_STRING,
5701                 },
5702                 [LNET_ROUTE_ATTR_TYPE]  = {
5703                         .lkp_value                      = "type",
5704                         .lkp_data_type                  = NLA_STRING,
5705                 },
5706         },
5707 };
5708
5709
5710 static int lnet_route_show_dump(struct sk_buff *msg,
5711                                 struct netlink_callback *cb)
5712 {
5713         struct lnet_genl_route_list *rlist = lnet_route_dump_ctx(cb);
5714         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5715 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5716         struct netlink_ext_ack *extack = NULL;
5717 #endif
5718         int portid = NETLINK_CB(cb->skb).portid;
5719         int seq = cb->nlh->nlmsg_seq;
5720         int idx = rlist->lgrl_index;
5721         int rc = 0;
5722
5723 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5724         extack = cb->extack;
5725 #endif
5726         if (!rlist->lgrl_count) {
5727                 NL_SET_ERR_MSG(extack, "No routes found");
5728                 GOTO(send_error, rc = -ENOENT);
5729         }
5730
5731         if (!idx) {
5732                 const struct ln_key_list *all[] = {
5733                         &route_props_list, NULL
5734                 };
5735
5736                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
5737                                                 &lnet_family,
5738                                                 NLM_F_CREATE | NLM_F_MULTI,
5739                                                 LNET_CMD_ROUTES, all);
5740                 if (rc < 0) {
5741                         NL_SET_ERR_MSG(extack, "failed to send key table");
5742                         GOTO(send_error, rc);
5743                 }
5744         }
5745
5746         /* If not routes found send an empty message and not an error */
5747         if (!rlist->lgrl_count) {
5748                 void *hdr;
5749
5750                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5751                                   NLM_F_MULTI, LNET_CMD_ROUTES);
5752                 if (!hdr) {
5753                         NL_SET_ERR_MSG(extack, "failed to send values");
5754                         genlmsg_cancel(msg, hdr);
5755                         GOTO(send_error, rc = -EMSGSIZE);
5756                 }
5757                 genlmsg_end(msg, hdr);
5758
5759                 goto send_error;
5760         }
5761
5762         while (idx < rlist->lgrl_count) {
5763                 struct lnet_route_properties *prop;
5764                 void *hdr;
5765
5766                 prop = genradix_ptr(&rlist->lgrl_list, idx++);
5767
5768                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
5769                                   NLM_F_MULTI, LNET_CMD_ROUTES);
5770                 if (!hdr) {
5771                         NL_SET_ERR_MSG(extack, "failed to send values");
5772                         genlmsg_cancel(msg, hdr);
5773                         GOTO(send_error, rc = -EMSGSIZE);
5774                 }
5775
5776                 if (idx == 1)
5777                         nla_put_string(msg, LNET_ROUTE_ATTR_HDR, "");
5778
5779                 nla_put_string(msg, LNET_ROUTE_ATTR_NET,
5780                                libcfs_net2str(prop->lrp_net));
5781                 nla_put_string(msg, LNET_ROUTE_ATTR_GATEWAY,
5782                                libcfs_nidstr(&prop->lrp_gateway));
5783                 if (gnlh->version) {
5784                         nla_put_s32(msg, LNET_ROUTE_ATTR_HOP, prop->lrp_hop);
5785                         nla_put_u32(msg, LNET_ROUTE_ATTR_PRIORITY, prop->lrp_priority);
5786                         nla_put_u32(msg, LNET_ROUTE_ATTR_HEALTH_SENSITIVITY,
5787                                     prop->lrp_sensitivity);
5788
5789                         nla_put_string(msg, LNET_ROUTE_ATTR_STATE,
5790                                        prop->lrp_flags & LNET_RT_ALIVE ?
5791                                        "up" : "down");
5792                         nla_put_string(msg, LNET_ROUTE_ATTR_TYPE,
5793                                        prop->lrp_flags & LNET_RT_MULTI_HOP ?
5794                                        "multi-hop" : "single-hop");
5795                 }
5796                 genlmsg_end(msg, hdr);
5797         }
5798         rlist->lgrl_index = idx;
5799 send_error:
5800         return lnet_nl_send_error(cb->skb, portid, seq, rc);
5801 };
5802
5803 #ifndef HAVE_NETLINK_CALLBACK_START
5804 static int lnet_old_route_show_dump(struct sk_buff *msg,
5805                                     struct netlink_callback *cb)
5806 {
5807         if (!cb->args[0]) {
5808                 int rc = lnet_route_show_start(cb);
5809
5810                 if (rc < 0)
5811                         return rc;
5812         }
5813
5814         return lnet_route_show_dump(msg, cb);
5815 }
5816 #endif /* !HAVE_NETLINK_CALLBACK_START */
5817
5818 static inline struct lnet_genl_ping_list *
5819 lnet_ping_dump_ctx(struct netlink_callback *cb)
5820 {
5821         return (struct lnet_genl_ping_list *)cb->args[0];
5822 }
5823
5824 static int lnet_ping_show_done(struct netlink_callback *cb)
5825 {
5826         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
5827
5828         if (plist) {
5829                 genradix_free(&plist->lgpl_failed);
5830                 genradix_free(&plist->lgpl_list);
5831                 LIBCFS_FREE(plist, sizeof(*plist));
5832                 cb->args[0] = 0;
5833         }
5834
5835         return 0;
5836 }
5837
5838 /* LNet ping ->start() handler for GET requests */
5839 static int lnet_ping_show_start(struct netlink_callback *cb)
5840 {
5841         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
5842 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
5843         struct netlink_ext_ack *extack = NULL;
5844 #endif
5845         struct lnet_genl_ping_list *plist;
5846         int msg_len = genlmsg_len(gnlh);
5847         struct nlattr *params, *top;
5848         int rem, rc = 0;
5849
5850 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
5851         extack = cb->extack;
5852 #endif
5853         if (the_lnet.ln_refcount == 0) {
5854                 NL_SET_ERR_MSG(extack, "Network is down");
5855                 return -ENETDOWN;
5856         }
5857
5858         if (!msg_len) {
5859                 NL_SET_ERR_MSG(extack, "Ping needs NID targets");
5860                 return -ENOENT;
5861         }
5862
5863         LIBCFS_ALLOC(plist, sizeof(*plist));
5864         if (!plist) {
5865                 NL_SET_ERR_MSG(extack, "failed to setup ping list");
5866                 return -ENOMEM;
5867         }
5868         genradix_init(&plist->lgpl_list);
5869         plist->lgpl_timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
5870         plist->lgpl_src_nid = LNET_ANY_NID;
5871         plist->lgpl_index = 0;
5872         plist->lgpl_list_count = 0;
5873         cb->args[0] = (long)plist;
5874
5875         params = genlmsg_data(gnlh);
5876         nla_for_each_attr(top, params, msg_len, rem) {
5877                 struct nlattr *nids;
5878                 int rem2;
5879
5880                 switch (nla_type(top)) {
5881                 case LN_SCALAR_ATTR_VALUE:
5882                         if (nla_strcmp(top, "timeout") == 0) {
5883                                 s64 timeout;
5884
5885                                 top = nla_next(top, &rem);
5886                                 if (nla_type(top) != LN_SCALAR_ATTR_INT_VALUE) {
5887                                         NL_SET_ERR_MSG(extack,
5888                                                        "invalid timeout param");
5889                                         GOTO(report_err, rc = -EINVAL);
5890                                 }
5891
5892                                 /* If timeout is negative then set default of
5893                                  * 3 minutes
5894                                  */
5895                                 timeout = nla_get_s64(top);
5896                                 if (timeout > 0 &&
5897                                     timeout < (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
5898                                         plist->lgpl_timeout =
5899                                                 nsecs_to_jiffies(timeout * NSEC_PER_MSEC);
5900                         } else if (nla_strcmp(top, "source") == 0) {
5901                                 char nidstr[LNET_NIDSTR_SIZE + 1];
5902
5903                                 top = nla_next(top, &rem);
5904                                 if (nla_type(top) != LN_SCALAR_ATTR_VALUE) {
5905                                         NL_SET_ERR_MSG(extack,
5906                                                        "invalid source param");
5907                                         GOTO(report_err, rc = -EINVAL);
5908                                 }
5909
5910                                 rc = nla_strscpy(nidstr, top, sizeof(nidstr));
5911                                 if (rc < 0) {
5912                                         NL_SET_ERR_MSG(extack,
5913                                                        "failed to parse source nid");
5914                                         GOTO(report_err, rc);
5915                                 }
5916
5917                                 rc = libcfs_strnid(&plist->lgpl_src_nid,
5918                                                    strim(nidstr));
5919                                 if (rc < 0) {
5920                                         NL_SET_ERR_MSG(extack,
5921                                                        "invalid source nid");
5922                                         GOTO(report_err, rc);
5923                                 }
5924                                 rc = 0;
5925                         }
5926                         break;
5927                 case LN_SCALAR_ATTR_LIST:
5928                         nla_for_each_nested(nids, top, rem2) {
5929                                 char nid[LNET_NIDSTR_SIZE + 1];
5930                                 struct lnet_processid *id;
5931
5932                                 if (nla_type(nids) != LN_SCALAR_ATTR_VALUE)
5933                                         continue;
5934
5935                                 memset(nid, 0, sizeof(nid));
5936                                 rc = nla_strscpy(nid, nids, sizeof(nid));
5937                                 if (rc < 0) {
5938                                         NL_SET_ERR_MSG(extack,
5939                                                        "failed to get NID");
5940                                         GOTO(report_err, rc);
5941                                 }
5942
5943                                 id = genradix_ptr_alloc(&plist->lgpl_list,
5944                                                         plist->lgpl_list_count++,
5945                                                         GFP_ATOMIC);
5946                                 if (!id) {
5947                                         NL_SET_ERR_MSG(extack,
5948                                                        "failed to allocate NID");
5949                                         GOTO(report_err, rc = -ENOMEM);
5950                                 }
5951
5952                                 rc = libcfs_strid(id, strim(nid));
5953                                 if (rc < 0) {
5954                                         NL_SET_ERR_MSG(extack, "invalid NID");
5955                                         GOTO(report_err, rc);
5956                                 }
5957                                 rc = 0;
5958                         }
5959                         fallthrough;
5960                 default:
5961                         break;
5962                 }
5963         }
5964 report_err:
5965         if (rc < 0)
5966                 lnet_ping_show_done(cb);
5967
5968         return rc;
5969 }
5970
5971 static const struct ln_key_list ping_props_list = {
5972         .lkl_maxattr                    = LNET_PING_ATTR_MAX,
5973         .lkl_list                       = {
5974                 [LNET_PING_ATTR_HDR]            = {
5975                         .lkp_value              = "ping",
5976                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5977                         .lkp_data_type          = NLA_NUL_STRING,
5978                 },
5979                 [LNET_PING_ATTR_PRIMARY_NID]    = {
5980                         .lkp_value              = "primary nid",
5981                         .lkp_data_type          = NLA_STRING
5982                 },
5983                 [LNET_PING_ATTR_ERRNO]          = {
5984                         .lkp_value              = "errno",
5985                         .lkp_data_type          = NLA_S16
5986                 },
5987                 [LNET_PING_ATTR_MULTIRAIL]      = {
5988                         .lkp_value              = "Multi-Rail",
5989                         .lkp_data_type          = NLA_FLAG
5990                 },
5991                 [LNET_PING_ATTR_PEER_NI_LIST]   = {
5992                         .lkp_value              = "peer_ni",
5993                         .lkp_key_format         = LNKF_SEQUENCE | LNKF_MAPPING,
5994                         .lkp_data_type          = NLA_NESTED
5995                 },
5996         },
5997 };
5998
5999 static struct ln_key_list ping_peer_ni_list = {
6000         .lkl_maxattr                    = LNET_PING_PEER_NI_ATTR_MAX,
6001         .lkl_list                       = {
6002                 [LNET_PING_PEER_NI_ATTR_NID]    = {
6003                         .lkp_value              = "nid",
6004                         .lkp_data_type          = NLA_STRING
6005                 },
6006         },
6007 };
6008
6009 static int lnet_ping_show_dump(struct sk_buff *msg,
6010                                struct netlink_callback *cb)
6011 {
6012         struct lnet_genl_ping_list *plist = lnet_ping_dump_ctx(cb);
6013         struct genlmsghdr *gnlh = nlmsg_data(cb->nlh);
6014 #ifdef HAVE_NL_PARSE_WITH_EXT_ACK
6015         struct netlink_ext_ack *extack = NULL;
6016 #endif
6017         int portid = NETLINK_CB(cb->skb).portid;
6018         int seq = cb->nlh->nlmsg_seq;
6019         int idx = plist->lgpl_index;
6020         int rc = 0, i = 0;
6021
6022 #ifdef HAVE_NL_DUMP_WITH_EXT_ACK
6023         extack = cb->extack;
6024 #endif
6025         if (!plist->lgpl_index) {
6026                 const struct ln_key_list *all[] = {
6027                         &ping_props_list, &ping_peer_ni_list, NULL
6028                 };
6029
6030                 rc = lnet_genl_send_scalar_list(msg, portid, seq,
6031                                                 &lnet_family,
6032                                                 NLM_F_CREATE | NLM_F_MULTI,
6033                                                 LNET_CMD_PING, all);
6034                 if (rc < 0) {
6035                         NL_SET_ERR_MSG(extack, "failed to send key table");
6036                         GOTO(send_error, rc);
6037                 }
6038
6039                 genradix_init(&plist->lgpl_failed);
6040         }
6041
6042         while (idx < plist->lgpl_list_count) {
6043                 struct lnet_nid primary_nid = LNET_ANY_NID;
6044                 struct lnet_genl_ping_list peers;
6045                 struct lnet_processid *id;
6046                 struct nlattr *nid_list;
6047                 struct lnet_peer *lp;
6048                 bool mr_flag = false;
6049                 unsigned int count;
6050                 void *hdr = NULL;
6051
6052                 id = genradix_ptr(&plist->lgpl_list, idx++);
6053                 if (nid_is_lo0(&id->nid))
6054                         continue;
6055
6056                 rc = lnet_ping(id, &plist->lgpl_src_nid, plist->lgpl_timeout,
6057                                &peers, lnet_interfaces_max);
6058                 if (rc < 0) {
6059                         struct lnet_fail_ping *fail;
6060
6061                         fail = genradix_ptr_alloc(&plist->lgpl_failed,
6062                                                   plist->lgpl_failed_count++,
6063                                                   GFP_ATOMIC);
6064                         if (!fail) {
6065                                 NL_SET_ERR_MSG(extack,
6066                                                "failed to allocate failed NID");
6067                                 GOTO(send_error, rc);
6068                         }
6069                         fail->lfp_id = *id;
6070                         fail->lfp_errno = rc;
6071                         goto cant_reach;
6072                 }
6073
6074                 mutex_lock(&the_lnet.ln_api_mutex);
6075                 lp = lnet_find_peer(&id->nid);
6076                 if (lp) {
6077                         primary_nid = lp->lp_primary_nid;
6078                         mr_flag = lnet_peer_is_multi_rail(lp);
6079                         lnet_peer_decref_locked(lp);
6080                 }
6081                 mutex_unlock(&the_lnet.ln_api_mutex);
6082
6083                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6084                                   NLM_F_MULTI, LNET_CMD_PING);
6085                 if (!hdr) {
6086                         NL_SET_ERR_MSG(extack, "failed to send values");
6087                         genlmsg_cancel(msg, hdr);
6088                         GOTO(send_error, rc = -EMSGSIZE);
6089                 }
6090
6091                 if (i++ == 0)
6092                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
6093
6094                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
6095                                libcfs_nidstr(&primary_nid));
6096                 if (mr_flag)
6097                         nla_put_flag(msg, LNET_PING_ATTR_MULTIRAIL);
6098
6099                 nid_list = nla_nest_start(msg, LNET_PING_ATTR_PEER_NI_LIST);
6100                 for (count = 0; count < rc; count++) {
6101                         struct lnet_processid *result;
6102                         struct nlattr *nid_attr;
6103                         char *idstr;
6104
6105                         result = genradix_ptr(&peers.lgpl_list, count);
6106                         if (nid_is_lo0(&result->nid))
6107                                 continue;
6108
6109                         nid_attr = nla_nest_start(msg, count + 1);
6110                         if (gnlh->version == 1)
6111                                 idstr = libcfs_nidstr(&result->nid);
6112                         else
6113                                 idstr = libcfs_idstr(result);
6114                         nla_put_string(msg, LNET_PING_PEER_NI_ATTR_NID, idstr);
6115                         nla_nest_end(msg, nid_attr);
6116                 }
6117                 nla_nest_end(msg, nid_list);
6118                 genlmsg_end(msg, hdr);
6119 cant_reach:
6120                 genradix_free(&peers.lgpl_list);
6121         }
6122
6123         for (i = 0; i < plist->lgpl_failed_count; i++) {
6124                 struct lnet_fail_ping *fail;
6125                 void *hdr;
6126
6127                 fail = genradix_ptr(&plist->lgpl_failed, i);
6128
6129                 hdr = genlmsg_put(msg, portid, seq, &lnet_family,
6130                                   NLM_F_MULTI, LNET_CMD_PING);
6131                 if (!hdr) {
6132                         NL_SET_ERR_MSG(extack, "failed to send failed values");
6133                         genlmsg_cancel(msg, hdr);
6134                         GOTO(send_error, rc = -EMSGSIZE);
6135                 }
6136
6137                 if (i == 0)
6138                         nla_put_string(msg, LNET_PING_ATTR_HDR, "");
6139
6140                 nla_put_string(msg, LNET_PING_ATTR_PRIMARY_NID,
6141                                libcfs_nidstr(&fail->lfp_id.nid));
6142                 nla_put_s16(msg, LNET_PING_ATTR_ERRNO, fail->lfp_errno);
6143                 genlmsg_end(msg, hdr);
6144         }
6145         rc = 0; /* don't treat it as an error */
6146
6147         plist->lgpl_index = idx;
6148 send_error:
6149         return lnet_nl_send_error(cb->skb, portid, seq, rc);
6150 }
6151
6152 #ifndef HAVE_NETLINK_CALLBACK_START
6153 static int lnet_old_ping_show_dump(struct sk_buff *msg,
6154                                    struct netlink_callback *cb)
6155 {
6156         if (!cb->args[0]) {
6157                 int rc = lnet_ping_show_start(cb);
6158
6159                 if (rc < 0)
6160                         return rc;
6161         }
6162
6163         return lnet_ping_show_dump(msg, cb);
6164 }
6165 #endif
6166
6167 static const struct genl_multicast_group lnet_mcast_grps[] = {
6168         { .name =       "ip2net",       },
6169         { .name =       "net",          },
6170         { .name =       "route",        },
6171         { .name =       "ping",         },
6172 };
6173
6174 static const struct genl_ops lnet_genl_ops[] = {
6175         {
6176                 .cmd            = LNET_CMD_NETS,
6177                 .flags          = GENL_ADMIN_PERM,
6178 #ifdef HAVE_NETLINK_CALLBACK_START
6179                 .start          = lnet_net_show_start,
6180                 .dumpit         = lnet_net_show_dump,
6181 #else
6182                 .dumpit         = lnet_old_net_show_dump,
6183 #endif
6184                 .done           = lnet_net_show_done,
6185                 .doit           = lnet_net_cmd,
6186         },
6187         {
6188                 .cmd            = LNET_CMD_ROUTES,
6189 #ifdef HAVE_NETLINK_CALLBACK_START
6190                 .start          = lnet_route_show_start,
6191                 .dumpit         = lnet_route_show_dump,
6192 #else
6193                 .dumpit         = lnet_old_route_show_dump,
6194 #endif
6195                 .done           = lnet_route_show_done,
6196         },
6197         {
6198                 .cmd            = LNET_CMD_PING,
6199 #ifdef HAVE_NETLINK_CALLBACK_START
6200                 .start          = lnet_ping_show_start,
6201                 .dumpit         = lnet_ping_show_dump,
6202 #else
6203                 .dumpit         = lnet_old_ping_show_dump,
6204 #endif
6205                 .done           = lnet_ping_show_done,
6206         },
6207 };
6208
6209 static struct genl_family lnet_family = {
6210         .name           = LNET_GENL_NAME,
6211         .version        = LNET_GENL_VERSION,
6212         .module         = THIS_MODULE,
6213         .netnsok        = true,
6214         .ops            = lnet_genl_ops,
6215         .n_ops          = ARRAY_SIZE(lnet_genl_ops),
6216         .mcgrps         = lnet_mcast_grps,
6217         .n_mcgrps       = ARRAY_SIZE(lnet_mcast_grps),
6218 #ifdef GENL_FAMILY_HAS_RESV_START_OP
6219         .resv_start_op  = __LNET_CMD_MAX_PLUS_ONE,
6220 #endif
6221 };
6222
6223 void LNetDebugPeer(struct lnet_processid *id)
6224 {
6225         lnet_debug_peer(&id->nid);
6226 }
6227 EXPORT_SYMBOL(LNetDebugPeer);
6228
6229 /**
6230  * Determine if the specified peer \a nid is on the local node.
6231  *
6232  * \param nid   peer nid to check
6233  *
6234  * \retval true         If peer NID is on the local node.
6235  * \retval false        If peer NID is not on the local node.
6236  */
6237 bool LNetIsPeerLocal(struct lnet_nid *nid)
6238 {
6239         struct lnet_net *net;
6240         struct lnet_ni *ni;
6241         int cpt;
6242
6243         cpt = lnet_net_lock_current();
6244         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6245                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6246                         if (nid_same(&ni->ni_nid, nid)) {
6247                                 lnet_net_unlock(cpt);
6248                                 return true;
6249                         }
6250                 }
6251         }
6252         lnet_net_unlock(cpt);
6253
6254         return false;
6255 }
6256 EXPORT_SYMBOL(LNetIsPeerLocal);
6257
6258 /**
6259  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
6260  * Note that all interfaces share a same PID, as requested by LNetNIInit().
6261  *
6262  * \param index Index of the interface to look up.
6263  * \param id On successful return, this location will hold the
6264  * struct lnet_process_id ID of the interface.
6265  *
6266  * \retval 0 If an interface exists at \a index.
6267  * \retval -ENOENT If no interface has been found.
6268  */
6269 int
6270 LNetGetId(unsigned int index, struct lnet_processid *id)
6271 {
6272         struct lnet_ni   *ni;
6273         struct lnet_net  *net;
6274         int               cpt;
6275         int               rc = -ENOENT;
6276
6277         LASSERT(the_lnet.ln_refcount > 0);
6278
6279         cpt = lnet_net_lock_current();
6280
6281         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
6282                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
6283                         if (!nid_is_nid4(&ni->ni_nid))
6284                                 /* FIXME this needs to be handled */
6285                                 continue;
6286                         if (index-- != 0)
6287                                 continue;
6288
6289                         id->nid = ni->ni_nid;
6290                         id->pid = the_lnet.ln_pid;
6291                         rc = 0;
6292                         break;
6293                 }
6294         }
6295
6296         lnet_net_unlock(cpt);
6297         return rc;
6298 }
6299 EXPORT_SYMBOL(LNetGetId);
6300
6301 struct ping_data {
6302         int rc;
6303         int replied;
6304         int pd_unlinked;
6305         struct lnet_handle_md mdh;
6306         struct completion completion;
6307 };
6308
6309 static void
6310 lnet_ping_event_handler(struct lnet_event *event)
6311 {
6312         struct ping_data *pd = event->md_user_ptr;
6313
6314         CDEBUG(D_NET, "ping event (%d %d)%s\n",
6315                event->type, event->status,
6316                event->unlinked ? " unlinked" : "");
6317
6318         if (event->status) {
6319                 if (!pd->rc)
6320                         pd->rc = event->status;
6321         } else if (event->type == LNET_EVENT_REPLY) {
6322                 pd->replied = 1;
6323                 pd->rc = event->mlength;
6324         }
6325
6326         if (event->unlinked)
6327                 pd->pd_unlinked = 1;
6328
6329         if (event->unlinked ||
6330             (event->type == LNET_EVENT_SEND && event->status))
6331                 complete(&pd->completion);
6332 }
6333
6334 static int lnet_ping(struct lnet_processid *id, struct lnet_nid *src_nid,
6335                      signed long timeout, struct lnet_genl_ping_list *plist,
6336                      int n_ids)
6337 {
6338         int id_bytes = sizeof(struct lnet_ni_status); /* For 0@lo */
6339         struct lnet_md md = { NULL };
6340         struct ping_data pd = { 0 };
6341         struct lnet_ping_buffer *pbuf;
6342         struct lnet_processid pid;
6343         struct lnet_ping_iter pi;
6344         int i = 0;
6345         u32 *st;
6346         int nob;
6347         int rc;
6348         int rc2;
6349
6350         genradix_init(&plist->lgpl_list);
6351
6352         /* n_ids limit is arbitrary */
6353         if (n_ids <= 0 || LNET_NID_IS_ANY(&id->nid))
6354                 return -EINVAL;
6355
6356         /* if the user buffer has more space than the lnet_interfaces_max
6357          * then only fill it up to lnet_interfaces_max
6358          */
6359         if (n_ids > lnet_interfaces_max)
6360                 n_ids = lnet_interfaces_max;
6361
6362         if (id->pid == LNET_PID_ANY)
6363                 id->pid = LNET_PID_LUSTRE;
6364
6365         id_bytes += lnet_ping_sts_size(&id->nid) * n_ids;
6366         pbuf = lnet_ping_buffer_alloc(id_bytes, GFP_NOFS);
6367         if (!pbuf)
6368                 return -ENOMEM;
6369
6370         /* initialize md content */
6371         md.start     = &pbuf->pb_info;
6372         md.length    = id_bytes;
6373         md.threshold = 2; /* GET/REPLY */
6374         md.max_size  = 0;
6375         md.options   = LNET_MD_TRUNCATE;
6376         md.user_ptr  = &pd;
6377         md.handler   = lnet_ping_event_handler;
6378
6379         init_completion(&pd.completion);
6380
6381         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
6382         if (rc != 0) {
6383                 CERROR("Can't bind MD: %d\n", rc);
6384                 goto fail_ping_buffer_decref;
6385         }
6386
6387         rc = LNetGet(src_nid, pd.mdh, id, LNET_RESERVED_PORTAL,
6388                      LNET_PROTO_PING_MATCHBITS, 0, false);
6389         if (rc != 0) {
6390                 /* Don't CERROR; this could be deliberate! */
6391                 rc2 = LNetMDUnlink(pd.mdh);
6392                 LASSERT(rc2 == 0);
6393
6394                 /* NB must wait for the UNLINK event below... */
6395         }
6396
6397         /* Ensure completion in finite time... */
6398         wait_for_completion_timeout(&pd.completion, timeout);
6399         if (!pd.pd_unlinked) {
6400                 LNetMDUnlink(pd.mdh);
6401                 wait_for_completion(&pd.completion);
6402         }
6403
6404         if (!pd.replied) {
6405                 rc = pd.rc ?: -EIO;
6406                 goto fail_ping_buffer_decref;
6407         }
6408
6409         nob = pd.rc;
6410         LASSERT(nob >= 0 && nob <= id_bytes);
6411
6412         rc = -EPROTO;           /* if I can't parse... */
6413
6414         if (nob < LNET_PING_INFO_HDR_SIZE) {
6415                 CERROR("%s: ping info too short %d\n",
6416                        libcfs_idstr(id), nob);
6417                 goto fail_ping_buffer_decref;
6418         }
6419
6420         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
6421                 lnet_swap_pinginfo(pbuf);
6422         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
6423                 CERROR("%s: Unexpected magic %08x\n",
6424                        libcfs_idstr(id), pbuf->pb_info.pi_magic);
6425                 goto fail_ping_buffer_decref;
6426         }
6427
6428         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
6429                 CERROR("%s: ping w/o NI status: 0x%x\n",
6430                        libcfs_idstr(id), pbuf->pb_info.pi_features);
6431                 goto fail_ping_buffer_decref;
6432         }
6433
6434         /* Test if smaller than lnet_pinginfo with just one pi_ni status info.
6435          * That one might contain size when large nids are used.
6436          */
6437         if (nob < offsetof(struct lnet_ping_info, pi_ni[1])) {
6438                 CERROR("%s: Short reply %d(%lu min)\n",
6439                        libcfs_idstr(id), nob,
6440                        offsetof(struct lnet_ping_info, pi_ni[1]));
6441                 goto fail_ping_buffer_decref;
6442         }
6443
6444         if (ping_info_count_entries(pbuf) < n_ids) {
6445                 n_ids = ping_info_count_entries(pbuf);
6446                 id_bytes = lnet_ping_info_size(&pbuf->pb_info);
6447         }
6448
6449         if (nob < id_bytes) {
6450                 CERROR("%s: Short reply %d(%d expected)\n",
6451                        libcfs_idstr(id), nob, id_bytes);
6452                 goto fail_ping_buffer_decref;
6453         }
6454
6455         for (st = ping_iter_first(&pi, pbuf, &pid.nid);
6456              st;
6457              st = ping_iter_next(&pi, &pid.nid)) {
6458                 id = genradix_ptr_alloc(&plist->lgpl_list, i++, GFP_ATOMIC);
6459                 if (!id) {
6460                         rc = -ENOMEM;
6461                         goto fail_ping_buffer_decref;
6462                 }
6463
6464                 id->pid = pbuf->pb_info.pi_pid;
6465                 id->nid = pid.nid;
6466         }
6467         rc = i;
6468 fail_ping_buffer_decref:
6469         lnet_ping_buffer_decref(pbuf);
6470         return rc;
6471 }
6472
6473 static int
6474 lnet_discover(struct lnet_process_id id4, __u32 force,
6475               struct lnet_process_id __user *ids, int n_ids)
6476 {
6477         struct lnet_peer_ni *lpni;
6478         struct lnet_peer_ni *p;
6479         struct lnet_peer *lp;
6480         struct lnet_process_id *buf;
6481         struct lnet_processid id;
6482         int cpt;
6483         int i;
6484         int rc;
6485
6486         if (n_ids <= 0 ||
6487             id4.nid == LNET_NID_ANY)
6488                 return -EINVAL;
6489
6490         lnet_pid4_to_pid(id4, &id);
6491         if (id.pid == LNET_PID_ANY)
6492                 id.pid = LNET_PID_LUSTRE;
6493
6494         /*
6495          * If the user buffer has more space than the lnet_interfaces_max,
6496          * then only fill it up to lnet_interfaces_max.
6497          */
6498         if (n_ids > lnet_interfaces_max)
6499                 n_ids = lnet_interfaces_max;
6500
6501         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
6502         if (!buf)
6503                 return -ENOMEM;
6504
6505         cpt = lnet_net_lock_current();
6506         lpni = lnet_peerni_by_nid_locked(&id.nid, NULL, cpt);
6507         if (IS_ERR(lpni)) {
6508                 rc = PTR_ERR(lpni);
6509                 goto out;
6510         }
6511
6512         /*
6513          * Clearing the NIDS_UPTODATE flag ensures the peer will
6514          * be discovered, provided discovery has not been disabled.
6515          */
6516         lp = lpni->lpni_peer_net->lpn_peer;
6517         spin_lock(&lp->lp_lock);
6518         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
6519         /* If the force flag is set, force a PING and PUSH as well. */
6520         if (force)
6521                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
6522         spin_unlock(&lp->lp_lock);
6523         rc = lnet_discover_peer_locked(lpni, cpt, true);
6524         if (rc)
6525                 goto out_decref;
6526
6527         /* The lpni (or lp) for this NID may have changed and our ref is
6528          * the only thing keeping the old one around. Release the ref
6529          * and lookup the lpni again
6530          */
6531         lnet_peer_ni_decref_locked(lpni);
6532         lpni = lnet_peer_ni_find_locked(&id.nid);
6533         if (!lpni) {
6534                 rc = -ENOENT;
6535                 goto out;
6536         }
6537         lp = lpni->lpni_peer_net->lpn_peer;
6538
6539         i = 0;
6540         p = NULL;
6541         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
6542                 buf[i].pid = id.pid;
6543                 buf[i].nid = lnet_nid_to_nid4(&p->lpni_nid);
6544                 if (++i >= n_ids)
6545                         break;
6546         }
6547         rc = i;
6548
6549 out_decref:
6550         lnet_peer_ni_decref_locked(lpni);
6551 out:
6552         lnet_net_unlock(cpt);
6553
6554         if (rc >= 0)
6555                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
6556                         rc = -EFAULT;
6557         CFS_FREE_PTR_ARRAY(buf, n_ids);
6558
6559         return rc;
6560 }
6561
6562 /**
6563  * Retrieve peer discovery status.
6564  *
6565  * \retval 1 if lnet_peer_discovery_disabled is 0
6566  * \retval 0 if lnet_peer_discovery_disabled is 1
6567  */
6568 int
6569 LNetGetPeerDiscoveryStatus(void)
6570 {
6571         return !lnet_peer_discovery_disabled;
6572 }
6573 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);