Whamcloud - gitweb
LU-9120 lnet: reset health value
[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->errors       += ctr->errors;
755                 counters->send_count   += ctr->send_count;
756                 counters->recv_count   += ctr->recv_count;
757                 counters->route_count  += ctr->route_count;
758                 counters->drop_count   += ctr->drop_count;
759                 counters->send_length  += ctr->send_length;
760                 counters->recv_length  += ctr->recv_length;
761                 counters->route_length += ctr->route_length;
762                 counters->drop_length  += ctr->drop_length;
763
764         }
765         lnet_net_unlock(LNET_LOCK_EX);
766 }
767 EXPORT_SYMBOL(lnet_counters_get);
768
769 void
770 lnet_counters_reset(void)
771 {
772         struct lnet_counters *counters;
773         int             i;
774
775         lnet_net_lock(LNET_LOCK_EX);
776
777         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
778                 memset(counters, 0, sizeof(struct lnet_counters));
779
780         lnet_net_unlock(LNET_LOCK_EX);
781 }
782
783 static char *
784 lnet_res_type2str(int type)
785 {
786         switch (type) {
787         default:
788                 LBUG();
789         case LNET_COOKIE_TYPE_MD:
790                 return "MD";
791         case LNET_COOKIE_TYPE_ME:
792                 return "ME";
793         case LNET_COOKIE_TYPE_EQ:
794                 return "EQ";
795         }
796 }
797
798 static void
799 lnet_res_container_cleanup(struct lnet_res_container *rec)
800 {
801         int     count = 0;
802
803         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
804                 return;
805
806         while (!list_empty(&rec->rec_active)) {
807                 struct list_head *e = rec->rec_active.next;
808
809                 list_del_init(e);
810                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
811                         lnet_eq_free(list_entry(e, struct lnet_eq, eq_list));
812
813                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
814                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
815
816                 } else { /* NB: Active MEs should be attached on portals */
817                         LBUG();
818                 }
819                 count++;
820         }
821
822         if (count > 0) {
823                 /* Found alive MD/ME/EQ, user really should unlink/free
824                  * all of them before finalize LNet, but if someone didn't,
825                  * we have to recycle garbage for him */
826                 CERROR("%d active elements on exit of %s container\n",
827                        count, lnet_res_type2str(rec->rec_type));
828         }
829
830         if (rec->rec_lh_hash != NULL) {
831                 LIBCFS_FREE(rec->rec_lh_hash,
832                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
833                 rec->rec_lh_hash = NULL;
834         }
835
836         rec->rec_type = 0; /* mark it as finalized */
837 }
838
839 static int
840 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
841 {
842         int     rc = 0;
843         int     i;
844
845         LASSERT(rec->rec_type == 0);
846
847         rec->rec_type = type;
848         INIT_LIST_HEAD(&rec->rec_active);
849
850         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
851
852         /* Arbitrary choice of hash table size */
853         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
854                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
855         if (rec->rec_lh_hash == NULL) {
856                 rc = -ENOMEM;
857                 goto out;
858         }
859
860         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
861                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
862
863         return 0;
864
865 out:
866         CERROR("Failed to setup %s resource container\n",
867                lnet_res_type2str(type));
868         lnet_res_container_cleanup(rec);
869         return rc;
870 }
871
872 static void
873 lnet_res_containers_destroy(struct lnet_res_container **recs)
874 {
875         struct lnet_res_container       *rec;
876         int                             i;
877
878         cfs_percpt_for_each(rec, i, recs)
879                 lnet_res_container_cleanup(rec);
880
881         cfs_percpt_free(recs);
882 }
883
884 static struct lnet_res_container **
885 lnet_res_containers_create(int type)
886 {
887         struct lnet_res_container       **recs;
888         struct lnet_res_container       *rec;
889         int                             rc;
890         int                             i;
891
892         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
893         if (recs == NULL) {
894                 CERROR("Failed to allocate %s resource containers\n",
895                        lnet_res_type2str(type));
896                 return NULL;
897         }
898
899         cfs_percpt_for_each(rec, i, recs) {
900                 rc = lnet_res_container_setup(rec, i, type);
901                 if (rc != 0) {
902                         lnet_res_containers_destroy(recs);
903                         return NULL;
904                 }
905         }
906
907         return recs;
908 }
909
910 struct lnet_libhandle *
911 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
912 {
913         /* ALWAYS called with lnet_res_lock held */
914         struct list_head        *head;
915         struct lnet_libhandle   *lh;
916         unsigned int            hash;
917
918         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
919                 return NULL;
920
921         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
922         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
923
924         list_for_each_entry(lh, head, lh_hash_chain) {
925                 if (lh->lh_cookie == cookie)
926                         return lh;
927         }
928
929         return NULL;
930 }
931
932 void
933 lnet_res_lh_initialize(struct lnet_res_container *rec,
934                        struct lnet_libhandle *lh)
935 {
936         /* ALWAYS called with lnet_res_lock held */
937         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
938         unsigned int    hash;
939
940         lh->lh_cookie = rec->rec_lh_cookie;
941         rec->rec_lh_cookie += 1 << ibits;
942
943         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
944
945         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
946 }
947
948 static int lnet_unprepare(void);
949
950 static int
951 lnet_prepare(lnet_pid_t requested_pid)
952 {
953         /* Prepare to bring up the network */
954         struct lnet_res_container **recs;
955         int                       rc = 0;
956
957         if (requested_pid == LNET_PID_ANY) {
958                 /* Don't instantiate LNET just for me */
959                 return -ENETDOWN;
960         }
961
962         LASSERT(the_lnet.ln_refcount == 0);
963
964         the_lnet.ln_routing = 0;
965
966         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
967         the_lnet.ln_pid = requested_pid;
968
969         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
970         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
971         INIT_LIST_HEAD(&the_lnet.ln_nets);
972         INIT_LIST_HEAD(&the_lnet.ln_routers);
973         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
974         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
975         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
976         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
977         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
978         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
979         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
980         init_waitqueue_head(&the_lnet.ln_dc_waitq);
981
982         rc = lnet_descriptor_setup();
983         if (rc != 0)
984                 goto failed;
985
986         rc = lnet_create_remote_nets_table();
987         if (rc != 0)
988                 goto failed;
989
990         /*
991          * NB the interface cookie in wire handles guards against delayed
992          * replies and ACKs appearing valid after reboot.
993          */
994         the_lnet.ln_interface_cookie = ktime_get_real_ns();
995
996         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
997                                                 sizeof(struct lnet_counters));
998         if (the_lnet.ln_counters == NULL) {
999                 CERROR("Failed to allocate counters for LNet\n");
1000                 rc = -ENOMEM;
1001                 goto failed;
1002         }
1003
1004         rc = lnet_peer_tables_create();
1005         if (rc != 0)
1006                 goto failed;
1007
1008         rc = lnet_msg_containers_create();
1009         if (rc != 0)
1010                 goto failed;
1011
1012         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1013                                       LNET_COOKIE_TYPE_EQ);
1014         if (rc != 0)
1015                 goto failed;
1016
1017         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
1018         if (recs == NULL) {
1019                 rc = -ENOMEM;
1020                 goto failed;
1021         }
1022
1023         the_lnet.ln_me_containers = recs;
1024
1025         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1026         if (recs == NULL) {
1027                 rc = -ENOMEM;
1028                 goto failed;
1029         }
1030
1031         the_lnet.ln_md_containers = recs;
1032
1033         rc = lnet_portals_create();
1034         if (rc != 0) {
1035                 CERROR("Failed to create portals for LNet: %d\n", rc);
1036                 goto failed;
1037         }
1038
1039         return 0;
1040
1041  failed:
1042         lnet_unprepare();
1043         return rc;
1044 }
1045
1046 static int
1047 lnet_unprepare (void)
1048 {
1049         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1050          * have shut down already, so it is safe to unlink and free all
1051          * descriptors, even those that appear committed to a network op (eg MD
1052          * with non-zero pending count) */
1053
1054         lnet_fail_nid(LNET_NID_ANY, 0);
1055
1056         LASSERT(the_lnet.ln_refcount == 0);
1057         LASSERT(list_empty(&the_lnet.ln_test_peers));
1058         LASSERT(list_empty(&the_lnet.ln_nets));
1059
1060         lnet_portals_destroy();
1061
1062         if (the_lnet.ln_md_containers != NULL) {
1063                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1064                 the_lnet.ln_md_containers = NULL;
1065         }
1066
1067         if (the_lnet.ln_me_containers != NULL) {
1068                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
1069                 the_lnet.ln_me_containers = NULL;
1070         }
1071
1072         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1073
1074         lnet_msg_containers_destroy();
1075         lnet_peer_uninit();
1076         lnet_rtrpools_free(0);
1077
1078         if (the_lnet.ln_counters != NULL) {
1079                 cfs_percpt_free(the_lnet.ln_counters);
1080                 the_lnet.ln_counters = NULL;
1081         }
1082         lnet_destroy_remote_nets_table();
1083         lnet_descriptor_cleanup();
1084
1085         return 0;
1086 }
1087
1088 struct lnet_ni  *
1089 lnet_net2ni_locked(__u32 net_id, int cpt)
1090 {
1091         struct lnet_ni   *ni;
1092         struct lnet_net  *net;
1093
1094         LASSERT(cpt != LNET_LOCK_EX);
1095
1096         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1097                 if (net->net_id == net_id) {
1098                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1099                                         ni_netlist);
1100                         return ni;
1101                 }
1102         }
1103
1104         return NULL;
1105 }
1106
1107 struct lnet_ni *
1108 lnet_net2ni_addref(__u32 net)
1109 {
1110         struct lnet_ni *ni;
1111
1112         lnet_net_lock(0);
1113         ni = lnet_net2ni_locked(net, 0);
1114         if (ni)
1115                 lnet_ni_addref_locked(ni, 0);
1116         lnet_net_unlock(0);
1117
1118         return ni;
1119 }
1120 EXPORT_SYMBOL(lnet_net2ni_addref);
1121
1122 struct lnet_net *
1123 lnet_get_net_locked(__u32 net_id)
1124 {
1125         struct lnet_net  *net;
1126
1127         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1128                 if (net->net_id == net_id)
1129                         return net;
1130         }
1131
1132         return NULL;
1133 }
1134
1135 unsigned int
1136 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1137 {
1138         __u64           key = nid;
1139         unsigned int    val;
1140
1141         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1142
1143         if (number == 1)
1144                 return 0;
1145
1146         val = hash_long(key, LNET_CPT_BITS);
1147         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1148         if (val < number)
1149                 return val;
1150
1151         return (unsigned int)(key + val + (val >> 1)) % number;
1152 }
1153
1154 int
1155 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1156 {
1157         struct lnet_net *net;
1158
1159         /* must called with hold of lnet_net_lock */
1160         if (LNET_CPT_NUMBER == 1)
1161                 return 0; /* the only one */
1162
1163         /*
1164          * If NI is provided then use the CPT identified in the NI cpt
1165          * list if one exists. If one doesn't exist, then that NI is
1166          * associated with all CPTs and it follows that the net it belongs
1167          * to is implicitly associated with all CPTs, so just hash the nid
1168          * and return that.
1169          */
1170         if (ni != NULL) {
1171                 if (ni->ni_cpts != NULL)
1172                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1173                                                              ni->ni_ncpts)];
1174                 else
1175                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1176         }
1177
1178         /* no NI provided so look at the net */
1179         net = lnet_get_net_locked(LNET_NIDNET(nid));
1180
1181         if (net != NULL && net->net_cpts != NULL) {
1182                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1183         }
1184
1185         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1186 }
1187
1188 int
1189 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1190 {
1191         int     cpt;
1192         int     cpt2;
1193
1194         if (LNET_CPT_NUMBER == 1)
1195                 return 0; /* the only one */
1196
1197         cpt = lnet_net_lock_current();
1198
1199         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1200
1201         lnet_net_unlock(cpt);
1202
1203         return cpt2;
1204 }
1205 EXPORT_SYMBOL(lnet_cpt_of_nid);
1206
1207 int
1208 lnet_islocalnet(__u32 net_id)
1209 {
1210         struct lnet_net *net;
1211         int             cpt;
1212         bool            local;
1213
1214         cpt = lnet_net_lock_current();
1215
1216         net = lnet_get_net_locked(net_id);
1217
1218         local = net != NULL;
1219
1220         lnet_net_unlock(cpt);
1221
1222         return local;
1223 }
1224
1225 bool
1226 lnet_is_ni_healthy_locked(struct lnet_ni *ni)
1227 {
1228         if (ni->ni_state & LNET_NI_STATE_ACTIVE)
1229                 return true;
1230
1231         return false;
1232 }
1233
1234 struct lnet_ni  *
1235 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1236 {
1237         struct lnet_net  *net;
1238         struct lnet_ni   *ni;
1239
1240         LASSERT(cpt != LNET_LOCK_EX);
1241
1242         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1243                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1244                         if (ni->ni_nid == nid)
1245                                 return ni;
1246                 }
1247         }
1248
1249         return NULL;
1250 }
1251
1252 struct lnet_ni *
1253 lnet_nid2ni_addref(lnet_nid_t nid)
1254 {
1255         struct lnet_ni *ni;
1256
1257         lnet_net_lock(0);
1258         ni = lnet_nid2ni_locked(nid, 0);
1259         if (ni)
1260                 lnet_ni_addref_locked(ni, 0);
1261         lnet_net_unlock(0);
1262
1263         return ni;
1264 }
1265 EXPORT_SYMBOL(lnet_nid2ni_addref);
1266
1267 int
1268 lnet_islocalnid(lnet_nid_t nid)
1269 {
1270         struct lnet_ni  *ni;
1271         int             cpt;
1272
1273         cpt = lnet_net_lock_current();
1274         ni = lnet_nid2ni_locked(nid, cpt);
1275         lnet_net_unlock(cpt);
1276
1277         return ni != NULL;
1278 }
1279
1280 int
1281 lnet_count_acceptor_nets(void)
1282 {
1283         /* Return the # of NIs that need the acceptor. */
1284         int              count = 0;
1285         struct lnet_net  *net;
1286         int              cpt;
1287
1288         cpt = lnet_net_lock_current();
1289         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1290                 /* all socklnd type networks should have the acceptor
1291                  * thread started */
1292                 if (net->net_lnd->lnd_accept != NULL)
1293                         count++;
1294         }
1295
1296         lnet_net_unlock(cpt);
1297
1298         return count;
1299 }
1300
1301 struct lnet_ping_buffer *
1302 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1303 {
1304         struct lnet_ping_buffer *pbuf;
1305
1306         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1307         if (pbuf) {
1308                 pbuf->pb_nnis = nnis;
1309                 atomic_set(&pbuf->pb_refcnt, 1);
1310         }
1311
1312         return pbuf;
1313 }
1314
1315 void
1316 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1317 {
1318         LASSERT(lnet_ping_buffer_numref(pbuf) == 0);
1319         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1320 }
1321
1322 static struct lnet_ping_buffer *
1323 lnet_ping_target_create(int nnis)
1324 {
1325         struct lnet_ping_buffer *pbuf;
1326
1327         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1328         if (pbuf == NULL) {
1329                 CERROR("Can't allocate ping source [%d]\n", nnis);
1330                 return NULL;
1331         }
1332
1333         pbuf->pb_info.pi_nnis = nnis;
1334         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1335         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1336         pbuf->pb_info.pi_features =
1337                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1338
1339         return pbuf;
1340 }
1341
1342 static inline int
1343 lnet_get_net_ni_count_locked(struct lnet_net *net)
1344 {
1345         struct lnet_ni  *ni;
1346         int             count = 0;
1347
1348         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1349                 count++;
1350
1351         return count;
1352 }
1353
1354 static inline int
1355 lnet_get_net_ni_count_pre(struct lnet_net *net)
1356 {
1357         struct lnet_ni  *ni;
1358         int             count = 0;
1359
1360         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1361                 count++;
1362
1363         return count;
1364 }
1365
1366 static inline int
1367 lnet_get_ni_count(void)
1368 {
1369         struct lnet_ni  *ni;
1370         struct lnet_net *net;
1371         int             count = 0;
1372
1373         lnet_net_lock(0);
1374
1375         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1376                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1377                         count++;
1378         }
1379
1380         lnet_net_unlock(0);
1381
1382         return count;
1383 }
1384
1385 int
1386 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1387 {
1388         if (!pinfo)
1389                 return -EINVAL;
1390         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1391                 return -EPROTO;
1392         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1393                 return -EPROTO;
1394         /* Loopback is guaranteed to be present */
1395         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1396                 return -ERANGE;
1397         if (LNET_NETTYP(LNET_NIDNET(LNET_PING_INFO_LONI(pinfo))) != LOLND)
1398                 return -EPROTO;
1399         return 0;
1400 }
1401
1402 static void
1403 lnet_ping_target_destroy(void)
1404 {
1405         struct lnet_net *net;
1406         struct lnet_ni  *ni;
1407
1408         lnet_net_lock(LNET_LOCK_EX);
1409
1410         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1411                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1412                         lnet_ni_lock(ni);
1413                         ni->ni_status = NULL;
1414                         lnet_ni_unlock(ni);
1415                 }
1416         }
1417
1418         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1419         the_lnet.ln_ping_target = NULL;
1420
1421         lnet_net_unlock(LNET_LOCK_EX);
1422 }
1423
1424 static void
1425 lnet_ping_target_event_handler(struct lnet_event *event)
1426 {
1427         struct lnet_ping_buffer *pbuf = event->md.user_ptr;
1428
1429         if (event->unlinked)
1430                 lnet_ping_buffer_decref(pbuf);
1431 }
1432
1433 static int
1434 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1435                        struct lnet_handle_md *ping_mdh,
1436                        int ni_count, bool set_eq)
1437 {
1438         struct lnet_process_id id = {
1439                 .nid = LNET_NID_ANY,
1440                 .pid = LNET_PID_ANY
1441         };
1442         struct lnet_handle_me me_handle;
1443         struct lnet_md md = { NULL };
1444         int rc, rc2;
1445
1446         if (set_eq) {
1447                 rc = LNetEQAlloc(0, lnet_ping_target_event_handler,
1448                                  &the_lnet.ln_ping_target_eq);
1449                 if (rc != 0) {
1450                         CERROR("Can't allocate ping buffer EQ: %d\n", rc);
1451                         return rc;
1452                 }
1453         }
1454
1455         *ppbuf = lnet_ping_target_create(ni_count);
1456         if (*ppbuf == NULL) {
1457                 rc = -ENOMEM;
1458                 goto fail_free_eq;
1459         }
1460
1461         /* Ping target ME/MD */
1462         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1463                           LNET_PROTO_PING_MATCHBITS, 0,
1464                           LNET_UNLINK, LNET_INS_AFTER,
1465                           &me_handle);
1466         if (rc != 0) {
1467                 CERROR("Can't create ping target ME: %d\n", rc);
1468                 goto fail_decref_ping_buffer;
1469         }
1470
1471         /* initialize md content */
1472         md.start     = &(*ppbuf)->pb_info;
1473         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1474         md.threshold = LNET_MD_THRESH_INF;
1475         md.max_size  = 0;
1476         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1477                        LNET_MD_MANAGE_REMOTE;
1478         md.eq_handle = the_lnet.ln_ping_target_eq;
1479         md.user_ptr  = *ppbuf;
1480
1481         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, ping_mdh);
1482         if (rc != 0) {
1483                 CERROR("Can't attach ping target MD: %d\n", rc);
1484                 goto fail_unlink_ping_me;
1485         }
1486         lnet_ping_buffer_addref(*ppbuf);
1487
1488         return 0;
1489
1490 fail_unlink_ping_me:
1491         rc2 = LNetMEUnlink(me_handle);
1492         LASSERT(rc2 == 0);
1493 fail_decref_ping_buffer:
1494         LASSERT(lnet_ping_buffer_numref(*ppbuf) == 1);
1495         lnet_ping_buffer_decref(*ppbuf);
1496         *ppbuf = NULL;
1497 fail_free_eq:
1498         if (set_eq) {
1499                 rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1500                 LASSERT(rc2 == 0);
1501         }
1502         return rc;
1503 }
1504
1505 static void
1506 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1507                     struct lnet_handle_md *ping_mdh)
1508 {
1509         sigset_t        blocked = cfs_block_allsigs();
1510
1511         LNetMDUnlink(*ping_mdh);
1512         LNetInvalidateMDHandle(ping_mdh);
1513
1514         /* NB the MD could be busy; this just starts the unlink */
1515         while (lnet_ping_buffer_numref(pbuf) > 1) {
1516                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1517                 set_current_state(TASK_UNINTERRUPTIBLE);
1518                 schedule_timeout(cfs_time_seconds(1));
1519         }
1520
1521         cfs_restore_sigs(blocked);
1522 }
1523
1524 static void
1525 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1526 {
1527         struct lnet_ni          *ni;
1528         struct lnet_net         *net;
1529         struct lnet_ni_status *ns;
1530         int                     i;
1531         int                     rc;
1532
1533         i = 0;
1534         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1535                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1536                         LASSERT(i < pbuf->pb_nnis);
1537
1538                         ns = &pbuf->pb_info.pi_ni[i];
1539
1540                         ns->ns_nid = ni->ni_nid;
1541
1542                         lnet_ni_lock(ni);
1543                         ns->ns_status = (ni->ni_status != NULL) ?
1544                                          ni->ni_status->ns_status :
1545                                                 LNET_NI_STATUS_UP;
1546                         ni->ni_status = ns;
1547                         lnet_ni_unlock(ni);
1548
1549                         i++;
1550                 }
1551         }
1552         /*
1553          * We (ab)use the ns_status of the loopback interface to
1554          * transmit the sequence number. The first interface listed
1555          * must be the loopback interface.
1556          */
1557         rc = lnet_ping_info_validate(&pbuf->pb_info);
1558         if (rc) {
1559                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1560                 LBUG();
1561         }
1562         LNET_PING_BUFFER_SEQNO(pbuf) =
1563                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1564 }
1565
1566 static void
1567 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1568                         struct lnet_handle_md ping_mdh)
1569 {
1570         struct lnet_ping_buffer *old_pbuf = NULL;
1571         struct lnet_handle_md old_ping_md;
1572
1573         /* switch the NIs to point to the new ping info created */
1574         lnet_net_lock(LNET_LOCK_EX);
1575
1576         if (!the_lnet.ln_routing)
1577                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1578         if (!lnet_peer_discovery_disabled)
1579                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1580
1581         /* Ensure only known feature bits have been set. */
1582         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1583         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1584
1585         lnet_ping_target_install_locked(pbuf);
1586
1587         if (the_lnet.ln_ping_target) {
1588                 old_pbuf = the_lnet.ln_ping_target;
1589                 old_ping_md = the_lnet.ln_ping_target_md;
1590         }
1591         the_lnet.ln_ping_target_md = ping_mdh;
1592         the_lnet.ln_ping_target = pbuf;
1593
1594         lnet_net_unlock(LNET_LOCK_EX);
1595
1596         if (old_pbuf) {
1597                 /* unlink and free the old ping info */
1598                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1599                 lnet_ping_buffer_decref(old_pbuf);
1600         }
1601
1602         lnet_push_update_to_peers(0);
1603 }
1604
1605 static void
1606 lnet_ping_target_fini(void)
1607 {
1608         int             rc;
1609
1610         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1611                             &the_lnet.ln_ping_target_md);
1612
1613         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1614         LASSERT(rc == 0);
1615
1616         lnet_ping_target_destroy();
1617 }
1618
1619 /* Resize the push target. */
1620 int lnet_push_target_resize(void)
1621 {
1622         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1623         struct lnet_md md = { NULL };
1624         struct lnet_handle_me meh;
1625         struct lnet_handle_md mdh;
1626         struct lnet_handle_md old_mdh;
1627         struct lnet_ping_buffer *pbuf;
1628         struct lnet_ping_buffer *old_pbuf;
1629         int nnis = the_lnet.ln_push_target_nnis;
1630         int rc;
1631
1632         if (nnis <= 0) {
1633                 rc = -EINVAL;
1634                 goto fail_return;
1635         }
1636 again:
1637         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1638         if (!pbuf) {
1639                 rc = -ENOMEM;
1640                 goto fail_return;
1641         }
1642
1643         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1644                           LNET_PROTO_PING_MATCHBITS, 0,
1645                           LNET_UNLINK, LNET_INS_AFTER,
1646                           &meh);
1647         if (rc) {
1648                 CERROR("Can't create push target ME: %d\n", rc);
1649                 goto fail_decref_pbuf;
1650         }
1651
1652         /* initialize md content */
1653         md.start     = &pbuf->pb_info;
1654         md.length    = LNET_PING_INFO_SIZE(nnis);
1655         md.threshold = LNET_MD_THRESH_INF;
1656         md.max_size  = 0;
1657         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE |
1658                        LNET_MD_MANAGE_REMOTE;
1659         md.user_ptr  = pbuf;
1660         md.eq_handle = the_lnet.ln_push_target_eq;
1661
1662         rc = LNetMDAttach(meh, md, LNET_RETAIN, &mdh);
1663         if (rc) {
1664                 CERROR("Can't attach push MD: %d\n", rc);
1665                 goto fail_unlink_meh;
1666         }
1667         lnet_ping_buffer_addref(pbuf);
1668
1669         lnet_net_lock(LNET_LOCK_EX);
1670         old_pbuf = the_lnet.ln_push_target;
1671         old_mdh = the_lnet.ln_push_target_md;
1672         the_lnet.ln_push_target = pbuf;
1673         the_lnet.ln_push_target_md = mdh;
1674         lnet_net_unlock(LNET_LOCK_EX);
1675
1676         if (old_pbuf) {
1677                 LNetMDUnlink(old_mdh);
1678                 lnet_ping_buffer_decref(old_pbuf);
1679         }
1680
1681         if (nnis < the_lnet.ln_push_target_nnis)
1682                 goto again;
1683
1684         CDEBUG(D_NET, "nnis %d success\n", nnis);
1685
1686         return 0;
1687
1688 fail_unlink_meh:
1689         LNetMEUnlink(meh);
1690 fail_decref_pbuf:
1691         lnet_ping_buffer_decref(pbuf);
1692 fail_return:
1693         CDEBUG(D_NET, "nnis %d error %d\n", nnis, rc);
1694         return rc;
1695 }
1696
1697 static void lnet_push_target_event_handler(struct lnet_event *ev)
1698 {
1699         struct lnet_ping_buffer *pbuf = ev->md.user_ptr;
1700
1701         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1702                 lnet_swap_pinginfo(pbuf);
1703
1704         lnet_peer_push_event(ev);
1705         if (ev->unlinked)
1706                 lnet_ping_buffer_decref(pbuf);
1707 }
1708
1709 /* Initialize the push target. */
1710 static int lnet_push_target_init(void)
1711 {
1712         int rc;
1713
1714         if (the_lnet.ln_push_target)
1715                 return -EALREADY;
1716
1717         rc = LNetEQAlloc(0, lnet_push_target_event_handler,
1718                          &the_lnet.ln_push_target_eq);
1719         if (rc) {
1720                 CERROR("Can't allocated push target EQ: %d\n", rc);
1721                 return rc;
1722         }
1723
1724         /* Start at the required minimum, we'll enlarge if required. */
1725         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
1726
1727         rc = lnet_push_target_resize();
1728
1729         if (rc) {
1730                 LNetEQFree(the_lnet.ln_push_target_eq);
1731                 LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1732         }
1733
1734         return rc;
1735 }
1736
1737 /* Clean up the push target. */
1738 static void lnet_push_target_fini(void)
1739 {
1740         if (!the_lnet.ln_push_target)
1741                 return;
1742
1743         /* Unlink and invalidate to prevent new references. */
1744         LNetMDUnlink(the_lnet.ln_push_target_md);
1745         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
1746
1747         /* Wait for the unlink to complete. */
1748         while (lnet_ping_buffer_numref(the_lnet.ln_push_target) > 1) {
1749                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1750                 set_current_state(TASK_UNINTERRUPTIBLE);
1751                 schedule_timeout(cfs_time_seconds(1));
1752         }
1753
1754         lnet_ping_buffer_decref(the_lnet.ln_push_target);
1755         the_lnet.ln_push_target = NULL;
1756         the_lnet.ln_push_target_nnis = 0;
1757
1758         LNetEQFree(the_lnet.ln_push_target_eq);
1759         LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1760 }
1761
1762 static int
1763 lnet_ni_tq_credits(struct lnet_ni *ni)
1764 {
1765         int     credits;
1766
1767         LASSERT(ni->ni_ncpts >= 1);
1768
1769         if (ni->ni_ncpts == 1)
1770                 return ni->ni_net->net_tunables.lct_max_tx_credits;
1771
1772         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
1773         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
1774         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
1775
1776         return credits;
1777 }
1778
1779 static void
1780 lnet_ni_unlink_locked(struct lnet_ni *ni)
1781 {
1782         if (!list_empty(&ni->ni_cptlist)) {
1783                 list_del_init(&ni->ni_cptlist);
1784                 lnet_ni_decref_locked(ni, 0);
1785         }
1786
1787         /* move it to zombie list and nobody can find it anymore */
1788         LASSERT(!list_empty(&ni->ni_netlist));
1789         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
1790         lnet_ni_decref_locked(ni, 0);
1791 }
1792
1793 static void
1794 lnet_clear_zombies_nis_locked(struct lnet_net *net)
1795 {
1796         int             i;
1797         int             islo;
1798         struct lnet_ni  *ni;
1799         struct list_head *zombie_list = &net->net_ni_zombie;
1800
1801         /*
1802          * Now wait for the NIs I just nuked to show up on the zombie
1803          * list and shut them down in guaranteed thread context
1804          */
1805         i = 2;
1806         while (!list_empty(zombie_list)) {
1807                 int     *ref;
1808                 int     j;
1809
1810                 ni = list_entry(zombie_list->next,
1811                                 struct lnet_ni, ni_netlist);
1812                 list_del_init(&ni->ni_netlist);
1813                 /* the ni should be in deleting state. If it's not it's
1814                  * a bug */
1815                 LASSERT(ni->ni_state & LNET_NI_STATE_DELETING);
1816                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1817                         if (*ref == 0)
1818                                 continue;
1819                         /* still busy, add it back to zombie list */
1820                         list_add(&ni->ni_netlist, zombie_list);
1821                         break;
1822                 }
1823
1824                 if (!list_empty(&ni->ni_netlist)) {
1825                         lnet_net_unlock(LNET_LOCK_EX);
1826                         ++i;
1827                         if ((i & (-i)) == i) {
1828                                 CDEBUG(D_WARNING,
1829                                        "Waiting for zombie LNI %s\n",
1830                                        libcfs_nid2str(ni->ni_nid));
1831                         }
1832                         set_current_state(TASK_UNINTERRUPTIBLE);
1833                         schedule_timeout(cfs_time_seconds(1));
1834                         lnet_net_lock(LNET_LOCK_EX);
1835                         continue;
1836                 }
1837
1838                 lnet_net_unlock(LNET_LOCK_EX);
1839
1840                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
1841
1842                 LASSERT(!in_interrupt());
1843                 (net->net_lnd->lnd_shutdown)(ni);
1844
1845                 if (!islo)
1846                         CDEBUG(D_LNI, "Removed LNI %s\n",
1847                               libcfs_nid2str(ni->ni_nid));
1848
1849                 lnet_ni_free(ni);
1850                 i = 2;
1851                 lnet_net_lock(LNET_LOCK_EX);
1852         }
1853 }
1854
1855 /* shutdown down the NI and release refcount */
1856 static void
1857 lnet_shutdown_lndni(struct lnet_ni *ni)
1858 {
1859         int i;
1860         struct lnet_net *net = ni->ni_net;
1861
1862         lnet_net_lock(LNET_LOCK_EX);
1863         lnet_ni_lock(ni);
1864         ni->ni_state |= LNET_NI_STATE_DELETING;
1865         ni->ni_state &= ~LNET_NI_STATE_ACTIVE;
1866         lnet_ni_unlock(ni);
1867         lnet_ni_unlink_locked(ni);
1868         lnet_incr_dlc_seq();
1869         lnet_net_unlock(LNET_LOCK_EX);
1870
1871         /* clear messages for this NI on the lazy portal */
1872         for (i = 0; i < the_lnet.ln_nportals; i++)
1873                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
1874
1875         lnet_net_lock(LNET_LOCK_EX);
1876         lnet_clear_zombies_nis_locked(net);
1877         lnet_net_unlock(LNET_LOCK_EX);
1878 }
1879
1880 static void
1881 lnet_shutdown_lndnet(struct lnet_net *net)
1882 {
1883         struct lnet_ni *ni;
1884
1885         lnet_net_lock(LNET_LOCK_EX);
1886
1887         net->net_state = LNET_NET_STATE_DELETING;
1888
1889         list_del_init(&net->net_list);
1890
1891         while (!list_empty(&net->net_ni_list)) {
1892                 ni = list_entry(net->net_ni_list.next,
1893                                 struct lnet_ni, ni_netlist);
1894                 lnet_net_unlock(LNET_LOCK_EX);
1895                 lnet_shutdown_lndni(ni);
1896                 lnet_net_lock(LNET_LOCK_EX);
1897         }
1898
1899         lnet_net_unlock(LNET_LOCK_EX);
1900
1901         /* Do peer table cleanup for this net */
1902         lnet_peer_tables_cleanup(net);
1903
1904         lnet_net_lock(LNET_LOCK_EX);
1905         /*
1906          * decrement ref count on lnd only when the entire network goes
1907          * away
1908          */
1909         net->net_lnd->lnd_refcount--;
1910
1911         lnet_net_unlock(LNET_LOCK_EX);
1912
1913         lnet_net_free(net);
1914 }
1915
1916 static void
1917 lnet_shutdown_lndnets(void)
1918 {
1919         struct lnet_net *net;
1920         struct list_head resend;
1921         struct lnet_msg *msg, *tmp;
1922
1923         INIT_LIST_HEAD(&resend);
1924
1925         /* NB called holding the global mutex */
1926
1927         /* All quiet on the API front */
1928         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
1929         LASSERT(the_lnet.ln_refcount == 0);
1930
1931         lnet_net_lock(LNET_LOCK_EX);
1932         the_lnet.ln_state = LNET_STATE_STOPPING;
1933
1934         while (!list_empty(&the_lnet.ln_nets)) {
1935                 /*
1936                  * move the nets to the zombie list to avoid them being
1937                  * picked up for new work. LONET is also included in the
1938                  * Nets that will be moved to the zombie list
1939                  */
1940                 net = list_entry(the_lnet.ln_nets.next,
1941                                  struct lnet_net, net_list);
1942                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
1943         }
1944
1945         /* Drop the cached loopback Net. */
1946         if (the_lnet.ln_loni != NULL) {
1947                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
1948                 the_lnet.ln_loni = NULL;
1949         }
1950         lnet_net_unlock(LNET_LOCK_EX);
1951
1952         /* iterate through the net zombie list and delete each net */
1953         while (!list_empty(&the_lnet.ln_net_zombie)) {
1954                 net = list_entry(the_lnet.ln_net_zombie.next,
1955                                  struct lnet_net, net_list);
1956                 lnet_shutdown_lndnet(net);
1957         }
1958
1959         spin_lock(&the_lnet.ln_msg_resend_lock);
1960         list_splice(&the_lnet.ln_msg_resend, &resend);
1961         spin_unlock(&the_lnet.ln_msg_resend_lock);
1962
1963         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
1964                 list_del_init(&msg->msg_list);
1965                 msg->msg_no_resend = true;
1966                 lnet_finalize(msg, -ECANCELED);
1967         }
1968
1969         lnet_net_lock(LNET_LOCK_EX);
1970         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
1971         lnet_net_unlock(LNET_LOCK_EX);
1972 }
1973
1974 static int
1975 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
1976 {
1977         int                     rc = -EINVAL;
1978         struct lnet_tx_queue    *tq;
1979         int                     i;
1980         struct lnet_net         *net = ni->ni_net;
1981
1982         mutex_lock(&the_lnet.ln_lnd_mutex);
1983
1984         if (tun) {
1985                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
1986                 ni->ni_lnd_tunables_set = true;
1987         }
1988
1989         rc = (net->net_lnd->lnd_startup)(ni);
1990
1991         mutex_unlock(&the_lnet.ln_lnd_mutex);
1992
1993         if (rc != 0) {
1994                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
1995                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
1996                 lnet_net_lock(LNET_LOCK_EX);
1997                 net->net_lnd->lnd_refcount--;
1998                 lnet_net_unlock(LNET_LOCK_EX);
1999                 goto failed0;
2000         }
2001
2002         lnet_ni_lock(ni);
2003         ni->ni_state |= LNET_NI_STATE_ACTIVE;
2004         ni->ni_state &= ~LNET_NI_STATE_INIT;
2005         lnet_ni_unlock(ni);
2006
2007         /* We keep a reference on the loopback net through the loopback NI */
2008         if (net->net_lnd->lnd_type == LOLND) {
2009                 lnet_ni_addref(ni);
2010                 LASSERT(the_lnet.ln_loni == NULL);
2011                 the_lnet.ln_loni = ni;
2012                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2013                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2014                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2015                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2016                 return 0;
2017         }
2018
2019         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2020             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2021                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2022                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2023                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2024                                         "" : "per-peer ");
2025                 /* shutdown the NI since if we get here then it must've already
2026                  * been started
2027                  */
2028                 lnet_shutdown_lndni(ni);
2029                 return -EINVAL;
2030         }
2031
2032         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2033                 tq->tq_credits_min =
2034                 tq->tq_credits_max =
2035                 tq->tq_credits = lnet_ni_tq_credits(ni);
2036         }
2037
2038         atomic_set(&ni->ni_tx_credits,
2039                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2040         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2041
2042         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2043                 libcfs_nid2str(ni->ni_nid),
2044                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2045                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2046                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2047                 ni->ni_net->net_tunables.lct_peer_timeout);
2048
2049         return 0;
2050 failed0:
2051         lnet_ni_free(ni);
2052         return rc;
2053 }
2054
2055 static int
2056 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2057 {
2058         struct lnet_ni *ni;
2059         struct lnet_net *net_l = NULL;
2060         struct list_head        local_ni_list;
2061         int                     rc;
2062         int                     ni_count = 0;
2063         __u32                   lnd_type;
2064         struct lnet_lnd *lnd;
2065         int                     peer_timeout =
2066                 net->net_tunables.lct_peer_timeout;
2067         int                     maxtxcredits =
2068                 net->net_tunables.lct_max_tx_credits;
2069         int                     peerrtrcredits =
2070                 net->net_tunables.lct_peer_rtr_credits;
2071
2072         INIT_LIST_HEAD(&local_ni_list);
2073
2074         /*
2075          * make sure that this net is unique. If it isn't then
2076          * we are adding interfaces to an already existing network, and
2077          * 'net' is just a convenient way to pass in the list.
2078          * if it is unique we need to find the LND and load it if
2079          * necessary.
2080          */
2081         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2082                 lnd_type = LNET_NETTYP(net->net_id);
2083
2084                 mutex_lock(&the_lnet.ln_lnd_mutex);
2085                 lnd = lnet_find_lnd_by_type(lnd_type);
2086
2087                 if (lnd == NULL) {
2088                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2089                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2090                         mutex_lock(&the_lnet.ln_lnd_mutex);
2091
2092                         lnd = lnet_find_lnd_by_type(lnd_type);
2093                         if (lnd == NULL) {
2094                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2095                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2096                                 libcfs_lnd2str(lnd_type),
2097                                 libcfs_lnd2modname(lnd_type), rc);
2098 #ifndef HAVE_MODULE_LOADING_SUPPORT
2099                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2100                                                 "compiled with kernel module "
2101                                                 "loading support.");
2102 #endif
2103                                 rc = -EINVAL;
2104                                 goto failed0;
2105                         }
2106                 }
2107
2108                 lnet_net_lock(LNET_LOCK_EX);
2109                 lnd->lnd_refcount++;
2110                 lnet_net_unlock(LNET_LOCK_EX);
2111
2112                 net->net_lnd = lnd;
2113
2114                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2115
2116                 net_l = net;
2117         }
2118
2119         /*
2120          * net_l: if the network being added is unique then net_l
2121          *        will point to that network
2122          *        if the network being added is not unique then
2123          *        net_l points to the existing network.
2124          *
2125          * When we enter the loop below, we'll pick NIs off he
2126          * network beign added and start them up, then add them to
2127          * a local ni list. Once we've successfully started all
2128          * the NIs then we join the local NI list (of started up
2129          * networks) with the net_l->net_ni_list, which should
2130          * point to the correct network to add the new ni list to
2131          *
2132          * If any of the new NIs fail to start up, then we want to
2133          * iterate through the local ni list, which should include
2134          * any NIs which were successfully started up, and shut
2135          * them down.
2136          *
2137          * After than we want to delete the network being added,
2138          * to avoid a memory leak.
2139          */
2140
2141         /*
2142          * When a network uses TCP bonding then all its interfaces
2143          * must be specified when the network is first defined: the
2144          * TCP bonding code doesn't allow for interfaces to be added
2145          * or removed.
2146          */
2147         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2148             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2149                 rc = -EINVAL;
2150                 goto failed0;
2151         }
2152
2153         while (!list_empty(&net->net_ni_added)) {
2154                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2155                                 ni_netlist);
2156                 list_del_init(&ni->ni_netlist);
2157
2158                 /* make sure that the the NI we're about to start
2159                  * up is actually unique. if it's not fail. */
2160                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2161                                         ni->ni_interfaces[0])) {
2162                         rc = -EINVAL;
2163                         goto failed1;
2164                 }
2165
2166                 /* adjust the pointer the parent network, just in case it
2167                  * the net is a duplicate */
2168                 ni->ni_net = net_l;
2169
2170                 rc = lnet_startup_lndni(ni, tun);
2171
2172                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
2173                         ni->ni_net->net_lnd->lnd_query != NULL);
2174
2175                 if (rc < 0)
2176                         goto failed1;
2177
2178                 lnet_ni_addref(ni);
2179                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2180
2181                 ni_count++;
2182         }
2183
2184         lnet_net_lock(LNET_LOCK_EX);
2185         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2186         lnet_incr_dlc_seq();
2187         lnet_net_unlock(LNET_LOCK_EX);
2188
2189         /* if the network is not unique then we don't want to keep
2190          * it around after we're done. Free it. Otherwise add that
2191          * net to the global the_lnet.ln_nets */
2192         if (net_l != net && net_l != NULL) {
2193                 /*
2194                  * TODO - note. currently the tunables can not be updated
2195                  * once added
2196                  */
2197                 lnet_net_free(net);
2198         } else {
2199                 net->net_state = LNET_NET_STATE_ACTIVE;
2200                 /*
2201                  * restore tunables after it has been overwitten by the
2202                  * lnd
2203                  */
2204                 if (peer_timeout != -1)
2205                         net->net_tunables.lct_peer_timeout = peer_timeout;
2206                 if (maxtxcredits != -1)
2207                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2208                 if (peerrtrcredits != -1)
2209                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2210
2211                 lnet_net_lock(LNET_LOCK_EX);
2212                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2213                 lnet_net_unlock(LNET_LOCK_EX);
2214         }
2215
2216         return ni_count;
2217
2218 failed1:
2219         /*
2220          * shutdown the new NIs that are being started up
2221          * free the NET being started
2222          */
2223         while (!list_empty(&local_ni_list)) {
2224                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2225                                 ni_netlist);
2226
2227                 lnet_shutdown_lndni(ni);
2228         }
2229
2230 failed0:
2231         lnet_net_free(net);
2232
2233         return rc;
2234 }
2235
2236 static int
2237 lnet_startup_lndnets(struct list_head *netlist)
2238 {
2239         struct lnet_net         *net;
2240         int                     rc;
2241         int                     ni_count = 0;
2242
2243         /*
2244          * Change to running state before bringing up the LNDs. This
2245          * allows lnet_shutdown_lndnets() to assert that we've passed
2246          * through here.
2247          */
2248         lnet_net_lock(LNET_LOCK_EX);
2249         the_lnet.ln_state = LNET_STATE_RUNNING;
2250         lnet_net_unlock(LNET_LOCK_EX);
2251
2252         while (!list_empty(netlist)) {
2253                 net = list_entry(netlist->next, struct lnet_net, net_list);
2254                 list_del_init(&net->net_list);
2255
2256                 rc = lnet_startup_lndnet(net, NULL);
2257
2258                 if (rc < 0)
2259                         goto failed;
2260
2261                 ni_count += rc;
2262         }
2263
2264         return ni_count;
2265 failed:
2266         lnet_shutdown_lndnets();
2267
2268         return rc;
2269 }
2270
2271 /**
2272  * Initialize LNet library.
2273  *
2274  * Automatically called at module loading time. Caller has to call
2275  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2276  * latter returned 0. It must be called exactly once.
2277  *
2278  * \retval 0 on success
2279  * \retval -ve on failures.
2280  */
2281 int lnet_lib_init(void)
2282 {
2283         int rc;
2284
2285         lnet_assert_wire_constants();
2286
2287         /* refer to global cfs_cpt_table for now */
2288         the_lnet.ln_cpt_table   = cfs_cpt_table;
2289         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2290
2291         LASSERT(the_lnet.ln_cpt_number > 0);
2292         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2293                 /* we are under risk of consuming all lh_cookie */
2294                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2295                        "please change setting of CPT-table and retry\n",
2296                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2297                 return -E2BIG;
2298         }
2299
2300         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2301                 the_lnet.ln_cpt_bits++;
2302
2303         rc = lnet_create_locks();
2304         if (rc != 0) {
2305                 CERROR("Can't create LNet global locks: %d\n", rc);
2306                 return rc;
2307         }
2308
2309         the_lnet.ln_refcount = 0;
2310         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2311         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2312         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2313         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2314         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2315         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2316
2317         /* The hash table size is the number of bits it takes to express the set
2318          * ln_num_routes, minus 1 (better to under estimate than over so we
2319          * don't waste memory). */
2320         if (rnet_htable_size <= 0)
2321                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2322         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2323                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2324         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2325                                            order_base_2(rnet_htable_size) - 1);
2326
2327         /* All LNDs apart from the LOLND are in separate modules.  They
2328          * register themselves when their module loads, and unregister
2329          * themselves when their module is unloaded. */
2330         lnet_register_lnd(&the_lolnd);
2331         return 0;
2332 }
2333
2334 /**
2335  * Finalize LNet library.
2336  *
2337  * \pre lnet_lib_init() called with success.
2338  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2339  */
2340 void lnet_lib_exit(void)
2341 {
2342         LASSERT(the_lnet.ln_refcount == 0);
2343
2344         while (!list_empty(&the_lnet.ln_lnds))
2345                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2346                                                struct lnet_lnd, lnd_list));
2347         lnet_destroy_locks();
2348 }
2349
2350 /**
2351  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2352  *
2353  * Users must call this function at least once before any other functions.
2354  * For each successful call there must be a corresponding call to
2355  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2356  * ignored.
2357  *
2358  * The PID used by LNet may be different from the one requested.
2359  * See LNetGetId().
2360  *
2361  * \param requested_pid PID requested by the caller.
2362  *
2363  * \return >= 0 on success, and < 0 error code on failures.
2364  */
2365 int
2366 LNetNIInit(lnet_pid_t requested_pid)
2367 {
2368         int                     im_a_router = 0;
2369         int                     rc;
2370         int                     ni_count;
2371         struct lnet_ping_buffer *pbuf;
2372         struct lnet_handle_md   ping_mdh;
2373         struct list_head        net_head;
2374         struct lnet_net         *net;
2375
2376         INIT_LIST_HEAD(&net_head);
2377
2378         mutex_lock(&the_lnet.ln_api_mutex);
2379
2380         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2381
2382         if (the_lnet.ln_refcount > 0) {
2383                 rc = the_lnet.ln_refcount++;
2384                 mutex_unlock(&the_lnet.ln_api_mutex);
2385                 return rc;
2386         }
2387
2388         rc = lnet_prepare(requested_pid);
2389         if (rc != 0) {
2390                 mutex_unlock(&the_lnet.ln_api_mutex);
2391                 return rc;
2392         }
2393
2394         /* create a network for Loopback network */
2395         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2396         if (net == NULL) {
2397                 rc = -ENOMEM;
2398                 goto err_empty_list;
2399         }
2400
2401         /* Add in the loopback NI */
2402         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2403                 rc = -ENOMEM;
2404                 goto err_empty_list;
2405         }
2406
2407         /* If LNet is being initialized via DLC it is possible
2408          * that the user requests not to load module parameters (ones which
2409          * are supported by DLC) on initialization.  Therefore, make sure not
2410          * to load networks, routes and forwarding from module parameters
2411          * in this case.  On cleanup in case of failure only clean up
2412          * routes if it has been loaded */
2413         if (!the_lnet.ln_nis_from_mod_params) {
2414                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2415                                          use_tcp_bonding);
2416                 if (rc < 0)
2417                         goto err_empty_list;
2418         }
2419
2420         ni_count = lnet_startup_lndnets(&net_head);
2421         if (ni_count < 0) {
2422                 rc = ni_count;
2423                 goto err_empty_list;
2424         }
2425
2426         if (!the_lnet.ln_nis_from_mod_params) {
2427                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2428                 if (rc != 0)
2429                         goto err_shutdown_lndnis;
2430
2431                 rc = lnet_check_routes();
2432                 if (rc != 0)
2433                         goto err_destroy_routes;
2434
2435                 rc = lnet_rtrpools_alloc(im_a_router);
2436                 if (rc != 0)
2437                         goto err_destroy_routes;
2438         }
2439
2440         rc = lnet_acceptor_start();
2441         if (rc != 0)
2442                 goto err_destroy_routes;
2443
2444         the_lnet.ln_refcount = 1;
2445         /* Now I may use my own API functions... */
2446
2447         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2448         if (rc != 0)
2449                 goto err_acceptor_stop;
2450
2451         lnet_ping_target_update(pbuf, ping_mdh);
2452
2453         rc = lnet_monitor_thr_start();
2454         if (rc != 0)
2455                 goto err_stop_ping;
2456
2457         rc = lnet_push_target_init();
2458         if (rc != 0)
2459                 goto err_stop_monitor_thr;
2460
2461         rc = lnet_peer_discovery_start();
2462         if (rc != 0)
2463                 goto err_destroy_push_target;
2464
2465         lnet_fault_init();
2466         lnet_router_debugfs_init();
2467
2468         mutex_unlock(&the_lnet.ln_api_mutex);
2469
2470         return 0;
2471
2472 err_destroy_push_target:
2473         lnet_push_target_fini();
2474 err_stop_monitor_thr:
2475         lnet_monitor_thr_stop();
2476 err_stop_ping:
2477         lnet_ping_target_fini();
2478 err_acceptor_stop:
2479         the_lnet.ln_refcount = 0;
2480         lnet_acceptor_stop();
2481 err_destroy_routes:
2482         if (!the_lnet.ln_nis_from_mod_params)
2483                 lnet_destroy_routes();
2484 err_shutdown_lndnis:
2485         lnet_shutdown_lndnets();
2486 err_empty_list:
2487         lnet_unprepare();
2488         LASSERT(rc < 0);
2489         mutex_unlock(&the_lnet.ln_api_mutex);
2490         while (!list_empty(&net_head)) {
2491                 struct lnet_net *net;
2492
2493                 net = list_entry(net_head.next, struct lnet_net, net_list);
2494                 list_del_init(&net->net_list);
2495                 lnet_net_free(net);
2496         }
2497         return rc;
2498 }
2499 EXPORT_SYMBOL(LNetNIInit);
2500
2501 /**
2502  * Stop LNet interfaces, routing, and forwarding.
2503  *
2504  * Users must call this function once for each successful call to LNetNIInit().
2505  * Once the LNetNIFini() operation has been started, the results of pending
2506  * API operations are undefined.
2507  *
2508  * \return always 0 for current implementation.
2509  */
2510 int
2511 LNetNIFini()
2512 {
2513         mutex_lock(&the_lnet.ln_api_mutex);
2514
2515         LASSERT(the_lnet.ln_refcount > 0);
2516
2517         if (the_lnet.ln_refcount != 1) {
2518                 the_lnet.ln_refcount--;
2519         } else {
2520                 LASSERT(!the_lnet.ln_niinit_self);
2521
2522                 lnet_fault_fini();
2523
2524                 lnet_router_debugfs_init();
2525                 lnet_peer_discovery_stop();
2526                 lnet_push_target_fini();
2527                 lnet_monitor_thr_stop();
2528                 lnet_ping_target_fini();
2529
2530                 /* Teardown fns that use my own API functions BEFORE here */
2531                 the_lnet.ln_refcount = 0;
2532
2533                 lnet_acceptor_stop();
2534                 lnet_destroy_routes();
2535                 lnet_shutdown_lndnets();
2536                 lnet_unprepare();
2537         }
2538
2539         mutex_unlock(&the_lnet.ln_api_mutex);
2540         return 0;
2541 }
2542 EXPORT_SYMBOL(LNetNIFini);
2543
2544 /**
2545  * Grabs the ni data from the ni structure and fills the out
2546  * parameters
2547  *
2548  * \param[in] ni network        interface structure
2549  * \param[out] cfg_ni           NI config information
2550  * \param[out] tun              network and LND tunables
2551  */
2552 static void
2553 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2554                    struct lnet_ioctl_config_lnd_tunables *tun,
2555                    struct lnet_ioctl_element_stats *stats,
2556                    __u32 tun_size)
2557 {
2558         size_t min_size = 0;
2559         int i;
2560
2561         if (!ni || !cfg_ni || !tun)
2562                 return;
2563
2564         if (ni->ni_interfaces[0] != NULL) {
2565                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2566                         if (ni->ni_interfaces[i] != NULL) {
2567                                 strncpy(cfg_ni->lic_ni_intf[i],
2568                                         ni->ni_interfaces[i],
2569                                         sizeof(cfg_ni->lic_ni_intf[i]));
2570                         }
2571                 }
2572         }
2573
2574         cfg_ni->lic_nid = ni->ni_nid;
2575         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2576                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2577         else
2578                 cfg_ni->lic_status = ni->ni_status->ns_status;
2579         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2580         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2581
2582         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2583
2584         if (stats) {
2585                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2586                                                        LNET_STATS_TYPE_SEND);
2587                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2588                                                        LNET_STATS_TYPE_RECV);
2589                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2590                                                        LNET_STATS_TYPE_DROP);
2591         }
2592
2593         /*
2594          * tun->lt_tun will always be present, but in order to be
2595          * backwards compatible, we need to deal with the cases when
2596          * tun->lt_tun is smaller than what the kernel has, because it
2597          * comes from an older version of a userspace program, then we'll
2598          * need to copy as much information as we have available space.
2599          */
2600         min_size = tun_size - sizeof(tun->lt_cmn);
2601         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2602
2603         /* copy over the cpts */
2604         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2605             ni->ni_cpts == NULL)  {
2606                 for (i = 0; i < ni->ni_ncpts; i++)
2607                         cfg_ni->lic_cpts[i] = i;
2608         } else {
2609                 for (i = 0;
2610                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2611                      i < LNET_MAX_SHOW_NUM_CPT;
2612                      i++)
2613                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2614         }
2615         cfg_ni->lic_ncpts = ni->ni_ncpts;
2616 }
2617
2618 /**
2619  * NOTE: This is a legacy function left in the code to be backwards
2620  * compatible with older userspace programs. It should eventually be
2621  * removed.
2622  *
2623  * Grabs the ni data from the ni structure and fills the out
2624  * parameters
2625  *
2626  * \param[in] ni network        interface structure
2627  * \param[out] config           config information
2628  */
2629 static void
2630 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2631                          struct lnet_ioctl_config_data *config)
2632 {
2633         struct lnet_ioctl_net_config *net_config;
2634         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2635         size_t min_size, tunable_size = 0;
2636         int i;
2637
2638         if (!ni || !config)
2639                 return;
2640
2641         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2642         if (!net_config)
2643                 return;
2644
2645         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2646                      ARRAY_SIZE(net_config->ni_interfaces));
2647
2648         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2649                 if (!ni->ni_interfaces[i])
2650                         break;
2651
2652                 strncpy(net_config->ni_interfaces[i],
2653                         ni->ni_interfaces[i],
2654                         sizeof(net_config->ni_interfaces[i]));
2655         }
2656
2657         config->cfg_nid = ni->ni_nid;
2658         config->cfg_config_u.cfg_net.net_peer_timeout =
2659                 ni->ni_net->net_tunables.lct_peer_timeout;
2660         config->cfg_config_u.cfg_net.net_max_tx_credits =
2661                 ni->ni_net->net_tunables.lct_max_tx_credits;
2662         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2663                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2664         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2665                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2666
2667         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2668                 net_config->ni_status = LNET_NI_STATUS_UP;
2669         else
2670                 net_config->ni_status = ni->ni_status->ns_status;
2671
2672         if (ni->ni_cpts) {
2673                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2674
2675                 for (i = 0; i < num_cpts; i++)
2676                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2677
2678                 config->cfg_ncpts = num_cpts;
2679         }
2680
2681         /*
2682          * See if user land tools sent in a newer and larger version
2683          * of struct lnet_tunables than what the kernel uses.
2684          */
2685         min_size = sizeof(*config) + sizeof(*net_config);
2686
2687         if (config->cfg_hdr.ioc_len > min_size)
2688                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2689
2690         /* Don't copy too much data to user space */
2691         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2692         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2693
2694         if (lnd_cfg && min_size) {
2695                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2696                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2697
2698                 /* Tell user land that kernel side has less data */
2699                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2700                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2701                         config->cfg_hdr.ioc_len -= min_size;
2702                 }
2703         }
2704 }
2705
2706 struct lnet_ni *
2707 lnet_get_ni_idx_locked(int idx)
2708 {
2709         struct lnet_ni          *ni;
2710         struct lnet_net         *net;
2711
2712         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2713                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2714                         if (idx-- == 0)
2715                                 return ni;
2716                 }
2717         }
2718
2719         return NULL;
2720 }
2721
2722 struct lnet_ni *
2723 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2724 {
2725         struct lnet_ni          *ni;
2726         struct lnet_net         *net = mynet;
2727
2728         /*
2729          * It is possible that the net has been cleaned out while there is
2730          * a message being sent. This function accessed the net without
2731          * checking if the list is empty
2732          */
2733         if (prev == NULL) {
2734                 if (net == NULL)
2735                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2736                                         net_list);
2737                 if (list_empty(&net->net_ni_list))
2738                         return NULL;
2739                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2740                                 ni_netlist);
2741
2742                 return ni;
2743         }
2744
2745         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2746                 /* if you reached the end of the ni list and the net is
2747                  * specified, then there are no more nis in that net */
2748                 if (net != NULL)
2749                         return NULL;
2750
2751                 /* we reached the end of this net ni list. move to the
2752                  * next net */
2753                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2754                         /* no more nets and no more NIs. */
2755                         return NULL;
2756
2757                 /* get the next net */
2758                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2759                                  net_list);
2760                 if (list_empty(&net->net_ni_list))
2761                         return NULL;
2762                 /* get the ni on it */
2763                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2764                                 ni_netlist);
2765
2766                 return ni;
2767         }
2768
2769         if (list_empty(&prev->ni_netlist))
2770                 return NULL;
2771
2772         /* there are more nis left */
2773         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2774
2775         return ni;
2776 }
2777
2778 int
2779 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2780 {
2781         struct lnet_ni *ni;
2782         int cpt;
2783         int rc = -ENOENT;
2784         int idx = config->cfg_count;
2785
2786         cpt = lnet_net_lock_current();
2787
2788         ni = lnet_get_ni_idx_locked(idx);
2789
2790         if (ni != NULL) {
2791                 rc = 0;
2792                 lnet_ni_lock(ni);
2793                 lnet_fill_ni_info_legacy(ni, config);
2794                 lnet_ni_unlock(ni);
2795         }
2796
2797         lnet_net_unlock(cpt);
2798         return rc;
2799 }
2800
2801 int
2802 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2803                    struct lnet_ioctl_config_lnd_tunables *tun,
2804                    struct lnet_ioctl_element_stats *stats,
2805                    __u32 tun_size)
2806 {
2807         struct lnet_ni          *ni;
2808         int                     cpt;
2809         int                     rc = -ENOENT;
2810
2811         if (!cfg_ni || !tun || !stats)
2812                 return -EINVAL;
2813
2814         cpt = lnet_net_lock_current();
2815
2816         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2817
2818         if (ni) {
2819                 rc = 0;
2820                 lnet_ni_lock(ni);
2821                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2822                 lnet_ni_unlock(ni);
2823         }
2824
2825         lnet_net_unlock(cpt);
2826         return rc;
2827 }
2828
2829 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2830 {
2831         struct lnet_ni *ni;
2832         int cpt;
2833         int rc = -ENOENT;
2834
2835         if (!msg_stats)
2836                 return -EINVAL;
2837
2838         cpt = lnet_net_lock_current();
2839
2840         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2841
2842         if (ni) {
2843                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2844                 rc = 0;
2845         }
2846
2847         lnet_net_unlock(cpt);
2848
2849         return rc;
2850 }
2851
2852 static int lnet_add_net_common(struct lnet_net *net,
2853                                struct lnet_ioctl_config_lnd_tunables *tun)
2854 {
2855         __u32                   net_id;
2856         struct lnet_ping_buffer *pbuf;
2857         struct lnet_handle_md   ping_mdh;
2858         int                     rc;
2859         struct lnet_remotenet *rnet;
2860         int                     net_ni_count;
2861         int                     num_acceptor_nets;
2862
2863         lnet_net_lock(LNET_LOCK_EX);
2864         rnet = lnet_find_rnet_locked(net->net_id);
2865         lnet_net_unlock(LNET_LOCK_EX);
2866         /*
2867          * make sure that the net added doesn't invalidate the current
2868          * configuration LNet is keeping
2869          */
2870         if (rnet) {
2871                 CERROR("Adding net %s will invalidate routing configuration\n",
2872                        libcfs_net2str(net->net_id));
2873                 lnet_net_free(net);
2874                 return -EUSERS;
2875         }
2876
2877         /*
2878          * make sure you calculate the correct number of slots in the ping
2879          * buffer. Since the ping info is a flattened list of all the NIs,
2880          * we should allocate enough slots to accomodate the number of NIs
2881          * which will be added.
2882          *
2883          * since ni hasn't been configured yet, use
2884          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
2885          */
2886         net_ni_count = lnet_get_net_ni_count_pre(net);
2887
2888         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2889                                     net_ni_count + lnet_get_ni_count(),
2890                                     false);
2891         if (rc < 0) {
2892                 lnet_net_free(net);
2893                 return rc;
2894         }
2895
2896         if (tun)
2897                 memcpy(&net->net_tunables,
2898                        &tun->lt_cmn, sizeof(net->net_tunables));
2899         else
2900                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
2901
2902         /*
2903          * before starting this network get a count of the current TCP
2904          * networks which require the acceptor thread running. If that
2905          * count is == 0 before we start up this network, then we'd want to
2906          * start up the acceptor thread after starting up this network
2907          */
2908         num_acceptor_nets = lnet_count_acceptor_nets();
2909
2910         net_id = net->net_id;
2911
2912         rc = lnet_startup_lndnet(net,
2913                                  (tun) ? &tun->lt_tun : NULL);
2914         if (rc < 0)
2915                 goto failed;
2916
2917         lnet_net_lock(LNET_LOCK_EX);
2918         net = lnet_get_net_locked(net_id);
2919         lnet_net_unlock(LNET_LOCK_EX);
2920
2921         LASSERT(net);
2922
2923         /*
2924          * Start the acceptor thread if this is the first network
2925          * being added that requires the thread.
2926          */
2927         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
2928                 rc = lnet_acceptor_start();
2929                 if (rc < 0) {
2930                         /* shutdown the net that we just started */
2931                         CERROR("Failed to start up acceptor thread\n");
2932                         lnet_shutdown_lndnet(net);
2933                         goto failed;
2934                 }
2935         }
2936
2937         lnet_net_lock(LNET_LOCK_EX);
2938         lnet_peer_net_added(net);
2939         lnet_net_unlock(LNET_LOCK_EX);
2940
2941         lnet_ping_target_update(pbuf, ping_mdh);
2942
2943         return 0;
2944
2945 failed:
2946         lnet_ping_md_unlink(pbuf, &ping_mdh);
2947         lnet_ping_buffer_decref(pbuf);
2948         return rc;
2949 }
2950
2951 static int lnet_handle_legacy_ip2nets(char *ip2nets,
2952                                       struct lnet_ioctl_config_lnd_tunables *tun)
2953 {
2954         struct lnet_net *net;
2955         char *nets;
2956         int rc;
2957         struct list_head net_head;
2958
2959         INIT_LIST_HEAD(&net_head);
2960
2961         rc = lnet_parse_ip2nets(&nets, ip2nets);
2962         if (rc < 0)
2963                 return rc;
2964
2965         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2966         if (rc < 0)
2967                 return rc;
2968
2969         mutex_lock(&the_lnet.ln_api_mutex);
2970         while (!list_empty(&net_head)) {
2971                 net = list_entry(net_head.next, struct lnet_net, net_list);
2972                 list_del_init(&net->net_list);
2973                 rc = lnet_add_net_common(net, tun);
2974                 if (rc < 0)
2975                         goto out;
2976         }
2977
2978 out:
2979         mutex_unlock(&the_lnet.ln_api_mutex);
2980
2981         while (!list_empty(&net_head)) {
2982                 net = list_entry(net_head.next, struct lnet_net, net_list);
2983                 list_del_init(&net->net_list);
2984                 lnet_net_free(net);
2985         }
2986         return rc;
2987 }
2988
2989 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
2990 {
2991         struct lnet_net *net;
2992         struct lnet_ni *ni;
2993         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
2994         int rc, i;
2995         __u32 net_id, lnd_type;
2996
2997         /* get the tunables if they are available */
2998         if (conf->lic_cfg_hdr.ioc_len >=
2999             sizeof(*conf) + sizeof(*tun))
3000                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3001                         conf->lic_bulk;
3002
3003         /* handle legacy ip2nets from DLC */
3004         if (conf->lic_legacy_ip2nets[0] != '\0')
3005                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3006                                                   tun);
3007
3008         net_id = LNET_NIDNET(conf->lic_nid);
3009         lnd_type = LNET_NETTYP(net_id);
3010
3011         if (!libcfs_isknown_lnd(lnd_type)) {
3012                 CERROR("No valid net and lnd information provided\n");
3013                 return -EINVAL;
3014         }
3015
3016         net = lnet_net_alloc(net_id, NULL);
3017         if (!net)
3018                 return -ENOMEM;
3019
3020         for (i = 0; i < conf->lic_ncpts; i++) {
3021                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3022                         return -EINVAL;
3023         }
3024
3025         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3026                                        conf->lic_ni_intf[0]);
3027         if (!ni)
3028                 return -ENOMEM;
3029
3030         mutex_lock(&the_lnet.ln_api_mutex);
3031
3032         rc = lnet_add_net_common(net, tun);
3033
3034         mutex_unlock(&the_lnet.ln_api_mutex);
3035
3036         return rc;
3037 }
3038
3039 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3040 {
3041         struct lnet_net  *net;
3042         struct lnet_ni *ni;
3043         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3044         struct lnet_ping_buffer *pbuf;
3045         struct lnet_handle_md  ping_mdh;
3046         int               rc;
3047         int               net_count;
3048         __u32             addr;
3049
3050         /* don't allow userspace to shutdown the LOLND */
3051         if (LNET_NETTYP(net_id) == LOLND)
3052                 return -EINVAL;
3053
3054         mutex_lock(&the_lnet.ln_api_mutex);
3055
3056         lnet_net_lock(0);
3057
3058         net = lnet_get_net_locked(net_id);
3059         if (!net) {
3060                 CERROR("net %s not found\n",
3061                        libcfs_net2str(net_id));
3062                 rc = -ENOENT;
3063                 goto unlock_net;
3064         }
3065
3066         addr = LNET_NIDADDR(conf->lic_nid);
3067         if (addr == 0) {
3068                 /* remove the entire net */
3069                 net_count = lnet_get_net_ni_count_locked(net);
3070
3071                 lnet_net_unlock(0);
3072
3073                 /* create and link a new ping info, before removing the old one */
3074                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3075                                         lnet_get_ni_count() - net_count,
3076                                         false);
3077                 if (rc != 0)
3078                         goto unlock_api_mutex;
3079
3080                 lnet_shutdown_lndnet(net);
3081
3082                 if (lnet_count_acceptor_nets() == 0)
3083                         lnet_acceptor_stop();
3084
3085                 lnet_ping_target_update(pbuf, ping_mdh);
3086
3087                 goto unlock_api_mutex;
3088         }
3089
3090         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3091         if (!ni) {
3092                 CERROR("nid %s not found\n",
3093                        libcfs_nid2str(conf->lic_nid));
3094                 rc = -ENOENT;
3095                 goto unlock_net;
3096         }
3097
3098         net_count = lnet_get_net_ni_count_locked(net);
3099
3100         lnet_net_unlock(0);
3101
3102         /* create and link a new ping info, before removing the old one */
3103         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3104                                   lnet_get_ni_count() - 1, false);
3105         if (rc != 0)
3106                 goto unlock_api_mutex;
3107
3108         lnet_shutdown_lndni(ni);
3109
3110         if (lnet_count_acceptor_nets() == 0)
3111                 lnet_acceptor_stop();
3112
3113         lnet_ping_target_update(pbuf, ping_mdh);
3114
3115         /* check if the net is empty and remove it if it is */
3116         if (net_count == 1)
3117                 lnet_shutdown_lndnet(net);
3118
3119         goto unlock_api_mutex;
3120
3121 unlock_net:
3122         lnet_net_unlock(0);
3123 unlock_api_mutex:
3124         mutex_unlock(&the_lnet.ln_api_mutex);
3125
3126         return rc;
3127 }
3128
3129 /*
3130  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3131  * They are only expected to be called for unique networks.
3132  * That can be as a result of older DLC library
3133  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3134  */
3135 int
3136 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3137 {
3138         struct lnet_net         *net;
3139         struct list_head        net_head;
3140         int                     rc;
3141         struct lnet_ioctl_config_lnd_tunables tun;
3142         char *nets = conf->cfg_config_u.cfg_net.net_intf;
3143
3144         INIT_LIST_HEAD(&net_head);
3145
3146         /* Create a net/ni structures for the network string */
3147         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3148         if (rc <= 0)
3149                 return rc == 0 ? -EINVAL : rc;
3150
3151         mutex_lock(&the_lnet.ln_api_mutex);
3152
3153         if (rc > 1) {
3154                 rc = -EINVAL; /* only add one network per call */
3155                 goto out_unlock_clean;
3156         }
3157
3158         net = list_entry(net_head.next, struct lnet_net, net_list);
3159         list_del_init(&net->net_list);
3160
3161         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3162
3163         memset(&tun, 0, sizeof(tun));
3164
3165         tun.lt_cmn.lct_peer_timeout =
3166           conf->cfg_config_u.cfg_net.net_peer_timeout;
3167         tun.lt_cmn.lct_peer_tx_credits =
3168           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3169         tun.lt_cmn.lct_peer_rtr_credits =
3170           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3171         tun.lt_cmn.lct_max_tx_credits =
3172           conf->cfg_config_u.cfg_net.net_max_tx_credits;
3173
3174         rc = lnet_add_net_common(net, &tun);
3175
3176 out_unlock_clean:
3177         mutex_unlock(&the_lnet.ln_api_mutex);
3178         while (!list_empty(&net_head)) {
3179                 /* net_head list is empty in success case */
3180                 net = list_entry(net_head.next, struct lnet_net, net_list);
3181                 list_del_init(&net->net_list);
3182                 lnet_net_free(net);
3183         }
3184         return rc;
3185 }
3186
3187 int
3188 lnet_dyn_del_net(__u32 net_id)
3189 {
3190         struct lnet_net  *net;
3191         struct lnet_ping_buffer *pbuf;
3192         struct lnet_handle_md ping_mdh;
3193         int               rc;
3194         int               net_ni_count;
3195
3196         /* don't allow userspace to shutdown the LOLND */
3197         if (LNET_NETTYP(net_id) == LOLND)
3198                 return -EINVAL;
3199
3200         mutex_lock(&the_lnet.ln_api_mutex);
3201
3202         lnet_net_lock(0);
3203
3204         net = lnet_get_net_locked(net_id);
3205         if (net == NULL) {
3206                 lnet_net_unlock(0);
3207                 rc = -EINVAL;
3208                 goto out;
3209         }
3210
3211         net_ni_count = lnet_get_net_ni_count_locked(net);
3212
3213         lnet_net_unlock(0);
3214
3215         /* create and link a new ping info, before removing the old one */
3216         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3217                                     lnet_get_ni_count() - net_ni_count, false);
3218         if (rc != 0)
3219                 goto out;
3220
3221         lnet_shutdown_lndnet(net);
3222
3223         if (lnet_count_acceptor_nets() == 0)
3224                 lnet_acceptor_stop();
3225
3226         lnet_ping_target_update(pbuf, ping_mdh);
3227
3228 out:
3229         mutex_unlock(&the_lnet.ln_api_mutex);
3230
3231         return rc;
3232 }
3233
3234 void lnet_incr_dlc_seq(void)
3235 {
3236         atomic_inc(&lnet_dlc_seq_no);
3237 }
3238
3239 __u32 lnet_get_dlc_seq_locked(void)
3240 {
3241         return atomic_read(&lnet_dlc_seq_no);
3242 }
3243
3244 static void
3245 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3246 {
3247         struct lnet_net *net;
3248         struct lnet_ni *ni;
3249
3250         lnet_net_lock(LNET_LOCK_EX);
3251         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3252                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3253                         if (ni->ni_nid == nid || all) {
3254                                 atomic_set(&ni->ni_healthv, value);
3255                                 if (list_empty(&ni->ni_recovery) &&
3256                                     value < LNET_MAX_HEALTH_VALUE) {
3257                                         CERROR("manually adding local NI %s to recovery\n",
3258                                                libcfs_nid2str(ni->ni_nid));
3259                                         list_add_tail(&ni->ni_recovery,
3260                                                       &the_lnet.ln_mt_localNIRecovq);
3261                                         lnet_ni_addref_locked(ni, 0);
3262                                 }
3263                                 if (!all) {
3264                                         lnet_net_unlock(LNET_LOCK_EX);
3265                                         return;
3266                                 }
3267                         }
3268                 }
3269         }
3270         lnet_net_unlock(LNET_LOCK_EX);
3271 }
3272
3273 /**
3274  * LNet ioctl handler.
3275  *
3276  */
3277 int
3278 LNetCtl(unsigned int cmd, void *arg)
3279 {
3280         struct libcfs_ioctl_data *data = arg;
3281         struct lnet_ioctl_config_data *config;
3282         struct lnet_process_id    id = {0};
3283         struct lnet_ni           *ni;
3284         int                       rc;
3285
3286         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3287                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3288
3289         switch (cmd) {
3290         case IOC_LIBCFS_GET_NI:
3291                 rc = LNetGetId(data->ioc_count, &id);
3292                 data->ioc_nid = id.nid;
3293                 return rc;
3294
3295         case IOC_LIBCFS_FAIL_NID:
3296                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3297
3298         case IOC_LIBCFS_ADD_ROUTE:
3299                 config = arg;
3300
3301                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3302                         return -EINVAL;
3303
3304                 mutex_lock(&the_lnet.ln_api_mutex);
3305                 rc = lnet_add_route(config->cfg_net,
3306                                     config->cfg_config_u.cfg_route.rtr_hop,
3307                                     config->cfg_nid,
3308                                     config->cfg_config_u.cfg_route.
3309                                         rtr_priority);
3310                 if (rc == 0) {
3311                         rc = lnet_check_routes();
3312                         if (rc != 0)
3313                                 lnet_del_route(config->cfg_net,
3314                                                config->cfg_nid);
3315                 }
3316                 mutex_unlock(&the_lnet.ln_api_mutex);
3317                 return rc;
3318
3319         case IOC_LIBCFS_DEL_ROUTE:
3320                 config = arg;
3321
3322                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3323                         return -EINVAL;
3324
3325                 mutex_lock(&the_lnet.ln_api_mutex);
3326                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3327                 mutex_unlock(&the_lnet.ln_api_mutex);
3328                 return rc;
3329
3330         case IOC_LIBCFS_GET_ROUTE:
3331                 config = arg;
3332
3333                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3334                         return -EINVAL;
3335
3336                 mutex_lock(&the_lnet.ln_api_mutex);
3337                 rc = lnet_get_route(config->cfg_count,
3338                                     &config->cfg_net,
3339                                     &config->cfg_config_u.cfg_route.rtr_hop,
3340                                     &config->cfg_nid,
3341                                     &config->cfg_config_u.cfg_route.rtr_flags,
3342                                     &config->cfg_config_u.cfg_route.
3343                                         rtr_priority);
3344                 mutex_unlock(&the_lnet.ln_api_mutex);
3345                 return rc;
3346
3347         case IOC_LIBCFS_GET_LOCAL_NI: {
3348                 struct lnet_ioctl_config_ni *cfg_ni;
3349                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3350                 struct lnet_ioctl_element_stats *stats;
3351                 __u32 tun_size;
3352
3353                 cfg_ni = arg;
3354
3355                 /* get the tunables if they are available */
3356                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3357                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3358                         return -EINVAL;
3359
3360                 stats = (struct lnet_ioctl_element_stats *)
3361                         cfg_ni->lic_bulk;
3362                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3363                                 (cfg_ni->lic_bulk + sizeof(*stats));
3364
3365                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3366                         sizeof(*stats);
3367
3368                 mutex_lock(&the_lnet.ln_api_mutex);
3369                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3370                 mutex_unlock(&the_lnet.ln_api_mutex);
3371                 return rc;
3372         }
3373
3374         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3375                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3376
3377                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3378                         return -EINVAL;
3379
3380                 mutex_lock(&the_lnet.ln_api_mutex);
3381                 rc = lnet_get_ni_stats(msg_stats);
3382                 mutex_unlock(&the_lnet.ln_api_mutex);
3383
3384                 return rc;
3385         }
3386
3387         case IOC_LIBCFS_GET_NET: {
3388                 size_t total = sizeof(*config) +
3389                                sizeof(struct lnet_ioctl_net_config);
3390                 config = arg;
3391
3392                 if (config->cfg_hdr.ioc_len < total)
3393                         return -EINVAL;
3394
3395                 mutex_lock(&the_lnet.ln_api_mutex);
3396                 rc = lnet_get_net_config(config);
3397                 mutex_unlock(&the_lnet.ln_api_mutex);
3398                 return rc;
3399         }
3400
3401         case IOC_LIBCFS_GET_LNET_STATS:
3402         {
3403                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3404
3405                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3406                         return -EINVAL;
3407
3408                 mutex_lock(&the_lnet.ln_api_mutex);
3409                 lnet_counters_get(&lnet_stats->st_cntrs);
3410                 mutex_unlock(&the_lnet.ln_api_mutex);
3411                 return 0;
3412         }
3413
3414         case IOC_LIBCFS_CONFIG_RTR:
3415                 config = arg;
3416
3417                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3418                         return -EINVAL;
3419
3420                 mutex_lock(&the_lnet.ln_api_mutex);
3421                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3422                         rc = lnet_rtrpools_enable();
3423                         mutex_unlock(&the_lnet.ln_api_mutex);
3424                         return rc;
3425                 }
3426                 lnet_rtrpools_disable();
3427                 mutex_unlock(&the_lnet.ln_api_mutex);
3428                 return 0;
3429
3430         case IOC_LIBCFS_ADD_BUF:
3431                 config = arg;
3432
3433                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3434                         return -EINVAL;
3435
3436                 mutex_lock(&the_lnet.ln_api_mutex);
3437                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3438                                                 buf_tiny,
3439                                           config->cfg_config_u.cfg_buffers.
3440                                                 buf_small,
3441                                           config->cfg_config_u.cfg_buffers.
3442                                                 buf_large);
3443                 mutex_unlock(&the_lnet.ln_api_mutex);
3444                 return rc;
3445
3446         case IOC_LIBCFS_SET_NUMA_RANGE: {
3447                 struct lnet_ioctl_set_value *numa;
3448                 numa = arg;
3449                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3450                         return -EINVAL;
3451                 lnet_net_lock(LNET_LOCK_EX);
3452                 lnet_numa_range = numa->sv_value;
3453                 lnet_net_unlock(LNET_LOCK_EX);
3454                 return 0;
3455         }
3456
3457         case IOC_LIBCFS_GET_NUMA_RANGE: {
3458                 struct lnet_ioctl_set_value *numa;
3459                 numa = arg;
3460                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3461                         return -EINVAL;
3462                 numa->sv_value = lnet_numa_range;
3463                 return 0;
3464         }
3465
3466         case IOC_LIBCFS_GET_BUF: {
3467                 struct lnet_ioctl_pool_cfg *pool_cfg;
3468                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3469
3470                 config = arg;
3471
3472                 if (config->cfg_hdr.ioc_len < total)
3473                         return -EINVAL;
3474
3475                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3476
3477                 mutex_lock(&the_lnet.ln_api_mutex);
3478                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3479                 mutex_unlock(&the_lnet.ln_api_mutex);
3480                 return rc;
3481         }
3482
3483         case IOC_LIBCFS_ADD_PEER_NI: {
3484                 struct lnet_ioctl_peer_cfg *cfg = arg;
3485
3486                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3487                         return -EINVAL;
3488
3489                 mutex_lock(&the_lnet.ln_api_mutex);
3490                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3491                                       cfg->prcfg_cfg_nid,
3492