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