Whamcloud - gitweb
LU-4330 lnet: Allocate MEs and small MDs in own kmem_caches
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2015, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_LNET
38 #include <linux/log2.h>
39 #include <lnet/lib-lnet.h>
40
41 #define D_LNI D_CONSOLE
42
43 lnet_t      the_lnet;                           /* THE state of the network */
44 EXPORT_SYMBOL(the_lnet);
45
46 static char *ip2nets = "";
47 module_param(ip2nets, charp, 0444);
48 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
49
50 static char *networks = "";
51 module_param(networks, charp, 0444);
52 MODULE_PARM_DESC(networks, "local networks");
53
54 static char *routes = "";
55 module_param(routes, charp, 0444);
56 MODULE_PARM_DESC(routes, "routes to non-local networks");
57
58 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
59 module_param(rnet_htable_size, int, 0444);
60 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
61
62 static int lnet_ping(lnet_process_id_t id, int timeout_ms,
63                      lnet_process_id_t __user *ids, int n_ids);
64
65 static char *
66 lnet_get_routes(void)
67 {
68         return routes;
69 }
70
71 static char *
72 lnet_get_networks(void)
73 {
74         char   *nets;
75         int     rc;
76
77         if (*networks != 0 && *ip2nets != 0) {
78                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
79                                    "'ip2nets' but not both at once\n");
80                 return NULL;
81         }
82
83         if (*ip2nets != 0) {
84                 rc = lnet_parse_ip2nets(&nets, ip2nets);
85                 return (rc == 0) ? nets : NULL;
86         }
87
88         if (*networks != 0)
89                 return networks;
90
91         return "tcp";
92 }
93
94 static void
95 lnet_init_locks(void)
96 {
97         spin_lock_init(&the_lnet.ln_eq_wait_lock);
98         init_waitqueue_head(&the_lnet.ln_eq_waitq);
99         init_waitqueue_head(&the_lnet.ln_rc_waitq);
100         mutex_init(&the_lnet.ln_lnd_mutex);
101         mutex_init(&the_lnet.ln_api_mutex);
102 }
103
104 static void
105 lnet_fini_locks(void)
106 {
107 }
108
109 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
110 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
111                                             *  MDs kmem_cache */
112
113 static int
114 lnet_descriptor_setup(void)
115 {
116         /* create specific kmem_cache for MEs and small MDs (i.e., originally
117          * allocated in <size-xxx> kmem_cache).
118          */
119         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(lnet_me_t),
120                                             0, 0, NULL);
121         if (!lnet_mes_cachep)
122                 return -ENOMEM;
123
124         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
125                                                   LNET_SMALL_MD_SIZE, 0, 0,
126                                                   NULL);
127         if (!lnet_small_mds_cachep)
128                 return -ENOMEM;
129
130         return 0;
131 }
132
133 static void
134 lnet_descriptor_cleanup(void)
135 {
136
137         if (lnet_small_mds_cachep) {
138                 kmem_cache_destroy(lnet_small_mds_cachep);
139                 lnet_small_mds_cachep = NULL;
140         }
141
142         if (lnet_mes_cachep) {
143                 kmem_cache_destroy(lnet_mes_cachep);
144                 lnet_mes_cachep = NULL;
145         }
146 }
147
148 static int
149 lnet_create_remote_nets_table(void)
150 {
151         int               i;
152         struct list_head *hash;
153
154         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
155         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
156         LIBCFS_ALLOC(hash, LNET_REMOTE_NETS_HASH_SIZE * sizeof(*hash));
157         if (hash == NULL) {
158                 CERROR("Failed to create remote nets hash table\n");
159                 return -ENOMEM;
160         }
161
162         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
163                 INIT_LIST_HEAD(&hash[i]);
164         the_lnet.ln_remote_nets_hash = hash;
165         return 0;
166 }
167
168 static void
169 lnet_destroy_remote_nets_table(void)
170 {
171         int i;
172
173         if (the_lnet.ln_remote_nets_hash == NULL)
174                 return;
175
176         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
177                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
178
179         LIBCFS_FREE(the_lnet.ln_remote_nets_hash,
180                     LNET_REMOTE_NETS_HASH_SIZE *
181                     sizeof(the_lnet.ln_remote_nets_hash[0]));
182         the_lnet.ln_remote_nets_hash = NULL;
183 }
184
185 static void
186 lnet_destroy_locks(void)
187 {
188         if (the_lnet.ln_res_lock != NULL) {
189                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
190                 the_lnet.ln_res_lock = NULL;
191         }
192
193         if (the_lnet.ln_net_lock != NULL) {
194                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
195                 the_lnet.ln_net_lock = NULL;
196         }
197
198         lnet_fini_locks();
199 }
200
201 static int
202 lnet_create_locks(void)
203 {
204         lnet_init_locks();
205
206         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
207         if (the_lnet.ln_res_lock == NULL)
208                 goto failed;
209
210         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
211         if (the_lnet.ln_net_lock == NULL)
212                 goto failed;
213
214         return 0;
215
216  failed:
217         lnet_destroy_locks();
218         return -ENOMEM;
219 }
220
221 static void lnet_assert_wire_constants(void)
222 {
223         /* Wire protocol assertions generated by 'wirecheck'
224          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
225          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
226          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
227
228         /* Constants... */
229         CLASSERT (LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
230         CLASSERT (LNET_PROTO_TCP_VERSION_MAJOR == 1);
231         CLASSERT (LNET_PROTO_TCP_VERSION_MINOR == 0);
232         CLASSERT (LNET_MSG_ACK == 0);
233         CLASSERT (LNET_MSG_PUT == 1);
234         CLASSERT (LNET_MSG_GET == 2);
235         CLASSERT (LNET_MSG_REPLY == 3);
236         CLASSERT (LNET_MSG_HELLO == 4);
237
238         /* Checks for struct ptl_handle_wire_t */
239         CLASSERT ((int)sizeof(lnet_handle_wire_t) == 16);
240         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_interface_cookie) == 0);
241         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_interface_cookie) == 8);
242         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_object_cookie) == 8);
243         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_object_cookie) == 8);
244
245         /* Checks for struct lnet_magicversion_t */
246         CLASSERT ((int)sizeof(lnet_magicversion_t) == 8);
247         CLASSERT ((int)offsetof(lnet_magicversion_t, magic) == 0);
248         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->magic) == 4);
249         CLASSERT ((int)offsetof(lnet_magicversion_t, version_major) == 4);
250         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_major) == 2);
251         CLASSERT ((int)offsetof(lnet_magicversion_t, version_minor) == 6);
252         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_minor) == 2);
253
254         /* Checks for struct lnet_hdr_t */
255         CLASSERT ((int)sizeof(lnet_hdr_t) == 72);
256         CLASSERT ((int)offsetof(lnet_hdr_t, dest_nid) == 0);
257         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_nid) == 8);
258         CLASSERT ((int)offsetof(lnet_hdr_t, src_nid) == 8);
259         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_nid) == 8);
260         CLASSERT ((int)offsetof(lnet_hdr_t, dest_pid) == 16);
261         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_pid) == 4);
262         CLASSERT ((int)offsetof(lnet_hdr_t, src_pid) == 20);
263         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_pid) == 4);
264         CLASSERT ((int)offsetof(lnet_hdr_t, type) == 24);
265         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->type) == 4);
266         CLASSERT ((int)offsetof(lnet_hdr_t, payload_length) == 28);
267         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->payload_length) == 4);
268         CLASSERT ((int)offsetof(lnet_hdr_t, msg) == 32);
269         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg) == 40);
270
271         /* Ack */
272         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.dst_wmd) == 32);
273         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.dst_wmd) == 16);
274         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.match_bits) == 48);
275         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.match_bits) == 8);
276         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.mlength) == 56);
277         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.mlength) == 4);
278
279         /* Put */
280         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ack_wmd) == 32);
281         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ack_wmd) == 16);
282         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.match_bits) == 48);
283         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.match_bits) == 8);
284         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.hdr_data) == 56);
285         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.hdr_data) == 8);
286         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ptl_index) == 64);
287         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ptl_index) == 4);
288         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.offset) == 68);
289         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.offset) == 4);
290
291         /* Get */
292         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.return_wmd) == 32);
293         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.return_wmd) == 16);
294         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.match_bits) == 48);
295         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.match_bits) == 8);
296         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.ptl_index) == 56);
297         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.ptl_index) == 4);
298         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.src_offset) == 60);
299         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.src_offset) == 4);
300         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.sink_length) == 64);
301         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.sink_length) == 4);
302
303         /* Reply */
304         CLASSERT ((int)offsetof(lnet_hdr_t, msg.reply.dst_wmd) == 32);
305         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.reply.dst_wmd) == 16);
306
307         /* Hello */
308         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.incarnation) == 32);
309         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.incarnation) == 8);
310         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.type) == 40);
311         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.type) == 4);
312 }
313
314 static lnd_t *lnet_find_lnd_by_type(__u32 type)
315 {
316         lnd_t            *lnd;
317         struct list_head *tmp;
318
319         /* holding lnd mutex */
320         list_for_each(tmp, &the_lnet.ln_lnds) {
321                 lnd = list_entry(tmp, lnd_t, lnd_list);
322
323                 if (lnd->lnd_type == type)
324                         return lnd;
325         }
326         return NULL;
327 }
328
329 void
330 lnet_register_lnd (lnd_t *lnd)
331 {
332         mutex_lock(&the_lnet.ln_lnd_mutex);
333
334         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
335         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
336
337         list_add_tail(&lnd->lnd_list, &the_lnet.ln_lnds);
338         lnd->lnd_refcount = 0;
339
340         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
341
342         mutex_unlock(&the_lnet.ln_lnd_mutex);
343 }
344 EXPORT_SYMBOL(lnet_register_lnd);
345
346 void
347 lnet_unregister_lnd (lnd_t *lnd)
348 {
349         mutex_lock(&the_lnet.ln_lnd_mutex);
350
351         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
352         LASSERT(lnd->lnd_refcount == 0);
353
354         list_del(&lnd->lnd_list);
355         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
356
357         mutex_unlock(&the_lnet.ln_lnd_mutex);
358 }
359 EXPORT_SYMBOL(lnet_unregister_lnd);
360
361 void
362 lnet_counters_get(lnet_counters_t *counters)
363 {
364         lnet_counters_t *ctr;
365         int             i;
366
367         memset(counters, 0, sizeof(*counters));
368
369         lnet_net_lock(LNET_LOCK_EX);
370
371         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
372                 counters->msgs_max     += ctr->msgs_max;
373                 counters->msgs_alloc   += ctr->msgs_alloc;
374                 counters->errors       += ctr->errors;
375                 counters->send_count   += ctr->send_count;
376                 counters->recv_count   += ctr->recv_count;
377                 counters->route_count  += ctr->route_count;
378                 counters->drop_count   += ctr->drop_count;
379                 counters->send_length  += ctr->send_length;
380                 counters->recv_length  += ctr->recv_length;
381                 counters->route_length += ctr->route_length;
382                 counters->drop_length  += ctr->drop_length;
383
384         }
385         lnet_net_unlock(LNET_LOCK_EX);
386 }
387 EXPORT_SYMBOL(lnet_counters_get);
388
389 void
390 lnet_counters_reset(void)
391 {
392         lnet_counters_t *counters;
393         int             i;
394
395         lnet_net_lock(LNET_LOCK_EX);
396
397         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
398                 memset(counters, 0, sizeof(lnet_counters_t));
399
400         lnet_net_unlock(LNET_LOCK_EX);
401 }
402
403 static __u64 lnet_create_interface_cookie(void)
404 {
405         /* NB the interface cookie in wire handles guards against delayed
406          * replies and ACKs appearing valid after reboot. Initialisation time,
407          * even if it's only implemented to millisecond resolution is probably
408          * easily good enough. */
409         struct timeval tv;
410         __u64          cookie;
411         do_gettimeofday(&tv);
412         cookie = tv.tv_sec;
413         cookie *= 1000000;
414         cookie += tv.tv_usec;
415         return cookie;
416 }
417
418 static char *
419 lnet_res_type2str(int type)
420 {
421         switch (type) {
422         default:
423                 LBUG();
424         case LNET_COOKIE_TYPE_MD:
425                 return "MD";
426         case LNET_COOKIE_TYPE_ME:
427                 return "ME";
428         case LNET_COOKIE_TYPE_EQ:
429                 return "EQ";
430         }
431 }
432
433 static void
434 lnet_res_container_cleanup(struct lnet_res_container *rec)
435 {
436         int     count = 0;
437
438         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
439                 return;
440
441         while (!list_empty(&rec->rec_active)) {
442                 struct list_head *e = rec->rec_active.next;
443
444                 list_del_init(e);
445                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
446                         lnet_eq_free(list_entry(e, lnet_eq_t, eq_list));
447
448                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
449                         lnet_md_free(list_entry(e, lnet_libmd_t, md_list));
450
451                 } else { /* NB: Active MEs should be attached on portals */
452                         LBUG();
453                 }
454                 count++;
455         }
456
457         if (count > 0) {
458                 /* Found alive MD/ME/EQ, user really should unlink/free
459                  * all of them before finalize LNet, but if someone didn't,
460                  * we have to recycle garbage for him */
461                 CERROR("%d active elements on exit of %s container\n",
462                        count, lnet_res_type2str(rec->rec_type));
463         }
464
465         if (rec->rec_lh_hash != NULL) {
466                 LIBCFS_FREE(rec->rec_lh_hash,
467                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
468                 rec->rec_lh_hash = NULL;
469         }
470
471         rec->rec_type = 0; /* mark it as finalized */
472 }
473
474 static int
475 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
476 {
477         int     rc = 0;
478         int     i;
479
480         LASSERT(rec->rec_type == 0);
481
482         rec->rec_type = type;
483         INIT_LIST_HEAD(&rec->rec_active);
484
485         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
486
487         /* Arbitrary choice of hash table size */
488         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
489                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
490         if (rec->rec_lh_hash == NULL) {
491                 rc = -ENOMEM;
492                 goto out;
493         }
494
495         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
496                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
497
498         return 0;
499
500 out:
501         CERROR("Failed to setup %s resource container\n",
502                lnet_res_type2str(type));
503         lnet_res_container_cleanup(rec);
504         return rc;
505 }
506
507 static void
508 lnet_res_containers_destroy(struct lnet_res_container **recs)
509 {
510         struct lnet_res_container       *rec;
511         int                             i;
512
513         cfs_percpt_for_each(rec, i, recs)
514                 lnet_res_container_cleanup(rec);
515
516         cfs_percpt_free(recs);
517 }
518
519 static struct lnet_res_container **
520 lnet_res_containers_create(int type)
521 {
522         struct lnet_res_container       **recs;
523         struct lnet_res_container       *rec;
524         int                             rc;
525         int                             i;
526
527         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
528         if (recs == NULL) {
529                 CERROR("Failed to allocate %s resource containers\n",
530                        lnet_res_type2str(type));
531                 return NULL;
532         }
533
534         cfs_percpt_for_each(rec, i, recs) {
535                 rc = lnet_res_container_setup(rec, i, type);
536                 if (rc != 0) {
537                         lnet_res_containers_destroy(recs);
538                         return NULL;
539                 }
540         }
541
542         return recs;
543 }
544
545 lnet_libhandle_t *
546 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
547 {
548         /* ALWAYS called with lnet_res_lock held */
549         struct list_head        *head;
550         lnet_libhandle_t        *lh;
551         unsigned int            hash;
552
553         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
554                 return NULL;
555
556         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
557         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
558
559         list_for_each_entry(lh, head, lh_hash_chain) {
560                 if (lh->lh_cookie == cookie)
561                         return lh;
562         }
563
564         return NULL;
565 }
566
567 void
568 lnet_res_lh_initialize(struct lnet_res_container *rec, lnet_libhandle_t *lh)
569 {
570         /* ALWAYS called with lnet_res_lock held */
571         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
572         unsigned int    hash;
573
574         lh->lh_cookie = rec->rec_lh_cookie;
575         rec->rec_lh_cookie += 1 << ibits;
576
577         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
578
579         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
580 }
581
582 static int lnet_unprepare(void);
583
584 static int
585 lnet_prepare(lnet_pid_t requested_pid)
586 {
587         /* Prepare to bring up the network */
588         struct lnet_res_container **recs;
589         int                       rc = 0;
590
591         if (requested_pid == LNET_PID_ANY) {
592                 /* Don't instantiate LNET just for me */
593                 return -ENETDOWN;
594         }
595
596         LASSERT(the_lnet.ln_refcount == 0);
597
598         the_lnet.ln_routing = 0;
599
600         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
601         the_lnet.ln_pid = requested_pid;
602
603         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
604         INIT_LIST_HEAD(&the_lnet.ln_nis);
605         INIT_LIST_HEAD(&the_lnet.ln_nis_cpt);
606         INIT_LIST_HEAD(&the_lnet.ln_nis_zombie);
607         INIT_LIST_HEAD(&the_lnet.ln_routers);
608         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
609         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
610
611         rc = lnet_descriptor_setup();
612         if (rc != 0)
613                 goto failed;
614
615         rc = lnet_create_remote_nets_table();
616         if (rc != 0)
617                 goto failed;
618
619         the_lnet.ln_interface_cookie = lnet_create_interface_cookie();
620
621         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
622                                                 sizeof(lnet_counters_t));
623         if (the_lnet.ln_counters == NULL) {
624                 CERROR("Failed to allocate counters for LNet\n");
625                 rc = -ENOMEM;
626                 goto failed;
627         }
628
629         rc = lnet_peer_tables_create();
630         if (rc != 0)
631                 goto failed;
632
633         rc = lnet_msg_containers_create();
634         if (rc != 0)
635                 goto failed;
636
637         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
638                                       LNET_COOKIE_TYPE_EQ);
639         if (rc != 0)
640                 goto failed;
641
642         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
643         if (recs == NULL) {
644                 rc = -ENOMEM;
645                 goto failed;
646         }
647
648         the_lnet.ln_me_containers = recs;
649
650         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
651         if (recs == NULL) {
652                 rc = -ENOMEM;
653                 goto failed;
654         }
655
656         the_lnet.ln_md_containers = recs;
657
658         rc = lnet_portals_create();
659         if (rc != 0) {
660                 CERROR("Failed to create portals for LNet: %d\n", rc);
661                 goto failed;
662         }
663
664         return 0;
665
666  failed:
667         lnet_unprepare();
668         return rc;
669 }
670
671 static int
672 lnet_unprepare (void)
673 {
674         /* NB no LNET_LOCK since this is the last reference.  All LND instances
675          * have shut down already, so it is safe to unlink and free all
676          * descriptors, even those that appear committed to a network op (eg MD
677          * with non-zero pending count) */
678
679         lnet_fail_nid(LNET_NID_ANY, 0);
680
681         LASSERT(the_lnet.ln_refcount == 0);
682         LASSERT(list_empty(&the_lnet.ln_test_peers));
683         LASSERT(list_empty(&the_lnet.ln_nis));
684         LASSERT(list_empty(&the_lnet.ln_nis_cpt));
685         LASSERT(list_empty(&the_lnet.ln_nis_zombie));
686
687         lnet_portals_destroy();
688
689         if (the_lnet.ln_md_containers != NULL) {
690                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
691                 the_lnet.ln_md_containers = NULL;
692         }
693
694         if (the_lnet.ln_me_containers != NULL) {
695                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
696                 the_lnet.ln_me_containers = NULL;
697         }
698
699         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
700
701         lnet_msg_containers_destroy();
702         lnet_peer_tables_destroy();
703         lnet_rtrpools_free(0);
704
705         if (the_lnet.ln_counters != NULL) {
706                 cfs_percpt_free(the_lnet.ln_counters);
707                 the_lnet.ln_counters = NULL;
708         }
709         lnet_destroy_remote_nets_table();
710         lnet_descriptor_cleanup();
711
712         return 0;
713 }
714
715 lnet_ni_t  *
716 lnet_net2ni_locked(__u32 net, int cpt)
717 {
718         struct list_head *tmp;
719         lnet_ni_t        *ni;
720
721         LASSERT(cpt != LNET_LOCK_EX);
722
723         list_for_each(tmp, &the_lnet.ln_nis) {
724                 ni = list_entry(tmp, lnet_ni_t, ni_list);
725
726                 if (LNET_NIDNET(ni->ni_nid) == net) {
727                         lnet_ni_addref_locked(ni, cpt);
728                         return ni;
729                 }
730         }
731
732         return NULL;
733 }
734
735 lnet_ni_t *
736 lnet_net2ni(__u32 net)
737 {
738         lnet_ni_t *ni;
739
740         lnet_net_lock(0);
741         ni = lnet_net2ni_locked(net, 0);
742         lnet_net_unlock(0);
743
744         return ni;
745 }
746 EXPORT_SYMBOL(lnet_net2ni);
747
748 static unsigned int
749 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
750 {
751         __u64           key = nid;
752         unsigned int    val;
753
754         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
755
756         if (number == 1)
757                 return 0;
758
759         val = hash_long(key, LNET_CPT_BITS);
760         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
761         if (val < number)
762                 return val;
763
764         return (unsigned int)(key + val + (val >> 1)) % number;
765 }
766
767 int
768 lnet_cpt_of_nid_locked(lnet_nid_t nid)
769 {
770         struct lnet_ni *ni;
771
772         /* must called with hold of lnet_net_lock */
773         if (LNET_CPT_NUMBER == 1)
774                 return 0; /* the only one */
775
776         /* take lnet_net_lock(any) would be OK */
777         if (!list_empty(&the_lnet.ln_nis_cpt)) {
778                 list_for_each_entry(ni, &the_lnet.ln_nis_cpt, ni_cptlist) {
779                         if (LNET_NIDNET(ni->ni_nid) != LNET_NIDNET(nid))
780                                 continue;
781
782                         LASSERT(ni->ni_cpts != NULL);
783                         return ni->ni_cpts[lnet_nid_cpt_hash
784                                            (nid, ni->ni_ncpts)];
785                 }
786         }
787
788         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
789 }
790
791 int
792 lnet_cpt_of_nid(lnet_nid_t nid)
793 {
794         int     cpt;
795         int     cpt2;
796
797         if (LNET_CPT_NUMBER == 1)
798                 return 0; /* the only one */
799
800         if (list_empty(&the_lnet.ln_nis_cpt))
801                 return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
802
803         cpt = lnet_net_lock_current();
804         cpt2 = lnet_cpt_of_nid_locked(nid);
805         lnet_net_unlock(cpt);
806
807         return cpt2;
808 }
809 EXPORT_SYMBOL(lnet_cpt_of_nid);
810
811 int
812 lnet_islocalnet(__u32 net)
813 {
814         struct lnet_ni  *ni;
815         int             cpt;
816
817         cpt = lnet_net_lock_current();
818
819         ni = lnet_net2ni_locked(net, cpt);
820         if (ni != NULL)
821                 lnet_ni_decref_locked(ni, cpt);
822
823         lnet_net_unlock(cpt);
824
825         return ni != NULL;
826 }
827
828 lnet_ni_t  *
829 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
830 {
831         struct lnet_ni   *ni;
832         struct list_head *tmp;
833
834         LASSERT(cpt != LNET_LOCK_EX);
835
836         list_for_each(tmp, &the_lnet.ln_nis) {
837                 ni = list_entry(tmp, lnet_ni_t, ni_list);
838
839                 if (ni->ni_nid == nid) {
840                         lnet_ni_addref_locked(ni, cpt);
841                         return ni;
842                 }
843         }
844
845         return NULL;
846 }
847
848 int
849 lnet_islocalnid(lnet_nid_t nid)
850 {
851         struct lnet_ni  *ni;
852         int             cpt;
853
854         cpt = lnet_net_lock_current();
855         ni = lnet_nid2ni_locked(nid, cpt);
856         if (ni != NULL)
857                 lnet_ni_decref_locked(ni, cpt);
858         lnet_net_unlock(cpt);
859
860         return ni != NULL;
861 }
862
863 int
864 lnet_count_acceptor_nis (void)
865 {
866         /* Return the # of NIs that need the acceptor. */
867         int              count = 0;
868         struct list_head *tmp;
869         struct lnet_ni   *ni;
870         int              cpt;
871
872         cpt = lnet_net_lock_current();
873         list_for_each(tmp, &the_lnet.ln_nis) {
874                 ni = list_entry(tmp, lnet_ni_t, ni_list);
875
876                 if (ni->ni_lnd->lnd_accept != NULL)
877                         count++;
878         }
879
880         lnet_net_unlock(cpt);
881
882         return count;
883 }
884
885 static lnet_ping_info_t *
886 lnet_ping_info_create(int num_ni)
887 {
888         lnet_ping_info_t *ping_info;
889         unsigned int     infosz;
890
891         infosz = offsetof(lnet_ping_info_t, pi_ni[num_ni]);
892         LIBCFS_ALLOC(ping_info, infosz);
893         if (ping_info == NULL) {
894                 CERROR("Can't allocate ping info[%d]\n", num_ni);
895                 return NULL;
896         }
897
898         ping_info->pi_nnis = num_ni;
899         ping_info->pi_pid = the_lnet.ln_pid;
900         ping_info->pi_magic = LNET_PROTO_PING_MAGIC;
901         ping_info->pi_features = LNET_PING_FEAT_NI_STATUS;
902
903         return ping_info;
904 }
905
906 static inline int
907 lnet_get_ni_count(void)
908 {
909         struct lnet_ni *ni;
910         int            count = 0;
911
912         lnet_net_lock(0);
913
914         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list)
915                 count++;
916
917         lnet_net_unlock(0);
918
919         return count;
920 }
921
922 static inline void
923 lnet_ping_info_free(lnet_ping_info_t *pinfo)
924 {
925         LIBCFS_FREE(pinfo,
926                     offsetof(lnet_ping_info_t,
927                              pi_ni[pinfo->pi_nnis]));
928 }
929
930 static void
931 lnet_ping_info_destroy(void)
932 {
933         struct lnet_ni  *ni;
934
935         lnet_net_lock(LNET_LOCK_EX);
936
937         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list) {
938                 lnet_ni_lock(ni);
939                 ni->ni_status = NULL;
940                 lnet_ni_unlock(ni);
941         }
942
943         lnet_ping_info_free(the_lnet.ln_ping_info);
944         the_lnet.ln_ping_info = NULL;
945
946         lnet_net_unlock(LNET_LOCK_EX);
947 }
948
949 static void
950 lnet_ping_event_handler(lnet_event_t *event)
951 {
952         lnet_ping_info_t *pinfo = event->md.user_ptr;
953
954         if (event->unlinked)
955                 pinfo->pi_features = LNET_PING_FEAT_INVAL;
956 }
957
958 static int
959 lnet_ping_info_setup(lnet_ping_info_t **ppinfo, lnet_handle_md_t *md_handle,
960                      int ni_count, bool set_eq)
961 {
962         lnet_handle_me_t  me_handle;
963         lnet_process_id_t id = {LNET_NID_ANY, LNET_PID_ANY};
964         lnet_md_t         md = {NULL};
965         int               rc, rc2;
966
967         if (set_eq) {
968                 rc = LNetEQAlloc(0, lnet_ping_event_handler,
969                                  &the_lnet.ln_ping_target_eq);
970                 if (rc != 0) {
971                         CERROR("Can't allocate ping EQ: %d\n", rc);
972                         return rc;
973                 }
974         }
975
976         *ppinfo = lnet_ping_info_create(ni_count);
977         if (*ppinfo == NULL) {
978                 rc = -ENOMEM;
979                 goto failed_0;
980         }
981
982         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
983                           LNET_PROTO_PING_MATCHBITS, 0,
984                           LNET_UNLINK, LNET_INS_AFTER,
985                           &me_handle);
986         if (rc != 0) {
987                 CERROR("Can't create ping ME: %d\n", rc);
988                 goto failed_1;
989         }
990
991         /* initialize md content */
992         md.start     = *ppinfo;
993         md.length    = offsetof(lnet_ping_info_t,
994                                 pi_ni[(*ppinfo)->pi_nnis]);
995         md.threshold = LNET_MD_THRESH_INF;
996         md.max_size  = 0;
997         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
998                        LNET_MD_MANAGE_REMOTE;
999         md.user_ptr  = NULL;
1000         md.eq_handle = the_lnet.ln_ping_target_eq;
1001         md.user_ptr = *ppinfo;
1002
1003         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, md_handle);
1004         if (rc != 0) {
1005                 CERROR("Can't attach ping MD: %d\n", rc);
1006                 goto failed_2;
1007         }
1008
1009         return 0;
1010
1011 failed_2:
1012         rc2 = LNetMEUnlink(me_handle);
1013         LASSERT(rc2 == 0);
1014 failed_1:
1015         lnet_ping_info_free(*ppinfo);
1016         *ppinfo = NULL;
1017 failed_0:
1018         if (set_eq)
1019                 LNetEQFree(the_lnet.ln_ping_target_eq);
1020         return rc;
1021 }
1022
1023 static void
1024 lnet_ping_md_unlink(lnet_ping_info_t *pinfo, lnet_handle_md_t *md_handle)
1025 {
1026         sigset_t        blocked = cfs_block_allsigs();
1027
1028         LNetMDUnlink(*md_handle);
1029         LNetInvalidateHandle(md_handle);
1030
1031         /* NB md could be busy; this just starts the unlink */
1032         while (pinfo->pi_features != LNET_PING_FEAT_INVAL) {
1033                 CDEBUG(D_NET, "Still waiting for ping MD to unlink\n");
1034                 set_current_state(TASK_UNINTERRUPTIBLE);
1035                 schedule_timeout(cfs_time_seconds(1));
1036         }
1037
1038         cfs_restore_sigs(blocked);
1039 }
1040
1041 static void
1042 lnet_ping_info_install_locked(lnet_ping_info_t *ping_info)
1043 {
1044         int                     i;
1045         lnet_ni_t               *ni;
1046         lnet_ni_status_t        *ns;
1047
1048         i = 0;
1049         list_for_each_entry(ni, &the_lnet.ln_nis, ni_list) {
1050                 LASSERT(i < ping_info->pi_nnis);
1051
1052                 ns = &ping_info->pi_ni[i];
1053
1054                 ns->ns_nid = ni->ni_nid;
1055
1056                 lnet_ni_lock(ni);
1057                 ns->ns_status = (ni->ni_status != NULL) ?
1058                                 ni->ni_status->ns_status : LNET_NI_STATUS_UP;
1059                 ni->ni_status = ns;
1060                 lnet_ni_unlock(ni);
1061
1062                 i++;
1063         }
1064 }
1065
1066 static void
1067 lnet_ping_target_update(lnet_ping_info_t *pinfo, lnet_handle_md_t md_handle)
1068 {
1069         lnet_ping_info_t *old_pinfo = NULL;
1070         lnet_handle_md_t old_md;
1071
1072         /* switch the NIs to point to the new ping info created */
1073         lnet_net_lock(LNET_LOCK_EX);
1074
1075         if (!the_lnet.ln_routing)
1076                 pinfo->pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1077         lnet_ping_info_install_locked(pinfo);
1078
1079         if (the_lnet.ln_ping_info != NULL) {
1080                 old_pinfo = the_lnet.ln_ping_info;
1081                 old_md = the_lnet.ln_ping_target_md;
1082         }
1083         the_lnet.ln_ping_target_md = md_handle;
1084         the_lnet.ln_ping_info = pinfo;
1085
1086         lnet_net_unlock(LNET_LOCK_EX);
1087
1088         if (old_pinfo != NULL) {
1089                 /* unlink the old ping info */
1090                 lnet_ping_md_unlink(old_pinfo, &old_md);
1091                 lnet_ping_info_free(old_pinfo);
1092         }
1093 }
1094
1095 static void
1096 lnet_ping_target_fini(void)
1097 {
1098         int             rc;
1099
1100         lnet_ping_md_unlink(the_lnet.ln_ping_info,
1101                             &the_lnet.ln_ping_target_md);
1102
1103         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1104         LASSERT(rc == 0);
1105
1106         lnet_ping_info_destroy();
1107 }
1108
1109 static int
1110 lnet_ni_tq_credits(lnet_ni_t *ni)
1111 {
1112         int     credits;
1113
1114         LASSERT(ni->ni_ncpts >= 1);
1115
1116         if (ni->ni_ncpts == 1)
1117                 return ni->ni_maxtxcredits;
1118
1119         credits = ni->ni_maxtxcredits / ni->ni_ncpts;
1120         credits = max(credits, 8 * ni->ni_peertxcredits);
1121         credits = min(credits, ni->ni_maxtxcredits);
1122
1123         return credits;
1124 }
1125
1126 static void
1127 lnet_ni_unlink_locked(lnet_ni_t *ni)
1128 {
1129         if (!list_empty(&ni->ni_cptlist)) {
1130                 list_del_init(&ni->ni_cptlist);
1131                 lnet_ni_decref_locked(ni, 0);
1132         }
1133
1134         /* move it to zombie list and nobody can find it anymore */
1135         LASSERT(!list_empty(&ni->ni_list));
1136         list_move(&ni->ni_list, &the_lnet.ln_nis_zombie);
1137         lnet_ni_decref_locked(ni, 0);   /* drop ln_nis' ref */
1138 }
1139
1140 static void
1141 lnet_clear_zombies_nis_locked(void)
1142 {
1143         int             i;
1144         int             islo;
1145         lnet_ni_t       *ni;
1146
1147         /* Now wait for the NI's I just nuked to show up on ln_zombie_nis
1148          * and shut them down in guaranteed thread context */
1149         i = 2;
1150         while (!list_empty(&the_lnet.ln_nis_zombie)) {
1151                 int     *ref;
1152                 int     j;
1153
1154                 ni = list_entry(the_lnet.ln_nis_zombie.next,
1155                                 lnet_ni_t, ni_list);
1156                 list_del_init(&ni->ni_list);
1157                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1158                         if (*ref == 0)
1159                                 continue;
1160                         /* still busy, add it back to zombie list */
1161                         list_add(&ni->ni_list, &the_lnet.ln_nis_zombie);
1162                         break;
1163                 }
1164
1165                 if (!list_empty(&ni->ni_list)) {
1166                         lnet_net_unlock(LNET_LOCK_EX);
1167                         ++i;
1168                         if ((i & (-i)) == i) {
1169                                 CDEBUG(D_WARNING,
1170                                        "Waiting for zombie LNI %s\n",
1171                                        libcfs_nid2str(ni->ni_nid));
1172                         }
1173                         set_current_state(TASK_UNINTERRUPTIBLE);
1174                         schedule_timeout(cfs_time_seconds(1));
1175                         lnet_net_lock(LNET_LOCK_EX);
1176                         continue;
1177                 }
1178
1179                 ni->ni_lnd->lnd_refcount--;
1180                 lnet_net_unlock(LNET_LOCK_EX);
1181
1182                 islo = ni->ni_lnd->lnd_type == LOLND;
1183
1184                 LASSERT(!in_interrupt());
1185                 (ni->ni_lnd->lnd_shutdown)(ni);
1186
1187                 /* can't deref lnd anymore now; it might have unregistered
1188                  * itself...  */
1189
1190                 if (!islo)
1191                         CDEBUG(D_LNI, "Removed LNI %s\n",
1192                               libcfs_nid2str(ni->ni_nid));
1193
1194                 lnet_ni_free(ni);
1195                 i = 2;
1196                 lnet_net_lock(LNET_LOCK_EX);
1197         }
1198 }
1199
1200 static void
1201 lnet_shutdown_lndnis(void)
1202 {
1203         int             i;
1204         lnet_ni_t       *ni;
1205
1206         /* NB called holding the global mutex */
1207
1208         /* All quiet on the API front */
1209         LASSERT(!the_lnet.ln_shutdown);
1210         LASSERT(the_lnet.ln_refcount == 0);
1211         LASSERT(list_empty(&the_lnet.ln_nis_zombie));
1212
1213         lnet_net_lock(LNET_LOCK_EX);
1214         the_lnet.ln_shutdown = 1;       /* flag shutdown */
1215
1216         /* Unlink NIs from the global table */
1217         while (!list_empty(&the_lnet.ln_nis)) {
1218                 ni = list_entry(the_lnet.ln_nis.next,
1219                                 lnet_ni_t, ni_list);
1220                 lnet_ni_unlink_locked(ni);
1221         }
1222
1223         /* Drop the cached loopback NI. */
1224         if (the_lnet.ln_loni != NULL) {
1225                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
1226                 the_lnet.ln_loni = NULL;
1227         }
1228
1229         lnet_net_unlock(LNET_LOCK_EX);
1230
1231         /* Clear lazy portals and drop delayed messages which hold refs
1232          * on their lnet_msg_t::msg_rxpeer */
1233         for (i = 0; i < the_lnet.ln_nportals; i++)
1234                 LNetClearLazyPortal(i);
1235
1236         /* Clear the peer table and wait for all peers to go (they hold refs on
1237          * their NIs) */
1238         lnet_peer_tables_cleanup(NULL);
1239
1240         lnet_net_lock(LNET_LOCK_EX);
1241
1242         lnet_clear_zombies_nis_locked();
1243         the_lnet.ln_shutdown = 0;
1244         lnet_net_unlock(LNET_LOCK_EX);
1245 }
1246
1247 /* shutdown down the NI and release refcount */
1248 static void
1249 lnet_shutdown_lndni(struct lnet_ni *ni)
1250 {
1251         int i;
1252
1253         lnet_net_lock(LNET_LOCK_EX);
1254         lnet_ni_unlink_locked(ni);
1255         lnet_net_unlock(LNET_LOCK_EX);
1256
1257         /* clear messages for this NI on the lazy portal */
1258         for (i = 0; i < the_lnet.ln_nportals; i++)
1259                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
1260
1261         /* Do peer table cleanup for this ni */
1262         lnet_peer_tables_cleanup(ni);
1263
1264         lnet_net_lock(LNET_LOCK_EX);
1265         lnet_clear_zombies_nis_locked();
1266         lnet_net_unlock(LNET_LOCK_EX);
1267 }
1268
1269 static int
1270 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_ioctl_config_data *conf)
1271 {
1272         struct lnet_ioctl_config_lnd_tunables *lnd_tunables = NULL;
1273         int                     rc = -EINVAL;
1274         __u32                   lnd_type;
1275         lnd_t                   *lnd;
1276         struct lnet_tx_queue    *tq;
1277         int                     i;
1278
1279         lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
1280
1281         LASSERT(libcfs_isknown_lnd(lnd_type));
1282
1283         if (lnd_type == CIBLND || lnd_type == OPENIBLND ||
1284             lnd_type == IIBLND || lnd_type == VIBLND) {
1285                 CERROR("LND %s obsoleted\n", libcfs_lnd2str(lnd_type));
1286                 goto failed0;
1287         }
1288
1289         /* Make sure this new NI is unique. */
1290         lnet_net_lock(LNET_LOCK_EX);
1291         rc = lnet_net_unique(LNET_NIDNET(ni->ni_nid), &the_lnet.ln_nis);
1292         lnet_net_unlock(LNET_LOCK_EX);
1293
1294         if (!rc) {
1295                 if (lnd_type == LOLND) {
1296                         lnet_ni_free(ni);
1297                         return 0;
1298                 }
1299
1300                 CERROR("Net %s is not unique\n",
1301                        libcfs_net2str(LNET_NIDNET(ni->ni_nid)));
1302
1303                 rc = -EEXIST;
1304                 goto failed0;
1305         }
1306
1307         mutex_lock(&the_lnet.ln_lnd_mutex);
1308         lnd = lnet_find_lnd_by_type(lnd_type);
1309
1310         if (lnd == NULL) {
1311                 mutex_unlock(&the_lnet.ln_lnd_mutex);
1312                 rc = request_module("%s", libcfs_lnd2modname(lnd_type));
1313                 mutex_lock(&the_lnet.ln_lnd_mutex);
1314
1315                 lnd = lnet_find_lnd_by_type(lnd_type);
1316                 if (lnd == NULL) {
1317                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1318                         CERROR("Can't load LND %s, module %s, rc=%d\n",
1319                                libcfs_lnd2str(lnd_type),
1320                                libcfs_lnd2modname(lnd_type), rc);
1321 #ifndef HAVE_MODULE_LOADING_SUPPORT
1322                         LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1323                                            "compiled with kernel module "
1324                                            "loading support.");
1325 #endif
1326                         rc = -EINVAL;
1327                         goto failed0;
1328                 }
1329         }
1330
1331         lnet_net_lock(LNET_LOCK_EX);
1332         lnd->lnd_refcount++;
1333         lnet_net_unlock(LNET_LOCK_EX);
1334
1335         ni->ni_lnd = lnd;
1336
1337         if (conf && conf->cfg_hdr.ioc_len > sizeof(*conf))
1338                 lnd_tunables = (struct lnet_ioctl_config_lnd_tunables *)conf->cfg_bulk;
1339
1340         if (lnd_tunables != NULL) {
1341                 LIBCFS_ALLOC(ni->ni_lnd_tunables,
1342                              sizeof(*ni->ni_lnd_tunables));
1343                 if (ni->ni_lnd_tunables == NULL) {
1344                         mutex_unlock(&the_lnet.ln_lnd_mutex);
1345                         rc = -ENOMEM;
1346                         goto failed0;
1347                 }
1348                 memcpy(ni->ni_lnd_tunables, lnd_tunables,
1349                        sizeof(*ni->ni_lnd_tunables));
1350         }
1351
1352         rc = (lnd->lnd_startup)(ni);
1353
1354         mutex_unlock(&the_lnet.ln_lnd_mutex);
1355
1356         if (rc != 0) {
1357                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
1358                                    rc, libcfs_lnd2str(lnd->lnd_type));
1359                 lnet_net_lock(LNET_LOCK_EX);
1360                 lnd->lnd_refcount--;
1361                 lnet_net_unlock(LNET_LOCK_EX);
1362                 goto failed0;
1363         }
1364
1365         /* If given some LND tunable parameters, parse those now to
1366          * override the values in the NI structure. */
1367         if (conf && conf->cfg_config_u.cfg_net.net_peer_rtr_credits >= 0) {
1368                 ni->ni_peerrtrcredits =
1369                         conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
1370         }
1371         if (conf && conf->cfg_config_u.cfg_net.net_peer_timeout >= 0) {
1372                 ni->ni_peertimeout =
1373                         conf->cfg_config_u.cfg_net.net_peer_timeout;
1374         }
1375
1376         /*
1377          * TODO
1378          * Note: For now, don't allow the user to change
1379          * peertxcredits as this number is used in the
1380          * IB LND to control queue depth.
1381          *
1382          * if (conf && conf->cfg_config_u.cfg_net.net_peer_tx_credits != -1)
1383          *      ni->ni_peertxcredits =
1384          *              conf->cfg_config_u.cfg_net.net_peer_tx_credits;
1385          */
1386         if (conf && conf->cfg_config_u.cfg_net.net_max_tx_credits >= 0) {
1387                 ni->ni_maxtxcredits =
1388                         conf->cfg_config_u.cfg_net.net_max_tx_credits;
1389         }
1390
1391         LASSERT(ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
1392
1393         lnet_net_lock(LNET_LOCK_EX);
1394         /* refcount for ln_nis */
1395         lnet_ni_addref_locked(ni, 0);
1396         list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
1397         if (ni->ni_cpts != NULL) {
1398                 lnet_ni_addref_locked(ni, 0);
1399                 list_add_tail(&ni->ni_cptlist, &the_lnet.ln_nis_cpt);
1400         }
1401
1402         lnet_net_unlock(LNET_LOCK_EX);
1403
1404         if (lnd->lnd_type == LOLND) {
1405                 lnet_ni_addref(ni);
1406                 LASSERT(the_lnet.ln_loni == NULL);
1407                 the_lnet.ln_loni = ni;
1408                 return 0;
1409         }
1410
1411         if (ni->ni_peertxcredits == 0 || ni->ni_maxtxcredits == 0) {
1412                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1413                                    libcfs_lnd2str(lnd->lnd_type),
1414                                    ni->ni_peertxcredits == 0 ?
1415                                         "" : "per-peer ");
1416                 /* shutdown the NI since if we get here then it must've already
1417                  * been started
1418                  */
1419                 lnet_shutdown_lndni(ni);
1420                 return -EINVAL;
1421         }
1422
1423         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
1424                 tq->tq_credits_min =
1425                 tq->tq_credits_max =
1426                 tq->tq_credits = lnet_ni_tq_credits(ni);
1427         }
1428
1429         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1430                 libcfs_nid2str(ni->ni_nid), ni->ni_peertxcredits,
1431                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
1432                 ni->ni_peerrtrcredits, ni->ni_peertimeout);
1433
1434         return 0;
1435 failed0:
1436         lnet_ni_free(ni);
1437         return rc;
1438 }
1439
1440 static int
1441 lnet_startup_lndnis(struct list_head *nilist)
1442 {
1443         struct lnet_ni          *ni;
1444         int                     rc;
1445         int                     ni_count = 0;
1446
1447         while (!list_empty(nilist)) {
1448                 ni = list_entry(nilist->next, lnet_ni_t, ni_list);
1449                 list_del(&ni->ni_list);
1450                 rc = lnet_startup_lndni(ni, NULL);
1451
1452                 if (rc < 0)
1453                         goto failed;
1454
1455                 ni_count++;
1456         }
1457
1458         return ni_count;
1459 failed:
1460         lnet_shutdown_lndnis();
1461
1462         return rc;
1463 }
1464
1465 /**
1466  * Initialize LNet library.
1467  *
1468  * Automatically called at module loading time. Caller has to call
1469  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
1470  * latter returned 0. It must be called exactly once.
1471  *
1472  * \retval 0 on success
1473  * \retval -ve on failures.
1474  */
1475 int lnet_lib_init(void)
1476 {
1477         int rc;
1478
1479         lnet_assert_wire_constants();
1480
1481         memset(&the_lnet, 0, sizeof(the_lnet));
1482
1483         /* refer to global cfs_cpt_table for now */
1484         the_lnet.ln_cpt_table   = cfs_cpt_table;
1485         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
1486
1487         LASSERT(the_lnet.ln_cpt_number > 0);
1488         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
1489                 /* we are under risk of consuming all lh_cookie */
1490                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
1491                        "please change setting of CPT-table and retry\n",
1492                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
1493                 return -E2BIG;
1494         }
1495
1496         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
1497                 the_lnet.ln_cpt_bits++;
1498
1499         rc = lnet_create_locks();
1500         if (rc != 0) {
1501                 CERROR("Can't create LNet global locks: %d\n", rc);
1502                 return rc;
1503         }
1504
1505         the_lnet.ln_refcount = 0;
1506         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1507         INIT_LIST_HEAD(&the_lnet.ln_lnds);
1508         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
1509         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
1510
1511         /* The hash table size is the number of bits it takes to express the set
1512          * ln_num_routes, minus 1 (better to under estimate than over so we
1513          * don't waste memory). */
1514         if (rnet_htable_size <= 0)
1515                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
1516         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
1517                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
1518         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
1519                                            order_base_2(rnet_htable_size) - 1);
1520
1521         /* All LNDs apart from the LOLND are in separate modules.  They
1522          * register themselves when their module loads, and unregister
1523          * themselves when their module is unloaded. */
1524         lnet_register_lnd(&the_lolnd);
1525         return 0;
1526 }
1527
1528 /**
1529  * Finalize LNet library.
1530  *
1531  * \pre lnet_lib_init() called with success.
1532  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1533  */
1534 void lnet_lib_exit(void)
1535 {
1536         LASSERT(the_lnet.ln_refcount == 0);
1537
1538         while (!list_empty(&the_lnet.ln_lnds))
1539                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
1540                                                lnd_t, lnd_list));
1541         lnet_destroy_locks();
1542 }
1543
1544 /**
1545  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1546  *
1547  * Users must call this function at least once before any other functions.
1548  * For each successful call there must be a corresponding call to
1549  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1550  * ignored.
1551  *
1552  * The PID used by LNet may be different from the one requested.
1553  * See LNetGetId().
1554  *
1555  * \param requested_pid PID requested by the caller.
1556  *
1557  * \return >= 0 on success, and < 0 error code on failures.
1558  */
1559 int
1560 LNetNIInit(lnet_pid_t requested_pid)
1561 {
1562         int                     im_a_router = 0;
1563         int                     rc;
1564         int                     ni_count;
1565         lnet_ping_info_t        *pinfo;
1566         lnet_handle_md_t        md_handle;
1567         struct list_head        net_head;
1568
1569         INIT_LIST_HEAD(&net_head);
1570
1571         mutex_lock(&the_lnet.ln_api_mutex);
1572
1573         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1574
1575         if (the_lnet.ln_refcount > 0) {
1576                 rc = the_lnet.ln_refcount++;
1577                 mutex_unlock(&the_lnet.ln_api_mutex);
1578                 return rc;
1579         }
1580
1581         rc = lnet_prepare(requested_pid);
1582         if (rc != 0) {
1583                 mutex_unlock(&the_lnet.ln_api_mutex);
1584                 return rc;
1585         }
1586
1587         /* Add in the loopback network */
1588         if (lnet_ni_alloc(LNET_MKNET(LOLND, 0), NULL, &net_head) == NULL) {
1589                 rc = -ENOMEM;
1590                 goto failed0;
1591         }
1592
1593         /* If LNet is being initialized via DLC it is possible
1594          * that the user requests not to load module parameters (ones which
1595          * are supported by DLC) on initialization.  Therefore, make sure not
1596          * to load networks, routes and forwarding from module parameters
1597          * in this case.  On cleanup in case of failure only clean up
1598          * routes if it has been loaded */
1599         if (!the_lnet.ln_nis_from_mod_params) {
1600                 rc = lnet_parse_networks(&net_head,
1601                                          lnet_get_networks());
1602                 if (rc < 0)
1603                         goto failed0;
1604         }
1605
1606         ni_count = lnet_startup_lndnis(&net_head);
1607         if (ni_count < 0) {
1608                 rc = ni_count;
1609                 goto failed0;
1610         }
1611
1612         if (!the_lnet.ln_nis_from_mod_params) {
1613                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1614                 if (rc != 0)
1615                         goto failed1;
1616
1617                 rc = lnet_check_routes();
1618                 if (rc != 0)
1619                         goto failed2;
1620
1621                 rc = lnet_rtrpools_alloc(im_a_router);
1622                 if (rc != 0)
1623                         goto failed2;
1624         }
1625
1626         rc = lnet_acceptor_start();
1627         if (rc != 0)
1628                 goto failed2;
1629         the_lnet.ln_refcount = 1;
1630         /* Now I may use my own API functions... */
1631
1632         rc = lnet_ping_info_setup(&pinfo, &md_handle, ni_count, true);
1633         if (rc != 0)
1634                 goto failed3;
1635
1636         lnet_ping_target_update(pinfo, md_handle);
1637
1638         rc = lnet_router_checker_start();
1639         if (rc != 0)
1640                 goto failed4;
1641
1642         lnet_fault_init();
1643         lnet_proc_init();
1644
1645         mutex_unlock(&the_lnet.ln_api_mutex);
1646
1647         return 0;
1648
1649 failed4:
1650         lnet_ping_target_fini();
1651 failed3:
1652         the_lnet.ln_refcount = 0;
1653         lnet_acceptor_stop();
1654 failed2:
1655         if (!the_lnet.ln_nis_from_mod_params)
1656                 lnet_destroy_routes();
1657 failed1:
1658         lnet_shutdown_lndnis();
1659 failed0:
1660         lnet_unprepare();
1661         LASSERT(rc < 0);
1662         mutex_unlock(&the_lnet.ln_api_mutex);
1663         while (!list_empty(&net_head)) {
1664                 struct lnet_ni *ni;
1665                 ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1666                 list_del_init(&ni->ni_list);
1667                 lnet_ni_free(ni);
1668         }
1669         return rc;
1670 }
1671 EXPORT_SYMBOL(LNetNIInit);
1672
1673 /**
1674  * Stop LNet interfaces, routing, and forwarding.
1675  *
1676  * Users must call this function once for each successful call to LNetNIInit().
1677  * Once the LNetNIFini() operation has been started, the results of pending
1678  * API operations are undefined.
1679  *
1680  * \return always 0 for current implementation.
1681  */
1682 int
1683 LNetNIFini()
1684 {
1685         mutex_lock(&the_lnet.ln_api_mutex);
1686
1687         LASSERT (the_lnet.ln_refcount > 0);
1688
1689         if (the_lnet.ln_refcount != 1) {
1690                 the_lnet.ln_refcount--;
1691         } else {
1692                 LASSERT(!the_lnet.ln_niinit_self);
1693
1694                 lnet_fault_fini();
1695
1696                 lnet_proc_fini();
1697                 lnet_router_checker_stop();
1698                 lnet_ping_target_fini();
1699
1700                 /* Teardown fns that use my own API functions BEFORE here */
1701                 the_lnet.ln_refcount = 0;
1702
1703                 lnet_acceptor_stop();
1704                 lnet_destroy_routes();
1705                 lnet_shutdown_lndnis();
1706                 lnet_unprepare();
1707         }
1708
1709         mutex_unlock(&the_lnet.ln_api_mutex);
1710         return 0;
1711 }
1712 EXPORT_SYMBOL(LNetNIFini);
1713
1714 /**
1715  * Grabs the ni data from the ni structure and fills the out
1716  * parameters
1717  *
1718  * \param[in] ni network        interface structure
1719  * \param[out] cpt_count        the number of cpts the ni is on
1720  * \param[out] nid              Network Interface ID
1721  * \param[out] peer_timeout     NI peer timeout
1722  * \param[out] peer_tx_crdits   NI peer transmit credits
1723  * \param[out] peer_rtr_credits NI peer router credits
1724  * \param[out] max_tx_credits   NI max transmit credit
1725  * \param[out] net_config       Network configuration
1726  */
1727 static void
1728 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_data *config)
1729 {
1730         struct lnet_ioctl_net_config *net_config;
1731         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
1732         size_t min_size, tunable_size = 0;
1733         int i;
1734
1735         if (!ni || !config)
1736                 return;
1737
1738         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
1739         if (!net_config)
1740                 return;
1741
1742         CLASSERT(ARRAY_SIZE(ni->ni_interfaces) ==
1743                  ARRAY_SIZE(net_config->ni_interfaces));
1744
1745         if (ni->ni_interfaces[0] != NULL) {
1746                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
1747                         if (ni->ni_interfaces[i] != NULL) {
1748                                 strncpy(net_config->ni_interfaces[i],
1749                                         ni->ni_interfaces[i],
1750                                         sizeof(net_config->ni_interfaces[i]));
1751                         }
1752                 }
1753         }
1754
1755         config->cfg_nid = ni->ni_nid;
1756         config->cfg_config_u.cfg_net.net_peer_timeout = ni->ni_peertimeout;
1757         config->cfg_config_u.cfg_net.net_max_tx_credits = ni->ni_maxtxcredits;
1758         config->cfg_config_u.cfg_net.net_peer_tx_credits = ni->ni_peertxcredits;
1759         config->cfg_config_u.cfg_net.net_peer_rtr_credits = ni->ni_peerrtrcredits;
1760
1761         net_config->ni_status = ni->ni_status->ns_status;
1762
1763         for (i = 0;
1764              ni->ni_cpts != NULL && i < ni->ni_ncpts &&
1765              i < LNET_MAX_SHOW_NUM_CPT;
1766              i++)
1767                 net_config->ni_cpts[i] = ni->ni_cpts[i];
1768
1769         config->cfg_ncpts = ni->ni_ncpts;
1770
1771         /*
1772          * See if user land tools sent in a newer and larger version
1773          * of struct lnet_tunables than what the kernel uses.
1774          */
1775         min_size = sizeof(*config) + sizeof(*net_config);
1776
1777         if (config->cfg_hdr.ioc_len > min_size)
1778                 tunable_size = config->cfg_hdr.ioc_len - min_size;
1779
1780         /* Don't copy to much data to user space */
1781         min_size = min(tunable_size, sizeof(*ni->ni_lnd_tunables));
1782         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
1783
1784         if (ni->ni_lnd_tunables && lnd_cfg && min_size) {
1785                 memcpy(lnd_cfg, ni->ni_lnd_tunables, min_size);
1786                 config->cfg_config_u.cfg_net.net_interface_count = 1;
1787
1788                 /* Tell user land that kernel side has less data */
1789                 if (tunable_size > sizeof(*ni->ni_lnd_tunables)) {
1790                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
1791                         config->cfg_hdr.ioc_len -= min_size;
1792                 }
1793         }
1794 }
1795
1796 static int
1797 lnet_get_net_config(struct lnet_ioctl_config_data *config)
1798 {
1799         struct lnet_ni *ni;
1800         struct list_head *tmp;
1801         int idx = config->cfg_count;
1802         int rc = -ENOENT;
1803         int cpt;
1804
1805         if (unlikely(!config->cfg_bulk))
1806                 return -EINVAL;
1807
1808         cpt = lnet_net_lock_current();
1809
1810         list_for_each(tmp, &the_lnet.ln_nis) {
1811                 ni = list_entry(tmp, lnet_ni_t, ni_list);
1812                 if (idx-- == 0) {
1813                         rc = 0;
1814                         lnet_ni_lock(ni);
1815                         lnet_fill_ni_info(ni, config);
1816                         lnet_ni_unlock(ni);
1817                         break;
1818                 }
1819         }
1820
1821         lnet_net_unlock(cpt);
1822         return rc;
1823 }
1824
1825 int
1826 lnet_dyn_add_ni(lnet_pid_t requested_pid, struct lnet_ioctl_config_data *conf)
1827 {
1828         char                    *nets = conf->cfg_config_u.cfg_net.net_intf;
1829         lnet_ping_info_t        *pinfo;
1830         lnet_handle_md_t        md_handle;
1831         struct lnet_ni          *ni;
1832         struct list_head        net_head;
1833         int                     rc;
1834         lnet_remotenet_t        *rnet;
1835
1836         INIT_LIST_HEAD(&net_head);
1837
1838         /* Create a ni structure for the network string */
1839         rc = lnet_parse_networks(&net_head, nets);
1840         if (rc <= 0)
1841                 return rc == 0 ? -EINVAL : rc;
1842
1843         mutex_lock(&the_lnet.ln_api_mutex);
1844
1845         if (rc > 1) {
1846                 rc = -EINVAL; /* only add one interface per call */
1847                 goto failed0;
1848         }
1849
1850         ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1851
1852         lnet_net_lock(LNET_LOCK_EX);
1853         rnet = lnet_find_net_locked(LNET_NIDNET(ni->ni_nid));
1854         lnet_net_unlock(LNET_LOCK_EX);
1855         /* make sure that the net added doesn't invalidate the current
1856          * configuration LNet is keeping */
1857         if (rnet != NULL) {
1858                 CERROR("Adding net %s will invalidate routing configuration\n",
1859                        nets);
1860                 rc = -EUSERS;
1861                 goto failed0;
1862         }
1863
1864         rc = lnet_ping_info_setup(&pinfo, &md_handle, 1 + lnet_get_ni_count(),
1865                                   false);
1866         if (rc != 0)
1867                 goto failed0;
1868
1869         list_del_init(&ni->ni_list);
1870
1871         rc = lnet_startup_lndni(ni, conf);
1872         if (rc != 0)
1873                 goto failed1;
1874
1875         if (ni->ni_lnd->lnd_accept != NULL) {
1876                 rc = lnet_acceptor_start();
1877                 if (rc < 0) {
1878                         /* shutdown the ni that we just started */
1879                         CERROR("Failed to start up acceptor thread\n");
1880                         lnet_shutdown_lndni(ni);
1881                         goto failed1;
1882                 }
1883         }
1884
1885         lnet_ping_target_update(pinfo, md_handle);
1886         mutex_unlock(&the_lnet.ln_api_mutex);
1887
1888         return 0;
1889
1890 failed1:
1891         lnet_ping_md_unlink(pinfo, &md_handle);
1892         lnet_ping_info_free(pinfo);
1893 failed0:
1894         mutex_unlock(&the_lnet.ln_api_mutex);
1895         while (!list_empty(&net_head)) {
1896                 ni = list_entry(net_head.next, struct lnet_ni, ni_list);
1897                 list_del_init(&ni->ni_list);
1898                 lnet_ni_free(ni);
1899         }
1900         return rc;
1901 }
1902
1903 int
1904 lnet_dyn_del_ni(__u32 net)
1905 {
1906         lnet_ni_t        *ni;
1907         lnet_ping_info_t *pinfo;
1908         lnet_handle_md_t  md_handle;
1909         int               rc;
1910
1911         /* don't allow userspace to shutdown the LOLND */
1912         if (LNET_NETTYP(net) == LOLND)
1913                 return -EINVAL;
1914
1915         mutex_lock(&the_lnet.ln_api_mutex);
1916         /* create and link a new ping info, before removing the old one */
1917         rc = lnet_ping_info_setup(&pinfo, &md_handle,
1918                                   lnet_get_ni_count() - 1, false);
1919         if (rc != 0)
1920                 goto out;
1921
1922         ni = lnet_net2ni(net);
1923         if (ni == NULL) {
1924                 rc = -EINVAL;
1925                 goto failed;
1926         }
1927
1928         /* decrement the reference counter taken by lnet_net2ni() */
1929         lnet_ni_decref_locked(ni, 0);
1930
1931         lnet_shutdown_lndni(ni);
1932
1933         if (lnet_count_acceptor_nis() == 0)
1934                 lnet_acceptor_stop();
1935
1936         lnet_ping_target_update(pinfo, md_handle);
1937         goto out;
1938 failed:
1939         lnet_ping_md_unlink(pinfo, &md_handle);
1940         lnet_ping_info_free(pinfo);
1941 out:
1942         mutex_unlock(&the_lnet.ln_api_mutex);
1943
1944         return rc;
1945 }
1946
1947 /**
1948  * LNet ioctl handler.
1949  *
1950  */
1951 int
1952 LNetCtl(unsigned int cmd, void *arg)
1953 {
1954         struct libcfs_ioctl_data *data = arg;
1955         struct lnet_ioctl_config_data *config;
1956         lnet_process_id_t         id = {0};
1957         lnet_ni_t                *ni;
1958         int                       rc;
1959
1960         CLASSERT(LIBCFS_IOC_DATA_MAX >= sizeof(struct lnet_ioctl_net_config) +
1961                                         sizeof(struct lnet_ioctl_config_data));
1962
1963         switch (cmd) {
1964         case IOC_LIBCFS_GET_NI:
1965                 rc = LNetGetId(data->ioc_count, &id);
1966                 data->ioc_nid = id.nid;
1967                 return rc;
1968
1969         case IOC_LIBCFS_FAIL_NID:
1970                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1971
1972         case IOC_LIBCFS_ADD_ROUTE:
1973                 config = arg;
1974
1975                 if (config->cfg_hdr.ioc_len < sizeof(*config))
1976                         return -EINVAL;
1977
1978                 mutex_lock(&the_lnet.ln_api_mutex);
1979                 rc = lnet_add_route(config->cfg_net,
1980                                     config->cfg_config_u.cfg_route.rtr_hop,
1981                                     config->cfg_nid,
1982                                     config->cfg_config_u.cfg_route.
1983                                         rtr_priority);
1984                 if (rc == 0) {
1985                         rc = lnet_check_routes();
1986                         if (rc != 0)
1987                                 lnet_del_route(config->cfg_net,
1988                                                config->cfg_nid);
1989                 }
1990                 mutex_unlock(&the_lnet.ln_api_mutex);
1991                 return rc;
1992
1993         case IOC_LIBCFS_DEL_ROUTE:
1994                 config = arg;
1995
1996                 if (config->cfg_hdr.ioc_len < sizeof(*config))
1997                         return -EINVAL;
1998
1999                 mutex_lock(&the_lnet.ln_api_mutex);
2000                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
2001                 mutex_unlock(&the_lnet.ln_api_mutex);
2002                 return rc;
2003
2004         case IOC_LIBCFS_GET_ROUTE:
2005                 config = arg;
2006
2007                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2008                         return -EINVAL;
2009
2010                 return lnet_get_route(config->cfg_count,
2011                                       &config->cfg_net,
2012                                       &config->cfg_config_u.cfg_route.rtr_hop,
2013                                       &config->cfg_nid,
2014                                       &config->cfg_config_u.cfg_route.rtr_flags,
2015                                       &config->cfg_config_u.cfg_route.
2016                                         rtr_priority);
2017
2018         case IOC_LIBCFS_GET_NET: {
2019                 size_t total = sizeof(*config) +
2020                                sizeof(struct lnet_ioctl_net_config);
2021                 config = arg;
2022
2023                 if (config->cfg_hdr.ioc_len < total)
2024                         return -EINVAL;
2025
2026                 return lnet_get_net_config(config);
2027         }
2028
2029         case IOC_LIBCFS_GET_LNET_STATS:
2030         {
2031                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
2032
2033                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
2034                         return -EINVAL;
2035
2036                 lnet_counters_get(&lnet_stats->st_cntrs);
2037                 return 0;
2038         }
2039
2040         case IOC_LIBCFS_CONFIG_RTR:
2041                 config = arg;
2042
2043                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2044                         return -EINVAL;
2045
2046                 mutex_lock(&the_lnet.ln_api_mutex);
2047                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
2048                         rc = lnet_rtrpools_enable();
2049                         mutex_unlock(&the_lnet.ln_api_mutex);
2050                         return rc;
2051                 }
2052                 lnet_rtrpools_disable();
2053                 mutex_unlock(&the_lnet.ln_api_mutex);
2054                 return 0;
2055
2056         case IOC_LIBCFS_ADD_BUF:
2057                 config = arg;
2058
2059                 if (config->cfg_hdr.ioc_len < sizeof(*config))
2060                         return -EINVAL;
2061
2062                 mutex_lock(&the_lnet.ln_api_mutex);
2063                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
2064                                                 buf_tiny,
2065                                           config->cfg_config_u.cfg_buffers.
2066                                                 buf_small,
2067                                           config->cfg_config_u.cfg_buffers.
2068                                                 buf_large);
2069                 mutex_unlock(&the_lnet.ln_api_mutex);
2070                 return rc;
2071
2072         case IOC_LIBCFS_GET_BUF: {
2073                 struct lnet_ioctl_pool_cfg *pool_cfg;
2074                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
2075
2076                 config = arg;
2077
2078                 if (config->cfg_hdr.ioc_len < total)
2079                         return -EINVAL;
2080
2081                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
2082                 return lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
2083         }
2084
2085         case IOC_LIBCFS_GET_PEER_INFO: {
2086                 struct lnet_ioctl_peer *peer_info = arg;
2087
2088                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
2089                         return -EINVAL;
2090
2091                 return lnet_get_peer_info(
2092                    peer_info->pr_count,
2093                    &peer_info->pr_nid,
2094                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
2095                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
2096                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
2097                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
2098                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
2099                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
2100                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_rtr_credits,
2101                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
2102         }
2103
2104         case IOC_LIBCFS_NOTIFY_ROUTER:
2105                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
2106                                    cfs_time_current() -
2107                                    cfs_time_seconds(cfs_time_current_sec() -
2108                                                     (time_t)data->ioc_u64[0]));
2109
2110         case IOC_LIBCFS_LNET_DIST:
2111                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
2112                 if (rc < 0 && rc != -EHOSTUNREACH)
2113                         return rc;
2114
2115                 data->ioc_u32[0] = rc;
2116                 return 0;
2117
2118         case IOC_LIBCFS_TESTPROTOCOMPAT:
2119                 lnet_net_lock(LNET_LOCK_EX);
2120                 the_lnet.ln_testprotocompat = data->ioc_flags;
2121                 lnet_net_unlock(LNET_LOCK_EX);
2122                 return 0;
2123
2124         case IOC_LIBCFS_LNET_FAULT:
2125                 return lnet_fault_ctl(data->ioc_flags, data);
2126
2127         case IOC_LIBCFS_PING:
2128                 id.nid = data->ioc_nid;
2129                 id.pid = data->ioc_u32[0];
2130                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
2131                                (lnet_process_id_t __user *)data->ioc_pbuf1,
2132                                data->ioc_plen1/sizeof(lnet_process_id_t));
2133                 if (rc < 0)
2134                         return rc;
2135                 data->ioc_count = rc;
2136                 return 0;
2137
2138         default:
2139                 ni = lnet_net2ni(data->ioc_net);
2140                 if (ni == NULL)
2141                         return -EINVAL;
2142
2143                 if (ni->ni_lnd->lnd_ctl == NULL)
2144                         rc = -EINVAL;
2145                 else
2146                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
2147
2148                 lnet_ni_decref(ni);
2149                 return rc;
2150         }
2151         /* not reached */
2152 }
2153 EXPORT_SYMBOL(LNetCtl);
2154
2155 void LNetDebugPeer(lnet_process_id_t id)
2156 {
2157         lnet_debug_peer(id.nid);
2158 }
2159 EXPORT_SYMBOL(LNetDebugPeer);
2160
2161 /**
2162  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
2163  * all interfaces share a same PID, as requested by LNetNIInit().
2164  *
2165  * \param index Index of the interface to look up.
2166  * \param id On successful return, this location will hold the
2167  * lnet_process_id_t ID of the interface.
2168  *
2169  * \retval 0 If an interface exists at \a index.
2170  * \retval -ENOENT If no interface has been found.
2171  */
2172 int
2173 LNetGetId(unsigned int index, lnet_process_id_t *id)
2174 {
2175         struct lnet_ni   *ni;
2176         struct list_head *tmp;
2177         int               cpt;
2178         int               rc = -ENOENT;
2179
2180         LASSERT(the_lnet.ln_refcount > 0);
2181
2182         cpt = lnet_net_lock_current();
2183
2184         list_for_each(tmp, &the_lnet.ln_nis) {
2185                 if (index-- != 0)
2186                         continue;
2187
2188                 ni = list_entry(tmp, lnet_ni_t, ni_list);
2189
2190                 id->nid = ni->ni_nid;
2191                 id->pid = the_lnet.ln_pid;
2192                 rc = 0;
2193                 break;
2194         }
2195
2196         lnet_net_unlock(cpt);
2197         return rc;
2198 }
2199 EXPORT_SYMBOL(LNetGetId);
2200
2201 /**
2202  * Print a string representation of handle \a h into buffer \a str of
2203  * \a len bytes.
2204  */
2205 void
2206 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
2207 {
2208         snprintf(str, len, LPX64, h.cookie);
2209 }
2210 EXPORT_SYMBOL(LNetSnprintHandle);
2211
2212 static int
2213 lnet_ping(lnet_process_id_t id, int timeout_ms, lnet_process_id_t __user *ids,
2214           int n_ids)
2215 {
2216         lnet_handle_eq_t     eqh;
2217         lnet_handle_md_t     mdh;
2218         lnet_event_t         event;
2219         lnet_md_t            md = { NULL };
2220         int                  which;
2221         int                  unlinked = 0;
2222         int                  replied = 0;
2223         const int            a_long_time = 60000; /* mS */
2224         int                  infosz;
2225         lnet_ping_info_t    *info;
2226         lnet_process_id_t    tmpid;
2227         int                  i;
2228         int                  nob;
2229         int                  rc;
2230         int                  rc2;
2231         sigset_t         blocked;
2232
2233         infosz = offsetof(lnet_ping_info_t, pi_ni[n_ids]);
2234
2235         if (n_ids <= 0 ||
2236             id.nid == LNET_NID_ANY ||
2237             timeout_ms > 500000 ||              /* arbitrary limit! */
2238             n_ids > 20)                         /* arbitrary limit! */
2239                 return -EINVAL;
2240
2241         if (id.pid == LNET_PID_ANY)
2242                 id.pid = LNET_PID_LUSTRE;
2243
2244         LIBCFS_ALLOC(info, infosz);
2245         if (info == NULL)
2246                 return -ENOMEM;
2247
2248         /* NB 2 events max (including any unlink event) */
2249         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
2250         if (rc != 0) {
2251                 CERROR("Can't allocate EQ: %d\n", rc);
2252                 goto out_0;
2253         }
2254
2255         /* initialize md content */
2256         md.start     = info;
2257         md.length    = infosz;
2258         md.threshold = 2; /*GET/REPLY*/
2259         md.max_size  = 0;
2260         md.options   = LNET_MD_TRUNCATE;
2261         md.user_ptr  = NULL;
2262         md.eq_handle = eqh;
2263
2264         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
2265         if (rc != 0) {
2266                 CERROR("Can't bind MD: %d\n", rc);
2267                 goto out_1;
2268         }
2269
2270         rc = LNetGet(LNET_NID_ANY, mdh, id,
2271                      LNET_RESERVED_PORTAL,
2272                      LNET_PROTO_PING_MATCHBITS, 0);
2273
2274         if (rc != 0) {
2275                 /* Don't CERROR; this could be deliberate! */
2276
2277                 rc2 = LNetMDUnlink(mdh);
2278                 LASSERT(rc2 == 0);
2279
2280                 /* NB must wait for the UNLINK event below... */
2281                 unlinked = 1;
2282                 timeout_ms = a_long_time;
2283         }
2284
2285         do {
2286                 /* MUST block for unlink to complete */
2287                 if (unlinked)
2288                         blocked = cfs_block_allsigs();
2289
2290                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
2291
2292                 if (unlinked)
2293                         cfs_restore_sigs(blocked);
2294
2295                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
2296                        (rc2 <= 0) ? -1 : event.type,
2297                        (rc2 <= 0) ? -1 : event.status,
2298                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
2299
2300                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
2301
2302                 if (rc2 <= 0 || event.status != 0) {
2303                         /* timeout or error */
2304                         if (!replied && rc == 0)
2305                                 rc = (rc2 < 0) ? rc2 :
2306                                      (rc2 == 0) ? -ETIMEDOUT :
2307                                      event.status;
2308
2309                         if (!unlinked) {
2310                                 /* Ensure completion in finite time... */
2311                                 LNetMDUnlink(mdh);
2312                                 /* No assertion (racing with network) */
2313                                 unlinked = 1;
2314                                 timeout_ms = a_long_time;
2315                         } else if (rc2 == 0) {
2316                                 /* timed out waiting for unlink */
2317                                 CWARN("ping %s: late network completion\n",
2318                                       libcfs_id2str(id));
2319                         }
2320                 } else if (event.type == LNET_EVENT_REPLY) {
2321                         replied = 1;
2322                         rc = event.mlength;
2323                 }
2324
2325         } while (rc2 <= 0 || !event.unlinked);
2326
2327         if (!replied) {
2328                 if (rc >= 0)
2329                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
2330                               libcfs_id2str(id));
2331                 rc = -EIO;
2332                 goto out_1;
2333         }
2334
2335         nob = rc;
2336         LASSERT(nob >= 0 && nob <= infosz);
2337
2338         rc = -EPROTO;                           /* if I can't parse... */
2339
2340         if (nob < 8) {
2341                 /* can't check magic/version */
2342                 CERROR("%s: ping info too short %d\n",
2343                        libcfs_id2str(id), nob);
2344                 goto out_1;
2345         }
2346
2347         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
2348                 lnet_swap_pinginfo(info);
2349         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
2350                 CERROR("%s: Unexpected magic %08x\n",
2351                        libcfs_id2str(id), info->pi_magic);
2352                 goto out_1;
2353         }
2354
2355         if ((info->pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
2356                 CERROR("%s: ping w/o NI status: 0x%x\n",
2357                        libcfs_id2str(id), info->pi_features);
2358                 goto out_1;
2359         }
2360
2361         if (nob < offsetof(lnet_ping_info_t, pi_ni[0])) {
2362                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
2363                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[0]));
2364                 goto out_1;
2365         }
2366
2367         if (info->pi_nnis < n_ids)
2368                 n_ids = info->pi_nnis;
2369
2370         if (nob < offsetof(lnet_ping_info_t, pi_ni[n_ids])) {
2371                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
2372                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[n_ids]));
2373                 goto out_1;
2374         }
2375
2376         rc = -EFAULT;                           /* If I SEGV... */
2377
2378         memset(&tmpid, 0, sizeof(tmpid));
2379         for (i = 0; i < n_ids; i++) {
2380                 tmpid.pid = info->pi_pid;
2381                 tmpid.nid = info->pi_ni[i].ns_nid;
2382                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
2383                         goto out_1;
2384         }
2385         rc = info->pi_nnis;
2386
2387  out_1:
2388         rc2 = LNetEQFree(eqh);
2389         if (rc2 != 0)
2390                 CERROR("rc2 %d\n", rc2);
2391         LASSERT(rc2 == 0);
2392
2393  out_0:
2394         LIBCFS_FREE(info, infosz);
2395         return rc;
2396 }