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