Whamcloud - gitweb
c08e929842b0b85d7a3961cb1ab4dad2dd1ae584
[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  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #define DEBUG_SUBSYSTEM S_LNET
34
35 #include <linux/ctype.h>
36 #include <linux/log2.h>
37 #include <linux/ktime.h>
38 #include <linux/moduleparam.h>
39 #include <linux/uaccess.h>
40
41 #include <lnet/lib-lnet.h>
42
43 #define D_LNI D_CONSOLE
44
45 /*
46  * initialize ln_api_mutex statically, since it needs to be used in
47  * discovery_set callback. That module parameter callback can be called
48  * before module init completes. The mutex needs to be ready for use then.
49  */
50 struct lnet the_lnet = {
51         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
52 };              /* THE state of the network */
53 EXPORT_SYMBOL(the_lnet);
54
55 static char *ip2nets = "";
56 module_param(ip2nets, charp, 0444);
57 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
58
59 static char *networks = "";
60 module_param(networks, charp, 0444);
61 MODULE_PARM_DESC(networks, "local networks");
62
63 static char *routes = "";
64 module_param(routes, charp, 0444);
65 MODULE_PARM_DESC(routes, "routes to non-local networks");
66
67 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
68 module_param(rnet_htable_size, int, 0444);
69 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
70
71 static int use_tcp_bonding = false;
72 module_param(use_tcp_bonding, int, 0444);
73 MODULE_PARM_DESC(use_tcp_bonding,
74                  "Set to 1 to use socklnd bonding. 0 to use Multi-Rail");
75
76 unsigned int lnet_numa_range = 0;
77 module_param(lnet_numa_range, uint, 0444);
78 MODULE_PARM_DESC(lnet_numa_range,
79                 "NUMA range to consider during Multi-Rail selection");
80
81 /*
82  * lnet_health_sensitivity determines by how much we decrement the health
83  * value on sending error. The value defaults to 0, which means health
84  * checking is turned off by default.
85  */
86 unsigned int lnet_health_sensitivity = 0;
87 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
88 #ifdef HAVE_KERNEL_PARAM_OPS
89 static struct kernel_param_ops param_ops_health_sensitivity = {
90         .set = sensitivity_set,
91         .get = param_get_int,
92 };
93 #define param_check_health_sensitivity(name, p) \
94                 __param_check(name, p, int)
95 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
96 #else
97 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
98                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
99 #endif
100 MODULE_PARM_DESC(lnet_health_sensitivity,
101                 "Value to decrement the health value by on error");
102
103 /*
104  * lnet_recovery_interval determines how often we should perform recovery
105  * on unhealthy interfaces.
106  */
107 unsigned int lnet_recovery_interval = 1;
108 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
109 #ifdef HAVE_KERNEL_PARAM_OPS
110 static struct kernel_param_ops param_ops_recovery_interval = {
111         .set = recovery_interval_set,
112         .get = param_get_int,
113 };
114 #define param_check_recovery_interval(name, p) \
115                 __param_check(name, p, int)
116 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
117 #else
118 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
119                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
120 #endif
121 MODULE_PARM_DESC(lnet_recovery_interval,
122                 "Interval to recover unhealthy interfaces in seconds");
123
124 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
125 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
126
127 static struct kernel_param_ops param_ops_interfaces_max = {
128         .set = intf_max_set,
129         .get = param_get_int,
130 };
131
132 #define param_check_interfaces_max(name, p) \
133                 __param_check(name, p, int)
134
135 #ifdef HAVE_KERNEL_PARAM_OPS
136 module_param(lnet_interfaces_max, interfaces_max, 0644);
137 #else
138 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
139                   &param_ops_interfaces_max, 0644);
140 #endif
141 MODULE_PARM_DESC(lnet_interfaces_max,
142                 "Maximum number of interfaces in a node.");
143
144 unsigned lnet_peer_discovery_disabled = 0;
145 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
146
147 static struct kernel_param_ops param_ops_discovery_disabled = {
148         .set = discovery_set,
149         .get = param_get_int,
150 };
151
152 #define param_check_discovery_disabled(name, p) \
153                 __param_check(name, p, int)
154 #ifdef HAVE_KERNEL_PARAM_OPS
155 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
156 #else
157 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
158                   &param_ops_discovery_disabled, 0644);
159 #endif
160 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
161                 "Set to 1 to disable peer discovery on this node.");
162
163 unsigned int lnet_drop_asym_route;
164 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
165
166 static struct kernel_param_ops param_ops_drop_asym_route = {
167         .set = drop_asym_route_set,
168         .get = param_get_int,
169 };
170
171 #define param_check_drop_asym_route(name, p)    \
172         __param_check(name, p, int)
173 #ifdef HAVE_KERNEL_PARAM_OPS
174 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
175 #else
176 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
177                   &param_ops_drop_asym_route, 0644);
178 #endif
179 MODULE_PARM_DESC(lnet_drop_asym_route,
180                  "Set to 1 to drop asymmetrical route messages.");
181
182 unsigned lnet_transaction_timeout = 50;
183 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
184 #ifdef HAVE_KERNEL_PARAM_OPS
185 static struct kernel_param_ops param_ops_transaction_timeout = {
186         .set = transaction_to_set,
187         .get = param_get_int,
188 };
189
190 #define param_check_transaction_timeout(name, p) \
191                 __param_check(name, p, int)
192 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
193 #else
194 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
195                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
196 #endif
197 MODULE_PARM_DESC(lnet_transaction_timeout,
198                 "Maximum number of seconds to wait for a peer response.");
199
200 unsigned lnet_retry_count = 0;
201 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
202 #ifdef HAVE_KERNEL_PARAM_OPS
203 static struct kernel_param_ops param_ops_retry_count = {
204         .set = retry_count_set,
205         .get = param_get_int,
206 };
207
208 #define param_check_retry_count(name, p) \
209                 __param_check(name, p, int)
210 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
211 #else
212 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
213                   &lnet_retry_count, S_IRUGO|S_IWUSR);
214 #endif
215 MODULE_PARM_DESC(lnet_retry_count,
216                  "Maximum number of times to retry transmitting a message");
217
218
219 unsigned lnet_lnd_timeout = LNET_LND_DEFAULT_TIMEOUT;
220
221 /*
222  * This sequence number keeps track of how many times DLC was used to
223  * update the local NIs. It is incremented when a NI is added or
224  * removed and checked when sending a message to determine if there is
225  * a need to re-run the selection algorithm. See lnet_select_pathway()
226  * for more details on its usage.
227  */
228 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
229
230 static int lnet_ping(struct lnet_process_id id, signed long timeout,
231                      struct lnet_process_id __user *ids, int n_ids);
232
233 static int lnet_discover(struct lnet_process_id id, __u32 force,
234                          struct lnet_process_id __user *ids, int n_ids);
235
236 static int
237 sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
238 {
239         int rc;
240         unsigned *sensitivity = (unsigned *)kp->arg;
241         unsigned long value;
242
243         rc = kstrtoul(val, 0, &value);
244         if (rc) {
245                 CERROR("Invalid module parameter value for 'lnet_health_sensitivity'\n");
246                 return rc;
247         }
248
249         /*
250          * The purpose of locking the api_mutex here is to ensure that
251          * the correct value ends up stored properly.
252          */
253         mutex_lock(&the_lnet.ln_api_mutex);
254
255         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
256                 mutex_unlock(&the_lnet.ln_api_mutex);
257                 return 0;
258         }
259
260         if (value > LNET_MAX_HEALTH_VALUE) {
261                 mutex_unlock(&the_lnet.ln_api_mutex);
262                 CERROR("Invalid health value. Maximum: %d value = %lu\n",
263                        LNET_MAX_HEALTH_VALUE, value);
264                 return -EINVAL;
265         }
266
267         *sensitivity = value;
268
269         mutex_unlock(&the_lnet.ln_api_mutex);
270
271         return 0;
272 }
273
274 static int
275 recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
276 {
277         int rc;
278         unsigned *interval = (unsigned *)kp->arg;
279         unsigned long value;
280
281         rc = kstrtoul(val, 0, &value);
282         if (rc) {
283                 CERROR("Invalid module parameter value for 'lnet_recovery_interval'\n");
284                 return rc;
285         }
286
287         if (value < 1) {
288                 CERROR("lnet_recovery_interval must be at least 1 second\n");
289                 return -EINVAL;
290         }
291
292         /*
293          * The purpose of locking the api_mutex here is to ensure that
294          * the correct value ends up stored properly.
295          */
296         mutex_lock(&the_lnet.ln_api_mutex);
297
298         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
299                 mutex_unlock(&the_lnet.ln_api_mutex);
300                 return 0;
301         }
302
303         *interval = value;
304
305         mutex_unlock(&the_lnet.ln_api_mutex);
306
307         return 0;
308 }
309
310 static int
311 discovery_set(const char *val, cfs_kernel_param_arg_t *kp)
312 {
313         int rc;
314         unsigned *discovery = (unsigned *)kp->arg;
315         unsigned long value;
316         struct lnet_ping_buffer *pbuf;
317
318         rc = kstrtoul(val, 0, &value);
319         if (rc) {
320                 CERROR("Invalid module parameter value for 'lnet_peer_discovery_disabled'\n");
321                 return rc;
322         }
323
324         value = (value) ? 1 : 0;
325
326         /*
327          * The purpose of locking the api_mutex here is to ensure that
328          * the correct value ends up stored properly.
329          */
330         mutex_lock(&the_lnet.ln_api_mutex);
331
332         if (value == *discovery) {
333                 mutex_unlock(&the_lnet.ln_api_mutex);
334                 return 0;
335         }
336
337         *discovery = value;
338
339         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
340                 mutex_unlock(&the_lnet.ln_api_mutex);
341                 return 0;
342         }
343
344         /* tell peers that discovery setting has changed */
345         lnet_net_lock(LNET_LOCK_EX);
346         pbuf = the_lnet.ln_ping_target;
347         if (value)
348                 pbuf->pb_info.pi_features &= ~LNET_PING_FEAT_DISCOVERY;
349         else
350                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
351         lnet_net_unlock(LNET_LOCK_EX);
352
353         lnet_push_update_to_peers(1);
354
355         mutex_unlock(&the_lnet.ln_api_mutex);
356
357         return 0;
358 }
359
360 static int
361 drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp)
362 {
363         int rc;
364         unsigned int *drop_asym_route = (unsigned int *)kp->arg;
365         unsigned long value;
366
367         rc = kstrtoul(val, 0, &value);
368         if (rc) {
369                 CERROR("Invalid module parameter value for "
370                        "'lnet_drop_asym_route'\n");
371                 return rc;
372         }
373
374         /*
375          * The purpose of locking the api_mutex here is to ensure that
376          * the correct value ends up stored properly.
377          */
378         mutex_lock(&the_lnet.ln_api_mutex);
379
380         if (value == *drop_asym_route) {
381                 mutex_unlock(&the_lnet.ln_api_mutex);
382                 return 0;
383         }
384
385         *drop_asym_route = value;
386
387         mutex_unlock(&the_lnet.ln_api_mutex);
388
389         return 0;
390 }
391
392 static int
393 transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp)
394 {
395         int rc;
396         unsigned *transaction_to = (unsigned *)kp->arg;
397         unsigned long value;
398
399         rc = kstrtoul(val, 0, &value);
400         if (rc) {
401                 CERROR("Invalid module parameter value for 'lnet_transaction_timeout'\n");
402                 return rc;
403         }
404
405         /*
406          * The purpose of locking the api_mutex here is to ensure that
407          * the correct value ends up stored properly.
408          */
409         mutex_lock(&the_lnet.ln_api_mutex);
410
411         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
412                 mutex_unlock(&the_lnet.ln_api_mutex);
413                 return 0;
414         }
415
416         if (value < lnet_retry_count || value == 0) {
417                 mutex_unlock(&the_lnet.ln_api_mutex);
418                 CERROR("Invalid value for lnet_transaction_timeout (%lu). "
419                        "Has to be greater than lnet_retry_count (%u)\n",
420                        value, lnet_retry_count);
421                 return -EINVAL;
422         }
423
424         if (value == *transaction_to) {
425                 mutex_unlock(&the_lnet.ln_api_mutex);
426                 return 0;
427         }
428
429         *transaction_to = value;
430         if (lnet_retry_count == 0)
431                 lnet_lnd_timeout = value;
432         else
433                 lnet_lnd_timeout = value / lnet_retry_count;
434
435         mutex_unlock(&the_lnet.ln_api_mutex);
436
437         return 0;
438 }
439
440 static int
441 retry_count_set(const char *val, cfs_kernel_param_arg_t *kp)
442 {
443         int rc;
444         unsigned *retry_count = (unsigned *)kp->arg;
445         unsigned long value;
446
447         rc = kstrtoul(val, 0, &value);
448         if (rc) {
449                 CERROR("Invalid module parameter value for 'lnet_retry_count'\n");
450                 return rc;
451         }
452
453         /*
454          * The purpose of locking the api_mutex here is to ensure that
455          * the correct value ends up stored properly.
456          */
457         mutex_lock(&the_lnet.ln_api_mutex);
458
459         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
460                 mutex_unlock(&the_lnet.ln_api_mutex);
461                 return 0;
462         }
463
464         if (value > lnet_transaction_timeout) {
465                 mutex_unlock(&the_lnet.ln_api_mutex);
466                 CERROR("Invalid value for lnet_retry_count (%lu). "
467                        "Has to be smaller than lnet_transaction_timeout (%u)\n",
468                        value, lnet_transaction_timeout);
469                 return -EINVAL;
470         }
471
472         if (value == *retry_count) {
473                 mutex_unlock(&the_lnet.ln_api_mutex);
474                 return 0;
475         }
476
477         *retry_count = value;
478
479         if (value == 0)
480                 lnet_lnd_timeout = lnet_transaction_timeout;
481         else
482                 lnet_lnd_timeout = lnet_transaction_timeout / value;
483
484         mutex_unlock(&the_lnet.ln_api_mutex);
485
486         return 0;
487 }
488
489 static int
490 intf_max_set(const char *val, cfs_kernel_param_arg_t *kp)
491 {
492         int value, rc;
493
494         rc = kstrtoint(val, 0, &value);
495         if (rc) {
496                 CERROR("Invalid module parameter value for 'lnet_interfaces_max'\n");
497                 return rc;
498         }
499
500         if (value < LNET_INTERFACES_MIN) {
501                 CWARN("max interfaces provided are too small, setting to %d\n",
502                       LNET_INTERFACES_MAX_DEFAULT);
503                 value = LNET_INTERFACES_MAX_DEFAULT;
504         }
505
506         *(int *)kp->arg = value;
507
508         return 0;
509 }
510
511 static char *
512 lnet_get_routes(void)
513 {
514         return routes;
515 }
516
517 static char *
518 lnet_get_networks(void)
519 {
520         char   *nets;
521         int     rc;
522
523         if (*networks != 0 && *ip2nets != 0) {
524                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
525                                    "'ip2nets' but not both at once\n");
526                 return NULL;
527         }
528
529         if (*ip2nets != 0) {
530                 rc = lnet_parse_ip2nets(&nets, ip2nets);
531                 return (rc == 0) ? nets : NULL;
532         }
533
534         if (*networks != 0)
535                 return networks;
536
537         return "tcp";
538 }
539
540 static void
541 lnet_init_locks(void)
542 {
543         spin_lock_init(&the_lnet.ln_eq_wait_lock);
544         spin_lock_init(&the_lnet.ln_msg_resend_lock);
545         init_waitqueue_head(&the_lnet.ln_eq_waitq);
546         init_waitqueue_head(&the_lnet.ln_mt_waitq);
547         mutex_init(&the_lnet.ln_lnd_mutex);
548 }
549
550 static void
551 lnet_fini_locks(void)
552 {
553 }
554
555 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
556 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
557                                             *  MDs kmem_cache */
558
559 static int
560 lnet_descriptor_setup(void)
561 {
562         /* create specific kmem_cache for MEs and small MDs (i.e., originally
563          * allocated in <size-xxx> kmem_cache).
564          */
565         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(struct lnet_me),
566                                             0, 0, NULL);
567         if (!lnet_mes_cachep)
568                 return -ENOMEM;
569
570         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
571                                                   LNET_SMALL_MD_SIZE, 0, 0,
572                                                   NULL);
573         if (!lnet_small_mds_cachep)
574                 return -ENOMEM;
575
576         return 0;
577 }
578
579 static void
580 lnet_descriptor_cleanup(void)
581 {
582
583         if (lnet_small_mds_cachep) {
584                 kmem_cache_destroy(lnet_small_mds_cachep);
585                 lnet_small_mds_cachep = NULL;
586         }
587
588         if (lnet_mes_cachep) {
589                 kmem_cache_destroy(lnet_mes_cachep);
590                 lnet_mes_cachep = NULL;
591         }
592 }
593
594 static int
595 lnet_create_remote_nets_table(void)
596 {
597         int               i;
598         struct list_head *hash;
599
600         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
601         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
602         LIBCFS_ALLOC(hash, LNET_REMOTE_NETS_HASH_SIZE * sizeof(*hash));
603         if (hash == NULL) {
604                 CERROR("Failed to create remote nets hash table\n");
605                 return -ENOMEM;
606         }
607
608         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
609                 INIT_LIST_HEAD(&hash[i]);
610         the_lnet.ln_remote_nets_hash = hash;
611         return 0;
612 }
613
614 static void
615 lnet_destroy_remote_nets_table(void)
616 {
617         int i;
618
619         if (the_lnet.ln_remote_nets_hash == NULL)
620                 return;
621
622         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
623                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
624
625         LIBCFS_FREE(the_lnet.ln_remote_nets_hash,
626                     LNET_REMOTE_NETS_HASH_SIZE *
627                     sizeof(the_lnet.ln_remote_nets_hash[0]));
628         the_lnet.ln_remote_nets_hash = NULL;
629 }
630
631 static void
632 lnet_destroy_locks(void)
633 {
634         if (the_lnet.ln_res_lock != NULL) {
635                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
636                 the_lnet.ln_res_lock = NULL;
637         }
638
639         if (the_lnet.ln_net_lock != NULL) {
640                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
641                 the_lnet.ln_net_lock = NULL;
642         }
643
644         lnet_fini_locks();
645 }
646
647 static int
648 lnet_create_locks(void)
649 {
650         lnet_init_locks();
651
652         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
653         if (the_lnet.ln_res_lock == NULL)
654                 goto failed;
655
656         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
657         if (the_lnet.ln_net_lock == NULL)
658                 goto failed;
659
660         return 0;
661
662  failed:
663         lnet_destroy_locks();
664         return -ENOMEM;
665 }
666
667 static void lnet_assert_wire_constants(void)
668 {
669         /* Wire protocol assertions generated by 'wirecheck'
670          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
671          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
672          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
673
674         /* Constants... */
675         CLASSERT(LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
676         CLASSERT(LNET_PROTO_TCP_VERSION_MAJOR == 1);
677         CLASSERT(LNET_PROTO_TCP_VERSION_MINOR == 0);
678         CLASSERT(LNET_MSG_ACK == 0);
679         CLASSERT(LNET_MSG_PUT == 1);
680         CLASSERT(LNET_MSG_GET == 2);
681         CLASSERT(LNET_MSG_REPLY == 3);
682         CLASSERT(LNET_MSG_HELLO == 4);
683
684         /* Checks for struct lnet_handle_wire */
685         CLASSERT((int)sizeof(struct lnet_handle_wire) == 16);
686         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_interface_cookie) == 0);
687         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) == 8);
688         CLASSERT((int)offsetof(struct lnet_handle_wire, wh_object_cookie) == 8);
689         CLASSERT((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) == 8);
690
691         /* Checks for struct struct lnet_magicversion */
692         CLASSERT((int)sizeof(struct lnet_magicversion) == 8);
693         CLASSERT((int)offsetof(struct lnet_magicversion, magic) == 0);
694         CLASSERT((int)sizeof(((struct lnet_magicversion *)0)->magic) == 4);
695         CLASSERT((int)offsetof(struct lnet_magicversion, version_major) == 4);
696         CLASSERT((int)sizeof(((struct lnet_magicversion *)0)->version_major) == 2);
697         CLASSERT((int)offsetof(struct lnet_magicversion, version_minor) == 6);
698         CLASSERT((int)sizeof(((struct lnet_magicversion *)0)->version_minor) == 2);
699
700         /* Checks for struct struct lnet_hdr */
701         CLASSERT((int)sizeof(struct lnet_hdr) == 72);
702         CLASSERT((int)offsetof(struct lnet_hdr, dest_nid) == 0);
703         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->dest_nid) == 8);
704         CLASSERT((int)offsetof(struct lnet_hdr, src_nid) == 8);
705         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->src_nid) == 8);
706         CLASSERT((int)offsetof(struct lnet_hdr, dest_pid) == 16);
707         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->dest_pid) == 4);
708         CLASSERT((int)offsetof(struct lnet_hdr, src_pid) == 20);
709         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->src_pid) == 4);
710         CLASSERT((int)offsetof(struct lnet_hdr, type) == 24);
711         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->type) == 4);
712         CLASSERT((int)offsetof(struct lnet_hdr, payload_length) == 28);
713         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->payload_length) == 4);
714         CLASSERT((int)offsetof(struct lnet_hdr, msg) == 32);
715         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg) == 40);
716
717         /* Ack */
718         CLASSERT((int)offsetof(struct lnet_hdr, msg.ack.dst_wmd) == 32);
719         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.ack.dst_wmd) == 16);
720         CLASSERT((int)offsetof(struct lnet_hdr, msg.ack.match_bits) == 48);
721         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.ack.match_bits) == 8);
722         CLASSERT((int)offsetof(struct lnet_hdr, msg.ack.mlength) == 56);
723         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.ack.mlength) == 4);
724
725         /* Put */
726         CLASSERT((int)offsetof(struct lnet_hdr, msg.put.ack_wmd) == 32);
727         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.put.ack_wmd) == 16);
728         CLASSERT((int)offsetof(struct lnet_hdr, msg.put.match_bits) == 48);
729         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.put.match_bits) == 8);
730         CLASSERT((int)offsetof(struct lnet_hdr, msg.put.hdr_data) == 56);
731         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.put.hdr_data) == 8);
732         CLASSERT((int)offsetof(struct lnet_hdr, msg.put.ptl_index) == 64);
733         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.put.ptl_index) == 4);
734         CLASSERT((int)offsetof(struct lnet_hdr, msg.put.offset) == 68);
735         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.put.offset) == 4);
736
737         /* Get */
738         CLASSERT((int)offsetof(struct lnet_hdr, msg.get.return_wmd) == 32);
739         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.get.return_wmd) == 16);
740         CLASSERT((int)offsetof(struct lnet_hdr, msg.get.match_bits) == 48);
741         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.get.match_bits) == 8);
742         CLASSERT((int)offsetof(struct lnet_hdr, msg.get.ptl_index) == 56);
743         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.get.ptl_index) == 4);
744         CLASSERT((int)offsetof(struct lnet_hdr, msg.get.src_offset) == 60);
745         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.get.src_offset) == 4);
746         CLASSERT((int)offsetof(struct lnet_hdr, msg.get.sink_length) == 64);
747         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.get.sink_length) == 4);
748
749         /* Reply */
750         CLASSERT((int)offsetof(struct lnet_hdr, msg.reply.dst_wmd) == 32);
751         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.reply.dst_wmd) == 16);
752
753         /* Hello */
754         CLASSERT((int)offsetof(struct lnet_hdr, msg.hello.incarnation) == 32);
755         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.hello.incarnation) == 8);
756         CLASSERT((int)offsetof(struct lnet_hdr, msg.hello.type) == 40);
757         CLASSERT((int)sizeof(((struct lnet_hdr *)0)->msg.hello.type) == 4);
758
759         /* Checks for struct lnet_ni_status and related constants */
760         CLASSERT(LNET_NI_STATUS_INVALID == 0x00000000);
761         CLASSERT(LNET_NI_STATUS_UP == 0x15aac0de);
762         CLASSERT(LNET_NI_STATUS_DOWN == 0xdeadface);
763
764         /* Checks for struct lnet_ni_status */
765         CLASSERT((int)sizeof(struct lnet_ni_status) == 16);
766         CLASSERT((int)offsetof(struct lnet_ni_status, ns_nid) == 0);
767         CLASSERT((int)sizeof(((struct lnet_ni_status *)0)->ns_nid) == 8);
768         CLASSERT((int)offsetof(struct lnet_ni_status, ns_status) == 8);
769         CLASSERT((int)sizeof(((struct lnet_ni_status *)0)->ns_status) == 4);
770         CLASSERT((int)offsetof(struct lnet_ni_status, ns_unused) == 12);
771         CLASSERT((int)sizeof(((struct lnet_ni_status *)0)->ns_unused) == 4);
772
773         /* Checks for struct lnet_ping_info and related constants */
774         CLASSERT(LNET_PROTO_PING_MAGIC == 0x70696E67);
775         CLASSERT(LNET_PING_FEAT_INVAL == 0);
776         CLASSERT(LNET_PING_FEAT_BASE == 1);
777         CLASSERT(LNET_PING_FEAT_NI_STATUS == 2);
778         CLASSERT(LNET_PING_FEAT_RTE_DISABLED == 4);
779         CLASSERT(LNET_PING_FEAT_MULTI_RAIL == 8);
780         CLASSERT(LNET_PING_FEAT_DISCOVERY == 16);
781         CLASSERT(LNET_PING_FEAT_BITS == 31);
782
783         /* Checks for struct lnet_ping_info */
784         CLASSERT((int)sizeof(struct lnet_ping_info) == 16);
785         CLASSERT((int)offsetof(struct lnet_ping_info, pi_magic) == 0);
786         CLASSERT((int)sizeof(((struct lnet_ping_info *)0)->pi_magic) == 4);
787         CLASSERT((int)offsetof(struct lnet_ping_info, pi_features) == 4);
788         CLASSERT((int)sizeof(((struct lnet_ping_info *)0)->pi_features) == 4);
789         CLASSERT((int)offsetof(struct lnet_ping_info, pi_pid) == 8);
790         CLASSERT((int)sizeof(((struct lnet_ping_info *)0)->pi_pid) == 4);
791         CLASSERT((int)offsetof(struct lnet_ping_info, pi_nnis) == 12);
792         CLASSERT((int)sizeof(((struct lnet_ping_info *)0)->pi_nnis) == 4);
793         CLASSERT((int)offsetof(struct lnet_ping_info, pi_ni) == 16);
794         CLASSERT((int)sizeof(((struct lnet_ping_info *)0)->pi_ni) == 0);
795 }
796
797 static struct lnet_lnd *lnet_find_lnd_by_type(__u32 type)
798 {
799         struct lnet_lnd *lnd;
800         struct list_head *tmp;
801
802         /* holding lnd mutex */
803         list_for_each(tmp, &the_lnet.ln_lnds) {
804                 lnd = list_entry(tmp, struct lnet_lnd, lnd_list);
805
806                 if (lnd->lnd_type == type)
807                         return lnd;
808         }
809         return NULL;
810 }
811
812 unsigned int
813 lnet_get_lnd_timeout(void)
814 {
815         return lnet_lnd_timeout;
816 }
817 EXPORT_SYMBOL(lnet_get_lnd_timeout);
818
819 void
820 lnet_register_lnd(struct lnet_lnd *lnd)
821 {
822         mutex_lock(&the_lnet.ln_lnd_mutex);
823
824         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
825         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
826
827         list_add_tail(&lnd->lnd_list, &the_lnet.ln_lnds);
828         lnd->lnd_refcount = 0;
829
830         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
831
832         mutex_unlock(&the_lnet.ln_lnd_mutex);
833 }
834 EXPORT_SYMBOL(lnet_register_lnd);
835
836 void
837 lnet_unregister_lnd(struct lnet_lnd *lnd)
838 {
839         mutex_lock(&the_lnet.ln_lnd_mutex);
840
841         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
842         LASSERT(lnd->lnd_refcount == 0);
843
844         list_del(&lnd->lnd_list);
845         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
846
847         mutex_unlock(&the_lnet.ln_lnd_mutex);
848 }
849 EXPORT_SYMBOL(lnet_unregister_lnd);
850
851 void
852 lnet_counters_get_common(struct lnet_counters_common *common)
853 {
854         struct lnet_counters *ctr;
855         int i;
856
857         memset(common, 0, sizeof(*common));
858
859         lnet_net_lock(LNET_LOCK_EX);
860
861         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
862                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
863                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
864                 common->lcc_errors       += ctr->lct_common.lcc_errors;
865                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
866                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
867                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
868                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
869                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
870                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
871                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
872                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
873         }
874         lnet_net_unlock(LNET_LOCK_EX);
875 }
876 EXPORT_SYMBOL(lnet_counters_get_common);
877
878 void
879 lnet_counters_get(struct lnet_counters *counters)
880 {
881         struct lnet_counters *ctr;
882         struct lnet_counters_health *health = &counters->lct_health;
883         int             i;
884
885         memset(counters, 0, sizeof(*counters));
886
887         lnet_counters_get_common(&counters->lct_common);
888
889         lnet_net_lock(LNET_LOCK_EX);
890
891         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
892                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
893                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
894                 health->lch_response_timeout_count +=
895                                 ctr->lct_health.lch_response_timeout_count;
896                 health->lch_local_interrupt_count +=
897                                 ctr->lct_health.lch_local_interrupt_count;
898                 health->lch_local_dropped_count +=
899                                 ctr->lct_health.lch_local_dropped_count;
900                 health->lch_local_aborted_count +=
901                                 ctr->lct_health.lch_local_aborted_count;
902                 health->lch_local_no_route_count +=
903                                 ctr->lct_health.lch_local_no_route_count;
904                 health->lch_local_timeout_count +=
905                                 ctr->lct_health.lch_local_timeout_count;
906                 health->lch_local_error_count +=
907                                 ctr->lct_health.lch_local_error_count;
908                 health->lch_remote_dropped_count +=
909                                 ctr->lct_health.lch_remote_dropped_count;
910                 health->lch_remote_error_count +=
911                                 ctr->lct_health.lch_remote_error_count;
912                 health->lch_remote_timeout_count +=
913                                 ctr->lct_health.lch_remote_timeout_count;
914                 health->lch_network_timeout_count +=
915                                 ctr->lct_health.lch_network_timeout_count;
916         }
917         lnet_net_unlock(LNET_LOCK_EX);
918 }
919 EXPORT_SYMBOL(lnet_counters_get);
920
921 void
922 lnet_counters_reset(void)
923 {
924         struct lnet_counters *counters;
925         int             i;
926
927         lnet_net_lock(LNET_LOCK_EX);
928
929         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
930                 memset(counters, 0, sizeof(struct lnet_counters));
931
932         lnet_net_unlock(LNET_LOCK_EX);
933 }
934
935 static char *
936 lnet_res_type2str(int type)
937 {
938         switch (type) {
939         default:
940                 LBUG();
941         case LNET_COOKIE_TYPE_MD:
942                 return "MD";
943         case LNET_COOKIE_TYPE_ME:
944                 return "ME";
945         case LNET_COOKIE_TYPE_EQ:
946                 return "EQ";
947         }
948 }
949
950 static void
951 lnet_res_container_cleanup(struct lnet_res_container *rec)
952 {
953         int     count = 0;
954
955         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
956                 return;
957
958         while (!list_empty(&rec->rec_active)) {
959                 struct list_head *e = rec->rec_active.next;
960
961                 list_del_init(e);
962                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
963                         lnet_eq_free(list_entry(e, struct lnet_eq, eq_list));
964
965                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
966                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
967
968                 } else { /* NB: Active MEs should be attached on portals */
969                         LBUG();
970                 }
971                 count++;
972         }
973
974         if (count > 0) {
975                 /* Found alive MD/ME/EQ, user really should unlink/free
976                  * all of them before finalize LNet, but if someone didn't,
977                  * we have to recycle garbage for him */
978                 CERROR("%d active elements on exit of %s container\n",
979                        count, lnet_res_type2str(rec->rec_type));
980         }
981
982         if (rec->rec_lh_hash != NULL) {
983                 LIBCFS_FREE(rec->rec_lh_hash,
984                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
985                 rec->rec_lh_hash = NULL;
986         }
987
988         rec->rec_type = 0; /* mark it as finalized */
989 }
990
991 static int
992 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
993 {
994         int     rc = 0;
995         int     i;
996
997         LASSERT(rec->rec_type == 0);
998
999         rec->rec_type = type;
1000         INIT_LIST_HEAD(&rec->rec_active);
1001
1002         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1003
1004         /* Arbitrary choice of hash table size */
1005         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1006                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1007         if (rec->rec_lh_hash == NULL) {
1008                 rc = -ENOMEM;
1009                 goto out;
1010         }
1011
1012         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1013                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1014
1015         return 0;
1016
1017 out:
1018         CERROR("Failed to setup %s resource container\n",
1019                lnet_res_type2str(type));
1020         lnet_res_container_cleanup(rec);
1021         return rc;
1022 }
1023
1024 static void
1025 lnet_res_containers_destroy(struct lnet_res_container **recs)
1026 {
1027         struct lnet_res_container       *rec;
1028         int                             i;
1029
1030         cfs_percpt_for_each(rec, i, recs)
1031                 lnet_res_container_cleanup(rec);
1032
1033         cfs_percpt_free(recs);
1034 }
1035
1036 static struct lnet_res_container **
1037 lnet_res_containers_create(int type)
1038 {
1039         struct lnet_res_container       **recs;
1040         struct lnet_res_container       *rec;
1041         int                             rc;
1042         int                             i;
1043
1044         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1045         if (recs == NULL) {
1046                 CERROR("Failed to allocate %s resource containers\n",
1047                        lnet_res_type2str(type));
1048                 return NULL;
1049         }
1050
1051         cfs_percpt_for_each(rec, i, recs) {
1052                 rc = lnet_res_container_setup(rec, i, type);
1053                 if (rc != 0) {
1054                         lnet_res_containers_destroy(recs);
1055                         return NULL;
1056                 }
1057         }
1058
1059         return recs;
1060 }
1061
1062 struct lnet_libhandle *
1063 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1064 {
1065         /* ALWAYS called with lnet_res_lock held */
1066         struct list_head        *head;
1067         struct lnet_libhandle   *lh;
1068         unsigned int            hash;
1069
1070         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1071                 return NULL;
1072
1073         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1074         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1075
1076         list_for_each_entry(lh, head, lh_hash_chain) {
1077                 if (lh->lh_cookie == cookie)
1078                         return lh;
1079         }
1080
1081         return NULL;
1082 }
1083
1084 void
1085 lnet_res_lh_initialize(struct lnet_res_container *rec,
1086                        struct lnet_libhandle *lh)
1087 {
1088         /* ALWAYS called with lnet_res_lock held */
1089         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1090         unsigned int    hash;
1091
1092         lh->lh_cookie = rec->rec_lh_cookie;
1093         rec->rec_lh_cookie += 1 << ibits;
1094
1095         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1096
1097         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1098 }
1099
1100 static int lnet_unprepare(void);
1101
1102 static int
1103 lnet_prepare(lnet_pid_t requested_pid)
1104 {
1105         /* Prepare to bring up the network */
1106         struct lnet_res_container **recs;
1107         int                       rc = 0;
1108
1109         if (requested_pid == LNET_PID_ANY) {
1110                 /* Don't instantiate LNET just for me */
1111                 return -ENETDOWN;
1112         }
1113
1114         LASSERT(the_lnet.ln_refcount == 0);
1115
1116         the_lnet.ln_routing = 0;
1117
1118         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1119         the_lnet.ln_pid = requested_pid;
1120
1121         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1122         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1123         INIT_LIST_HEAD(&the_lnet.ln_nets);
1124         INIT_LIST_HEAD(&the_lnet.ln_routers);
1125         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1126         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1127         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1128         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1129         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1130         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1131         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1132         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1133
1134         rc = lnet_descriptor_setup();
1135         if (rc != 0)
1136                 goto failed;
1137
1138         rc = lnet_create_remote_nets_table();
1139         if (rc != 0)
1140                 goto failed;
1141
1142         /*
1143          * NB the interface cookie in wire handles guards against delayed
1144          * replies and ACKs appearing valid after reboot.
1145          */
1146         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1147
1148         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1149                                                 sizeof(struct lnet_counters));
1150         if (the_lnet.ln_counters == NULL) {
1151                 CERROR("Failed to allocate counters for LNet\n");
1152                 rc = -ENOMEM;
1153                 goto failed;
1154         }
1155
1156         rc = lnet_peer_tables_create();
1157         if (rc != 0)
1158                 goto failed;
1159
1160         rc = lnet_msg_containers_create();
1161         if (rc != 0)
1162                 goto failed;
1163
1164         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1165                                       LNET_COOKIE_TYPE_EQ);
1166         if (rc != 0)
1167                 goto failed;
1168
1169         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
1170         if (recs == NULL) {
1171                 rc = -ENOMEM;
1172                 goto failed;
1173         }
1174
1175         the_lnet.ln_me_containers = recs;
1176
1177         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1178         if (recs == NULL) {
1179                 rc = -ENOMEM;
1180                 goto failed;
1181         }
1182
1183         the_lnet.ln_md_containers = recs;
1184
1185         rc = lnet_portals_create();
1186         if (rc != 0) {
1187                 CERROR("Failed to create portals for LNet: %d\n", rc);
1188                 goto failed;
1189         }
1190
1191         return 0;
1192
1193  failed:
1194         lnet_unprepare();
1195         return rc;
1196 }
1197
1198 static int
1199 lnet_unprepare (void)
1200 {
1201         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1202          * have shut down already, so it is safe to unlink and free all
1203          * descriptors, even those that appear committed to a network op (eg MD
1204          * with non-zero pending count) */
1205
1206         lnet_fail_nid(LNET_NID_ANY, 0);
1207
1208         LASSERT(the_lnet.ln_refcount == 0);
1209         LASSERT(list_empty(&the_lnet.ln_test_peers));
1210         LASSERT(list_empty(&the_lnet.ln_nets));
1211
1212         lnet_portals_destroy();
1213
1214         if (the_lnet.ln_md_containers != NULL) {
1215                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1216                 the_lnet.ln_md_containers = NULL;
1217         }
1218
1219         if (the_lnet.ln_me_containers != NULL) {
1220                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
1221                 the_lnet.ln_me_containers = NULL;
1222         }
1223
1224         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1225
1226         lnet_msg_containers_destroy();
1227         lnet_peer_uninit();
1228         lnet_rtrpools_free(0);
1229
1230         if (the_lnet.ln_counters != NULL) {
1231                 cfs_percpt_free(the_lnet.ln_counters);
1232                 the_lnet.ln_counters = NULL;
1233         }
1234         lnet_destroy_remote_nets_table();
1235         lnet_descriptor_cleanup();
1236
1237         return 0;
1238 }
1239
1240 struct lnet_ni  *
1241 lnet_net2ni_locked(__u32 net_id, int cpt)
1242 {
1243         struct lnet_ni   *ni;
1244         struct lnet_net  *net;
1245
1246         LASSERT(cpt != LNET_LOCK_EX);
1247
1248         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1249                 if (net->net_id == net_id) {
1250                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1251                                         ni_netlist);
1252                         return ni;
1253                 }
1254         }
1255
1256         return NULL;
1257 }
1258
1259 struct lnet_ni *
1260 lnet_net2ni_addref(__u32 net)
1261 {
1262         struct lnet_ni *ni;
1263
1264         lnet_net_lock(0);
1265         ni = lnet_net2ni_locked(net, 0);
1266         if (ni)
1267                 lnet_ni_addref_locked(ni, 0);
1268         lnet_net_unlock(0);
1269
1270         return ni;
1271 }
1272 EXPORT_SYMBOL(lnet_net2ni_addref);
1273
1274 struct lnet_net *
1275 lnet_get_net_locked(__u32 net_id)
1276 {
1277         struct lnet_net  *net;
1278
1279         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1280                 if (net->net_id == net_id)
1281                         return net;
1282         }
1283
1284         return NULL;
1285 }
1286
1287 unsigned int
1288 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1289 {
1290         __u64           key = nid;
1291         unsigned int    val;
1292
1293         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1294
1295         if (number == 1)
1296                 return 0;
1297
1298         val = hash_long(key, LNET_CPT_BITS);
1299         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1300         if (val < number)
1301                 return val;
1302
1303         return (unsigned int)(key + val + (val >> 1)) % number;
1304 }
1305
1306 int
1307 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1308 {
1309         struct lnet_net *net;
1310
1311         /* must called with hold of lnet_net_lock */
1312         if (LNET_CPT_NUMBER == 1)
1313                 return 0; /* the only one */
1314
1315         /*
1316          * If NI is provided then use the CPT identified in the NI cpt
1317          * list if one exists. If one doesn't exist, then that NI is
1318          * associated with all CPTs and it follows that the net it belongs
1319          * to is implicitly associated with all CPTs, so just hash the nid
1320          * and return that.
1321          */
1322         if (ni != NULL) {
1323                 if (ni->ni_cpts != NULL)
1324                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1325                                                              ni->ni_ncpts)];
1326                 else
1327                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1328         }
1329
1330         /* no NI provided so look at the net */
1331         net = lnet_get_net_locked(LNET_NIDNET(nid));
1332
1333         if (net != NULL && net->net_cpts != NULL) {
1334                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1335         }
1336
1337         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1338 }
1339
1340 int
1341 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1342 {
1343         int     cpt;
1344         int     cpt2;
1345
1346         if (LNET_CPT_NUMBER == 1)
1347                 return 0; /* the only one */
1348
1349         cpt = lnet_net_lock_current();
1350
1351         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1352
1353         lnet_net_unlock(cpt);
1354
1355         return cpt2;
1356 }
1357 EXPORT_SYMBOL(lnet_cpt_of_nid);
1358
1359 int
1360 lnet_islocalnet(__u32 net_id)
1361 {
1362         struct lnet_net *net;
1363         int             cpt;
1364         bool            local;
1365
1366         cpt = lnet_net_lock_current();
1367
1368         net = lnet_get_net_locked(net_id);
1369
1370         local = net != NULL;
1371
1372         lnet_net_unlock(cpt);
1373
1374         return local;
1375 }
1376
1377 struct lnet_ni  *
1378 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1379 {
1380         struct lnet_net  *net;
1381         struct lnet_ni   *ni;
1382
1383         LASSERT(cpt != LNET_LOCK_EX);
1384
1385         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1386                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1387                         if (ni->ni_nid == nid)
1388                                 return ni;
1389                 }
1390         }
1391
1392         return NULL;
1393 }
1394
1395 struct lnet_ni *
1396 lnet_nid2ni_addref(lnet_nid_t nid)
1397 {
1398         struct lnet_ni *ni;
1399
1400         lnet_net_lock(0);
1401         ni = lnet_nid2ni_locked(nid, 0);
1402         if (ni)
1403                 lnet_ni_addref_locked(ni, 0);
1404         lnet_net_unlock(0);
1405
1406         return ni;
1407 }
1408 EXPORT_SYMBOL(lnet_nid2ni_addref);
1409
1410 int
1411 lnet_islocalnid(lnet_nid_t nid)
1412 {
1413         struct lnet_ni  *ni;
1414         int             cpt;
1415
1416         cpt = lnet_net_lock_current();
1417         ni = lnet_nid2ni_locked(nid, cpt);
1418         lnet_net_unlock(cpt);
1419
1420         return ni != NULL;
1421 }
1422
1423 int
1424 lnet_count_acceptor_nets(void)
1425 {
1426         /* Return the # of NIs that need the acceptor. */
1427         int              count = 0;
1428         struct lnet_net  *net;
1429         int              cpt;
1430
1431         cpt = lnet_net_lock_current();
1432         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1433                 /* all socklnd type networks should have the acceptor
1434                  * thread started */
1435                 if (net->net_lnd->lnd_accept != NULL)
1436                         count++;
1437         }
1438
1439         lnet_net_unlock(cpt);
1440
1441         return count;
1442 }
1443
1444 struct lnet_ping_buffer *
1445 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1446 {
1447         struct lnet_ping_buffer *pbuf;
1448
1449         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1450         if (pbuf) {
1451                 pbuf->pb_nnis = nnis;
1452                 atomic_set(&pbuf->pb_refcnt, 1);
1453         }
1454
1455         return pbuf;
1456 }
1457
1458 void
1459 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1460 {
1461         LASSERT(lnet_ping_buffer_numref(pbuf) == 0);
1462         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1463 }
1464
1465 static struct lnet_ping_buffer *
1466 lnet_ping_target_create(int nnis)
1467 {
1468         struct lnet_ping_buffer *pbuf;
1469
1470         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1471         if (pbuf == NULL) {
1472                 CERROR("Can't allocate ping source [%d]\n", nnis);
1473                 return NULL;
1474         }
1475
1476         pbuf->pb_info.pi_nnis = nnis;
1477         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1478         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1479         pbuf->pb_info.pi_features =
1480                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1481
1482         return pbuf;
1483 }
1484
1485 static inline int
1486 lnet_get_net_ni_count_locked(struct lnet_net *net)
1487 {
1488         struct lnet_ni  *ni;
1489         int             count = 0;
1490
1491         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1492                 count++;
1493
1494         return count;
1495 }
1496
1497 static inline int
1498 lnet_get_net_ni_count_pre(struct lnet_net *net)
1499 {
1500         struct lnet_ni  *ni;
1501         int             count = 0;
1502
1503         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1504                 count++;
1505
1506         return count;
1507 }
1508
1509 static inline int
1510 lnet_get_ni_count(void)
1511 {
1512         struct lnet_ni  *ni;
1513         struct lnet_net *net;
1514         int             count = 0;
1515
1516         lnet_net_lock(0);
1517
1518         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1519                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1520                         count++;
1521         }
1522
1523         lnet_net_unlock(0);
1524
1525         return count;
1526 }
1527
1528 int
1529 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1530 {
1531         if (!pinfo)
1532                 return -EINVAL;
1533         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1534                 return -EPROTO;
1535         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1536                 return -EPROTO;
1537         /* Loopback is guaranteed to be present */
1538         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1539                 return -ERANGE;
1540         if (LNET_NETTYP(LNET_NIDNET(LNET_PING_INFO_LONI(pinfo))) != LOLND)
1541                 return -EPROTO;
1542         return 0;
1543 }
1544
1545 static void
1546 lnet_ping_target_destroy(void)
1547 {
1548         struct lnet_net *net;
1549         struct lnet_ni  *ni;
1550
1551         lnet_net_lock(LNET_LOCK_EX);
1552
1553         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1554                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1555                         lnet_ni_lock(ni);
1556                         ni->ni_status = NULL;
1557                         lnet_ni_unlock(ni);
1558                 }
1559         }
1560
1561         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1562         the_lnet.ln_ping_target = NULL;
1563
1564         lnet_net_unlock(LNET_LOCK_EX);
1565 }
1566
1567 static void
1568 lnet_ping_target_event_handler(struct lnet_event *event)
1569 {
1570         struct lnet_ping_buffer *pbuf = event->md.user_ptr;
1571
1572         if (event->unlinked)
1573                 lnet_ping_buffer_decref(pbuf);
1574 }
1575
1576 static int
1577 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1578                        struct lnet_handle_md *ping_mdh,
1579                        int ni_count, bool set_eq)
1580 {
1581         struct lnet_process_id id = {
1582                 .nid = LNET_NID_ANY,
1583                 .pid = LNET_PID_ANY
1584         };
1585         struct lnet_handle_me me_handle;
1586         struct lnet_md md = { NULL };
1587         int rc, rc2;
1588
1589         if (set_eq) {
1590                 rc = LNetEQAlloc(0, lnet_ping_target_event_handler,
1591                                  &the_lnet.ln_ping_target_eq);
1592                 if (rc != 0) {
1593                         CERROR("Can't allocate ping buffer EQ: %d\n", rc);
1594                         return rc;
1595                 }
1596         }
1597
1598         *ppbuf = lnet_ping_target_create(ni_count);
1599         if (*ppbuf == NULL) {
1600                 rc = -ENOMEM;
1601                 goto fail_free_eq;
1602         }
1603
1604         /* Ping target ME/MD */
1605         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1606                           LNET_PROTO_PING_MATCHBITS, 0,
1607                           LNET_UNLINK, LNET_INS_AFTER,
1608                           &me_handle);
1609         if (rc != 0) {
1610                 CERROR("Can't create ping target ME: %d\n", rc);
1611                 goto fail_decref_ping_buffer;
1612         }
1613
1614         /* initialize md content */
1615         md.start     = &(*ppbuf)->pb_info;
1616         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1617         md.threshold = LNET_MD_THRESH_INF;
1618         md.max_size  = 0;
1619         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1620                        LNET_MD_MANAGE_REMOTE;
1621         md.eq_handle = the_lnet.ln_ping_target_eq;
1622         md.user_ptr  = *ppbuf;
1623
1624         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, ping_mdh);
1625         if (rc != 0) {
1626                 CERROR("Can't attach ping target MD: %d\n", rc);
1627                 goto fail_unlink_ping_me;
1628         }
1629         lnet_ping_buffer_addref(*ppbuf);
1630
1631         return 0;
1632
1633 fail_unlink_ping_me:
1634         rc2 = LNetMEUnlink(me_handle);
1635         LASSERT(rc2 == 0);
1636 fail_decref_ping_buffer:
1637         LASSERT(lnet_ping_buffer_numref(*ppbuf) == 1);
1638         lnet_ping_buffer_decref(*ppbuf);
1639         *ppbuf = NULL;
1640 fail_free_eq:
1641         if (set_eq) {
1642                 rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1643                 LASSERT(rc2 == 0);
1644         }
1645         return rc;
1646 }
1647
1648 static void
1649 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1650                     struct lnet_handle_md *ping_mdh)
1651 {
1652         sigset_t        blocked = cfs_block_allsigs();
1653
1654         LNetMDUnlink(*ping_mdh);
1655         LNetInvalidateMDHandle(ping_mdh);
1656
1657         /* NB the MD could be busy; this just starts the unlink */
1658         while (lnet_ping_buffer_numref(pbuf) > 1) {
1659                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1660                 set_current_state(TASK_UNINTERRUPTIBLE);
1661                 schedule_timeout(cfs_time_seconds(1));
1662         }
1663
1664         cfs_restore_sigs(blocked);
1665 }
1666
1667 static void
1668 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1669 {
1670         struct lnet_ni          *ni;
1671         struct lnet_net         *net;
1672         struct lnet_ni_status *ns;
1673         int                     i;
1674         int                     rc;
1675
1676         i = 0;
1677         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1678                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1679                         LASSERT(i < pbuf->pb_nnis);
1680
1681                         ns = &pbuf->pb_info.pi_ni[i];
1682
1683                         ns->ns_nid = ni->ni_nid;
1684
1685                         lnet_ni_lock(ni);
1686                         ns->ns_status = (ni->ni_status != NULL) ?
1687                                          ni->ni_status->ns_status :
1688                                                 LNET_NI_STATUS_UP;
1689                         ni->ni_status = ns;
1690                         lnet_ni_unlock(ni);
1691
1692                         i++;
1693                 }
1694         }
1695         /*
1696          * We (ab)use the ns_status of the loopback interface to
1697          * transmit the sequence number. The first interface listed
1698          * must be the loopback interface.
1699          */
1700         rc = lnet_ping_info_validate(&pbuf->pb_info);
1701         if (rc) {
1702                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1703                 LBUG();
1704         }
1705         LNET_PING_BUFFER_SEQNO(pbuf) =
1706                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1707 }
1708
1709 static void
1710 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1711                         struct lnet_handle_md ping_mdh)
1712 {
1713         struct lnet_ping_buffer *old_pbuf = NULL;
1714         struct lnet_handle_md old_ping_md;
1715
1716         /* switch the NIs to point to the new ping info created */
1717         lnet_net_lock(LNET_LOCK_EX);
1718
1719         if (!the_lnet.ln_routing)
1720                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1721         if (!lnet_peer_discovery_disabled)
1722                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1723
1724         /* Ensure only known feature bits have been set. */
1725         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1726         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1727
1728         lnet_ping_target_install_locked(pbuf);
1729
1730         if (the_lnet.ln_ping_target) {
1731                 old_pbuf = the_lnet.ln_ping_target;
1732                 old_ping_md = the_lnet.ln_ping_target_md;
1733         }
1734         the_lnet.ln_ping_target_md = ping_mdh;
1735         the_lnet.ln_ping_target = pbuf;
1736
1737         lnet_net_unlock(LNET_LOCK_EX);
1738
1739         if (old_pbuf) {
1740                 /* unlink and free the old ping info */
1741                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1742                 lnet_ping_buffer_decref(old_pbuf);
1743         }
1744
1745         lnet_push_update_to_peers(0);
1746 }
1747
1748 static void
1749 lnet_ping_target_fini(void)
1750 {
1751         int             rc;
1752
1753         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1754                             &the_lnet.ln_ping_target_md);
1755
1756         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1757         LASSERT(rc == 0);
1758
1759         lnet_ping_target_destroy();
1760 }
1761
1762 /* Resize the push target. */
1763 int lnet_push_target_resize(void)
1764 {
1765         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1766         struct lnet_md md = { NULL };
1767         struct lnet_handle_me meh;
1768         struct lnet_handle_md mdh;
1769         struct lnet_handle_md old_mdh;
1770         struct lnet_ping_buffer *pbuf;
1771         struct lnet_ping_buffer *old_pbuf;
1772         int nnis = the_lnet.ln_push_target_nnis;
1773         int rc;
1774
1775         if (nnis <= 0) {
1776                 rc = -EINVAL;
1777                 goto fail_return;
1778         }
1779 again:
1780         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1781         if (!pbuf) {
1782                 rc = -ENOMEM;
1783                 goto fail_return;
1784         }
1785
1786         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1787                           LNET_PROTO_PING_MATCHBITS, 0,
1788                           LNET_UNLINK, LNET_INS_AFTER,
1789                           &meh);
1790         if (rc) {
1791                 CERROR("Can't create push target ME: %d\n", rc);
1792                 goto fail_decref_pbuf;
1793         }
1794
1795         /* initialize md content */
1796         md.start     = &pbuf->pb_info;
1797         md.length    = LNET_PING_INFO_SIZE(nnis);
1798         md.threshold = LNET_MD_THRESH_INF;
1799         md.max_size  = 0;
1800         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE |
1801                        LNET_MD_MANAGE_REMOTE;
1802         md.user_ptr  = pbuf;
1803         md.eq_handle = the_lnet.ln_push_target_eq;
1804
1805         rc = LNetMDAttach(meh, md, LNET_RETAIN, &mdh);
1806         if (rc) {
1807                 CERROR("Can't attach push MD: %d\n", rc);
1808                 goto fail_unlink_meh;
1809         }
1810         lnet_ping_buffer_addref(pbuf);
1811
1812         lnet_net_lock(LNET_LOCK_EX);
1813         old_pbuf = the_lnet.ln_push_target;
1814         old_mdh = the_lnet.ln_push_target_md;
1815         the_lnet.ln_push_target = pbuf;
1816         the_lnet.ln_push_target_md = mdh;
1817         lnet_net_unlock(LNET_LOCK_EX);
1818
1819         if (old_pbuf) {
1820                 LNetMDUnlink(old_mdh);
1821                 lnet_ping_buffer_decref(old_pbuf);
1822         }
1823
1824         if (nnis < the_lnet.ln_push_target_nnis)
1825                 goto again;
1826
1827         CDEBUG(D_NET, "nnis %d success\n", nnis);
1828
1829         return 0;
1830
1831 fail_unlink_meh:
1832         LNetMEUnlink(meh);
1833 fail_decref_pbuf:
1834         lnet_ping_buffer_decref(pbuf);
1835 fail_return:
1836         CDEBUG(D_NET, "nnis %d error %d\n", nnis, rc);
1837         return rc;
1838 }
1839
1840 static void lnet_push_target_event_handler(struct lnet_event *ev)
1841 {
1842         struct lnet_ping_buffer *pbuf = ev->md.user_ptr;
1843
1844         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1845                 lnet_swap_pinginfo(pbuf);
1846
1847         lnet_peer_push_event(ev);
1848         if (ev->unlinked)
1849                 lnet_ping_buffer_decref(pbuf);
1850 }
1851
1852 /* Initialize the push target. */
1853 static int lnet_push_target_init(void)
1854 {
1855         int rc;
1856
1857         if (the_lnet.ln_push_target)
1858                 return -EALREADY;
1859
1860         rc = LNetEQAlloc(0, lnet_push_target_event_handler,
1861                          &the_lnet.ln_push_target_eq);
1862         if (rc) {
1863                 CERROR("Can't allocated push target EQ: %d\n", rc);
1864                 return rc;
1865         }
1866
1867         /* Start at the required minimum, we'll enlarge if required. */
1868         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
1869
1870         rc = lnet_push_target_resize();
1871
1872         if (rc) {
1873                 LNetEQFree(the_lnet.ln_push_target_eq);
1874                 LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1875         }
1876
1877         return rc;
1878 }
1879
1880 /* Clean up the push target. */
1881 static void lnet_push_target_fini(void)
1882 {
1883         if (!the_lnet.ln_push_target)
1884                 return;
1885
1886         /* Unlink and invalidate to prevent new references. */
1887         LNetMDUnlink(the_lnet.ln_push_target_md);
1888         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
1889
1890         /* Wait for the unlink to complete. */
1891         while (lnet_ping_buffer_numref(the_lnet.ln_push_target) > 1) {
1892                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1893                 set_current_state(TASK_UNINTERRUPTIBLE);
1894                 schedule_timeout(cfs_time_seconds(1));
1895         }
1896
1897         lnet_ping_buffer_decref(the_lnet.ln_push_target);
1898         the_lnet.ln_push_target = NULL;
1899         the_lnet.ln_push_target_nnis = 0;
1900
1901         LNetEQFree(the_lnet.ln_push_target_eq);
1902         LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1903 }
1904
1905 static int
1906 lnet_ni_tq_credits(struct lnet_ni *ni)
1907 {
1908         int     credits;
1909
1910         LASSERT(ni->ni_ncpts >= 1);
1911
1912         if (ni->ni_ncpts == 1)
1913                 return ni->ni_net->net_tunables.lct_max_tx_credits;
1914
1915         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
1916         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
1917         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
1918
1919         return credits;
1920 }
1921
1922 static void
1923 lnet_ni_unlink_locked(struct lnet_ni *ni)
1924 {
1925         /* move it to zombie list and nobody can find it anymore */
1926         LASSERT(!list_empty(&ni->ni_netlist));
1927         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
1928         lnet_ni_decref_locked(ni, 0);
1929 }
1930
1931 static void
1932 lnet_clear_zombies_nis_locked(struct lnet_net *net)
1933 {
1934         int             i;
1935         int             islo;
1936         struct lnet_ni  *ni;
1937         struct list_head *zombie_list = &net->net_ni_zombie;
1938
1939         /*
1940          * Now wait for the NIs I just nuked to show up on the zombie
1941          * list and shut them down in guaranteed thread context
1942          */
1943         i = 2;
1944         while (!list_empty(zombie_list)) {
1945                 int     *ref;
1946                 int     j;
1947
1948                 ni = list_entry(zombie_list->next,
1949                                 struct lnet_ni, ni_netlist);
1950                 list_del_init(&ni->ni_netlist);
1951                 /* the ni should be in deleting state. If it's not it's
1952                  * a bug */
1953                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
1954                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1955                         if (*ref == 0)
1956                                 continue;
1957                         /* still busy, add it back to zombie list */
1958                         list_add(&ni->ni_netlist, zombie_list);
1959                         break;
1960                 }
1961
1962                 if (!list_empty(&ni->ni_netlist)) {
1963                         lnet_net_unlock(LNET_LOCK_EX);
1964                         ++i;
1965                         if ((i & (-i)) == i) {
1966                                 CDEBUG(D_WARNING,
1967                                        "Waiting for zombie LNI %s\n",
1968                                        libcfs_nid2str(ni->ni_nid));
1969                         }
1970                         set_current_state(TASK_UNINTERRUPTIBLE);
1971                         schedule_timeout(cfs_time_seconds(1));
1972                         lnet_net_lock(LNET_LOCK_EX);
1973                         continue;
1974                 }
1975
1976                 lnet_net_unlock(LNET_LOCK_EX);
1977
1978                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
1979
1980                 LASSERT(!in_interrupt());
1981                 (net->net_lnd->lnd_shutdown)(ni);
1982
1983                 if (!islo)
1984                         CDEBUG(D_LNI, "Removed LNI %s\n",
1985                               libcfs_nid2str(ni->ni_nid));
1986
1987                 lnet_ni_free(ni);
1988                 i = 2;
1989                 lnet_net_lock(LNET_LOCK_EX);
1990         }
1991 }
1992
1993 /* shutdown down the NI and release refcount */
1994 static void
1995 lnet_shutdown_lndni(struct lnet_ni *ni)
1996 {
1997         int i;
1998         struct lnet_net *net = ni->ni_net;
1999
2000         lnet_net_lock(LNET_LOCK_EX);
2001         lnet_ni_lock(ni);
2002         ni->ni_state = LNET_NI_STATE_DELETING;
2003         lnet_ni_unlock(ni);
2004         lnet_ni_unlink_locked(ni);
2005         lnet_incr_dlc_seq();
2006         lnet_net_unlock(LNET_LOCK_EX);
2007
2008         /* clear messages for this NI on the lazy portal */
2009         for (i = 0; i < the_lnet.ln_nportals; i++)
2010                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2011
2012         lnet_net_lock(LNET_LOCK_EX);
2013         lnet_clear_zombies_nis_locked(net);
2014         lnet_net_unlock(LNET_LOCK_EX);
2015 }
2016
2017 static void
2018 lnet_shutdown_lndnet(struct lnet_net *net)
2019 {
2020         struct lnet_ni *ni;
2021
2022         lnet_net_lock(LNET_LOCK_EX);
2023
2024         net->net_state = LNET_NET_STATE_DELETING;
2025
2026         list_del_init(&net->net_list);
2027
2028         while (!list_empty(&net->net_ni_list)) {
2029                 ni = list_entry(net->net_ni_list.next,
2030                                 struct lnet_ni, ni_netlist);
2031                 lnet_net_unlock(LNET_LOCK_EX);
2032                 lnet_shutdown_lndni(ni);
2033                 lnet_net_lock(LNET_LOCK_EX);
2034         }
2035
2036         lnet_net_unlock(LNET_LOCK_EX);
2037
2038         /* Do peer table cleanup for this net */
2039         lnet_peer_tables_cleanup(net);
2040
2041         lnet_net_lock(LNET_LOCK_EX);
2042         /*
2043          * decrement ref count on lnd only when the entire network goes
2044          * away
2045          */
2046         net->net_lnd->lnd_refcount--;
2047
2048         lnet_net_unlock(LNET_LOCK_EX);
2049
2050         lnet_net_free(net);
2051 }
2052
2053 static void
2054 lnet_shutdown_lndnets(void)
2055 {
2056         struct lnet_net *net;
2057         struct list_head resend;
2058         struct lnet_msg *msg, *tmp;
2059
2060         INIT_LIST_HEAD(&resend);
2061
2062         /* NB called holding the global mutex */
2063
2064         /* All quiet on the API front */
2065         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2066         LASSERT(the_lnet.ln_refcount == 0);
2067
2068         lnet_net_lock(LNET_LOCK_EX);
2069         the_lnet.ln_state = LNET_STATE_STOPPING;
2070
2071         while (!list_empty(&the_lnet.ln_nets)) {
2072                 /*
2073                  * move the nets to the zombie list to avoid them being
2074                  * picked up for new work. LONET is also included in the
2075                  * Nets that will be moved to the zombie list
2076                  */
2077                 net = list_entry(the_lnet.ln_nets.next,
2078                                  struct lnet_net, net_list);
2079                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
2080         }
2081
2082         /* Drop the cached loopback Net. */
2083         if (the_lnet.ln_loni != NULL) {
2084                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2085                 the_lnet.ln_loni = NULL;
2086         }
2087         lnet_net_unlock(LNET_LOCK_EX);
2088
2089         /* iterate through the net zombie list and delete each net */
2090         while (!list_empty(&the_lnet.ln_net_zombie)) {
2091                 net = list_entry(the_lnet.ln_net_zombie.next,
2092                                  struct lnet_net, net_list);
2093                 lnet_shutdown_lndnet(net);
2094         }
2095
2096         spin_lock(&the_lnet.ln_msg_resend_lock);
2097         list_splice(&the_lnet.ln_msg_resend, &resend);
2098         spin_unlock(&the_lnet.ln_msg_resend_lock);
2099
2100         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2101                 list_del_init(&msg->msg_list);
2102                 msg->msg_no_resend = true;
2103                 lnet_finalize(msg, -ECANCELED);
2104         }
2105
2106         lnet_net_lock(LNET_LOCK_EX);
2107         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2108         lnet_net_unlock(LNET_LOCK_EX);
2109 }
2110
2111 static int
2112 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2113 {
2114         int                     rc = -EINVAL;
2115         struct lnet_tx_queue    *tq;
2116         int                     i;
2117         struct lnet_net         *net = ni->ni_net;
2118
2119         mutex_lock(&the_lnet.ln_lnd_mutex);
2120
2121         if (tun) {
2122                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2123                 ni->ni_lnd_tunables_set = true;
2124         }
2125
2126         rc = (net->net_lnd->lnd_startup)(ni);
2127
2128         mutex_unlock(&the_lnet.ln_lnd_mutex);
2129
2130         if (rc != 0) {
2131                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2132                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2133                 lnet_net_lock(LNET_LOCK_EX);
2134                 net->net_lnd->lnd_refcount--;
2135                 lnet_net_unlock(LNET_LOCK_EX);
2136                 goto failed0;
2137         }
2138
2139         lnet_ni_lock(ni);
2140         ni->ni_state = LNET_NI_STATE_ACTIVE;
2141         lnet_ni_unlock(ni);
2142
2143         /* We keep a reference on the loopback net through the loopback NI */
2144         if (net->net_lnd->lnd_type == LOLND) {
2145                 lnet_ni_addref(ni);
2146                 LASSERT(the_lnet.ln_loni == NULL);
2147                 the_lnet.ln_loni = ni;
2148                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2149                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2150                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2151                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2152                 return 0;
2153         }
2154
2155         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2156             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2157                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2158                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2159                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2160                                         "" : "per-peer ");
2161                 /* shutdown the NI since if we get here then it must've already
2162                  * been started
2163                  */
2164                 lnet_shutdown_lndni(ni);
2165                 return -EINVAL;
2166         }
2167
2168         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2169                 tq->tq_credits_min =
2170                 tq->tq_credits_max =
2171                 tq->tq_credits = lnet_ni_tq_credits(ni);
2172         }
2173
2174         atomic_set(&ni->ni_tx_credits,
2175                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2176         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2177
2178         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2179                 libcfs_nid2str(ni->ni_nid),
2180                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2181                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2182                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2183                 ni->ni_net->net_tunables.lct_peer_timeout);
2184
2185         return 0;
2186 failed0:
2187         lnet_ni_free(ni);
2188         return rc;
2189 }
2190
2191 static int
2192 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2193 {
2194         struct lnet_ni *ni;
2195         struct lnet_net *net_l = NULL;
2196         struct list_head        local_ni_list;
2197         int                     rc;
2198         int                     ni_count = 0;
2199         __u32                   lnd_type;
2200         struct lnet_lnd *lnd;
2201         int                     peer_timeout =
2202                 net->net_tunables.lct_peer_timeout;
2203         int                     maxtxcredits =
2204                 net->net_tunables.lct_max_tx_credits;
2205         int                     peerrtrcredits =
2206                 net->net_tunables.lct_peer_rtr_credits;
2207
2208         INIT_LIST_HEAD(&local_ni_list);
2209
2210         /*
2211          * make sure that this net is unique. If it isn't then
2212          * we are adding interfaces to an already existing network, and
2213          * 'net' is just a convenient way to pass in the list.
2214          * if it is unique we need to find the LND and load it if
2215          * necessary.
2216          */
2217         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2218                 lnd_type = LNET_NETTYP(net->net_id);
2219
2220                 mutex_lock(&the_lnet.ln_lnd_mutex);
2221                 lnd = lnet_find_lnd_by_type(lnd_type);
2222
2223                 if (lnd == NULL) {
2224                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2225                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2226                         mutex_lock(&the_lnet.ln_lnd_mutex);
2227
2228                         lnd = lnet_find_lnd_by_type(lnd_type);
2229                         if (lnd == NULL) {
2230                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2231                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2232                                 libcfs_lnd2str(lnd_type),
2233                                 libcfs_lnd2modname(lnd_type), rc);
2234 #ifndef HAVE_MODULE_LOADING_SUPPORT
2235                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2236                                                 "compiled with kernel module "
2237                                                 "loading support.");
2238 #endif
2239                                 rc = -EINVAL;
2240                                 goto failed0;
2241                         }
2242                 }
2243
2244                 lnet_net_lock(LNET_LOCK_EX);
2245                 lnd->lnd_refcount++;
2246                 lnet_net_unlock(LNET_LOCK_EX);
2247
2248                 net->net_lnd = lnd;
2249
2250                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2251
2252                 net_l = net;
2253         }
2254
2255         /*
2256          * net_l: if the network being added is unique then net_l
2257          *        will point to that network
2258          *        if the network being added is not unique then
2259          *        net_l points to the existing network.
2260          *
2261          * When we enter the loop below, we'll pick NIs off he
2262          * network beign added and start them up, then add them to
2263          * a local ni list. Once we've successfully started all
2264          * the NIs then we join the local NI list (of started up
2265          * networks) with the net_l->net_ni_list, which should
2266          * point to the correct network to add the new ni list to
2267          *
2268          * If any of the new NIs fail to start up, then we want to
2269          * iterate through the local ni list, which should include
2270          * any NIs which were successfully started up, and shut
2271          * them down.
2272          *
2273          * After than we want to delete the network being added,
2274          * to avoid a memory leak.
2275          */
2276
2277         /*
2278          * When a network uses TCP bonding then all its interfaces
2279          * must be specified when the network is first defined: the
2280          * TCP bonding code doesn't allow for interfaces to be added
2281          * or removed.
2282          */
2283         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2284             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2285                 rc = -EINVAL;
2286                 goto failed0;
2287         }
2288
2289         while (!list_empty(&net->net_ni_added)) {
2290                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2291                                 ni_netlist);
2292                 list_del_init(&ni->ni_netlist);
2293
2294                 /* make sure that the the NI we're about to start
2295                  * up is actually unique. if it's not fail. */
2296                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2297                                         ni->ni_interfaces[0])) {
2298                         rc = -EINVAL;
2299                         goto failed1;
2300                 }
2301
2302                 /* adjust the pointer the parent network, just in case it
2303                  * the net is a duplicate */
2304                 ni->ni_net = net_l;
2305
2306                 rc = lnet_startup_lndni(ni, tun);
2307
2308                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
2309                         ni->ni_net->net_lnd->lnd_query != NULL);
2310
2311                 if (rc < 0)
2312                         goto failed1;
2313
2314                 lnet_ni_addref(ni);
2315                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2316
2317                 ni_count++;
2318         }
2319
2320         lnet_net_lock(LNET_LOCK_EX);
2321         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2322         lnet_incr_dlc_seq();
2323         lnet_net_unlock(LNET_LOCK_EX);
2324
2325         /* if the network is not unique then we don't want to keep
2326          * it around after we're done. Free it. Otherwise add that
2327          * net to the global the_lnet.ln_nets */
2328         if (net_l != net && net_l != NULL) {
2329                 /*
2330                  * TODO - note. currently the tunables can not be updated
2331                  * once added
2332                  */
2333                 lnet_net_free(net);
2334         } else {
2335                 net->net_state = LNET_NET_STATE_ACTIVE;
2336                 /*
2337                  * restore tunables after it has been overwitten by the
2338                  * lnd
2339                  */
2340                 if (peer_timeout != -1)
2341                         net->net_tunables.lct_peer_timeout = peer_timeout;
2342                 if (maxtxcredits != -1)
2343                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2344                 if (peerrtrcredits != -1)
2345                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2346
2347                 lnet_net_lock(LNET_LOCK_EX);
2348                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2349                 lnet_net_unlock(LNET_LOCK_EX);
2350         }
2351
2352         return ni_count;
2353
2354 failed1:
2355         /*
2356          * shutdown the new NIs that are being started up
2357          * free the NET being started
2358          */
2359         while (!list_empty(&local_ni_list)) {
2360                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2361                                 ni_netlist);
2362
2363                 lnet_shutdown_lndni(ni);
2364         }
2365
2366 failed0:
2367         lnet_net_free(net);
2368
2369         return rc;
2370 }
2371
2372 static int
2373 lnet_startup_lndnets(struct list_head *netlist)
2374 {
2375         struct lnet_net         *net;
2376         int                     rc;
2377         int                     ni_count = 0;
2378
2379         /*
2380          * Change to running state before bringing up the LNDs. This
2381          * allows lnet_shutdown_lndnets() to assert that we've passed
2382          * through here.
2383          */
2384         lnet_net_lock(LNET_LOCK_EX);
2385         the_lnet.ln_state = LNET_STATE_RUNNING;
2386         lnet_net_unlock(LNET_LOCK_EX);
2387
2388         while (!list_empty(netlist)) {
2389                 net = list_entry(netlist->next, struct lnet_net, net_list);
2390                 list_del_init(&net->net_list);
2391
2392                 rc = lnet_startup_lndnet(net, NULL);
2393
2394                 if (rc < 0)
2395                         goto failed;
2396
2397                 ni_count += rc;
2398         }
2399
2400         return ni_count;
2401 failed:
2402         lnet_shutdown_lndnets();
2403
2404         return rc;
2405 }
2406
2407 /**
2408  * Initialize LNet library.
2409  *
2410  * Automatically called at module loading time. Caller has to call
2411  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2412  * latter returned 0. It must be called exactly once.
2413  *
2414  * \retval 0 on success
2415  * \retval -ve on failures.
2416  */
2417 int lnet_lib_init(void)
2418 {
2419         int rc;
2420
2421         lnet_assert_wire_constants();
2422
2423         /* refer to global cfs_cpt_table for now */
2424         the_lnet.ln_cpt_table   = cfs_cpt_table;
2425         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2426
2427         LASSERT(the_lnet.ln_cpt_number > 0);
2428         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2429                 /* we are under risk of consuming all lh_cookie */
2430                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2431                        "please change setting of CPT-table and retry\n",
2432                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2433                 return -E2BIG;
2434         }
2435
2436         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2437                 the_lnet.ln_cpt_bits++;
2438
2439         rc = lnet_create_locks();
2440         if (rc != 0) {
2441                 CERROR("Can't create LNet global locks: %d\n", rc);
2442                 return rc;
2443         }
2444
2445         the_lnet.ln_refcount = 0;
2446         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2447         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2448         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2449         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2450         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2451         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2452
2453         /* The hash table size is the number of bits it takes to express the set
2454          * ln_num_routes, minus 1 (better to under estimate than over so we
2455          * don't waste memory). */
2456         if (rnet_htable_size <= 0)
2457                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2458         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2459                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2460         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2461                                            order_base_2(rnet_htable_size) - 1);
2462
2463         /* All LNDs apart from the LOLND are in separate modules.  They
2464          * register themselves when their module loads, and unregister
2465          * themselves when their module is unloaded. */
2466         lnet_register_lnd(&the_lolnd);
2467         return 0;
2468 }
2469
2470 /**
2471  * Finalize LNet library.
2472  *
2473  * \pre lnet_lib_init() called with success.
2474  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2475  */
2476 void lnet_lib_exit(void)
2477 {
2478         LASSERT(the_lnet.ln_refcount == 0);
2479
2480         while (!list_empty(&the_lnet.ln_lnds))
2481                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2482                                                struct lnet_lnd, lnd_list));
2483         lnet_destroy_locks();
2484 }
2485
2486 /**
2487  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2488  *
2489  * Users must call this function at least once before any other functions.
2490  * For each successful call there must be a corresponding call to
2491  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2492  * ignored.
2493  *
2494  * The PID used by LNet may be different from the one requested.
2495  * See LNetGetId().
2496  *
2497  * \param requested_pid PID requested by the caller.
2498  *
2499  * \return >= 0 on success, and < 0 error code on failures.
2500  */
2501 int
2502 LNetNIInit(lnet_pid_t requested_pid)
2503 {
2504         int                     im_a_router = 0;
2505         int                     rc;
2506         int                     ni_count;
2507         struct lnet_ping_buffer *pbuf;
2508         struct lnet_handle_md   ping_mdh;
2509         struct list_head        net_head;
2510         struct lnet_net         *net;
2511
2512         INIT_LIST_HEAD(&net_head);
2513
2514         mutex_lock(&the_lnet.ln_api_mutex);
2515
2516         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2517
2518         if (the_lnet.ln_refcount > 0) {
2519                 rc = the_lnet.ln_refcount++;
2520                 mutex_unlock(&the_lnet.ln_api_mutex);
2521                 return rc;
2522         }
2523
2524         rc = lnet_prepare(requested_pid);
2525         if (rc != 0) {
2526                 mutex_unlock(&the_lnet.ln_api_mutex);
2527                 return rc;
2528         }
2529
2530         /* create a network for Loopback network */
2531         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2532         if (net == NULL) {
2533                 rc = -ENOMEM;
2534                 goto err_empty_list;
2535         }
2536
2537         /* Add in the loopback NI */
2538         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2539                 rc = -ENOMEM;
2540                 goto err_empty_list;
2541         }
2542
2543         /* If LNet is being initialized via DLC it is possible
2544          * that the user requests not to load module parameters (ones which
2545          * are supported by DLC) on initialization.  Therefore, make sure not
2546          * to load networks, routes and forwarding from module parameters
2547          * in this case.  On cleanup in case of failure only clean up
2548          * routes if it has been loaded */
2549         if (!the_lnet.ln_nis_from_mod_params) {
2550                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2551                                          use_tcp_bonding);
2552                 if (rc < 0)
2553                         goto err_empty_list;
2554         }
2555
2556         ni_count = lnet_startup_lndnets(&net_head);
2557         if (ni_count < 0) {
2558                 rc = ni_count;
2559                 goto err_empty_list;
2560         }
2561
2562         if (!the_lnet.ln_nis_from_mod_params) {
2563                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2564                 if (rc != 0)
2565                         goto err_shutdown_lndnis;
2566
2567                 rc = lnet_check_routes();
2568                 if (rc != 0)
2569                         goto err_destroy_routes;
2570
2571                 rc = lnet_rtrpools_alloc(im_a_router);
2572                 if (rc != 0)
2573                         goto err_destroy_routes;
2574         }
2575
2576         rc = lnet_acceptor_start();
2577         if (rc != 0)
2578                 goto err_destroy_routes;
2579
2580         the_lnet.ln_refcount = 1;
2581         /* Now I may use my own API functions... */
2582
2583         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2584         if (rc != 0)
2585                 goto err_acceptor_stop;
2586
2587         lnet_ping_target_update(pbuf, ping_mdh);
2588
2589         rc = lnet_monitor_thr_start();
2590         if (rc != 0)
2591                 goto err_stop_ping;
2592
2593         rc = lnet_push_target_init();
2594         if (rc != 0)
2595                 goto err_stop_monitor_thr;
2596
2597         rc = lnet_peer_discovery_start();
2598         if (rc != 0)
2599                 goto err_destroy_push_target;
2600
2601         lnet_fault_init();
2602         lnet_router_debugfs_init();
2603
2604         mutex_unlock(&the_lnet.ln_api_mutex);
2605
2606         return 0;
2607
2608 err_destroy_push_target:
2609         lnet_push_target_fini();
2610 err_stop_monitor_thr:
2611         lnet_monitor_thr_stop();
2612 err_stop_ping:
2613         lnet_ping_target_fini();
2614 err_acceptor_stop:
2615         the_lnet.ln_refcount = 0;
2616         lnet_acceptor_stop();
2617 err_destroy_routes:
2618         if (!the_lnet.ln_nis_from_mod_params)
2619                 lnet_destroy_routes();
2620 err_shutdown_lndnis:
2621         lnet_shutdown_lndnets();
2622 err_empty_list:
2623         lnet_unprepare();
2624         LASSERT(rc < 0);
2625         mutex_unlock(&the_lnet.ln_api_mutex);
2626         while (!list_empty(&net_head)) {
2627                 struct lnet_net *net;
2628
2629                 net = list_entry(net_head.next, struct lnet_net, net_list);
2630                 list_del_init(&net->net_list);
2631                 lnet_net_free(net);
2632         }
2633         return rc;
2634 }
2635 EXPORT_SYMBOL(LNetNIInit);
2636
2637 /**
2638  * Stop LNet interfaces, routing, and forwarding.
2639  *
2640  * Users must call this function once for each successful call to LNetNIInit().
2641  * Once the LNetNIFini() operation has been started, the results of pending
2642  * API operations are undefined.
2643  *
2644  * \return always 0 for current implementation.
2645  */
2646 int
2647 LNetNIFini()
2648 {
2649         mutex_lock(&the_lnet.ln_api_mutex);
2650
2651         LASSERT(the_lnet.ln_refcount > 0);
2652
2653         if (the_lnet.ln_refcount != 1) {
2654                 the_lnet.ln_refcount--;
2655         } else {
2656                 LASSERT(!the_lnet.ln_niinit_self);
2657
2658                 lnet_fault_fini();
2659
2660                 lnet_router_debugfs_fini();
2661                 lnet_peer_discovery_stop();
2662                 lnet_push_target_fini();
2663                 lnet_monitor_thr_stop();
2664                 lnet_ping_target_fini();
2665
2666                 /* Teardown fns that use my own API functions BEFORE here */
2667                 the_lnet.ln_refcount = 0;
2668
2669                 lnet_acceptor_stop();
2670                 lnet_destroy_routes();
2671                 lnet_shutdown_lndnets();
2672                 lnet_unprepare();
2673         }
2674
2675         mutex_unlock(&the_lnet.ln_api_mutex);
2676         return 0;
2677 }
2678 EXPORT_SYMBOL(LNetNIFini);
2679
2680 /**
2681  * Grabs the ni data from the ni structure and fills the out
2682  * parameters
2683  *
2684  * \param[in] ni network        interface structure
2685  * \param[out] cfg_ni           NI config information
2686  * \param[out] tun              network and LND tunables
2687  */
2688 static void
2689 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2690                    struct lnet_ioctl_config_lnd_tunables *tun,
2691                    struct lnet_ioctl_element_stats *stats,
2692                    __u32 tun_size)
2693 {
2694         size_t min_size = 0;
2695         int i;
2696
2697         if (!ni || !cfg_ni || !tun)
2698                 return;
2699
2700         if (ni->ni_interfaces[0] != NULL) {
2701                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2702                         if (ni->ni_interfaces[i] != NULL) {
2703                                 strncpy(cfg_ni->lic_ni_intf[i],
2704                                         ni->ni_interfaces[i],
2705                                         sizeof(cfg_ni->lic_ni_intf[i]));
2706                         }
2707                 }
2708         }
2709
2710         cfg_ni->lic_nid = ni->ni_nid;
2711         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2712                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2713         else
2714                 cfg_ni->lic_status = ni->ni_status->ns_status;
2715         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2716         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2717
2718         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2719
2720         if (stats) {
2721                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2722                                                        LNET_STATS_TYPE_SEND);
2723                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2724                                                        LNET_STATS_TYPE_RECV);
2725                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2726                                                        LNET_STATS_TYPE_DROP);
2727         }
2728
2729         /*
2730          * tun->lt_tun will always be present, but in order to be
2731          * backwards compatible, we need to deal with the cases when
2732          * tun->lt_tun is smaller than what the kernel has, because it
2733          * comes from an older version of a userspace program, then we'll
2734          * need to copy as much information as we have available space.
2735          */
2736         min_size = tun_size - sizeof(tun->lt_cmn);
2737         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2738
2739         /* copy over the cpts */
2740         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2741             ni->ni_cpts == NULL)  {
2742                 for (i = 0; i < ni->ni_ncpts; i++)
2743                         cfg_ni->lic_cpts[i] = i;
2744         } else {
2745                 for (i = 0;
2746                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2747                      i < LNET_MAX_SHOW_NUM_CPT;
2748                      i++)
2749                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2750         }
2751         cfg_ni->lic_ncpts = ni->ni_ncpts;
2752 }
2753
2754 /**
2755  * NOTE: This is a legacy function left in the code to be backwards
2756  * compatible with older userspace programs. It should eventually be
2757  * removed.
2758  *
2759  * Grabs the ni data from the ni structure and fills the out
2760  * parameters
2761  *
2762  * \param[in] ni network        interface structure
2763  * \param[out] config           config information
2764  */
2765 static void
2766 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2767                          struct lnet_ioctl_config_data *config)
2768 {
2769         struct lnet_ioctl_net_config *net_config;
2770         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2771         size_t min_size, tunable_size = 0;
2772         int i;
2773
2774         if (!ni || !config)
2775                 return;
2776
2777         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2778         if (!net_config)
2779                 return;
2780
2781         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2782                      ARRAY_SIZE(net_config->ni_interfaces));
2783
2784         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2785                 if (!ni->ni_interfaces[i])
2786                         break;
2787
2788                 strncpy(net_config->ni_interfaces[i],
2789                         ni->ni_interfaces[i],
2790                         sizeof(net_config->ni_interfaces[i]));
2791         }
2792
2793         config->cfg_nid = ni->ni_nid;
2794         config->cfg_config_u.cfg_net.net_peer_timeout =
2795                 ni->ni_net->net_tunables.lct_peer_timeout;
2796         config->cfg_config_u.cfg_net.net_max_tx_credits =
2797                 ni->ni_net->net_tunables.lct_max_tx_credits;
2798         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2799                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2800         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2801                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2802
2803         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2804                 net_config->ni_status = LNET_NI_STATUS_UP;
2805         else
2806                 net_config->ni_status = ni->ni_status->ns_status;
2807
2808         if (ni->ni_cpts) {
2809                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2810
2811                 for (i = 0; i < num_cpts; i++)
2812                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2813
2814                 config->cfg_ncpts = num_cpts;
2815         }
2816
2817         /*
2818          * See if user land tools sent in a newer and larger version
2819          * of struct lnet_tunables than what the kernel uses.
2820          */
2821         min_size = sizeof(*config) + sizeof(*net_config);
2822
2823         if (config->cfg_hdr.ioc_len > min_size)
2824                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2825
2826         /* Don't copy too much data to user space */
2827         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2828         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2829
2830         if (lnd_cfg && min_size) {
2831                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2832                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2833
2834                 /* Tell user land that kernel side has less data */
2835                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2836                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2837                         config->cfg_hdr.ioc_len -= min_size;
2838                 }
2839         }
2840 }
2841
2842 struct lnet_ni *
2843 lnet_get_ni_idx_locked(int idx)
2844 {
2845         struct lnet_ni          *ni;
2846         struct lnet_net         *net;
2847
2848         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2849                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2850                         if (idx-- == 0)
2851                                 return ni;
2852                 }
2853         }
2854
2855         return NULL;
2856 }
2857
2858 struct lnet_ni *
2859 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2860 {
2861         struct lnet_ni          *ni;
2862         struct lnet_net         *net = mynet;
2863
2864         /*
2865          * It is possible that the net has been cleaned out while there is
2866          * a message being sent. This function accessed the net without
2867          * checking if the list is empty
2868          */
2869         if (prev == NULL) {
2870                 if (net == NULL)
2871                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2872                                         net_list);
2873                 if (list_empty(&net->net_ni_list))
2874                         return NULL;
2875                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2876                                 ni_netlist);
2877
2878                 return ni;
2879         }
2880
2881         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2882                 /* if you reached the end of the ni list and the net is
2883                  * specified, then there are no more nis in that net */
2884                 if (net != NULL)
2885                         return NULL;
2886
2887                 /* we reached the end of this net ni list. move to the
2888                  * next net */
2889                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2890                         /* no more nets and no more NIs. */
2891                         return NULL;
2892
2893                 /* get the next net */
2894                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2895                                  net_list);
2896                 if (list_empty(&net->net_ni_list))
2897                         return NULL;
2898                 /* get the ni on it */
2899                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2900                                 ni_netlist);
2901
2902                 return ni;
2903         }
2904
2905         if (list_empty(&prev->ni_netlist))
2906                 return NULL;
2907
2908         /* there are more nis left */
2909         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2910
2911         return ni;
2912 }
2913
2914 int
2915 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2916 {
2917         struct lnet_ni *ni;
2918         int cpt;
2919         int rc = -ENOENT;
2920         int idx = config->cfg_count;
2921
2922         cpt = lnet_net_lock_current();
2923
2924         ni = lnet_get_ni_idx_locked(idx);
2925
2926         if (ni != NULL) {
2927                 rc = 0;
2928                 lnet_ni_lock(ni);
2929                 lnet_fill_ni_info_legacy(ni, config);
2930                 lnet_ni_unlock(ni);
2931         }
2932
2933         lnet_net_unlock(cpt);
2934         return rc;
2935 }
2936
2937 int
2938 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2939                    struct lnet_ioctl_config_lnd_tunables *tun,
2940                    struct lnet_ioctl_element_stats *stats,
2941                    __u32 tun_size)
2942 {
2943         struct lnet_ni          *ni;
2944         int                     cpt;
2945         int                     rc = -ENOENT;
2946
2947         if (!cfg_ni || !tun || !stats)
2948                 return -EINVAL;
2949
2950         cpt = lnet_net_lock_current();
2951
2952         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2953
2954         if (ni) {
2955                 rc = 0;
2956                 lnet_ni_lock(ni);
2957                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2958                 lnet_ni_unlock(ni);
2959         }
2960
2961         lnet_net_unlock(cpt);
2962         return rc;
2963 }
2964
2965 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2966 {
2967         struct lnet_ni *ni;
2968         int cpt;
2969         int rc = -ENOENT;
2970
2971         if (!msg_stats)
2972                 return -EINVAL;
2973
2974         cpt = lnet_net_lock_current();
2975
2976         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2977
2978         if (ni) {
2979                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2980                 rc = 0;
2981         }
2982
2983         lnet_net_unlock(cpt);
2984
2985         return rc;
2986 }
2987
2988 static int lnet_add_net_common(struct lnet_net *net,
2989                                struct lnet_ioctl_config_lnd_tunables *tun)
2990 {
2991         __u32                   net_id;
2992         struct lnet_ping_buffer *pbuf;
2993         struct lnet_handle_md   ping_mdh;
2994         int                     rc;
2995         struct lnet_remotenet *rnet;
2996         int                     net_ni_count;
2997         int                     num_acceptor_nets;
2998
2999         lnet_net_lock(LNET_LOCK_EX);
3000         rnet = lnet_find_rnet_locked(net->net_id);
3001         lnet_net_unlock(LNET_LOCK_EX);
3002         /*
3003          * make sure that the net added doesn't invalidate the current
3004          * configuration LNet is keeping
3005          */
3006         if (rnet) {
3007                 CERROR("Adding net %s will invalidate routing configuration\n",
3008                        libcfs_net2str(net->net_id));
3009                 lnet_net_free(net);
3010                 return -EUSERS;
3011         }
3012
3013         /*
3014          * make sure you calculate the correct number of slots in the ping
3015          * buffer. Since the ping info is a flattened list of all the NIs,
3016          * we should allocate enough slots to accomodate the number of NIs
3017          * which will be added.
3018          *
3019          * since ni hasn't been configured yet, use
3020          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3021          */
3022         net_ni_count = lnet_get_net_ni_count_pre(net);
3023
3024         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3025                                     net_ni_count + lnet_get_ni_count(),
3026                                     false);
3027         if (rc < 0) {
3028                 lnet_net_free(net);
3029                 return rc;
3030         }
3031
3032         if (tun)
3033                 memcpy(&net->net_tunables,
3034                        &tun->lt_cmn, sizeof(net->net_tunables));
3035         else
3036                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3037
3038         /*
3039          * before starting this network get a count of the current TCP
3040          * networks which require the acceptor thread running. If that
3041          * count is == 0 before we start up this network, then we'd want to
3042          * start up the acceptor thread after starting up this network
3043          */
3044         num_acceptor_nets = lnet_count_acceptor_nets();
3045
3046         net_id = net->net_id;
3047
3048         rc = lnet_startup_lndnet(net,
3049                                  (tun) ? &tun->lt_tun : NULL);
3050         if (rc < 0)
3051                 goto failed;
3052
3053         lnet_net_lock(LNET_LOCK_EX);
3054         net = lnet_get_net_locked(net_id);
3055         lnet_net_unlock(LNET_LOCK_EX);
3056
3057         LASSERT(net);
3058
3059         /*
3060          * Start the acceptor thread if this is the first network
3061          * being added that requires the thread.
3062          */
3063         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
3064                 rc = lnet_acceptor_start();
3065                 if (rc < 0) {
3066                         /* shutdown the net that we just started */
3067                         CERROR("Failed to start up acceptor thread\n");
3068                         lnet_shutdown_lndnet(net);
3069                         goto failed;
3070                 }
3071         }
3072
3073         lnet_net_lock(LNET_LOCK_EX);
3074         lnet_peer_net_added(net);
3075         lnet_net_unlock(LNET_LOCK_EX);
3076
3077         lnet_ping_target_update(pbuf, ping_mdh);
3078
3079         return 0;
3080
3081 failed:
3082         lnet_ping_md_unlink(pbuf, &ping_mdh);
3083         lnet_ping_buffer_decref(pbuf);
3084         return rc;
3085 }
3086
3087 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3088                                       struct lnet_ioctl_config_lnd_tunables *tun)
3089 {
3090         struct lnet_net *net;
3091         char *nets;
3092         int rc;
3093         struct list_head net_head;
3094
3095         INIT_LIST_HEAD(&net_head);
3096
3097         rc = lnet_parse_ip2nets(&nets, ip2nets);
3098         if (rc < 0)
3099                 return rc;
3100
3101         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3102         if (rc < 0)
3103                 return rc;
3104
3105         mutex_lock(&the_lnet.ln_api_mutex);
3106         while (!list_empty(&net_head)) {
3107                 net = list_entry(net_head.next, struct lnet_net, net_list);
3108                 list_del_init(&net->net_list);
3109                 rc = lnet_add_net_common(net, tun);
3110                 if (rc < 0)
3111                         goto out;
3112         }
3113
3114 out:
3115         mutex_unlock(&the_lnet.ln_api_mutex);
3116
3117         while (!list_empty(&net_head)) {
3118                 net = list_entry(net_head.next, struct lnet_net, net_list);
3119                 list_del_init(&net->net_list);
3120                 lnet_net_free(net);
3121         }
3122         return rc;
3123 }
3124
3125 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3126 {
3127         struct lnet_net *net;
3128         struct lnet_ni *ni;
3129         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3130         int rc, i;
3131         __u32 net_id, lnd_type;
3132
3133         /* get the tunables if they are available */
3134         if (conf->lic_cfg_hdr.ioc_len >=
3135             sizeof(*conf) + sizeof(*tun))
3136                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3137                         conf->lic_bulk;
3138
3139         /* handle legacy ip2nets from DLC */
3140         if (conf->lic_legacy_ip2nets[0] != '\0')
3141                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3142                                                   tun);
3143
3144         net_id = LNET_NIDNET(conf->lic_nid);
3145         lnd_type = LNET_NETTYP(net_id);
3146
3147         if (!libcfs_isknown_lnd(lnd_type)) {
3148                 CERROR("No valid net and lnd information provided\n");
3149                 return -EINVAL;
3150         }
3151
3152         net = lnet_net_alloc(net_id, NULL);
3153         if (!net)
3154                 return -ENOMEM;
3155
3156         for (i = 0; i < conf->lic_ncpts; i++) {
3157                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3158                         return -EINVAL;
3159         }
3160
3161         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3162                                        conf->lic_ni_intf[0]);
3163         if (!ni)
3164                 return -ENOMEM;
3165
3166         mutex_lock(&the_lnet.ln_api_mutex);
3167
3168         rc = lnet_add_net_common(net, tun);
3169
3170         mutex_unlock(&the_lnet.ln_api_mutex);
3171
3172         return rc;
3173 }
3174
3175 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3176 {
3177         struct lnet_net  *net;
3178         struct lnet_ni *ni;
3179         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3180         struct lnet_ping_buffer *pbuf;
3181         struct lnet_handle_md  ping_mdh;
3182         int               rc;
3183         int               net_count;
3184         __u32             addr;
3185
3186         /* don't allow userspace to shutdown the LOLND */
3187         if (LNET_NETTYP(net_id) == LOLND)
3188                 return -EINVAL;
3189
3190         mutex_lock(&the_lnet.ln_api_mutex);
3191
3192         lnet_net_lock(0);
3193
3194         net = lnet_get_net_locked(net_id);
3195         if (!net) {
3196                 CERROR("net %s not found\n",
3197                        libcfs_net2str(net_id));
3198                 rc = -ENOENT;
3199                 goto unlock_net;
3200         }
3201
3202         addr = LNET_NIDADDR(conf->lic_nid);
3203         if (addr == 0) {
3204                 /* remove the entire net */
3205                 net_count = lnet_get_net_ni_count_locked(net);
3206
3207                 lnet_net_unlock(0);
3208
3209                 /* create and link a new ping info, before removing the old one */
3210                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3211                                         lnet_get_ni_count() - net_count,
3212                                         false);
3213                 if (rc != 0)
3214                         goto unlock_api_mutex;
3215
3216                 lnet_shutdown_lndnet(net);
3217
3218                 if (lnet_count_acceptor_nets() == 0)
3219                         lnet_acceptor_stop();
3220
3221                 lnet_ping_target_update(pbuf, ping_mdh);
3222
3223                 goto unlock_api_mutex;
3224         }
3225
3226         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3227         if (!ni) {
3228                 CERROR("nid %s not found\n",
3229                        libcfs_nid2str(conf->lic_nid));
3230                 rc = -ENOENT;
3231                 goto unlock_net;
3232         }
3233
3234         net_count = lnet_get_net_ni_count_locked(net);
3235
3236         lnet_net_unlock(0);
3237
3238         /* create and link a new ping info, before removing the old one */
3239         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3240                                   lnet_get_ni_count() - 1, false);
3241         if (rc != 0)
3242                 goto unlock_api_mutex;
3243
3244         lnet_shutdown_lndni(ni);
3245
3246         if (lnet_count_acceptor_nets() == 0)
3247                 lnet_acceptor_stop();
3248
3249         lnet_ping_target_update(pbuf, ping_mdh);
3250
3251         /* check if the net is empty and remove it if it is */
3252         if (net_count == 1)
3253                 lnet_shutdown_lndnet(net);
3254
3255         goto unlock_api_mutex;
3256
3257 unlock_net:
3258         lnet_net_unlock(0);
3259 unlock_api_mutex:
3260         mutex_unlock(&the_lnet.ln_api_mutex);
3261
3262         return rc;
3263 }
3264
3265 /*
3266  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3267  * They are only expected to be called for unique networks.
3268  * That can be as a result of older DLC library
3269  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3270  */
3271 int
3272 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3273 {
3274         struct lnet_net         *net;
3275         struct list_head        net_head;
3276         int                     rc;
3277         struct lnet_ioctl_config_lnd_tunables tun;
3278         char *nets = conf->cfg_config_u.cfg_net.net_intf;
3279
3280         INIT_LIST_HEAD(&net_head);
3281
3282         /* Create a net/ni structures for the network string */
3283         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3284         if (rc <= 0)
3285                 return rc == 0 ? -EINVAL : rc;
3286
3287         mutex_lock(&the_lnet.ln_api_mutex);
3288
3289         if (rc > 1) {
3290                 rc = -EINVAL; /* only add one network per call */
3291                 goto out_unlock_clean;
3292         }
3293
3294         net = list_entry(net_head.next, struct lnet_net, net_list);
3295         list_del_init(&net->net_list);
3296
3297         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3298
3299         memset(&tun, 0, sizeof(tun));
3300
3301         tun.lt_cmn.lct_peer_timeout =
3302           conf->cfg_config_u.cfg_net.net_peer_timeout;
3303         tun.lt_cmn.lct_peer_tx_credits =
3304           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3305         tun.lt_cmn.lct_peer_rtr_credits =
3306           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3307         tun.lt_cmn.lct_max_tx_credits =
3308           conf->cfg_config_u.cfg_net.net_max_tx_credits;
3309
3310         rc = lnet_add_net_common(net, &tun);
3311
3312 out_unlock_clean:
3313         mutex_unlock(&the_lnet.ln_api_mutex);
3314         while (!list_empty(&net_head)) {
3315                 /* net_head list is empty in success case */
3316                 net = list_entry(net_head.next, struct lnet_net, net_list);
3317                 list_del_init(&net->net_list);
3318                 lnet_net_free(net);
3319         }
3320         return rc;
3321 }
3322
3323 int
3324 lnet_dyn_del_net(__u32 net_id)
3325 {
3326         struct lnet_net  *net;
3327         struct lnet_ping_buffer *pbuf;
3328         struct lnet_handle_md ping_mdh;
3329         int               rc;
3330         int               net_ni_count;
3331
3332         /* don't allow userspace to shutdown the LOLND */
3333         if (LNET_NETTYP(net_id) == LOLND)
3334                 return -EINVAL;
3335
3336         mutex_lock(&the_lnet.ln_api_mutex);
3337
3338         lnet_net_lock(0);
3339
3340         net = lnet_get_net_locked(net_id);
3341         if (net == NULL) {
3342                 lnet_net_unlock(0);
3343                 rc = -EINVAL;
3344                 goto out;
3345         }
3346
3347         net_ni_count = lnet_get_net_ni_count_locked(net);
3348
3349         lnet_net_unlock(0);
3350
3351         /* create and link a new ping info, before removing the old one */
3352         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3353                                     lnet_get_ni_count() - net_ni_count, false);
3354         if (rc != 0)
3355                 goto out;
3356
3357         lnet_shutdown_lndnet(net);
3358
3359         if (lnet_count_acceptor_nets() == 0)
3360                 lnet_acceptor_stop();
3361
3362         lnet_ping_target_update(pbuf, ping_mdh);
3363
3364 out:
3365         mutex_unlock(&the_lnet.ln_api_mutex);
3366
3367         return rc;
3368 }
3369
3370 void lnet_incr_dlc_seq(void)
3371 {
3372         atomic_inc(&lnet_dlc_seq_no);
3373 }
3374
3375 __u32 lnet_get_dlc_seq_locked(void)
3376 {
3377         return atomic_read(&lnet_dlc_seq_no);
3378 }
3379
3380 static void
3381 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3382 {
3383         struct lnet_net *net;
3384         struct lnet_ni *ni;
3385
3386         lnet_net_lock(LNET_LOCK_EX);
3387         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3388                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3389                         if (ni->ni_nid == nid || all) {
3390                                 atomic_set(&ni->ni_healthv, value);
3391                                 if (list_empty(&ni->ni_recovery) &&
3392                                     value < LNET_MAX_HEALTH_VALUE) {
3393                                         CERROR("manually adding local NI %s to recovery\n",
3394                                                libcfs_nid2str(ni->ni_nid));
3395                                         list_add_tail(&ni->ni_recovery,
3396                                                       &the_lnet.ln_mt_localNIRecovq);
3397                                         lnet_ni_addref_locked(ni, 0);
3398                                 }
3399                                 if (!all) {
3400                                         lnet_net_unlock(LNET_LOCK_EX);
3401                                         return;
3402                                 }
3403                         }
3404                 }
3405         }
3406         lnet_net_unlock(LNET_LOCK_EX);
3407 }
3408
3409 static int
3410 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3411 {
3412         int cpt, rc = 0;
3413         struct lnet_ni *ni;
3414         lnet_nid_t nid = stats->hlni_nid;
3415
3416         cpt = lnet_net_lock_current();
3417         ni = lnet_nid2ni_locked(nid, cpt);
3418
3419         if (!ni) {
3420                 rc = -ENOENT;
3421                 goto unlock;
3422         }
3423
3424         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3425         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3426         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3427         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3428         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3429         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3430         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3431
3432 unlock:
3433         lnet_net_unlock(cpt);
3434
3435         return rc;
3436 }
3437
3438 static int
3439 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3440 {
3441         struct lnet_ni *ni;
3442         int i = 0;
3443
3444         lnet_net_lock(LNET_LOCK_EX);
3445         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3446                 list->rlst_nid_array[i] = ni->ni_nid;
3447                 i++;
3448                 if (i >= LNET_MAX_SHOW_NUM_NID)
3449                         break;
3450         }
3451         lnet_net_unlock(LNET_LOCK_EX);
3452         list->rlst_num_nids = i;
3453
3454         return 0;
3455 }
3456
3457 static int
3458 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3459 {
3460         struct lnet_peer_ni *lpni;
3461         int i = 0;
3462
3463         lnet_net_lock(LNET_LOCK_EX);
3464         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3465                 list->rlst_nid_array[i] = lpni->lpni_nid;
3466                 i++;
3467                 if (i >= LNET_MAX_SHOW_NUM_NID)
3468                         break;
3469         }
3470         lnet_net_unlock(LNET_LOCK_EX);
3471         list->rlst_num_nids = i;
3472
3473         return 0;
3474 }
3475
3476 /**
3477  * LNet ioctl handler.
3478  *
3479  */
3480 int
3481 LNetCtl(unsigned int cmd, void *arg)
3482 {
3483         struct libcfs_ioctl_data *data = arg;
3484         struct lnet_ioctl_config_data *config;
3485         struct lnet_process_id    id = {0};
3486         struct lnet_ni           *ni;
3487         int                       rc;
3488
3489         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3490                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3491
3492         switch (cmd) {
3493         case IOC_LIBCFS_GET_NI:
3494                 rc = LNetGetId(data->ioc_count, &id);
3495                 data->ioc_nid = id.nid;
3496                 return rc;
3497
3498         case IOC_LIBCFS_FAIL_NID:
3499                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3500
3501         case IOC_LIBCFS_ADD_ROUTE:
3502                 config = arg;
3503
3504                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3505                         return -EINVAL;
3506
3507                 mutex_lock(&the_lnet.ln_api_mutex);
3508                 rc = lnet_add_route(config->cfg_net,
3509                                     config->cfg_config_u.cfg_route.rtr_hop,
3510                                     config->cfg_nid,
3511                                     config->cfg_config_u.cfg_route.
3512                                         rtr_priority);
3513                 if (rc == 0) {
3514                         rc = lnet_check_routes();
3515                         if (rc != 0)
3516                                 lnet_del_route(config->cfg_net,
3517                                                config->cfg_nid);
3518                 }
3519                 mutex_unlock(&the_lnet.ln_api_mutex);
3520                 return rc;
3521
3522         case IOC_LIBCFS_DEL_ROUTE:
3523                 config = arg;
3524
3525                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3526                         return -EINVAL;
3527
3528                 mutex_lock(&the_lnet.ln_api_mutex);
3529                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3530                 mutex_unlock(&the_lnet.ln_api_mutex);
3531                 return rc;
3532
3533         case IOC_LIBCFS_GET_ROUTE:
3534                 config = arg;
3535
3536                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3537                         return -EINVAL;
3538
3539                 mutex_lock(&the_lnet.ln_api_mutex);
3540                 rc = lnet_get_route(config->cfg_count,
3541                                     &config->cfg_net,
3542                                     &config->cfg_config_u.cfg_route.rtr_hop,
3543                                     &config->cfg_nid,
3544                                     &config->cfg_config_u.cfg_route.rtr_flags,
3545                                     &config->cfg_config_u.cfg_route.
3546                                         rtr_priority);
3547                 mutex_unlock(&the_lnet.ln_api_mutex);
3548                 return rc;
3549
3550         case IOC_LIBCFS_GET_LOCAL_NI: {
3551                 struct lnet_ioctl_config_ni *cfg_ni;
3552                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3553                 struct lnet_ioctl_element_stats *stats;
3554                 __u32 tun_size;
3555
3556                 cfg_ni = arg;
3557
3558                 /* get the tunables if they are available */
3559                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3560                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3561                         return -EINVAL;
3562
3563                 stats = (struct lnet_ioctl_element_stats *)
3564                         cfg_ni->lic_bulk;
3565                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3566                                 (cfg_ni->lic_bulk + sizeof(*stats));
3567
3568                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3569                         sizeof(*stats);
3570
3571                 mutex_lock(&the_lnet.ln_api_mutex);
3572                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3573                 mutex_unlock(&the_lnet.ln_api_mutex);
3574                 return rc;
3575         }
3576
3577         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3578                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3579
3580                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3581                         return -EINVAL;
3582
3583                 mutex_lock(&the_lnet.ln_api_mutex);
3584                 rc = lnet_get_ni_stats(msg_stats);
3585                 mutex_unlock(&the_lnet.ln_api_mutex);
3586
3587                 return rc;
3588         }
3589
3590         case IOC_LIBCFS_GET_NET: {
3591                 size_t total = sizeof(*config) +
3592                                sizeof(struct lnet_ioctl_net_config);
3593                 config = arg;
3594
3595                 if (config->cfg_hdr.ioc_len < total)
3596                         return -EINVAL;
3597
3598                 mutex_lock(&the_lnet.ln_api_mutex);
3599                 rc = lnet_get_net_config(config);
3600                 mutex_unlock(&the_lnet.ln_api_mutex);
3601                 return rc;
3602         }
3603
3604         case IOC_LIBCFS_GET_LNET_STATS:
3605         {
3606                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3607
3608                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3609                         return -EINVAL;
3610
3611                 mutex_lock(&the_lnet.ln_api_mutex);
3612                 lnet_counters_get(&lnet_stats->st_cntrs);
3613                 mutex_unlock(&the_lnet.ln_api_mutex);
3614                 return 0;
3615         }
3616
3617         case IOC_LIBCFS_CONFIG_RTR:
3618                 config = arg;
3619
3620                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3621                         return -EINVAL;
3622
3623                 mutex_lock(&the_lnet.ln_api_mutex);
3624                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3625                         rc = lnet_rtrpools_enable();
3626                         mutex_unlock(&the_lnet.ln_api_mutex);
3627                         return rc;
3628                 }
3629                 lnet_rtrpools_disable();
3630                 mutex_unlock(&the_lnet.ln_api_mutex);
3631                 return 0;
3632
3633         case IOC_LIBCFS_ADD_BUF:
3634                 config = arg;
3635
3636                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3637                         return -EINVAL;
3638
3639                 mutex_lock(&the_lnet.ln_api_mutex);
3640                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3641                                                 buf_tiny,
3642                                           config->cfg_config_u.cfg_buffers.
3643                                                 buf_small,
3644                                           config->cfg_config_u.cfg_buffers.
3645                                                 buf_large);
3646                 mutex_unlock(&the_lnet.ln_api_mutex);
3647                 return rc;
3648
3649         case IOC_LIBCFS_SET_NUMA_RANGE: {
3650                 struct lnet_ioctl_set_value *numa;
3651                 numa = arg;
3652                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3653                         return -EINVAL;
3654                 lnet_net_lock(LNET_LOCK_EX);
3655                 lnet_numa_range = numa->sv_value;
3656                 lnet_net_unlock(LNET_LOCK_EX);
3657                 return 0;
3658         }
3659
3660         case IOC_LIBCFS_GET_NUMA_RANGE: {
3661                 struct lnet_ioctl_set_value *numa;
3662                 numa = arg;
3663                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3664                         return -EINVAL;
3665                 numa->sv_value = lnet_numa_range;
3666                 return 0;
3667         }
3668
3669         case IOC_LIBCFS_GET_BUF: {
3670                 struct lnet_ioctl_pool_cfg *pool_cfg;
3671                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3672
3673                 config = arg;
3674
3675                 if (config->cfg_hdr.ioc_len < total)
3676                         return -EINVAL;
3677
3678                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3679
3680                 mutex_lock(&the_lnet.ln_api_mutex);
3681                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3682                 mutex_unlock(&the_lnet.ln_api_mutex);
3683                 return rc;
3684         }
3685
3686         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3687                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3688
3689                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3690                         return -EINVAL;
3691
3692                 mutex_lock(&the_lnet.ln_api_mutex);
3693                 rc = lnet_get_local_ni_hstats(stats);
3694                 mutex_unlock(&the_lnet.ln_api_mutex);
3695
3696                 return rc;
3697         }
3698
3699         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3700                 struct lnet_ioctl_recovery_list *list = arg;
3701                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3702                         return -EINVAL;
3703
3704                 mutex_lock(&the_lnet.ln_api_mutex);
3705                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3706                         rc = lnet_get_local_ni_recovery_list(list);
3707                 else
3708                         rc = lnet_get_peer_ni_recovery_list(list);
3709                 mutex_unlock(&the_lnet.ln_api_mutex);
3710                 return rc;
3711         }
3712
3713         case IOC_LIBCFS_ADD_PEER_NI: {
3714                 struct lnet_ioctl_peer_cfg *cfg = arg;
3715
3716                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3717                         return -EINVAL;
3718
3719                 mutex_lock(&the_lnet.ln_api_mutex);
3720                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3721                                       cfg->prcfg_cfg_nid,
3722                                       cfg->prcfg_mr);
3723                 mutex_unlock(&the_lnet.ln_api_mutex);
3724                 return rc;
3725         }
3726
3727         case IOC_LIBCFS_DEL_PEER_NI: {
3728                 struct lnet_ioctl_peer_cfg *cfg = arg;
3729
3730                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3731                         return -EINVAL;
3732
3733                 mutex_lock(&the_lnet.ln_api_mutex);
3734                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3735                                       cfg->prcfg_cfg_nid);
3736                 mutex_unlock(&the_lnet.ln_api_mutex);
3737                 return rc;
3738         }
3739
3740         case IOC_LIBCFS_GET_PEER_INFO: {
3741                 struct lnet_ioctl_peer *peer_info = arg;
3742
3743                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3744                         return -EINVAL;
3745
3746                 mutex_lock(&the_lnet.ln_api_mutex);
3747                 rc = lnet_get_peer_ni_info(
3748                    peer_info->pr_count,
3749                    &peer_info->pr_nid,
3750                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3751                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3752                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3753                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3754                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3755                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3756                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3757                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3758                 mutex_unlock(&the_lnet.ln_api_mutex);
3759                 return rc;
3760         }
3761
3762         case IOC_LIBCFS_GET_PEER_NI: {
3763                 struct lnet_ioctl_peer_cfg *cfg = arg;
3764
3765                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3766                         return -EINVAL;
3767
3768                 mutex_lock(&the_lnet.ln_api_mutex);
3769                 rc = lnet_get_peer_info(cfg,
3770                                         (void __user *)cfg->prcfg_bulk);
3771                 mutex_unlock(&the_lnet.ln_api_mutex);
3772                 return rc;
3773         }
3774
3775         case IOC_LIBCFS_GET_PEER_LIST: {
3776                 struct lnet_ioctl_peer_cfg *cfg = arg;
3777
3778                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3779                         return -EINVAL;
3780
3781                 mutex_lock(&the_lnet.ln_api_mutex);
3782                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3783                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3784                 mutex_unlock(&the_lnet.ln_api_mutex);
3785                 return rc;
3786         }
3787
3788         case IOC_LIBCFS_SET_HEALHV: {
3789                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3790                 int value;
3791                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3792                         return -EINVAL;
3793                 if (cfg->rh_value < 0 ||
3794                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3795                         value = LNET_MAX_HEALTH_VALUE;
3796                 else
3797                         value = cfg->rh_value;
3798                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3799                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3800                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3801                 mutex_lock(&the_lnet.ln_api_mutex);
3802                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3803                         lnet_ni_set_healthv(cfg->rh_nid, value,
3804                                              cfg->rh_all);
3805                 else
3806                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3807                                                   cfg->rh_all);
3808                 mutex_unlock(&the_lnet.ln_api_mutex);
3809                 return 0;
3810         }
3811
3812         case IOC_LIBCFS_NOTIFY_ROUTER: {
3813                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3814
3815                 /* The deadline passed in by the user should be some time in
3816                  * seconds in the future since the UNIX epoch. We have to map
3817                  * that deadline to the wall clock.
3818                  */
3819                 deadline += ktime_get_seconds();
3820                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
3821                                    deadline);
3822         }
3823
3824         case IOC_LIBCFS_LNET_DIST:
3825                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3826                 if (rc < 0 && rc != -EHOSTUNREACH)
3827                         return rc;
3828
3829                 data->ioc_u32[0] = rc;
3830                 return 0;
3831
3832         case IOC_LIBCFS_TESTPROTOCOMPAT:
3833                 lnet_net_lock(LNET_LOCK_EX);
3834                 the_lnet.ln_testprotocompat = data->ioc_flags;
3835                 lnet_net_unlock(LNET_LOCK_EX);
3836                 return 0;
3837
3838         case IOC_LIBCFS_LNET_FAULT:
3839                 return lnet_fault_ctl(data->ioc_flags, data);
3840
3841         case IOC_LIBCFS_PING: {
3842                 signed long timeout;
3843
3844                 id.nid = data->ioc_nid;
3845                 id.pid = data->ioc_u32[0];
3846
3847                 /* If timeout is negative then set default of 3 minutes */
3848                 if (((s32)data->ioc_u32[1] <= 0) ||
3849                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3850                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3851                 else
3852                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
3853
3854                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3855                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3856
3857                 if (rc < 0)
3858                         return rc;
3859
3860                 data->ioc_count = rc;
3861                 return 0;
3862         }
3863
3864         case IOC_LIBCFS_PING_PEER: {
3865                 struct lnet_ioctl_ping_data *ping = arg;
3866                 struct lnet_peer *lp;
3867                 signed long timeout;
3868
3869                 /* If timeout is negative then set default of 3 minutes */
3870                 if (((s32)ping->op_param) <= 0 ||
3871                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3872                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3873                 else
3874                         timeout = msecs_to_jiffies(ping->op_param);
3875
3876                 rc = lnet_ping(ping->ping_id, timeout,
3877                                ping->ping_buf,
3878                                ping->ping_count);
3879                 if (rc < 0)
3880                         return rc;
3881
3882                 mutex_lock(&the_lnet.ln_api_mutex);
3883                 lp = lnet_find_peer(ping->ping_id.nid);
3884                 if (lp) {
3885                         ping->ping_id.nid = lp->lp_primary_nid;
3886                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3887                         lnet_peer_decref_locked(lp);
3888                 }
3889                 mutex_unlock(&the_lnet.ln_api_mutex);
3890
3891                 ping->ping_count = rc;
3892                 return 0;
3893         }
3894
3895         case IOC_LIBCFS_DISCOVER: {
3896                 struct lnet_ioctl_ping_data *discover = arg;
3897                 struct lnet_peer *lp;
3898
3899                 rc = lnet_discover(discover->ping_id, discover->op_param,
3900                                    discover->ping_buf,
3901                                    discover->ping_count);
3902                 if (rc < 0)
3903                         return rc;
3904
3905                 mutex_lock(&the_lnet.ln_api_mutex);
3906                 lp = lnet_find_peer(discover->ping_id.nid);
3907                 if (lp) {
3908                         discover->ping_id.nid = lp->lp_primary_nid;
3909                         discover->mr_info = lnet_peer_is_multi_rail(lp);
3910                         lnet_peer_decref_locked(lp);
3911                 }
3912                 mutex_unlock(&the_lnet.ln_api_mutex);
3913
3914                 discover->ping_count = rc;
3915                 return 0;
3916         }
3917
3918         default:
3919                 ni = lnet_net2ni_addref(data->ioc_net);
3920                 if (ni == NULL)
3921                         return -EINVAL;
3922
3923                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
3924                         rc = -EINVAL;
3925                 else
3926                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
3927
3928                 lnet_ni_decref(ni);
3929                 return rc;
3930         }
3931         /* not reached */
3932 }
3933 EXPORT_SYMBOL(LNetCtl);
3934
3935 void LNetDebugPeer(struct lnet_process_id id)
3936 {
3937         lnet_debug_peer(id.nid);
3938 }
3939 EXPORT_SYMBOL(LNetDebugPeer);
3940
3941 /**
3942  * Determine if the specified peer \a nid is on the local node.
3943  *
3944  * \param nid   peer nid to check
3945  *
3946  * \retval true         If peer NID is on the local node.
3947  * \retval false        If peer NID is not on the local node.
3948  */
3949 bool LNetIsPeerLocal(lnet_nid_t nid)
3950 {
3951         struct lnet_net *net;
3952         struct lnet_ni *ni;
3953         int cpt;
3954
3955         cpt = lnet_net_lock_current();
3956         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3957                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3958                         if (ni->ni_nid == nid) {
3959                                 lnet_net_unlock(cpt);
3960                                 return true;
3961                         }
3962                 }
3963         }
3964         lnet_net_unlock(cpt);
3965
3966         return false;
3967 }
3968 EXPORT_SYMBOL(LNetIsPeerLocal);
3969
3970 /**
3971  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
3972  * Note that all interfaces share a same PID, as requested by LNetNIInit().
3973  *
3974  * \param index Index of the interface to look up.
3975  * \param id On successful return, this location will hold the
3976  * struct lnet_process_id ID of the interface.
3977  *
3978  * \retval 0 If an interface exists at \a index.
3979  * \retval -ENOENT If no interface has been found.
3980  */
3981 int
3982 LNetGetId(unsigned int index, struct lnet_process_id *id)
3983 {
3984         struct lnet_ni   *ni;
3985         struct lnet_net  *net;
3986         int               cpt;
3987         int               rc = -ENOENT;
3988
3989         LASSERT(the_lnet.ln_refcount > 0);
3990
3991         cpt = lnet_net_lock_current();
3992
3993         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3994                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3995                         if (index-- != 0)
3996                                 continue;
3997
3998                         id->nid = ni->ni_nid;
3999                         id->pid = the_lnet.ln_pid;
4000                         rc = 0;
4001                         break;
4002                 }
4003         }
4004
4005         lnet_net_unlock(cpt);
4006         return rc;
4007 }
4008 EXPORT_SYMBOL(LNetGetId);
4009
4010 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4011                      struct lnet_process_id __user *ids, int n_ids)
4012 {
4013         struct lnet_handle_eq eqh;
4014         struct lnet_handle_md mdh;
4015         struct lnet_event event;
4016         struct lnet_md md = { NULL };
4017         int which;
4018         int unlinked = 0;
4019         int replied = 0;
4020         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
4021         struct lnet_ping_buffer *pbuf;
4022         struct lnet_process_id tmpid;
4023         int i;
4024         int nob;
4025         int rc;
4026         int rc2;
4027         sigset_t blocked;
4028
4029         /* n_ids limit is arbitrary */
4030         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4031                 return -EINVAL;
4032
4033         /*
4034          * if the user buffer has more space than the lnet_interfaces_max
4035          * then only fill it up to lnet_interfaces_max
4036          */
4037         if (n_ids > lnet_interfaces_max)
4038                 n_ids = lnet_interfaces_max;
4039
4040         if (id.pid == LNET_PID_ANY)
4041                 id.pid = LNET_PID_LUSTRE;
4042
4043         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4044         if (!pbuf)
4045                 return -ENOMEM;
4046
4047         /* NB 2 events max (including any unlink event) */
4048         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
4049         if (rc != 0) {
4050                 CERROR("Can't allocate EQ: %d\n", rc);
4051                 goto fail_ping_buffer_decref;
4052         }
4053
4054         /* initialize md content */
4055         md.start     = &pbuf->pb_info;
4056         md.length    = LNET_PING_INFO_SIZE(n_ids);
4057         md.threshold = 2; /* GET/REPLY */
4058         md.max_size  = 0;
4059         md.options   = LNET_MD_TRUNCATE;
4060         md.user_ptr  = NULL;
4061         md.eq_handle = eqh;
4062
4063         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
4064         if (rc != 0) {
4065                 CERROR("Can't bind MD: %d\n", rc);
4066                 goto fail_free_eq;
4067         }
4068
4069         rc = LNetGet(LNET_NID_ANY, mdh, id,
4070                      LNET_RESERVED_PORTAL,
4071                      LNET_PROTO_PING_MATCHBITS, 0, false);
4072
4073         if (rc != 0) {
4074                 /* Don't CERROR; this could be deliberate! */
4075                 rc2 = LNetMDUnlink(mdh);
4076                 LASSERT(rc2 == 0);
4077
4078                 /* NB must wait for the UNLINK event below... */
4079                 unlinked = 1;
4080                 timeout = a_long_time;
4081         }
4082
4083         do {
4084                 /* MUST block for unlink to complete */
4085                 if (unlinked)
4086                         blocked = cfs_block_allsigs();
4087
4088                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
4089
4090                 if (unlinked)
4091                         cfs_restore_sigs(blocked);
4092
4093                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
4094                        (rc2 <= 0) ? -1 : event.type,
4095                        (rc2 <= 0) ? -1 : event.status,
4096                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
4097
4098                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
4099
4100                 if (rc2 <= 0 || event.status != 0) {
4101                         /* timeout or error */
4102                         if (!replied && rc == 0)
4103                                 rc = (rc2 < 0) ? rc2 :
4104                                      (rc2 == 0) ? -ETIMEDOUT :
4105                                      event.status;
4106
4107                         if (!unlinked) {
4108                                 /* Ensure completion in finite time... */
4109                                 LNetMDUnlink(mdh);
4110                                 /* No assertion (racing with network) */
4111                                 unlinked = 1;
4112                                 timeout = a_long_time;
4113                         } else if (rc2 == 0) {
4114                                 /* timed out waiting for unlink */
4115                                 CWARN("ping %s: late network completion\n",
4116                                       libcfs_id2str(id));
4117                         }
4118                 } else if (event.type == LNET_EVENT_REPLY) {
4119                         replied = 1;
4120                         rc = event.mlength;
4121                 }
4122         } while (rc2 <= 0 || !event.unlinked);
4123
4124         if (!replied) {
4125                 if (rc >= 0)
4126                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
4127                               libcfs_id2str(id));
4128                 rc = -EIO;
4129                 goto fail_free_eq;
4130         }
4131
4132         nob = rc;
4133         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4134
4135         rc = -EPROTO;           /* if I can't parse... */
4136
4137         if (nob < 8) {
4138                 CERROR("%s: ping info too short %d\n",
4139                        libcfs_id2str(id), nob);
4140                 goto fail_free_eq;
4141         }
4142
4143         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4144                 lnet_swap_pinginfo(pbuf);
4145         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4146                 CERROR("%s: Unexpected magic %08x\n",
4147                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4148                 goto fail_free_eq;
4149         }
4150
4151         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4152                 CERROR("%s: ping w/o NI status: 0x%x\n",
4153                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4154                 goto fail_free_eq;
4155         }
4156
4157         if (nob < LNET_PING_INFO_SIZE(0)) {
4158                 CERROR("%s: Short reply %d(%d min)\n",
4159                        libcfs_id2str(id),
4160                        nob, (int)LNET_PING_INFO_SIZE(0));
4161                 goto fail_free_eq;
4162         }
4163
4164         if (pbuf->pb_info.pi_nnis < n_ids)
4165                 n_ids = pbuf->pb_info.pi_nnis;
4166
4167         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4168                 CERROR("%s: Short reply %d(%d expected)\n",
4169                        libcfs_id2str(id),
4170                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4171                 goto fail_free_eq;
4172         }
4173
4174         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4175
4176         memset(&tmpid, 0, sizeof(tmpid));
4177         for (i = 0; i < n_ids; i++) {
4178                 tmpid.pid = pbuf->pb_info.pi_pid;
4179                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4180                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4181                         goto fail_free_eq;
4182         }
4183         rc = pbuf->pb_info.pi_nnis;
4184
4185  fail_free_eq:
4186         rc2 = LNetEQFree(eqh);
4187         if (rc2 != 0)
4188                 CERROR("rc2 %d\n", rc2);
4189         LASSERT(rc2 == 0);
4190
4191  fail_ping_buffer_decref:
4192         lnet_ping_buffer_decref(pbuf);
4193         return rc;
4194 }
4195
4196 static int
4197 lnet_discover(struct lnet_process_id id, __u32 force,
4198               struct lnet_process_id __user *ids, int n_ids)
4199 {
4200         struct lnet_peer_ni *lpni;
4201         struct lnet_peer_ni *p;
4202         struct lnet_peer *lp;
4203         struct lnet_process_id *buf;
4204         int cpt;
4205         int i;
4206         int rc;
4207         int max_intf = lnet_interfaces_max;
4208         size_t buf_size;
4209
4210         if (n_ids <= 0 ||
4211             id.nid == LNET_NID_ANY)
4212                 return -EINVAL;
4213
4214         if (id.pid == LNET_PID_ANY)
4215                 id.pid = LNET_PID_LUSTRE;
4216
4217         /*
4218          * if the user buffer has more space than the max_intf
4219          * then only fill it up to max_intf
4220          */
4221         if (n_ids > max_intf)
4222                 n_ids = max_intf;
4223
4224         buf_size = n_ids * sizeof(*buf);
4225
4226         LIBCFS_ALLOC(buf, buf_size);
4227         if (!buf)
4228                 return -ENOMEM;
4229
4230         cpt = lnet_net_lock_current();
4231         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4232         if (IS_ERR(lpni)) {
4233                 rc = PTR_ERR(lpni);
4234                 goto out;
4235         }
4236
4237         /*
4238          * Clearing the NIDS_UPTODATE flag ensures the peer will
4239          * be discovered, provided discovery has not been disabled.
4240          */
4241         lp = lpni->lpni_peer_net->lpn_peer;
4242         spin_lock(&lp->lp_lock);
4243         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4244         /* If the force flag is set, force a PING and PUSH as well. */
4245         if (force)
4246                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4247         spin_unlock(&lp->lp_lock);
4248         rc = lnet_discover_peer_locked(lpni, cpt, true);
4249         if (rc)
4250                 goto out_decref;
4251
4252         /* Peer may have changed. */
4253         lp = lpni->lpni_peer_net->lpn_peer;
4254         if (lp->lp_nnis < n_ids)
4255                 n_ids = lp->lp_nnis;
4256
4257         i = 0;
4258         p = NULL;
4259         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4260                 buf[i].pid = id.pid;
4261                 buf[i].nid = p->lpni_nid;
4262                 if (++i >= n_ids)
4263                         break;
4264         }
4265
4266         lnet_net_unlock(cpt);
4267
4268         rc = -EFAULT;
4269         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
4270                 goto out_relock;
4271         rc = n_ids;
4272 out_relock:
4273         lnet_net_lock(cpt);
4274 out_decref:
4275         lnet_peer_ni_decref_locked(lpni);
4276 out:
4277         lnet_net_unlock(cpt);
4278
4279         LIBCFS_FREE(buf, buf_size);
4280
4281         return rc;
4282 }
4283
4284 /**
4285  * Retrieve peer discovery status.
4286  *
4287  * \retval 1 if lnet_peer_discovery_disabled is 0
4288  * \retval 0 if lnet_peer_discovery_disabled is 1
4289  */
4290 int
4291 LNetGetPeerDiscoveryStatus(void)
4292 {
4293         return !lnet_peer_discovery_disabled;
4294 }
4295 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);