Whamcloud - gitweb
d10ff58e1e5f3c717af2d7e5fbd11f746ae214bc
[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         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
1837
1838         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1839                 libcfs_nid2str(ni->ni_nid),
1840                 ni->ni_net->net_tunables.lct_peer_tx_credits,
1841                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
1842                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
1843                 ni->ni_net->net_tunables.lct_peer_timeout);
1844
1845         return 0;
1846 failed0:
1847         lnet_ni_free(ni);
1848         return rc;
1849 }
1850
1851 static int
1852 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
1853 {
1854         struct lnet_ni *ni;
1855         struct lnet_net *net_l = NULL;
1856         struct list_head        local_ni_list;
1857         int                     rc;
1858         int                     ni_count = 0;
1859         __u32                   lnd_type;
1860         struct lnet_lnd *lnd;
1861         int                     peer_timeout =
1862                 net->net_tunables.lct_peer_timeout;
1863         int                     maxtxcredits =
1864                 net->net_tunables.lct_max_tx_credits;
1865         int                     peerrtrcredits =
1866                 net->net_tunables.lct_peer_rtr_credits;
1867
1868         INIT_LIST_HEAD(&local_ni_list);
1869
1870         /*
1871          * make sure that this net is unique. If it isn't then
1872          * we are adding interfaces to an already existing network, and
1873          * 'net' is just a convenient way to pass in the list.
1874          * if it is unique we need to find the LND and load it if
1875          * necessary.
1876          */
1877         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
1878                 lnd_type = LNET_NETTYP(net->net_id);
1879
1880                 mutex_lock(&the_lnet.ln_lnd_mutex);
1881                 lnd = lnet_find_lnd_by_type(lnd_type);
1882
1883                 if (lnd == NULL) {
1884                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1885                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
1886                         mutex_lock(&the_lnet.ln_lnd_mutex);
1887
1888                         lnd = lnet_find_lnd_by_type(lnd_type);
1889                         if (lnd == NULL) {
1890                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1891                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1892                                 libcfs_lnd2str(lnd_type),
1893                                 libcfs_lnd2modname(lnd_type), rc);
1894 #ifndef HAVE_MODULE_LOADING_SUPPORT
1895                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1896                                                 "compiled with kernel module "
1897                                                 "loading support.");
1898 #endif
1899                                 rc = -EINVAL;
1900                                 goto failed0;
1901                         }
1902                 }
1903
1904                 lnet_net_lock(LNET_LOCK_EX);
1905                 lnd->lnd_refcount++;
1906                 lnet_net_unlock(LNET_LOCK_EX);
1907
1908                 net->net_lnd = lnd;
1909
1910                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1911
1912                 net_l = net;
1913         }
1914
1915         /*
1916          * net_l: if the network being added is unique then net_l
1917          *        will point to that network
1918          *        if the network being added is not unique then
1919          *        net_l points to the existing network.
1920          *
1921          * When we enter the loop below, we'll pick NIs off he
1922          * network beign added and start them up, then add them to
1923          * a local ni list. Once we've successfully started all
1924          * the NIs then we join the local NI list (of started up
1925          * networks) with the net_l->net_ni_list, which should
1926          * point to the correct network to add the new ni list to
1927          *
1928          * If any of the new NIs fail to start up, then we want to
1929          * iterate through the local ni list, which should include
1930          * any NIs which were successfully started up, and shut
1931          * them down.
1932          *
1933          * After than we want to delete the network being added,
1934          * to avoid a memory leak.
1935          */
1936
1937         /*
1938          * When a network uses TCP bonding then all its interfaces
1939          * must be specified when the network is first defined: the
1940          * TCP bonding code doesn't allow for interfaces to be added
1941          * or removed.
1942          */
1943         if (net_l != net && net_l != NULL && use_tcp_bonding &&
1944             LNET_NETTYP(net_l->net_id) == SOCKLND) {
1945                 rc = -EINVAL;
1946                 goto failed0;
1947         }
1948
1949         while (!list_empty(&net->net_ni_added)) {
1950                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
1951                                 ni_netlist);
1952                 list_del_init(&ni->ni_netlist);
1953
1954                 /* make sure that the the NI we're about to start
1955                  * up is actually unique. if it's not fail. */
1956                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
1957                                         ni->ni_interfaces[0])) {
1958                         rc = -EINVAL;
1959                         goto failed1;
1960                 }
1961
1962                 /* adjust the pointer the parent network, just in case it
1963                  * the net is a duplicate */
1964                 ni->ni_net = net_l;
1965
1966                 rc = lnet_startup_lndni(ni, tun);
1967
1968                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
1969                         ni->ni_net->net_lnd->lnd_query != NULL);
1970
1971                 if (rc < 0)
1972                         goto failed1;
1973
1974                 lnet_ni_addref(ni);
1975                 list_add_tail(&ni->ni_netlist, &local_ni_list);
1976
1977                 ni_count++;
1978         }
1979
1980         lnet_net_lock(LNET_LOCK_EX);
1981         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
1982         lnet_incr_dlc_seq();
1983         lnet_net_unlock(LNET_LOCK_EX);
1984
1985         /* if the network is not unique then we don't want to keep
1986          * it around after we're done. Free it. Otherwise add that
1987          * net to the global the_lnet.ln_nets */
1988         if (net_l != net && net_l != NULL) {
1989                 /*
1990                  * TODO - note. currently the tunables can not be updated
1991                  * once added
1992                  */
1993                 lnet_net_free(net);
1994         } else {
1995                 net->net_state = LNET_NET_STATE_ACTIVE;
1996                 /*
1997                  * restore tunables after it has been overwitten by the
1998                  * lnd
1999                  */
2000                 if (peer_timeout != -1)
2001                         net->net_tunables.lct_peer_timeout = peer_timeout;
2002                 if (maxtxcredits != -1)
2003                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2004                 if (peerrtrcredits != -1)
2005                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2006
2007                 lnet_net_lock(LNET_LOCK_EX);
2008                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2009                 lnet_net_unlock(LNET_LOCK_EX);
2010         }
2011
2012         return ni_count;
2013
2014 failed1:
2015         /*
2016          * shutdown the new NIs that are being started up
2017          * free the NET being started
2018          */
2019         while (!list_empty(&local_ni_list)) {
2020                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2021                                 ni_netlist);
2022
2023                 lnet_shutdown_lndni(ni);
2024         }
2025
2026 failed0:
2027         lnet_net_free(net);
2028
2029         return rc;
2030 }
2031
2032 static int
2033 lnet_startup_lndnets(struct list_head *netlist)
2034 {
2035         struct lnet_net         *net;
2036         int                     rc;
2037         int                     ni_count = 0;
2038
2039         /*
2040          * Change to running state before bringing up the LNDs. This
2041          * allows lnet_shutdown_lndnets() to assert that we've passed
2042          * through here.
2043          */
2044         lnet_net_lock(LNET_LOCK_EX);
2045         the_lnet.ln_state = LNET_STATE_RUNNING;
2046         lnet_net_unlock(LNET_LOCK_EX);
2047
2048         while (!list_empty(netlist)) {
2049                 net = list_entry(netlist->next, struct lnet_net, net_list);
2050                 list_del_init(&net->net_list);
2051
2052                 rc = lnet_startup_lndnet(net, NULL);
2053
2054                 if (rc < 0)
2055                         goto failed;
2056
2057                 ni_count += rc;
2058         }
2059
2060         return ni_count;
2061 failed:
2062         lnet_shutdown_lndnets();
2063
2064         return rc;
2065 }
2066
2067 /**
2068  * Initialize LNet library.
2069  *
2070  * Automatically called at module loading time. Caller has to call
2071  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2072  * latter returned 0. It must be called exactly once.
2073  *
2074  * \retval 0 on success
2075  * \retval -ve on failures.
2076  */
2077 int lnet_lib_init(void)
2078 {
2079         int rc;
2080
2081         lnet_assert_wire_constants();
2082
2083         /* refer to global cfs_cpt_table for now */
2084         the_lnet.ln_cpt_table   = cfs_cpt_table;
2085         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2086
2087         LASSERT(the_lnet.ln_cpt_number > 0);
2088         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2089                 /* we are under risk of consuming all lh_cookie */
2090                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2091                        "please change setting of CPT-table and retry\n",
2092                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2093                 return -E2BIG;
2094         }
2095
2096         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2097                 the_lnet.ln_cpt_bits++;
2098
2099         rc = lnet_create_locks();
2100         if (rc != 0) {
2101                 CERROR("Can't create LNet global locks: %d\n", rc);
2102                 return rc;
2103         }
2104
2105         the_lnet.ln_refcount = 0;
2106         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2107         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2108         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2109         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2110         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2111         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2112
2113         /* The hash table size is the number of bits it takes to express the set
2114          * ln_num_routes, minus 1 (better to under estimate than over so we
2115          * don't waste memory). */
2116         if (rnet_htable_size <= 0)
2117                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2118         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2119                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2120         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2121                                            order_base_2(rnet_htable_size) - 1);
2122
2123         /* All LNDs apart from the LOLND are in separate modules.  They
2124          * register themselves when their module loads, and unregister
2125          * themselves when their module is unloaded. */
2126         lnet_register_lnd(&the_lolnd);
2127         return 0;
2128 }
2129
2130 /**
2131  * Finalize LNet library.
2132  *
2133  * \pre lnet_lib_init() called with success.
2134  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2135  */
2136 void lnet_lib_exit(void)
2137 {
2138         LASSERT(the_lnet.ln_refcount == 0);
2139
2140         while (!list_empty(&the_lnet.ln_lnds))
2141                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2142                                                struct lnet_lnd, lnd_list));
2143         lnet_destroy_locks();
2144 }
2145
2146 /**
2147  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2148  *
2149  * Users must call this function at least once before any other functions.
2150  * For each successful call there must be a corresponding call to
2151  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2152  * ignored.
2153  *
2154  * The PID used by LNet may be different from the one requested.
2155  * See LNetGetId().
2156  *
2157  * \param requested_pid PID requested by the caller.
2158  *
2159  * \return >= 0 on success, and < 0 error code on failures.
2160  */
2161 int
2162 LNetNIInit(lnet_pid_t requested_pid)
2163 {
2164         int                     im_a_router = 0;
2165         int                     rc;
2166         int                     ni_count;
2167         struct lnet_ping_buffer *pbuf;
2168         struct lnet_handle_md   ping_mdh;
2169         struct list_head        net_head;
2170         struct lnet_net         *net;
2171
2172         INIT_LIST_HEAD(&net_head);
2173
2174         mutex_lock(&the_lnet.ln_api_mutex);
2175
2176         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2177
2178         if (the_lnet.ln_refcount > 0) {
2179                 rc = the_lnet.ln_refcount++;
2180                 mutex_unlock(&the_lnet.ln_api_mutex);
2181                 return rc;
2182         }
2183
2184         rc = lnet_prepare(requested_pid);
2185         if (rc != 0) {
2186                 mutex_unlock(&the_lnet.ln_api_mutex);
2187                 return rc;
2188         }
2189
2190         /* create a network for Loopback network */
2191         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2192         if (net == NULL) {
2193                 rc = -ENOMEM;
2194                 goto err_empty_list;
2195         }
2196
2197         /* Add in the loopback NI */
2198         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2199                 rc = -ENOMEM;
2200                 goto err_empty_list;
2201         }
2202
2203         /* If LNet is being initialized via DLC it is possible
2204          * that the user requests not to load module parameters (ones which
2205          * are supported by DLC) on initialization.  Therefore, make sure not
2206          * to load networks, routes and forwarding from module parameters
2207          * in this case.  On cleanup in case of failure only clean up
2208          * routes if it has been loaded */
2209         if (!the_lnet.ln_nis_from_mod_params) {
2210                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2211                                          use_tcp_bonding);
2212                 if (rc < 0)
2213                         goto err_empty_list;
2214         }
2215
2216         ni_count = lnet_startup_lndnets(&net_head);
2217         if (ni_count < 0) {
2218                 rc = ni_count;
2219                 goto err_empty_list;
2220         }
2221
2222         if (!the_lnet.ln_nis_from_mod_params) {
2223                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2224                 if (rc != 0)
2225                         goto err_shutdown_lndnis;
2226
2227                 rc = lnet_check_routes();
2228                 if (rc != 0)
2229                         goto err_destroy_routes;
2230
2231                 rc = lnet_rtrpools_alloc(im_a_router);
2232                 if (rc != 0)
2233                         goto err_destroy_routes;
2234         }
2235
2236         rc = lnet_acceptor_start();
2237         if (rc != 0)
2238                 goto err_destroy_routes;
2239
2240         the_lnet.ln_refcount = 1;
2241         /* Now I may use my own API functions... */
2242
2243         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2244         if (rc != 0)
2245                 goto err_acceptor_stop;
2246
2247         lnet_ping_target_update(pbuf, ping_mdh);
2248
2249         rc = lnet_router_checker_start();
2250         if (rc != 0)
2251                 goto err_stop_ping;
2252
2253         rc = lnet_push_target_init();
2254         if (rc != 0)
2255                 goto err_stop_router_checker;
2256
2257         rc = lnet_peer_discovery_start();
2258         if (rc != 0)
2259                 goto err_destroy_push_target;
2260
2261         lnet_fault_init();
2262         lnet_router_debugfs_init();
2263
2264         mutex_unlock(&the_lnet.ln_api_mutex);
2265
2266         return 0;
2267
2268 err_destroy_push_target:
2269         lnet_push_target_fini();
2270 err_stop_router_checker:
2271         lnet_router_checker_stop();
2272 err_stop_ping:
2273         lnet_ping_target_fini();
2274 err_acceptor_stop:
2275         the_lnet.ln_refcount = 0;
2276         lnet_acceptor_stop();
2277 err_destroy_routes:
2278         if (!the_lnet.ln_nis_from_mod_params)
2279                 lnet_destroy_routes();
2280 err_shutdown_lndnis:
2281         lnet_shutdown_lndnets();
2282 err_empty_list:
2283         lnet_unprepare();
2284         LASSERT(rc < 0);
2285         mutex_unlock(&the_lnet.ln_api_mutex);
2286         while (!list_empty(&net_head)) {
2287                 struct lnet_net *net;
2288
2289                 net = list_entry(net_head.next, struct lnet_net, net_list);
2290                 list_del_init(&net->net_list);
2291                 lnet_net_free(net);
2292         }
2293         return rc;
2294 }
2295 EXPORT_SYMBOL(LNetNIInit);
2296
2297 /**
2298  * Stop LNet interfaces, routing, and forwarding.
2299  *
2300  * Users must call this function once for each successful call to LNetNIInit().
2301  * Once the LNetNIFini() operation has been started, the results of pending
2302  * API operations are undefined.
2303  *
2304  * \return always 0 for current implementation.
2305  */
2306 int
2307 LNetNIFini()
2308 {
2309         mutex_lock(&the_lnet.ln_api_mutex);
2310
2311         LASSERT(the_lnet.ln_refcount > 0);
2312
2313         if (the_lnet.ln_refcount != 1) {
2314                 the_lnet.ln_refcount--;
2315         } else {
2316                 LASSERT(!the_lnet.ln_niinit_self);
2317
2318                 lnet_fault_fini();
2319
2320                 lnet_router_debugfs_init();
2321                 lnet_peer_discovery_stop();
2322                 lnet_push_target_fini();
2323                 lnet_router_checker_stop();
2324                 lnet_ping_target_fini();
2325
2326                 /* Teardown fns that use my own API functions BEFORE here */
2327                 the_lnet.ln_refcount = 0;
2328
2329                 lnet_acceptor_stop();
2330                 lnet_destroy_routes();
2331                 lnet_shutdown_lndnets();
2332                 lnet_unprepare();
2333         }
2334
2335         mutex_unlock(&the_lnet.ln_api_mutex);
2336         return 0;
2337 }
2338 EXPORT_SYMBOL(LNetNIFini);
2339
2340 /**
2341  * Grabs the ni data from the ni structure and fills the out
2342  * parameters
2343  *
2344  * \param[in] ni network        interface structure
2345  * \param[out] cfg_ni           NI config information
2346  * \param[out] tun              network and LND tunables
2347  */
2348 static void
2349 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2350                    struct lnet_ioctl_config_lnd_tunables *tun,
2351                    struct lnet_ioctl_element_stats *stats,
2352                    __u32 tun_size)
2353 {
2354         size_t min_size = 0;
2355         int i;
2356
2357         if (!ni || !cfg_ni || !tun)
2358                 return;
2359
2360         if (ni->ni_interfaces[0] != NULL) {
2361                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2362                         if (ni->ni_interfaces[i] != NULL) {
2363                                 strncpy(cfg_ni->lic_ni_intf[i],
2364                                         ni->ni_interfaces[i],
2365                                         sizeof(cfg_ni->lic_ni_intf[i]));
2366                         }
2367                 }
2368         }
2369
2370         cfg_ni->lic_nid = ni->ni_nid;
2371         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2372                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2373         else
2374                 cfg_ni->lic_status = ni->ni_status->ns_status;
2375         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2376         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2377
2378         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2379
2380         if (stats) {
2381                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2382                                                        LNET_STATS_TYPE_SEND);
2383                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2384                                                        LNET_STATS_TYPE_RECV);
2385                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2386                                                        LNET_STATS_TYPE_DROP);
2387         }
2388
2389         /*
2390          * tun->lt_tun will always be present, but in order to be
2391          * backwards compatible, we need to deal with the cases when
2392          * tun->lt_tun is smaller than what the kernel has, because it
2393          * comes from an older version of a userspace program, then we'll
2394          * need to copy as much information as we have available space.
2395          */
2396         min_size = tun_size - sizeof(tun->lt_cmn);
2397         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2398
2399         /* copy over the cpts */
2400         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2401             ni->ni_cpts == NULL)  {
2402                 for (i = 0; i < ni->ni_ncpts; i++)
2403                         cfg_ni->lic_cpts[i] = i;
2404         } else {
2405                 for (i = 0;
2406                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2407                      i < LNET_MAX_SHOW_NUM_CPT;
2408                      i++)
2409                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2410         }
2411         cfg_ni->lic_ncpts = ni->ni_ncpts;
2412 }
2413
2414 /**
2415  * NOTE: This is a legacy function left in the code to be backwards
2416  * compatible with older userspace programs. It should eventually be
2417  * removed.
2418  *
2419  * Grabs the ni data from the ni structure and fills the out
2420  * parameters
2421  *
2422  * \param[in] ni network        interface structure
2423  * \param[out] config           config information
2424  */
2425 static void
2426 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2427                          struct lnet_ioctl_config_data *config)
2428 {
2429         struct lnet_ioctl_net_config *net_config;
2430         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2431         size_t min_size, tunable_size = 0;
2432         int i;
2433
2434         if (!ni || !config)
2435                 return;
2436
2437         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2438         if (!net_config)
2439                 return;
2440
2441         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2442                      ARRAY_SIZE(net_config->ni_interfaces));
2443
2444         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2445                 if (!ni->ni_interfaces[i])
2446                         break;
2447
2448                 strncpy(net_config->ni_interfaces[i],
2449                         ni->ni_interfaces[i],
2450                         sizeof(net_config->ni_interfaces[i]));
2451         }
2452
2453         config->cfg_nid = ni->ni_nid;
2454         config->cfg_config_u.cfg_net.net_peer_timeout =
2455                 ni->ni_net->net_tunables.lct_peer_timeout;
2456         config->cfg_config_u.cfg_net.net_max_tx_credits =
2457                 ni->ni_net->net_tunables.lct_max_tx_credits;
2458         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2459                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2460         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2461                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2462
2463         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2464                 net_config->ni_status = LNET_NI_STATUS_UP;
2465         else
2466                 net_config->ni_status = ni->ni_status->ns_status;
2467
2468         if (ni->ni_cpts) {
2469                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2470
2471                 for (i = 0; i < num_cpts; i++)
2472                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2473
2474                 config->cfg_ncpts = num_cpts;
2475         }
2476
2477         /*
2478          * See if user land tools sent in a newer and larger version
2479          * of struct lnet_tunables than what the kernel uses.
2480          */
2481         min_size = sizeof(*config) + sizeof(*net_config);
2482
2483         if (config->cfg_hdr.ioc_len > min_size)
2484                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2485
2486         /* Don't copy too much data to user space */
2487         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2488         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2489
2490         if (lnd_cfg && min_size) {
2491                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2492                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2493
2494                 /* Tell user land that kernel side has less data */
2495                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2496                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2497                         config->cfg_hdr.ioc_len -= min_size;
2498                 }
2499         }
2500 }
2501
2502 struct lnet_ni *
2503 lnet_get_ni_idx_locked(int idx)
2504 {
2505         struct lnet_ni          *ni;
2506         struct lnet_net         *net;
2507
2508         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2509                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2510                         if (idx-- == 0)
2511                                 return ni;
2512                 }
2513         }
2514
2515         return NULL;
2516 }
2517
2518 struct lnet_ni *
2519 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2520 {
2521         struct lnet_ni          *ni;
2522         struct lnet_net         *net = mynet;
2523
2524         if (prev == NULL) {
2525                 if (net == NULL)
2526                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2527                                         net_list);
2528                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2529                                 ni_netlist);
2530
2531                 return ni;
2532         }
2533
2534         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2535                 /* if you reached the end of the ni list and the net is
2536                  * specified, then there are no more nis in that net */
2537                 if (net != NULL)
2538                         return NULL;
2539
2540                 /* we reached the end of this net ni list. move to the
2541                  * next net */
2542                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2543                         /* no more nets and no more NIs. */
2544                         return NULL;
2545
2546                 /* get the next net */
2547                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2548                                  net_list);
2549                 /* get the ni on it */
2550                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2551                                 ni_netlist);
2552
2553                 return ni;
2554         }
2555
2556         /* there are more nis left */
2557         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2558
2559         return ni;
2560 }
2561
2562 int
2563 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2564 {
2565         struct lnet_ni *ni;
2566         int cpt;
2567         int rc = -ENOENT;
2568         int idx = config->cfg_count;
2569
2570         cpt = lnet_net_lock_current();
2571
2572         ni = lnet_get_ni_idx_locked(idx);
2573
2574         if (ni != NULL) {
2575                 rc = 0;
2576                 lnet_ni_lock(ni);
2577                 lnet_fill_ni_info_legacy(ni, config);
2578                 lnet_ni_unlock(ni);
2579         }
2580
2581         lnet_net_unlock(cpt);
2582         return rc;
2583 }
2584
2585 int
2586 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2587                    struct lnet_ioctl_config_lnd_tunables *tun,
2588                    struct lnet_ioctl_element_stats *stats,
2589                    __u32 tun_size)
2590 {
2591         struct lnet_ni          *ni;
2592         int                     cpt;
2593         int                     rc = -ENOENT;
2594
2595         if (!cfg_ni || !tun || !stats)
2596                 return -EINVAL;
2597
2598         cpt = lnet_net_lock_current();
2599
2600         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2601
2602         if (ni) {
2603                 rc = 0;
2604                 lnet_ni_lock(ni);
2605                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2606                 lnet_ni_unlock(ni);
2607         }
2608
2609         lnet_net_unlock(cpt);
2610         return rc;
2611 }
2612
2613 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2614 {
2615         struct lnet_ni *ni;
2616         int cpt;
2617         int rc = -ENOENT;
2618
2619         if (!msg_stats)
2620                 return -EINVAL;
2621
2622         cpt = lnet_net_lock_current();
2623
2624         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2625
2626         if (ni) {
2627                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2628                 rc = 0;
2629         }
2630
2631         lnet_net_unlock(cpt);
2632
2633         return rc;
2634 }
2635
2636 static int lnet_add_net_common(struct lnet_net *net,
2637                                struct lnet_ioctl_config_lnd_tunables *tun)
2638 {
2639         __u32                   net_id;
2640         struct lnet_ping_buffer *pbuf;
2641         struct lnet_handle_md   ping_mdh;
2642         int                     rc;
2643         struct lnet_remotenet *rnet;
2644         int                     net_ni_count;
2645         int                     num_acceptor_nets;
2646
2647         lnet_net_lock(LNET_LOCK_EX);
2648         rnet = lnet_find_rnet_locked(net->net_id);
2649         lnet_net_unlock(LNET_LOCK_EX);
2650         /*
2651          * make sure that the net added doesn't invalidate the current
2652          * configuration LNet is keeping
2653          */
2654         if (rnet) {
2655                 CERROR("Adding net %s will invalidate routing configuration\n",
2656                        libcfs_net2str(net->net_id));
2657                 lnet_net_free(net);
2658                 return -EUSERS;
2659         }
2660
2661         /*
2662          * make sure you calculate the correct number of slots in the ping
2663          * buffer. Since the ping info is a flattened list of all the NIs,
2664          * we should allocate enough slots to accomodate the number of NIs
2665          * which will be added.
2666          *
2667          * since ni hasn't been configured yet, use
2668          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
2669          */
2670         net_ni_count = lnet_get_net_ni_count_pre(net);
2671
2672         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2673                                     net_ni_count + lnet_get_ni_count(),
2674                                     false);
2675         if (rc < 0) {
2676                 lnet_net_free(net);
2677                 return rc;
2678         }
2679
2680         if (tun)
2681                 memcpy(&net->net_tunables,
2682                        &tun->lt_cmn, sizeof(net->net_tunables));
2683         else
2684                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
2685
2686         /*
2687          * before starting this network get a count of the current TCP
2688          * networks which require the acceptor thread running. If that
2689          * count is == 0 before we start up this network, then we'd want to
2690          * start up the acceptor thread after starting up this network
2691          */
2692         num_acceptor_nets = lnet_count_acceptor_nets();
2693
2694         net_id = net->net_id;
2695
2696         rc = lnet_startup_lndnet(net,
2697                                  (tun) ? &tun->lt_tun : NULL);
2698         if (rc < 0)
2699                 goto failed;
2700
2701         lnet_net_lock(LNET_LOCK_EX);
2702         net = lnet_get_net_locked(net_id);
2703         lnet_net_unlock(LNET_LOCK_EX);
2704
2705         LASSERT(net);
2706
2707         /*
2708          * Start the acceptor thread if this is the first network
2709          * being added that requires the thread.
2710          */
2711         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
2712                 rc = lnet_acceptor_start();
2713                 if (rc < 0) {
2714                         /* shutdown the net that we just started */
2715                         CERROR("Failed to start up acceptor thread\n");
2716                         lnet_shutdown_lndnet(net);
2717                         goto failed;
2718                 }
2719         }
2720
2721         lnet_net_lock(LNET_LOCK_EX);
2722         lnet_peer_net_added(net);
2723         lnet_net_unlock(LNET_LOCK_EX);
2724
2725         lnet_ping_target_update(pbuf, ping_mdh);
2726
2727         return 0;
2728
2729 failed:
2730         lnet_ping_md_unlink(pbuf, &ping_mdh);
2731         lnet_ping_buffer_decref(pbuf);
2732         return rc;
2733 }
2734
2735 static int lnet_handle_legacy_ip2nets(char *ip2nets,
2736                                       struct lnet_ioctl_config_lnd_tunables *tun)
2737 {
2738         struct lnet_net *net;
2739         char *nets;
2740         int rc;
2741         struct list_head net_head;
2742
2743         INIT_LIST_HEAD(&net_head);
2744
2745         rc = lnet_parse_ip2nets(&nets, ip2nets);
2746         if (rc < 0)
2747                 return rc;
2748
2749         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2750         if (rc < 0)
2751                 return rc;
2752
2753         mutex_lock(&the_lnet.ln_api_mutex);
2754         while (!list_empty(&net_head)) {
2755                 net = list_entry(net_head.next, struct lnet_net, net_list);
2756                 list_del_init(&net->net_list);
2757                 rc = lnet_add_net_common(net, tun);
2758                 if (rc < 0)
2759                         goto out;
2760         }
2761
2762 out:
2763         mutex_unlock(&the_lnet.ln_api_mutex);
2764
2765         while (!list_empty(&net_head)) {
2766                 net = list_entry(net_head.next, struct lnet_net, net_list);
2767                 list_del_init(&net->net_list);
2768                 lnet_net_free(net);
2769         }
2770         return rc;
2771 }
2772
2773 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
2774 {
2775         struct lnet_net *net;
2776         struct lnet_ni *ni;
2777         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
2778         int rc, i;
2779         __u32 net_id, lnd_type;
2780
2781         /* get the tunables if they are available */
2782         if (conf->lic_cfg_hdr.ioc_len >=
2783             sizeof(*conf) + sizeof(*tun))
2784                 tun = (struct lnet_ioctl_config_lnd_tunables *)
2785                         conf->lic_bulk;
2786
2787         /* handle legacy ip2nets from DLC */
2788         if (conf->lic_legacy_ip2nets[0] != '\0')
2789                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
2790                                                   tun);
2791
2792         net_id = LNET_NIDNET(conf->lic_nid);
2793         lnd_type = LNET_NETTYP(net_id);
2794
2795         if (!libcfs_isknown_lnd(lnd_type)) {
2796                 CERROR("No valid net and lnd information provided\n");
2797                 return -EINVAL;
2798         }
2799
2800         net = lnet_net_alloc(net_id, NULL);
2801         if (!net)
2802                 return -ENOMEM;
2803
2804         for (i = 0; i < conf->lic_ncpts; i++) {
2805                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
2806                         return -EINVAL;
2807         }
2808
2809         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
2810                                        conf->lic_ni_intf[0]);
2811         if (!ni)
2812                 return -ENOMEM;
2813
2814         mutex_lock(&the_lnet.ln_api_mutex);
2815
2816         rc = lnet_add_net_common(net, tun);
2817
2818         mutex_unlock(&the_lnet.ln_api_mutex);
2819
2820         return rc;
2821 }
2822
2823 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
2824 {
2825         struct lnet_net  *net;
2826         struct lnet_ni *ni;
2827         __u32 net_id = LNET_NIDNET(conf->lic_nid);
2828         struct lnet_ping_buffer *pbuf;
2829         struct lnet_handle_md  ping_mdh;
2830         int               rc;
2831         int               net_count;
2832         __u32             addr;
2833
2834         /* don't allow userspace to shutdown the LOLND */
2835         if (LNET_NETTYP(net_id) == LOLND)
2836                 return -EINVAL;
2837
2838         mutex_lock(&the_lnet.ln_api_mutex);
2839
2840         lnet_net_lock(0);
2841
2842         net = lnet_get_net_locked(net_id);
2843         if (!net) {
2844                 CERROR("net %s not found\n",
2845                        libcfs_net2str(net_id));
2846                 rc = -ENOENT;
2847                 goto unlock_net;
2848         }
2849
2850         addr = LNET_NIDADDR(conf->lic_nid);
2851         if (addr == 0) {
2852                 /* remove the entire net */
2853                 net_count = lnet_get_net_ni_count_locked(net);
2854
2855                 lnet_net_unlock(0);
2856
2857                 /* create and link a new ping info, before removing the old one */
2858                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2859                                         lnet_get_ni_count() - net_count,
2860                                         false);
2861                 if (rc != 0)
2862                         goto unlock_api_mutex;
2863
2864                 lnet_shutdown_lndnet(net);
2865
2866                 if (lnet_count_acceptor_nets() == 0)
2867                         lnet_acceptor_stop();
2868
2869                 lnet_ping_target_update(pbuf, ping_mdh);
2870
2871                 goto unlock_api_mutex;
2872         }
2873
2874         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
2875         if (!ni) {
2876                 CERROR("nid %s not found\n",
2877                        libcfs_nid2str(conf->lic_nid));
2878                 rc = -ENOENT;
2879                 goto unlock_net;
2880         }
2881
2882         net_count = lnet_get_net_ni_count_locked(net);
2883
2884         lnet_net_unlock(0);
2885
2886         /* create and link a new ping info, before removing the old one */
2887         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2888                                   lnet_get_ni_count() - 1, false);
2889         if (rc != 0)
2890                 goto unlock_api_mutex;
2891
2892         lnet_shutdown_lndni(ni);
2893
2894         if (lnet_count_acceptor_nets() == 0)
2895                 lnet_acceptor_stop();
2896
2897         lnet_ping_target_update(pbuf, ping_mdh);
2898
2899         /* check if the net is empty and remove it if it is */
2900         if (net_count == 1)
2901                 lnet_shutdown_lndnet(net);
2902
2903         goto unlock_api_mutex;
2904
2905 unlock_net:
2906         lnet_net_unlock(0);
2907 unlock_api_mutex:
2908         mutex_unlock(&the_lnet.ln_api_mutex);
2909
2910         return rc;
2911 }
2912
2913 /*
2914  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
2915  * They are only expected to be called for unique networks.
2916  * That can be as a result of older DLC library
2917  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
2918  */
2919 int
2920 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
2921 {
2922         struct lnet_net         *net;
2923         struct list_head        net_head;
2924         int                     rc;
2925         struct lnet_ioctl_config_lnd_tunables tun;
2926         char *nets = conf->cfg_config_u.cfg_net.net_intf;
2927
2928         INIT_LIST_HEAD(&net_head);
2929
2930         /* Create a net/ni structures for the network string */
2931         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
2932         if (rc <= 0)
2933                 return rc == 0 ? -EINVAL : rc;
2934
2935         mutex_lock(&the_lnet.ln_api_mutex);
2936
2937         if (rc > 1) {
2938                 rc = -EINVAL; /* only add one network per call */
2939                 goto out_unlock_clean;
2940         }
2941
2942         net = list_entry(net_head.next, struct lnet_net, net_list);
2943         list_del_init(&net->net_list);
2944
2945         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
2946
2947         memset(&tun, 0, sizeof(tun));
2948
2949         tun.lt_cmn.lct_peer_timeout =
2950           conf->cfg_config_u.cfg_net.net_peer_timeout;
2951         tun.lt_cmn.lct_peer_tx_credits =
2952           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
2953         tun.lt_cmn.lct_peer_rtr_credits =
2954           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
2955         tun.lt_cmn.lct_max_tx_credits =
2956           conf->cfg_config_u.cfg_net.net_max_tx_credits;
2957
2958         rc = lnet_add_net_common(net, &tun);
2959
2960 out_unlock_clean:
2961         mutex_unlock(&the_lnet.ln_api_mutex);
2962         while (!list_empty(&net_head)) {
2963                 /* net_head list is empty in success case */
2964                 net = list_entry(net_head.next, struct lnet_net, net_list);
2965                 list_del_init(&net->net_list);
2966                 lnet_net_free(net);
2967         }
2968         return rc;
2969 }
2970
2971 int
2972 lnet_dyn_del_net(__u32 net_id)
2973 {
2974         struct lnet_net  *net;
2975         struct lnet_ping_buffer *pbuf;
2976         struct lnet_handle_md ping_mdh;
2977         int               rc;
2978         int               net_ni_count;
2979
2980         /* don't allow userspace to shutdown the LOLND */
2981         if (LNET_NETTYP(net_id) == LOLND)
2982                 return -EINVAL;
2983
2984         mutex_lock(&the_lnet.ln_api_mutex);
2985
2986         lnet_net_lock(0);
2987
2988         net = lnet_get_net_locked(net_id);
2989         if (net == NULL) {
2990                 lnet_net_unlock(0);
2991                 rc = -EINVAL;
2992                 goto out;
2993         }
2994
2995         net_ni_count = lnet_get_net_ni_count_locked(net);
2996
2997         lnet_net_unlock(0);
2998
2999         /* create and link a new ping info, before removing the old one */
3000         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3001                                     lnet_get_ni_count() - net_ni_count, false);
3002         if (rc != 0)
3003                 goto out;
3004
3005         lnet_shutdown_lndnet(net);
3006
3007         if (lnet_count_acceptor_nets() == 0)
3008                 lnet_acceptor_stop();
3009
3010         lnet_ping_target_update(pbuf, ping_mdh);
3011
3012 out:
3013         mutex_unlock(&the_lnet.ln_api_mutex);
3014
3015         return rc;
3016 }
3017
3018 void lnet_incr_dlc_seq(void)
3019 {
3020         atomic_inc(&lnet_dlc_seq_no);
3021 }
3022
3023 __u32 lnet_get_dlc_seq_locked(void)
3024 {
3025         return atomic_read(&lnet_dlc_seq_no);
3026 }
3027
3028 /**
3029  * LNet ioctl handler.
3030  *
3031  */
3032 int
3033 LNetCtl(unsigned int cmd, void *arg)
3034 {
3035         struct libcfs_ioctl_data *data = arg;
3036         struct lnet_ioctl_config_data *config;
3037         struct lnet_process_id    id = {0};
3038         struct lnet_ni           *ni;
3039         int                       rc;
3040
3041         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3042                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3043
3044         switch (cmd) {
3045         case IOC_LIBCFS_GET_NI:
3046                 rc = LNetGetId(data->ioc_count, &id);
3047                 data->ioc_nid = id.nid;
3048                 return rc;
3049
3050         case IOC_LIBCFS_FAIL_NID:
3051                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3052
3053         case IOC_LIBCFS_ADD_ROUTE:
3054                 config = arg;
3055
3056                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3057                         return -EINVAL;
3058
3059                 mutex_lock(&the_lnet.ln_api_mutex);
3060                 rc = lnet_add_route(config->cfg_net,
3061                                     config->cfg_config_u.cfg_route.rtr_hop,
3062                                     config->cfg_nid,
3063                                     config->cfg_config_u.cfg_route.
3064                                         rtr_priority);
3065                 if (rc == 0) {
3066                         rc = lnet_check_routes();
3067                         if (rc != 0)
3068                                 lnet_del_route(config->cfg_net,
3069                                                config->cfg_nid);
3070                 }
3071                 mutex_unlock(&the_lnet.ln_api_mutex);
3072                 return rc;
3073
3074         case IOC_LIBCFS_DEL_ROUTE:
3075                 config = arg;
3076
3077                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3078                         return -EINVAL;
3079
3080                 mutex_lock(&the_lnet.ln_api_mutex);
3081                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3082                 mutex_unlock(&the_lnet.ln_api_mutex);
3083                 return rc;
3084
3085         case IOC_LIBCFS_GET_ROUTE:
3086                 config = arg;
3087
3088                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3089                         return -EINVAL;
3090
3091                 mutex_lock(&the_lnet.ln_api_mutex);
3092                 rc = lnet_get_route(config->cfg_count,
3093                                     &config->cfg_net,
3094                                     &config->cfg_config_u.cfg_route.rtr_hop,
3095                                     &config->cfg_nid,
3096                                     &config->cfg_config_u.cfg_route.rtr_flags,
3097                                     &config->cfg_config_u.cfg_route.
3098                                         rtr_priority);
3099                 mutex_unlock(&the_lnet.ln_api_mutex);
3100                 return rc;
3101
3102         case IOC_LIBCFS_GET_LOCAL_NI: {
3103                 struct lnet_ioctl_config_ni *cfg_ni;
3104                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3105                 struct lnet_ioctl_element_stats *stats;
3106                 __u32 tun_size;
3107
3108                 cfg_ni = arg;
3109
3110                 /* get the tunables if they are available */
3111                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3112                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3113                         return -EINVAL;
3114
3115                 stats = (struct lnet_ioctl_element_stats *)
3116                         cfg_ni->lic_bulk;
3117                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3118                                 (cfg_ni->lic_bulk + sizeof(*stats));
3119
3120                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3121                         sizeof(*stats);
3122
3123                 mutex_lock(&the_lnet.ln_api_mutex);
3124                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3125                 mutex_unlock(&the_lnet.ln_api_mutex);
3126                 return rc;
3127         }
3128
3129         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3130                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3131
3132                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3133                         return -EINVAL;
3134
3135                 mutex_lock(&the_lnet.ln_api_mutex);
3136                 rc = lnet_get_ni_stats(msg_stats);
3137                 mutex_unlock(&the_lnet.ln_api_mutex);
3138
3139                 return rc;
3140         }
3141
3142         case IOC_LIBCFS_GET_NET: {
3143                 size_t total = sizeof(*config) +
3144                                sizeof(struct lnet_ioctl_net_config);
3145                 config = arg;
3146
3147                 if (config->cfg_hdr.ioc_len < total)
3148                         return -EINVAL;
3149
3150                 mutex_lock(&the_lnet.ln_api_mutex);
3151                 rc = lnet_get_net_config(config);
3152                 mutex_unlock(&the_lnet.ln_api_mutex);
3153                 return rc;
3154         }
3155
3156         case IOC_LIBCFS_GET_LNET_STATS:
3157         {
3158                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3159
3160                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3161                         return -EINVAL;
3162
3163                 mutex_lock(&the_lnet.ln_api_mutex);
3164                 lnet_counters_get(&lnet_stats->st_cntrs);
3165                 mutex_unlock(&the_lnet.ln_api_mutex);
3166                 return 0;
3167         }
3168
3169         case IOC_LIBCFS_CONFIG_RTR:
3170                 config = arg;
3171
3172                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3173                         return -EINVAL;
3174
3175                 mutex_lock(&the_lnet.ln_api_mutex);
3176                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3177                         rc = lnet_rtrpools_enable();
3178                         mutex_unlock(&the_lnet.ln_api_mutex);
3179                         return rc;
3180                 }
3181                 lnet_rtrpools_disable();
3182                 mutex_unlock(&the_lnet.ln_api_mutex);
3183                 return 0;
3184
3185         case IOC_LIBCFS_ADD_BUF:
3186                 config = arg;
3187
3188                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3189                         return -EINVAL;
3190
3191                 mutex_lock(&the_lnet.ln_api_mutex);
3192                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3193                                                 buf_tiny,
3194                                           config->cfg_config_u.cfg_buffers.
3195                                                 buf_small,
3196                                           config->cfg_config_u.cfg_buffers.
3197                                                 buf_large);
3198                 mutex_unlock(&the_lnet.ln_api_mutex);
3199                 return rc;
3200
3201         case IOC_LIBCFS_SET_NUMA_RANGE: {
3202                 struct lnet_ioctl_set_value *numa;
3203                 numa = arg;
3204                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3205                         return -EINVAL;
3206                 lnet_net_lock(LNET_LOCK_EX);
3207                 lnet_numa_range = numa->sv_value;
3208                 lnet_net_unlock(LNET_LOCK_EX);
3209                 return 0;
3210         }
3211
3212         case IOC_LIBCFS_GET_NUMA_RANGE: {
3213                 struct lnet_ioctl_set_value *numa;
3214                 numa = arg;
3215                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3216                         return -EINVAL;
3217                 numa->sv_value = lnet_numa_range;
3218                 return 0;
3219         }
3220
3221         case IOC_LIBCFS_GET_BUF: {
3222                 struct lnet_ioctl_pool_cfg *pool_cfg;
3223                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3224
3225                 config = arg;
3226
3227                 if (config->cfg_hdr.ioc_len < total)
3228                         return -EINVAL;
3229
3230                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3231
3232                 mutex_lock(&the_lnet.ln_api_mutex);
3233                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3234                 mutex_unlock(&the_lnet.ln_api_mutex);
3235                 return rc;
3236         }
3237
3238         case IOC_LIBCFS_ADD_PEER_NI: {
3239                 struct lnet_ioctl_peer_cfg *cfg = arg;
3240
3241                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3242                         return -EINVAL;
3243
3244                 mutex_lock(&the_lnet.ln_api_mutex);
3245                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3246                                       cfg->prcfg_cfg_nid,
3247                                       cfg->prcfg_mr);
3248                 mutex_unlock(&the_lnet.ln_api_mutex);
3249                 return rc;
3250         }
3251
3252         case IOC_LIBCFS_DEL_PEER_NI: {
3253                 struct lnet_ioctl_peer_cfg *cfg = arg;
3254
3255                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3256                         return -EINVAL;
3257
3258                 mutex_lock(&the_lnet.ln_api_mutex);
3259                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3260                                       cfg->prcfg_cfg_nid);
3261                 mutex_unlock(&the_lnet.ln_api_mutex);
3262                 return rc;
3263         }
3264
3265         case IOC_LIBCFS_GET_PEER_INFO: {
3266                 struct lnet_ioctl_peer *peer_info = arg;
3267
3268                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3269                         return -EINVAL;
3270
3271                 mutex_lock(&the_lnet.ln_api_mutex);
3272                 rc = lnet_get_peer_ni_info(
3273                    peer_info->pr_count,
3274                    &peer_info->pr_nid,
3275                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3276                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3277                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3278                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3279                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3280                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3281                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3282                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3283                 mutex_unlock(&the_lnet.ln_api_mutex);
3284                 return rc;
3285         }
3286
3287         case IOC_LIBCFS_GET_PEER_NI: {
3288                 struct lnet_ioctl_peer_cfg *cfg = arg;
3289
3290                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3291                         return -EINVAL;
3292
3293                 mutex_lock(&the_lnet.ln_api_mutex);
3294                 rc = lnet_get_peer_info(cfg,
3295                                         (void __user *)cfg->prcfg_bulk);
3296                 mutex_unlock(&the_lnet.ln_api_mutex);
3297                 return rc;
3298         }
3299
3300         case IOC_LIBCFS_GET_PEER_LIST: {
3301                 struct lnet_ioctl_peer_cfg *cfg = arg;
3302
3303                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3304                         return -EINVAL;
3305
3306                 mutex_lock(&the_lnet.ln_api_mutex);
3307                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3308                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3309                 mutex_unlock(&the_lnet.ln_api_mutex);
3310                 return rc;
3311         }
3312
3313         case IOC_LIBCFS_NOTIFY_ROUTER: {
3314                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3315
3316                 /* The deadline passed in by the user should be some time in
3317                  * seconds in the future since the UNIX epoch. We have to map
3318                  * that deadline to the wall clock.
3319                  */
3320                 deadline += ktime_get_seconds();
3321                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
3322                                    deadline);
3323         }
3324
3325         case IOC_LIBCFS_LNET_DIST:
3326                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3327                 if (rc < 0 && rc != -EHOSTUNREACH)
3328                         return rc;
3329
3330                 data->ioc_u32[0] = rc;
3331                 return 0;
3332
3333         case IOC_LIBCFS_TESTPROTOCOMPAT:
3334                 lnet_net_lock(LNET_LOCK_EX);
3335                 the_lnet.ln_testprotocompat = data->ioc_flags;
3336                 lnet_net_unlock(LNET_LOCK_EX);
3337                 return 0;
3338
3339         case IOC_LIBCFS_LNET_FAULT:
3340                 return lnet_fault_ctl(data->ioc_flags, data);
3341
3342         case IOC_LIBCFS_PING: {
3343                 signed long timeout;
3344
3345                 id.nid = data->ioc_nid;
3346                 id.pid = data->ioc_u32[0];
3347
3348                 /* If timeout is negative then set default of 3 minutes */
3349                 if (((s32)data->ioc_u32[1] <= 0) ||
3350                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3351                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3352                 else
3353                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
3354
3355                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3356                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3357
3358                 if (rc < 0)
3359                         return rc;
3360
3361                 data->ioc_count = rc;
3362                 return 0;
3363         }
3364
3365         case IOC_LIBCFS_PING_PEER: {
3366                 struct lnet_ioctl_ping_data *ping = arg;
3367                 struct lnet_peer *lp;
3368                 signed long timeout;
3369
3370                 /* If timeout is negative then set default of 3 minutes */
3371                 if (((s32)ping->op_param) <= 0 ||
3372                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3373                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3374                 else
3375                         timeout = msecs_to_jiffies(ping->op_param);
3376
3377                 rc = lnet_ping(ping->ping_id, timeout,
3378                                ping->ping_buf,
3379                                ping->ping_count);
3380                 if (rc < 0)
3381                         return rc;
3382
3383                 mutex_lock(&the_lnet.ln_api_mutex);
3384                 lp = lnet_find_peer(ping->ping_id.nid);
3385                 if (lp) {
3386                         ping->ping_id.nid = lp->lp_primary_nid;
3387                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3388                         lnet_peer_decref_locked(lp);
3389                 }
3390                 mutex_unlock(&the_lnet.ln_api_mutex);
3391
3392                 ping->ping_count = rc;
3393                 return 0;
3394         }
3395
3396         case IOC_LIBCFS_DISCOVER: {
3397                 struct lnet_ioctl_ping_data *discover = arg;
3398                 struct lnet_peer *lp;
3399
3400                 rc = lnet_discover(discover->ping_id, discover->op_param,
3401                                    discover->ping_buf,
3402                                    discover->ping_count);
3403                 if (rc < 0)
3404                         return rc;
3405
3406                 mutex_lock(&the_lnet.ln_api_mutex);
3407                 lp = lnet_find_peer(discover->ping_id.nid);
3408                 if (lp) {
3409                         discover->ping_id.nid = lp->lp_primary_nid;
3410                         discover->mr_info = lnet_peer_is_multi_rail(lp);
3411                         lnet_peer_decref_locked(lp);
3412                 }
3413                 mutex_unlock(&the_lnet.ln_api_mutex);
3414
3415                 discover->ping_count = rc;
3416                 return 0;
3417         }
3418
3419         default:
3420                 ni = lnet_net2ni_addref(data->ioc_net);
3421                 if (ni == NULL)
3422                         return -EINVAL;
3423
3424                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
3425                         rc = -EINVAL;
3426                 else
3427                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
3428
3429                 lnet_ni_decref(ni);
3430                 return rc;
3431         }
3432         /* not reached */
3433 }
3434 EXPORT_SYMBOL(LNetCtl);
3435
3436 void LNetDebugPeer(struct lnet_process_id id)
3437 {
3438         lnet_debug_peer(id.nid);
3439 }
3440 EXPORT_SYMBOL(LNetDebugPeer);
3441
3442 /**
3443  * Determine if the specified peer \a nid is on the local node.
3444  *
3445  * \param nid   peer nid to check
3446  *
3447  * \retval true         If peer NID is on the local node.
3448  * \retval false        If peer NID is not on the local node.
3449  */
3450 bool LNetIsPeerLocal(lnet_nid_t nid)
3451 {
3452         struct lnet_net *net;
3453         struct lnet_ni *ni;
3454         int cpt;
3455
3456         cpt = lnet_net_lock_current();
3457         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3458                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3459                         if (ni->ni_nid == nid) {
3460                                 lnet_net_unlock(cpt);
3461                                 return true;
3462                         }
3463                 }
3464         }
3465         lnet_net_unlock(cpt);
3466
3467         return false;
3468 }
3469 EXPORT_SYMBOL(LNetIsPeerLocal);
3470
3471 /**
3472  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
3473  * Note that all interfaces share a same PID, as requested by LNetNIInit().
3474  *
3475  * \param index Index of the interface to look up.
3476  * \param id On successful return, this location will hold the
3477  * struct lnet_process_id ID of the interface.
3478  *
3479  * \retval 0 If an interface exists at \a index.
3480  * \retval -ENOENT If no interface has been found.
3481  */
3482 int
3483 LNetGetId(unsigned int index, struct lnet_process_id *id)
3484 {
3485         struct lnet_ni   *ni;
3486         struct lnet_net  *net;
3487         int               cpt;
3488         int               rc = -ENOENT;
3489
3490         LASSERT(the_lnet.ln_refcount > 0);
3491
3492         cpt = lnet_net_lock_current();
3493
3494         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3495                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3496                         if (index-- != 0)
3497                                 continue;
3498
3499                         id->nid = ni->ni_nid;
3500                         id->pid = the_lnet.ln_pid;
3501                         rc = 0;
3502                         break;
3503                 }
3504         }
3505
3506         lnet_net_unlock(cpt);
3507         return rc;
3508 }
3509 EXPORT_SYMBOL(LNetGetId);
3510
3511 static int lnet_ping(struct lnet_process_id id, signed long timeout,
3512                      struct lnet_process_id __user *ids, int n_ids)
3513 {
3514         struct lnet_handle_eq eqh;
3515         struct lnet_handle_md mdh;
3516         struct lnet_event event;
3517         struct lnet_md md = { NULL };
3518         int which;
3519         int unlinked = 0;
3520         int replied = 0;
3521         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
3522         struct lnet_ping_buffer *pbuf;
3523         struct lnet_process_id tmpid;
3524         int i;
3525         int nob;
3526         int rc;
3527         int rc2;
3528         sigset_t blocked;
3529
3530         /* n_ids limit is arbitrary */
3531         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
3532                 return -EINVAL;
3533
3534         /*
3535          * if the user buffer has more space than the lnet_interfaces_max
3536          * then only fill it up to lnet_interfaces_max
3537          */
3538         if (n_ids > lnet_interfaces_max)
3539                 n_ids = lnet_interfaces_max;
3540
3541         if (id.pid == LNET_PID_ANY)
3542                 id.pid = LNET_PID_LUSTRE;
3543
3544         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
3545         if (!pbuf)
3546                 return -ENOMEM;
3547
3548         /* NB 2 events max (including any unlink event) */
3549         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
3550         if (rc != 0) {
3551                 CERROR("Can't allocate EQ: %d\n", rc);
3552                 goto fail_ping_buffer_decref;
3553         }
3554
3555         /* initialize md content */
3556         md.start     = &pbuf->pb_info;
3557         md.length    = LNET_PING_INFO_SIZE(n_ids);
3558         md.threshold = 2; /* GET/REPLY */
3559         md.max_size  = 0;
3560         md.options   = LNET_MD_TRUNCATE;
3561         md.user_ptr  = NULL;
3562         md.eq_handle = eqh;
3563
3564         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
3565         if (rc != 0) {
3566                 CERROR("Can't bind MD: %d\n", rc);
3567                 goto fail_free_eq;
3568         }
3569
3570         rc = LNetGet(LNET_NID_ANY, mdh, id,
3571                      LNET_RESERVED_PORTAL,
3572                      LNET_PROTO_PING_MATCHBITS, 0);
3573
3574         if (rc != 0) {
3575                 /* Don't CERROR; this could be deliberate! */
3576                 rc2 = LNetMDUnlink(mdh);
3577                 LASSERT(rc2 == 0);
3578
3579                 /* NB must wait for the UNLINK event below... */
3580                 unlinked = 1;
3581                 timeout = a_long_time;
3582         }
3583
3584         do {
3585                 /* MUST block for unlink to complete */
3586                 if (unlinked)
3587                         blocked = cfs_block_allsigs();
3588
3589                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
3590
3591                 if (unlinked)
3592                         cfs_restore_sigs(blocked);
3593
3594                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
3595                        (rc2 <= 0) ? -1 : event.type,
3596                        (rc2 <= 0) ? -1 : event.status,
3597                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
3598
3599                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
3600
3601                 if (rc2 <= 0 || event.status != 0) {
3602                         /* timeout or error */
3603                         if (!replied && rc == 0)
3604                                 rc = (rc2 < 0) ? rc2 :
3605                                      (rc2 == 0) ? -ETIMEDOUT :
3606                                      event.status;
3607
3608                         if (!unlinked) {
3609                                 /* Ensure completion in finite time... */
3610                                 LNetMDUnlink(mdh);
3611                                 /* No assertion (racing with network) */
3612                                 unlinked = 1;
3613                                 timeout = a_long_time;
3614                         } else if (rc2 == 0) {
3615                                 /* timed out waiting for unlink */
3616                                 CWARN("ping %s: late network completion\n",
3617                                       libcfs_id2str(id));
3618                         }
3619                 } else if (event.type == LNET_EVENT_REPLY) {
3620                         replied = 1;
3621                         rc = event.mlength;
3622                 }
3623         } while (rc2 <= 0 || !event.unlinked);
3624
3625         if (!replied) {
3626                 if (rc >= 0)
3627                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
3628                               libcfs_id2str(id));
3629                 rc = -EIO;
3630                 goto fail_free_eq;
3631         }
3632
3633         nob = rc;
3634         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
3635
3636         rc = -EPROTO;           /* if I can't parse... */
3637
3638         if (nob < 8) {
3639                 CERROR("%s: ping info too short %d\n",
3640                        libcfs_id2str(id), nob);
3641                 goto fail_free_eq;
3642         }
3643
3644         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
3645                 lnet_swap_pinginfo(pbuf);
3646         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
3647                 CERROR("%s: Unexpected magic %08x\n",
3648                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
3649                 goto fail_free_eq;
3650         }
3651
3652         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
3653                 CERROR("%s: ping w/o NI status: 0x%x\n",
3654                        libcfs_id2str(id), pbuf->pb_info.pi_features);
3655                 goto fail_free_eq;
3656         }
3657
3658         if (nob < LNET_PING_INFO_SIZE(0)) {
3659                 CERROR("%s: Short reply %d(%d min)\n",
3660                        libcfs_id2str(id),
3661                        nob, (int)LNET_PING_INFO_SIZE(0));
3662                 goto fail_free_eq;
3663         }
3664
3665         if (pbuf->pb_info.pi_nnis < n_ids)
3666                 n_ids = pbuf->pb_info.pi_nnis;
3667
3668         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
3669                 CERROR("%s: Short reply %d(%d expected)\n",
3670                        libcfs_id2str(id),
3671                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
3672                 goto fail_free_eq;
3673         }
3674
3675         rc = -EFAULT;           /* if I segv in copy_to_user()... */
3676
3677         memset(&tmpid, 0, sizeof(tmpid));
3678         for (i = 0; i < n_ids; i++) {
3679                 tmpid.pid = pbuf->pb_info.pi_pid;
3680                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
3681                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
3682                         goto fail_free_eq;
3683         }
3684         rc = pbuf->pb_info.pi_nnis;
3685
3686  fail_free_eq:
3687         rc2 = LNetEQFree(eqh);
3688         if (rc2 != 0)
3689                 CERROR("rc2 %d\n", rc2);
3690         LASSERT(rc2 == 0);
3691
3692  fail_ping_buffer_decref:
3693         lnet_ping_buffer_decref(pbuf);
3694         return rc;
3695 }
3696
3697 static int
3698 lnet_discover(struct lnet_process_id id, __u32 force,
3699               struct lnet_process_id __user *ids, int n_ids)
3700 {
3701         struct lnet_peer_ni *lpni;
3702         struct lnet_peer_ni *p;
3703         struct lnet_peer *lp;
3704         struct lnet_process_id *buf;
3705         int cpt;
3706         int i;
3707         int rc;
3708         int max_intf = lnet_interfaces_max;
3709         size_t buf_size;
3710
3711         if (n_ids <= 0 ||
3712             id.nid == LNET_NID_ANY)
3713                 return -EINVAL;
3714
3715         if (id.pid == LNET_PID_ANY)
3716                 id.pid = LNET_PID_LUSTRE;
3717
3718         /*
3719          * if the user buffer has more space than the max_intf
3720          * then only fill it up to max_intf
3721          */
3722         if (n_ids > max_intf)
3723                 n_ids = max_intf;
3724
3725         buf_size = n_ids * sizeof(*buf);
3726
3727         LIBCFS_ALLOC(buf, buf_size);
3728         if (!buf)
3729                 return -ENOMEM;
3730
3731         cpt = lnet_net_lock_current();
3732         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
3733         if (IS_ERR(lpni)) {
3734                 rc = PTR_ERR(lpni);
3735                 goto out;
3736         }
3737
3738         /*
3739          * Clearing the NIDS_UPTODATE flag ensures the peer will
3740          * be discovered, provided discovery has not been disabled.
3741          */
3742         lp = lpni->lpni_peer_net->lpn_peer;
3743         spin_lock(&lp->lp_lock);
3744         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
3745         /* If the force flag is set, force a PING and PUSH as well. */
3746         if (force)
3747                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
3748         spin_unlock(&lp->lp_lock);
3749         rc = lnet_discover_peer_locked(lpni, cpt, true);
3750         if (rc)
3751                 goto out_decref;
3752
3753         /* Peer may have changed. */
3754         lp = lpni->lpni_peer_net->lpn_peer;
3755         if (lp->lp_nnis < n_ids)
3756                 n_ids = lp->lp_nnis;
3757
3758         i = 0;
3759         p = NULL;
3760         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
3761                 buf[i].pid = id.pid;
3762                 buf[i].nid = p->lpni_nid;
3763                 if (++i >= n_ids)
3764                         break;
3765         }
3766
3767         lnet_net_unlock(cpt);
3768
3769         rc = -EFAULT;
3770         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
3771                 goto out_relock;
3772         rc = n_ids;
3773 out_relock:
3774         lnet_net_lock(cpt);
3775 out_decref:
3776         lnet_peer_ni_decref_locked(lpni);
3777 out:
3778         lnet_net_unlock(cpt);
3779
3780         LIBCFS_FREE(buf, buf_size);
3781
3782         return rc;
3783 }