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