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