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