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