Whamcloud - gitweb
b=22860 lnet_msg_alloc does double memset to zero
[fs/lustre-release.git] / lnet / lnet / api-ni.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
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
40 #ifdef __KERNEL__
41 #define D_LNI D_CONSOLE
42 #else
43 #define D_LNI D_CONFIG
44 #endif
45
46 lnet_t      the_lnet;                           /* THE state of the network */
47
48 #ifdef __KERNEL__
49
50 static char *ip2nets = "";
51 CFS_MODULE_PARM(ip2nets, "s", charp, 0444,
52                 "LNET network <- IP table");
53
54 static char *networks = "";
55 CFS_MODULE_PARM(networks, "s", charp, 0444,
56                 "local networks");
57
58 static char *routes = "";
59 CFS_MODULE_PARM(routes, "s", charp, 0444,
60                 "routes to non-local networks");
61
62 char *
63 lnet_get_routes(void)
64 {
65         return routes;
66 }
67
68 char *
69 lnet_get_networks(void)
70 {
71         char   *nets;
72         int     rc;
73
74         if (*networks != 0 && *ip2nets != 0) {
75                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
76                                    "'ip2nets' but not both at once\n");
77                 return NULL;
78         }
79
80         if (*ip2nets != 0) {
81                 rc = lnet_parse_ip2nets(&nets, ip2nets);
82                 return (rc == 0) ? nets : NULL;
83         }
84
85         if (*networks != 0)
86                 return networks;
87
88         return "tcp";
89 }
90
91 void
92 lnet_init_locks(void)
93 {
94         cfs_spin_lock_init (&the_lnet.ln_lock);
95         cfs_waitq_init (&the_lnet.ln_waitq);
96         cfs_init_mutex(&the_lnet.ln_lnd_mutex);
97         cfs_init_mutex(&the_lnet.ln_api_mutex);
98 }
99
100 void
101 lnet_fini_locks(void)
102 {
103 }
104
105 #else
106
107 char *
108 lnet_get_routes(void)
109 {
110         char *str = getenv("LNET_ROUTES");
111
112         return (str == NULL) ? "" : str;
113 }
114
115 char *
116 lnet_get_networks (void)
117 {
118         static char       default_networks[256];
119         char             *networks = getenv ("LNET_NETWORKS");
120         char             *ip2nets  = getenv ("LNET_IP2NETS");
121         char             *str;
122         char             *sep;
123         int               len;
124         int               nob;
125         int               rc;
126         cfs_list_t       *tmp;
127
128 #ifdef NOT_YET
129         if (networks != NULL && ip2nets != NULL) {
130                 LCONSOLE_ERROR_MSG(0x103, "Please set EITHER 'LNET_NETWORKS' or"
131                                    " 'LNET_IP2NETS' but not both at once\n");
132                 return NULL;
133         }
134
135         if (ip2nets != NULL) {
136                 rc = lnet_parse_ip2nets(&networks, ip2nets);
137                 return (rc == 0) ? networks : NULL;
138         }
139 #else
140         ip2nets = NULL;
141         rc = 0;
142 #endif
143         if (networks != NULL)
144                 return networks;
145
146         /* In userland, the default 'networks=' is the list of known net types */
147
148         len = sizeof(default_networks);
149         str = default_networks;
150         *str = 0;
151         sep = "";
152
153         cfs_list_for_each (tmp, &the_lnet.ln_lnds) {
154                 lnd_t *lnd = cfs_list_entry(tmp, lnd_t, lnd_list);
155
156                 nob = snprintf(str, len, "%s%s", sep,
157                                libcfs_lnd2str(lnd->lnd_type));
158                 len -= nob;
159                 if (len < 0) {
160                         /* overflowed the string; leave it where it was */
161                         *str = 0;
162                         break;
163                 }
164
165                 str += nob;
166                 sep = ",";
167         }
168
169         return default_networks;
170 }
171
172 # ifndef HAVE_LIBPTHREAD
173
174 void lnet_init_locks(void)
175 {
176         the_lnet.ln_lock = 0;
177         the_lnet.ln_lnd_mutex = 0;
178         the_lnet.ln_api_mutex = 0;
179 }
180
181 void lnet_fini_locks(void)
182 {
183         LASSERT (the_lnet.ln_api_mutex == 0);
184         LASSERT (the_lnet.ln_lnd_mutex == 0);
185         LASSERT (the_lnet.ln_lock == 0);
186 }
187
188 # else
189
190 void lnet_init_locks(void)
191 {
192         pthread_cond_init(&the_lnet.ln_cond, NULL);
193         pthread_mutex_init(&the_lnet.ln_lock, NULL);
194         pthread_mutex_init(&the_lnet.ln_lnd_mutex, NULL);
195         pthread_mutex_init(&the_lnet.ln_api_mutex, NULL);
196 }
197
198 void lnet_fini_locks(void)
199 {
200         pthread_mutex_destroy(&the_lnet.ln_api_mutex);
201         pthread_mutex_destroy(&the_lnet.ln_lnd_mutex);
202         pthread_mutex_destroy(&the_lnet.ln_lock);
203         pthread_cond_destroy(&the_lnet.ln_cond);
204 }
205
206 # endif
207 #endif
208
209 void lnet_assert_wire_constants (void)
210 {
211         /* Wire protocol assertions generated by 'wirecheck'
212          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
213          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
214          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
215
216         /* Constants... */
217         CLASSERT (LNET_PROTO_TCP_MAGIC == 0xeebc0ded);
218         CLASSERT (LNET_PROTO_TCP_VERSION_MAJOR == 1);
219         CLASSERT (LNET_PROTO_TCP_VERSION_MINOR == 0);
220         CLASSERT (LNET_MSG_ACK == 0);
221         CLASSERT (LNET_MSG_PUT == 1);
222         CLASSERT (LNET_MSG_GET == 2);
223         CLASSERT (LNET_MSG_REPLY == 3);
224         CLASSERT (LNET_MSG_HELLO == 4);
225
226         /* Checks for struct ptl_handle_wire_t */
227         CLASSERT ((int)sizeof(lnet_handle_wire_t) == 16);
228         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_interface_cookie) == 0);
229         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_interface_cookie) == 8);
230         CLASSERT ((int)offsetof(lnet_handle_wire_t, wh_object_cookie) == 8);
231         CLASSERT ((int)sizeof(((lnet_handle_wire_t *)0)->wh_object_cookie) == 8);
232
233         /* Checks for struct lnet_magicversion_t */
234         CLASSERT ((int)sizeof(lnet_magicversion_t) == 8);
235         CLASSERT ((int)offsetof(lnet_magicversion_t, magic) == 0);
236         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->magic) == 4);
237         CLASSERT ((int)offsetof(lnet_magicversion_t, version_major) == 4);
238         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_major) == 2);
239         CLASSERT ((int)offsetof(lnet_magicversion_t, version_minor) == 6);
240         CLASSERT ((int)sizeof(((lnet_magicversion_t *)0)->version_minor) == 2);
241
242         /* Checks for struct lnet_hdr_t */
243         CLASSERT ((int)sizeof(lnet_hdr_t) == 72);
244         CLASSERT ((int)offsetof(lnet_hdr_t, dest_nid) == 0);
245         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_nid) == 8);
246         CLASSERT ((int)offsetof(lnet_hdr_t, src_nid) == 8);
247         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_nid) == 8);
248         CLASSERT ((int)offsetof(lnet_hdr_t, dest_pid) == 16);
249         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->dest_pid) == 4);
250         CLASSERT ((int)offsetof(lnet_hdr_t, src_pid) == 20);
251         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->src_pid) == 4);
252         CLASSERT ((int)offsetof(lnet_hdr_t, type) == 24);
253         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->type) == 4);
254         CLASSERT ((int)offsetof(lnet_hdr_t, payload_length) == 28);
255         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->payload_length) == 4);
256         CLASSERT ((int)offsetof(lnet_hdr_t, msg) == 32);
257         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg) == 40);
258
259         /* Ack */
260         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.dst_wmd) == 32);
261         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.dst_wmd) == 16);
262         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.match_bits) == 48);
263         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.match_bits) == 8);
264         CLASSERT ((int)offsetof(lnet_hdr_t, msg.ack.mlength) == 56);
265         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.ack.mlength) == 4);
266
267         /* Put */
268         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ack_wmd) == 32);
269         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ack_wmd) == 16);
270         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.match_bits) == 48);
271         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.match_bits) == 8);
272         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.hdr_data) == 56);
273         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.hdr_data) == 8);
274         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.ptl_index) == 64);
275         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.ptl_index) == 4);
276         CLASSERT ((int)offsetof(lnet_hdr_t, msg.put.offset) == 68);
277         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.put.offset) == 4);
278
279         /* Get */
280         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.return_wmd) == 32);
281         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.return_wmd) == 16);
282         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.match_bits) == 48);
283         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.match_bits) == 8);
284         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.ptl_index) == 56);
285         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.ptl_index) == 4);
286         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.src_offset) == 60);
287         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.src_offset) == 4);
288         CLASSERT ((int)offsetof(lnet_hdr_t, msg.get.sink_length) == 64);
289         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.get.sink_length) == 4);
290
291         /* Reply */
292         CLASSERT ((int)offsetof(lnet_hdr_t, msg.reply.dst_wmd) == 32);
293         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.reply.dst_wmd) == 16);
294
295         /* Hello */
296         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.incarnation) == 32);
297         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.incarnation) == 8);
298         CLASSERT ((int)offsetof(lnet_hdr_t, msg.hello.type) == 40);
299         CLASSERT ((int)sizeof(((lnet_hdr_t *)0)->msg.hello.type) == 4);
300 }
301
302 lnd_t *
303 lnet_find_lnd_by_type (int type)
304 {
305         lnd_t              *lnd;
306         cfs_list_t         *tmp;
307
308         /* holding lnd mutex */
309         cfs_list_for_each (tmp, &the_lnet.ln_lnds) {
310                 lnd = cfs_list_entry(tmp, lnd_t, lnd_list);
311
312                 if ((int)lnd->lnd_type == type)
313                         return lnd;
314         }
315
316         return NULL;
317 }
318
319 void
320 lnet_register_lnd (lnd_t *lnd)
321 {
322         LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
323
324         LASSERT (the_lnet.ln_init);
325         LASSERT (libcfs_isknown_lnd(lnd->lnd_type));
326         LASSERT (lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
327
328         cfs_list_add_tail (&lnd->lnd_list, &the_lnet.ln_lnds);
329         lnd->lnd_refcount = 0;
330
331         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
332
333         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
334 }
335
336 void
337 lnet_unregister_lnd (lnd_t *lnd)
338 {
339         LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
340
341         LASSERT (the_lnet.ln_init);
342         LASSERT (lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
343         LASSERT (lnd->lnd_refcount == 0);
344
345         cfs_list_del (&lnd->lnd_list);
346         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
347
348         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
349 }
350
351 #ifndef LNET_USE_LIB_FREELIST
352
353 int
354 lnet_descriptor_setup (void)
355 {
356         return 0;
357 }
358
359 void
360 lnet_descriptor_cleanup (void)
361 {
362 }
363
364 #else
365
366 int
367 lnet_freelist_init (lnet_freelist_t *fl, int n, int size)
368 {
369         char *space;
370
371         LASSERT (n > 0);
372
373         size += offsetof (lnet_freeobj_t, fo_contents);
374
375         LIBCFS_ALLOC(space, n * size);
376         if (space == NULL)
377                 return (-ENOMEM);
378
379         CFS_INIT_LIST_HEAD (&fl->fl_list);
380         fl->fl_objs = space;
381         fl->fl_nobjs = n;
382         fl->fl_objsize = size;
383
384         do
385         {
386                 memset (space, 0, size);
387                 cfs_list_add ((cfs_list_t *)space, &fl->fl_list);
388                 space += size;
389         } while (--n != 0);
390
391         return (0);
392 }
393
394 void
395 lnet_freelist_fini (lnet_freelist_t *fl)
396 {
397         cfs_list_t       *el;
398         int               count;
399
400         if (fl->fl_nobjs == 0)
401                 return;
402
403         count = 0;
404         for (el = fl->fl_list.next; el != &fl->fl_list; el = el->next)
405                 count++;
406
407         LASSERT (count == fl->fl_nobjs);
408
409         LIBCFS_FREE(fl->fl_objs, fl->fl_nobjs * fl->fl_objsize);
410         memset (fl, 0, sizeof (*fl));
411 }
412
413 int
414 lnet_descriptor_setup (void)
415 {
416         /* NB on failure caller must still call lnet_descriptor_cleanup */
417         /*               ******                                         */
418         int        rc;
419
420         memset (&the_lnet.ln_free_mes,  0, sizeof (the_lnet.ln_free_mes));
421         memset (&the_lnet.ln_free_msgs, 0, sizeof (the_lnet.ln_free_msgs));
422         memset (&the_lnet.ln_free_mds,  0, sizeof (the_lnet.ln_free_mds));
423         memset (&the_lnet.ln_free_eqs,  0, sizeof (the_lnet.ln_free_eqs));
424
425         rc = lnet_freelist_init(&the_lnet.ln_free_mes,
426                                 MAX_MES, sizeof (lnet_me_t));
427         if (rc != 0)
428                 return (rc);
429
430         rc = lnet_freelist_init(&the_lnet.ln_free_msgs,
431                                 MAX_MSGS, sizeof (lnet_msg_t));
432         if (rc != 0)
433                 return (rc);
434
435         rc = lnet_freelist_init(&the_lnet.ln_free_mds,
436                                 MAX_MDS, sizeof (lnet_libmd_t));
437         if (rc != 0)
438                 return (rc);
439
440         rc = lnet_freelist_init(&the_lnet.ln_free_eqs,
441                                 MAX_EQS, sizeof (lnet_eq_t));
442         return (rc);
443 }
444
445 void
446 lnet_descriptor_cleanup (void)
447 {
448         lnet_freelist_fini (&the_lnet.ln_free_mes);
449         lnet_freelist_fini (&the_lnet.ln_free_msgs);
450         lnet_freelist_fini (&the_lnet.ln_free_mds);
451         lnet_freelist_fini (&the_lnet.ln_free_eqs);
452 }
453
454 #endif
455
456 __u64
457 lnet_create_interface_cookie (void)
458 {
459         /* NB the interface cookie in wire handles guards against delayed
460          * replies and ACKs appearing valid after reboot. Initialisation time,
461          * even if it's only implemented to millisecond resolution is probably
462          * easily good enough. */
463         struct timeval tv;
464         __u64          cookie;
465 #ifndef __KERNEL__
466         int            rc = gettimeofday (&tv, NULL);
467         LASSERT (rc == 0);
468 #else
469         cfs_gettimeofday(&tv);
470 #endif
471         cookie = tv.tv_sec;
472         cookie *= 1000000;
473         cookie += tv.tv_usec;
474         return cookie;
475 }
476
477 int
478 lnet_setup_handle_hash (void)
479 {
480         int       i;
481
482         /* Arbitrary choice of hash table size */
483 #ifdef __KERNEL__
484         the_lnet.ln_lh_hash_size =
485                 (2 * CFS_PAGE_SIZE) / sizeof (cfs_list_t);
486 #else
487         the_lnet.ln_lh_hash_size = (MAX_MES + MAX_MDS + MAX_EQS)/4;
488 #endif
489         LIBCFS_ALLOC(the_lnet.ln_lh_hash_table,
490                      the_lnet.ln_lh_hash_size * sizeof (cfs_list_t));
491         if (the_lnet.ln_lh_hash_table == NULL)
492                 return (-ENOMEM);
493
494         for (i = 0; i < the_lnet.ln_lh_hash_size; i++)
495                 CFS_INIT_LIST_HEAD (&the_lnet.ln_lh_hash_table[i]);
496
497         the_lnet.ln_next_object_cookie = LNET_COOKIE_TYPES;
498
499         return (0);
500 }
501
502 void
503 lnet_cleanup_handle_hash (void)
504 {
505         if (the_lnet.ln_lh_hash_table == NULL)
506                 return;
507
508         LIBCFS_FREE(the_lnet.ln_lh_hash_table,
509                     the_lnet.ln_lh_hash_size * sizeof (cfs_list_t));
510 }
511
512 lnet_libhandle_t *
513 lnet_lookup_cookie (__u64 cookie, int type)
514 {
515         /* ALWAYS called with LNET_LOCK held */
516         cfs_list_t          *list;
517         cfs_list_t          *el;
518         unsigned int         hash;
519
520         if ((cookie & (LNET_COOKIE_TYPES - 1)) != type)
521                 return (NULL);
522
523         hash = ((unsigned int)(cookie >> LNET_COOKIE_TYPE_BITS)) % the_lnet.ln_lh_hash_size;
524         list = &the_lnet.ln_lh_hash_table[hash];
525
526         cfs_list_for_each (el, list) {
527                 lnet_libhandle_t *lh = cfs_list_entry (el, lnet_libhandle_t,
528                                                       lh_hash_chain);
529
530                 if (lh->lh_cookie == cookie)
531                         return (lh);
532         }
533
534         return (NULL);
535 }
536
537 void
538 lnet_initialise_handle (lnet_libhandle_t *lh, int type)
539 {
540         /* ALWAYS called with LNET_LOCK held */
541         unsigned int    hash;
542
543         LASSERT (type >= 0 && type < LNET_COOKIE_TYPES);
544         lh->lh_cookie = the_lnet.ln_next_object_cookie | type;
545         the_lnet.ln_next_object_cookie += LNET_COOKIE_TYPES;
546
547         hash = ((unsigned int)(lh->lh_cookie >> LNET_COOKIE_TYPE_BITS)) % the_lnet.ln_lh_hash_size;
548         cfs_list_add (&lh->lh_hash_chain, &the_lnet.ln_lh_hash_table[hash]);
549 }
550
551 void
552 lnet_invalidate_handle (lnet_libhandle_t *lh)
553 {
554         /* ALWAYS called with LNET_LOCK held */
555         cfs_list_del (&lh->lh_hash_chain);
556 }
557
558 cfs_list_t *
559 lnet_portal_mhash_alloc(void)
560 {
561         cfs_list_t       *mhash;
562         int               i;
563
564         LIBCFS_ALLOC(mhash, sizeof(cfs_list_t) * LNET_PORTAL_HASH_SIZE);
565         if (mhash == NULL)
566                 return NULL;
567
568         for (i = 0; i < LNET_PORTAL_HASH_SIZE; i++)
569                 CFS_INIT_LIST_HEAD(&mhash[i]);
570
571         return mhash;
572 }
573
574 void
575 lnet_portal_mhash_free(cfs_list_t *mhash)
576 {
577         int     i;
578
579         for (i = 0; i < LNET_PORTAL_HASH_SIZE; i++) {
580                 while (!cfs_list_empty(&mhash[i])) {
581                         lnet_me_t *me = cfs_list_entry(mhash[i].next,
582                                                        lnet_me_t, me_list);
583                         CERROR ("Active ME %p on exit portal mhash\n", me);
584                         cfs_list_del(&me->me_list);
585                         lnet_me_free(me);
586                 }
587         }
588         LIBCFS_FREE(mhash, sizeof(cfs_list_t) * LNET_PORTAL_HASH_SIZE);
589 }
590
591 int
592 lnet_init_finalizers(void)
593 {
594 #ifdef __KERNEL__
595         int    i;
596
597         the_lnet.ln_nfinalizers = (int) cfs_num_online_cpus();
598
599         LIBCFS_ALLOC(the_lnet.ln_finalizers,
600                      the_lnet.ln_nfinalizers *
601                      sizeof(*the_lnet.ln_finalizers));
602         if (the_lnet.ln_finalizers == NULL) {
603                 CERROR("Can't allocate ln_finalizers\n");
604                 return -ENOMEM;
605         }
606
607         for (i = 0; i < the_lnet.ln_nfinalizers; i++)
608                 the_lnet.ln_finalizers[i] = NULL;
609 #else
610         the_lnet.ln_finalizing = 0;
611 #endif
612
613         CFS_INIT_LIST_HEAD(&the_lnet.ln_finalizeq);
614         return 0;
615 }
616
617 void
618 lnet_fini_finalizers(void)
619 {
620 #ifdef __KERNEL__
621         int    i;
622
623         for (i = 0; i < the_lnet.ln_nfinalizers; i++)
624                 LASSERT (the_lnet.ln_finalizers[i] == NULL);
625
626         LIBCFS_FREE(the_lnet.ln_finalizers,
627                     the_lnet.ln_nfinalizers *
628                     sizeof(*the_lnet.ln_finalizers));
629 #else
630         LASSERT (!the_lnet.ln_finalizing);
631 #endif
632         LASSERT (cfs_list_empty(&the_lnet.ln_finalizeq));
633 }
634
635 #ifndef __KERNEL__
636 /**
637  * Reserved API - do not use.
638  * Temporary workaround to allow uOSS and test programs force server
639  * mode in userspace. See comments near ln_server_mode_flag in
640  * lnet/lib-types.h */
641
642 void
643 lnet_server_mode() {
644         the_lnet.ln_server_mode_flag = 1;
645 }
646 #endif
647
648 int
649 lnet_prepare(lnet_pid_t requested_pid)
650 {
651         /* Prepare to bring up the network */
652         int               rc = 0;
653         int               i;
654
655         LASSERT (the_lnet.ln_refcount == 0);
656
657         the_lnet.ln_routing = 0;
658
659 #ifdef __KERNEL__
660         LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
661         the_lnet.ln_pid = requested_pid;
662 #else
663         if (the_lnet.ln_server_mode_flag) {/* server case (uOSS) */
664                 LASSERT ((requested_pid & LNET_PID_USERFLAG) == 0);
665
666                 if (cfs_curproc_uid())/* Only root can run user-space server */
667                         return -EPERM;
668                 the_lnet.ln_pid = requested_pid;
669
670         } else {/* client case (liblustre) */
671
672                 /* My PID must be unique on this node and flag I'm userspace */
673                 the_lnet.ln_pid = getpid() | LNET_PID_USERFLAG;
674         }
675 #endif
676
677         rc = lnet_descriptor_setup();
678         if (rc != 0)
679                 goto failed0;
680
681         memset(&the_lnet.ln_counters, 0,
682                sizeof(the_lnet.ln_counters));
683
684         CFS_INIT_LIST_HEAD (&the_lnet.ln_active_msgs);
685         CFS_INIT_LIST_HEAD (&the_lnet.ln_active_mds);
686         CFS_INIT_LIST_HEAD (&the_lnet.ln_active_eqs);
687         CFS_INIT_LIST_HEAD (&the_lnet.ln_test_peers);
688         CFS_INIT_LIST_HEAD (&the_lnet.ln_nis);
689         CFS_INIT_LIST_HEAD (&the_lnet.ln_zombie_nis);
690         CFS_INIT_LIST_HEAD (&the_lnet.ln_remote_nets);
691         CFS_INIT_LIST_HEAD (&the_lnet.ln_routers);
692
693         the_lnet.ln_interface_cookie = lnet_create_interface_cookie();
694
695         lnet_init_rtrpools();
696
697         rc = lnet_setup_handle_hash ();
698         if (rc != 0)
699                 goto failed0;
700
701         rc = lnet_create_peer_table();
702         if (rc != 0)
703                 goto failed1;
704
705         rc = lnet_init_finalizers();
706         if (rc != 0)
707                 goto failed2;
708
709         the_lnet.ln_nportals = MAX_PORTALS;
710         LIBCFS_ALLOC(the_lnet.ln_portals,
711                      the_lnet.ln_nportals *
712                      sizeof(*the_lnet.ln_portals));
713         if (the_lnet.ln_portals == NULL) {
714                 rc = -ENOMEM;
715                 goto failed3;
716         }
717
718         for (i = 0; i < the_lnet.ln_nportals; i++) {
719                 CFS_INIT_LIST_HEAD(&(the_lnet.ln_portals[i].ptl_mlist));
720                 CFS_INIT_LIST_HEAD(&(the_lnet.ln_portals[i].ptl_msgq));
721                 the_lnet.ln_portals[i].ptl_options = 0;
722         }
723
724         return 0;
725
726  failed3:
727         lnet_fini_finalizers();
728  failed2:
729         lnet_destroy_peer_table();
730  failed1:
731         lnet_cleanup_handle_hash();
732  failed0:
733         lnet_descriptor_cleanup();
734         return rc;
735 }
736
737 int
738 lnet_unprepare (void)
739 {
740         int       idx;
741
742         /* NB no LNET_LOCK since this is the last reference.  All LND instances
743          * have shut down already, so it is safe to unlink and free all
744          * descriptors, even those that appear committed to a network op (eg MD
745          * with non-zero pending count) */
746
747         lnet_fail_nid(LNET_NID_ANY, 0);
748
749         LASSERT (cfs_list_empty(&the_lnet.ln_test_peers));
750         LASSERT (the_lnet.ln_refcount == 0);
751         LASSERT (cfs_list_empty(&the_lnet.ln_nis));
752         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
753         LASSERT (the_lnet.ln_nzombie_nis == 0);
754
755         for (idx = 0; idx < the_lnet.ln_nportals; idx++) {
756                 lnet_portal_t *ptl = &the_lnet.ln_portals[idx];
757
758                 LASSERT (cfs_list_empty(&ptl->ptl_msgq));
759
760                 while (!cfs_list_empty(&ptl->ptl_mlist)) {
761                         lnet_me_t *me = cfs_list_entry(ptl->ptl_mlist.next,
762                                                        lnet_me_t, me_list);
763                         CERROR ("Active ME %p on exit\n", me);
764                         cfs_list_del (&me->me_list);
765                         lnet_me_free (me);
766                 }
767
768                 if (ptl->ptl_mhash != NULL) {
769                         LASSERT (lnet_portal_is_unique(ptl));
770                         lnet_portal_mhash_free(ptl->ptl_mhash);
771                 }
772         }
773
774         while (!cfs_list_empty (&the_lnet.ln_active_mds)) {
775                 lnet_libmd_t *md = cfs_list_entry (the_lnet.ln_active_mds.next,
776                                                    lnet_libmd_t, md_list);
777
778                 CERROR ("Active MD %p on exit\n", md);
779                 cfs_list_del_init (&md->md_list);
780                 lnet_md_free (md);
781         }
782
783         while (!cfs_list_empty (&the_lnet.ln_active_eqs)) {
784                 lnet_eq_t *eq = cfs_list_entry (the_lnet.ln_active_eqs.next,
785                                                 lnet_eq_t, eq_list);
786
787                 CERROR ("Active EQ %p on exit\n", eq);
788                 cfs_list_del (&eq->eq_list);
789                 lnet_eq_free (eq);
790         }
791
792         while (!cfs_list_empty (&the_lnet.ln_active_msgs)) {
793                 lnet_msg_t *msg = cfs_list_entry (the_lnet.ln_active_msgs.next,
794                                                   lnet_msg_t, msg_activelist);
795
796                 CERROR ("Active msg %p on exit\n", msg);
797                 LASSERT (msg->msg_onactivelist);
798                 msg->msg_onactivelist = 0;
799                 cfs_list_del (&msg->msg_activelist);
800                 lnet_msg_free (msg);
801         }
802
803         LIBCFS_FREE(the_lnet.ln_portals,  
804                     the_lnet.ln_nportals * sizeof(*the_lnet.ln_portals));
805
806         lnet_free_rtrpools();
807         lnet_fini_finalizers();
808         lnet_destroy_peer_table();
809         lnet_cleanup_handle_hash();
810         lnet_descriptor_cleanup();
811
812         return (0);
813 }
814
815 lnet_ni_t  *
816 lnet_net2ni_locked (__u32 net)
817 {
818         cfs_list_t       *tmp;
819         lnet_ni_t        *ni;
820
821         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
822                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
823
824                 if (LNET_NIDNET(ni->ni_nid) == net) {
825                         lnet_ni_addref_locked(ni);
826                         return ni;
827                 }
828         }
829
830         return NULL;
831 }
832
833 int
834 lnet_islocalnet (__u32 net)
835 {
836         lnet_ni_t        *ni;
837
838         LNET_LOCK();
839         ni = lnet_net2ni_locked(net);
840         if (ni != NULL)
841                 lnet_ni_decref_locked(ni);
842         LNET_UNLOCK();
843
844         return ni != NULL;
845 }
846
847 lnet_ni_t  *
848 lnet_nid2ni_locked (lnet_nid_t nid)
849 {
850         cfs_list_t       *tmp;
851         lnet_ni_t        *ni;
852
853         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
854                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
855
856                 if (ni->ni_nid == nid) {
857                         lnet_ni_addref_locked(ni);
858                         return ni;
859                 }
860         }
861
862         return NULL;
863 }
864
865 int
866 lnet_islocalnid (lnet_nid_t nid)
867 {
868         lnet_ni_t     *ni;
869
870         LNET_LOCK();
871         ni = lnet_nid2ni_locked(nid);
872         if (ni != NULL)
873                 lnet_ni_decref_locked(ni);
874         LNET_UNLOCK();
875
876         return ni != NULL;
877 }
878
879 int
880 lnet_count_acceptor_nis (void)
881 {
882         /* Return the # of NIs that need the acceptor. */
883         int            count = 0;
884 #if defined(__KERNEL__) || defined(HAVE_LIBPTHREAD)
885         cfs_list_t    *tmp;
886         lnet_ni_t     *ni;
887
888         LNET_LOCK();
889         cfs_list_for_each (tmp, &the_lnet.ln_nis) {
890                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
891
892                 if (ni->ni_lnd->lnd_accept != NULL)
893                         count++;
894         }
895
896         LNET_UNLOCK();
897
898 #endif /* defined(__KERNEL__) || defined(HAVE_LIBPTHREAD) */
899         return count;
900 }
901
902 void
903 lnet_shutdown_lndnis (void)
904 {
905         int                i;
906         int                islo;
907         lnet_ni_t         *ni;
908
909         /* NB called holding the global mutex */
910
911         /* All quiet on the API front */
912         LASSERT (!the_lnet.ln_shutdown);
913         LASSERT (the_lnet.ln_refcount == 0);
914         LASSERT (cfs_list_empty(&the_lnet.ln_zombie_nis));
915         LASSERT (the_lnet.ln_nzombie_nis == 0);
916         LASSERT (cfs_list_empty(&the_lnet.ln_remote_nets));
917
918         LNET_LOCK();
919         the_lnet.ln_shutdown = 1;               /* flag shutdown */
920
921         /* Unlink NIs from the global table */
922         while (!cfs_list_empty(&the_lnet.ln_nis)) {
923                 ni = cfs_list_entry(the_lnet.ln_nis.next,
924                                     lnet_ni_t, ni_list);
925                 cfs_list_del (&ni->ni_list);
926
927                 the_lnet.ln_nzombie_nis++;
928                 lnet_ni_decref_locked(ni); /* drop apini's ref */
929         }
930
931         /* Drop the cached eqwait NI. */
932         if (the_lnet.ln_eqwaitni != NULL) {
933                 lnet_ni_decref_locked(the_lnet.ln_eqwaitni);
934                 the_lnet.ln_eqwaitni = NULL;
935         }
936
937         /* Drop the cached loopback NI. */
938         if (the_lnet.ln_loni != NULL) {
939                 lnet_ni_decref_locked(the_lnet.ln_loni);
940                 the_lnet.ln_loni = NULL;
941         }
942
943         LNET_UNLOCK();
944
945         /* Clear lazy portals and drop delayed messages which hold refs
946          * on their lnet_msg_t::msg_rxpeer */
947         for (i = 0; i < the_lnet.ln_nportals; i++)
948                 LNetClearLazyPortal(i);
949
950         /* Clear the peer table and wait for all peers to go (they hold refs on
951          * their NIs) */
952         lnet_clear_peer_table();
953
954         LNET_LOCK();
955         /* Now wait for the NI's I just nuked to show up on apini_zombie_nis
956          * and shut them down in guaranteed thread context */
957         i = 2;
958         while (the_lnet.ln_nzombie_nis != 0) {
959
960                 while (cfs_list_empty(&the_lnet.ln_zombie_nis)) {
961                         LNET_UNLOCK();
962                         ++i;
963                         if ((i & (-i)) == i)
964                                 CDEBUG(D_WARNING,"Waiting for %d zombie NIs\n",
965                                        the_lnet.ln_nzombie_nis);
966                         cfs_pause(cfs_time_seconds(1));
967                         LNET_LOCK();
968                 }
969
970                 ni = cfs_list_entry(the_lnet.ln_zombie_nis.next,
971                                     lnet_ni_t, ni_list);
972                 cfs_list_del(&ni->ni_list);
973                 ni->ni_lnd->lnd_refcount--;
974
975                 LNET_UNLOCK();
976
977                 islo = ni->ni_lnd->lnd_type == LOLND;
978
979                 LASSERT (!cfs_in_interrupt ());
980                 (ni->ni_lnd->lnd_shutdown)(ni);
981
982                 /* can't deref lnd anymore now; it might have unregistered
983                  * itself...  */
984
985                 if (!islo)
986                         CDEBUG(D_LNI, "Removed LNI %s\n",
987                                libcfs_nid2str(ni->ni_nid));
988
989                 LIBCFS_FREE(ni, sizeof(*ni));
990
991                 LNET_LOCK();
992                 the_lnet.ln_nzombie_nis--;
993         }
994
995         the_lnet.ln_shutdown = 0;
996         LNET_UNLOCK();
997
998         if (the_lnet.ln_network_tokens != NULL) {
999                 LIBCFS_FREE(the_lnet.ln_network_tokens,
1000                             the_lnet.ln_network_tokens_nob);
1001                 the_lnet.ln_network_tokens = NULL;
1002         }
1003 }
1004
1005 int
1006 lnet_startup_lndnis (void)
1007 {
1008         lnd_t             *lnd;
1009         lnet_ni_t         *ni;
1010         cfs_list_t         nilist;
1011         int                rc = 0;
1012         int                lnd_type;
1013         int                nicount = 0;
1014         char              *nets = lnet_get_networks();
1015
1016         CFS_INIT_LIST_HEAD(&nilist);
1017
1018         if (nets == NULL)
1019                 goto failed;
1020
1021         rc = lnet_parse_networks(&nilist, nets);
1022         if (rc != 0)
1023                 goto failed;
1024
1025         while (!cfs_list_empty(&nilist)) {
1026                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
1027                 lnd_type = LNET_NETTYP(LNET_NIDNET(ni->ni_nid));
1028
1029                 LASSERT (libcfs_isknown_lnd(lnd_type));
1030
1031                 if (lnd_type == CIBLND    ||
1032                     lnd_type == OPENIBLND ||
1033                     lnd_type == IIBLND    ||
1034                     lnd_type == VIBLND) {
1035                         CERROR("LND %s obsoleted\n",
1036                                libcfs_lnd2str(lnd_type));
1037                         goto failed;
1038                 }
1039
1040                 LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
1041                 lnd = lnet_find_lnd_by_type(lnd_type);
1042
1043 #ifdef __KERNEL__
1044                 if (lnd == NULL) {
1045                         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1046                         rc = cfs_request_module("%s",
1047                                                 libcfs_lnd2modname(lnd_type));
1048                         LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
1049
1050                         lnd = lnet_find_lnd_by_type(lnd_type);
1051                         if (lnd == NULL) {
1052                                 LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1053                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1054                                        libcfs_lnd2str(lnd_type),
1055                                        libcfs_lnd2modname(lnd_type), rc);
1056 #ifndef HAVE_MODULE_LOADING_SUPPORT
1057                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1058                                          "compiled with kernel module "
1059                                          "loading support.");
1060 #endif
1061                                 goto failed;
1062                         }
1063                 }
1064 #else
1065                 if (lnd == NULL) {
1066                         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1067                         CERROR("LND %s not supported\n",
1068                                libcfs_lnd2str(lnd_type));
1069                         goto failed;
1070                 }
1071 #endif
1072
1073                 ni->ni_refcount = 1;
1074
1075                 LNET_LOCK();
1076                 lnd->lnd_refcount++;
1077                 LNET_UNLOCK();
1078
1079                 ni->ni_lnd = lnd;
1080
1081                 rc = (lnd->lnd_startup)(ni);
1082
1083                 LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1084
1085                 if (rc != 0) {
1086                         LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s"
1087                                            "\n",
1088                                            rc, libcfs_lnd2str(lnd->lnd_type));
1089                         LNET_LOCK();
1090                         lnd->lnd_refcount--;
1091                         LNET_UNLOCK();
1092                         goto failed;
1093                 }
1094
1095                 LASSERT (ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
1096
1097                 cfs_list_del(&ni->ni_list);
1098
1099                 LNET_LOCK();
1100                 cfs_list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
1101                 LNET_UNLOCK();
1102
1103                 if (lnd->lnd_type == LOLND) {
1104                         lnet_ni_addref(ni);
1105                         LASSERT (the_lnet.ln_loni == NULL);
1106                         the_lnet.ln_loni = ni;
1107                         continue;
1108                 }
1109
1110 #ifndef __KERNEL__
1111                 if (lnd->lnd_wait != NULL) {
1112                         if (the_lnet.ln_eqwaitni == NULL) {
1113                                 lnet_ni_addref(ni);
1114                                 the_lnet.ln_eqwaitni = ni;
1115                         }
1116                 } else {
1117 # ifndef HAVE_LIBPTHREAD
1118                         LCONSOLE_ERROR_MSG(0x106, "LND %s not supported in a "
1119                                            "single-threaded runtime\n",
1120                                            libcfs_lnd2str(lnd_type));
1121                         goto failed;
1122 # endif
1123                 }
1124 #endif
1125                 if (ni->ni_peertxcredits == 0 ||
1126                     ni->ni_maxtxcredits == 0) {
1127                         LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1128                                            libcfs_lnd2str(lnd->lnd_type),
1129                                            ni->ni_peertxcredits == 0 ?
1130                                            "" : "per-peer ");
1131                         goto failed;
1132                 }
1133
1134                 ni->ni_txcredits = ni->ni_mintxcredits = ni->ni_maxtxcredits;
1135
1136                 CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1137                        libcfs_nid2str(ni->ni_nid),
1138                        ni->ni_peertxcredits, ni->ni_txcredits,
1139                        ni->ni_peerrtrcredits, ni->ni_peertimeout);
1140
1141                 nicount++;
1142         }
1143
1144         if (the_lnet.ln_eqwaitni != NULL && nicount > 1) {
1145                 lnd_type = the_lnet.ln_eqwaitni->ni_lnd->lnd_type;
1146                 LCONSOLE_ERROR_MSG(0x109, "LND %s can only run single-network"
1147                                    "\n",
1148                                    libcfs_lnd2str(lnd_type));
1149                 goto failed;
1150         }
1151
1152         return 0;
1153
1154  failed:
1155         lnet_shutdown_lndnis();
1156
1157         while (!cfs_list_empty(&nilist)) {
1158                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
1159                 cfs_list_del(&ni->ni_list);
1160                 LIBCFS_FREE(ni, sizeof(*ni));
1161         }
1162
1163         return -ENETDOWN;
1164 }
1165
1166 /**
1167  * Initialize LNet library.
1168  *
1169  * Only userspace program needs to call this function - it's automatically
1170  * called in the kernel at module loading time. Caller has to call LNetFini()
1171  * after a call to LNetInit(), if and only if the latter returned 0. It must
1172  * be called exactly once.
1173  *
1174  * \return 0 on success, and -ve on failures.
1175  */
1176 int
1177 LNetInit(void)
1178 {
1179         lnet_assert_wire_constants ();
1180         LASSERT (!the_lnet.ln_init);
1181
1182         memset(&the_lnet, 0, sizeof(the_lnet));
1183
1184         lnet_init_locks();
1185         the_lnet.ln_refcount = 0;
1186         the_lnet.ln_init = 1;
1187         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1188         CFS_INIT_LIST_HEAD(&the_lnet.ln_lnds);
1189         CFS_INIT_LIST_HEAD(&the_lnet.ln_zombie_rcd);
1190
1191 #ifdef __KERNEL__
1192         /* All LNDs apart from the LOLND are in separate modules.  They
1193          * register themselves when their module loads, and unregister
1194          * themselves when their module is unloaded. */
1195 #else
1196         /* Register LNDs
1197          * NB the order here determines default 'networks=' order */
1198 # ifdef CRAY_XT3
1199         LNET_REGISTER_ULND(the_ptllnd);
1200 # endif
1201 # ifdef HAVE_LIBPTHREAD
1202         LNET_REGISTER_ULND(the_tcplnd);
1203 # endif
1204 #endif
1205         lnet_register_lnd(&the_lolnd);
1206         return 0;
1207 }
1208
1209 /**
1210  * Finalize LNet library.
1211  *
1212  * Only userspace program needs to call this function. It can be called
1213  * at most once.
1214  *
1215  * \pre LNetInit() called with success.
1216  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1217  */
1218 void
1219 LNetFini(void)
1220 {
1221         LASSERT (the_lnet.ln_init);
1222         LASSERT (the_lnet.ln_refcount == 0);
1223
1224         while (!cfs_list_empty(&the_lnet.ln_lnds))
1225                 lnet_unregister_lnd(cfs_list_entry(the_lnet.ln_lnds.next,
1226                                                    lnd_t, lnd_list));
1227         lnet_fini_locks();
1228
1229         the_lnet.ln_init = 0;
1230 }
1231
1232 /**
1233  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1234  *
1235  * Userspace program should call this after a successful call to LNetInit().
1236  * Users must call this function at least once before any other functions.
1237  * For each successful call there must be a corresponding call to
1238  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1239  * ignored.
1240  *
1241  * The PID used by LNet may be different from the one requested.
1242  * See LNetGetId().
1243  *
1244  * \param requested_pid PID requested by the caller.
1245  *
1246  * \return 0 on success, and non-zero error code on failures.
1247  */
1248 int
1249 LNetNIInit(lnet_pid_t requested_pid)
1250 {
1251         int         im_a_router = 0;
1252         int         rc;
1253
1254         LNET_MUTEX_DOWN(&the_lnet.ln_api_mutex);
1255
1256         LASSERT (the_lnet.ln_init);
1257         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1258
1259         if (the_lnet.ln_refcount > 0) {
1260                 rc = the_lnet.ln_refcount++;
1261                 goto out;
1262         }
1263
1264         lnet_get_tunables();
1265
1266         if (requested_pid == LNET_PID_ANY) {
1267                 /* Don't instantiate LNET just for me */
1268                 rc = -ENETDOWN;
1269                 goto failed0;
1270         }
1271
1272         rc = lnet_prepare(requested_pid);
1273         if (rc != 0)
1274                 goto failed0;
1275
1276         rc = lnet_startup_lndnis();
1277         if (rc != 0)
1278                 goto failed1;
1279
1280         rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1281         if (rc != 0)
1282                 goto failed2;
1283
1284         rc = lnet_check_routes();
1285         if (rc != 0)
1286                 goto failed2;
1287
1288         rc = lnet_alloc_rtrpools(im_a_router);
1289         if (rc != 0)
1290                 goto failed2;
1291
1292         rc = lnet_acceptor_start();
1293         if (rc != 0)
1294                 goto failed2;
1295
1296         the_lnet.ln_refcount = 1;
1297         /* Now I may use my own API functions... */
1298
1299         /* NB router checker needs the_lnet.ln_ping_info in
1300          * lnet_router_checker -> lnet_update_ni_status */
1301         rc = lnet_ping_target_init();
1302         if (rc != 0)
1303                 goto failed3;
1304
1305         rc = lnet_router_checker_start();
1306         if (rc != 0)
1307                 goto failed4;
1308
1309         lnet_proc_init();
1310         goto out;
1311
1312  failed4:
1313         lnet_ping_target_fini();
1314  failed3:
1315         the_lnet.ln_refcount = 0;
1316         lnet_acceptor_stop();
1317  failed2:
1318         lnet_destroy_routes();
1319         lnet_shutdown_lndnis();
1320  failed1:
1321         lnet_unprepare();
1322  failed0:
1323         LASSERT (rc < 0);
1324  out:
1325         LNET_MUTEX_UP(&the_lnet.ln_api_mutex);
1326         return rc;
1327 }
1328
1329 /**
1330  * Stop LNet interfaces, routing, and forwarding.
1331  *
1332  * Users must call this function once for each successful call to LNetNIInit().
1333  * Once the LNetNIFini() operation has been started, the results of pending
1334  * API operations are undefined.
1335  *
1336  * \return always 0 for current implementation.
1337  */
1338 int
1339 LNetNIFini()
1340 {
1341         LNET_MUTEX_DOWN(&the_lnet.ln_api_mutex);
1342
1343         LASSERT (the_lnet.ln_init);
1344         LASSERT (the_lnet.ln_refcount > 0);
1345
1346         if (the_lnet.ln_refcount != 1) {
1347                 the_lnet.ln_refcount--;
1348         } else {
1349                 LASSERT (!the_lnet.ln_niinit_self);
1350
1351                 lnet_proc_fini();
1352                 lnet_router_checker_stop();
1353                 lnet_ping_target_fini();
1354
1355                 /* Teardown fns that use my own API functions BEFORE here */
1356                 the_lnet.ln_refcount = 0;
1357
1358                 lnet_acceptor_stop();
1359                 lnet_destroy_routes();
1360                 lnet_shutdown_lndnis();
1361                 lnet_unprepare();
1362         }
1363
1364         LNET_MUTEX_UP(&the_lnet.ln_api_mutex);
1365         return 0;
1366 }
1367
1368 /**
1369  * This is an ugly hack to export IOC_LIBCFS_DEBUG_PEER and
1370  * IOC_LIBCFS_PORTALS_COMPATIBILITY commands to users, by tweaking the LNet
1371  * internal ioctl handler.
1372  *
1373  * IOC_LIBCFS_PORTALS_COMPATIBILITY is now deprecated, don't use it.
1374  *
1375  * \param cmd IOC_LIBCFS_DEBUG_PEER to print debugging data about a peer.
1376  * The data will be printed to system console. Don't use it excessively.
1377  * \param arg A pointer to lnet_process_id_t, process ID of the peer.
1378  *
1379  * \return Always return 0 when called by users directly (i.e., not via ioctl).
1380  */
1381 int
1382 LNetCtl(unsigned int cmd, void *arg)
1383 {
1384         struct libcfs_ioctl_data *data = arg;
1385         lnet_process_id_t         id = {0};
1386         lnet_ni_t                *ni;
1387         int                       rc;
1388
1389         LASSERT (the_lnet.ln_init);
1390         LASSERT (the_lnet.ln_refcount > 0);
1391
1392         switch (cmd) {
1393         case IOC_LIBCFS_GET_NI:
1394                 rc = LNetGetId(data->ioc_count, &id);
1395                 data->ioc_nid = id.nid;
1396                 return rc;
1397
1398         case IOC_LIBCFS_FAIL_NID:
1399                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1400
1401         case IOC_LIBCFS_ADD_ROUTE:
1402                 rc = lnet_add_route(data->ioc_net, data->ioc_count,
1403                                     data->ioc_nid);
1404                 return (rc != 0) ? rc : lnet_check_routes();
1405
1406         case IOC_LIBCFS_DEL_ROUTE:
1407                 return lnet_del_route(data->ioc_net, data->ioc_nid);
1408
1409         case IOC_LIBCFS_GET_ROUTE:
1410                 return lnet_get_route(data->ioc_count,
1411                                       &data->ioc_net, &data->ioc_count,
1412                                       &data->ioc_nid, &data->ioc_flags);
1413         case IOC_LIBCFS_NOTIFY_ROUTER:
1414                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
1415                                    cfs_time_current() -
1416                                    cfs_time_seconds(cfs_time_current_sec() -
1417                                                     (time_t)data->ioc_u64[0]));
1418
1419         case IOC_LIBCFS_PORTALS_COMPATIBILITY:
1420                 /* This can be removed once lustre stops calling it */
1421                 return 0;
1422
1423         case IOC_LIBCFS_LNET_DIST:
1424                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
1425                 if (rc < 0 && rc != -EHOSTUNREACH)
1426                         return rc;
1427
1428                 data->ioc_u32[0] = rc;
1429                 return 0;
1430
1431         case IOC_LIBCFS_TESTPROTOCOMPAT:
1432                 LNET_LOCK();
1433                 the_lnet.ln_testprotocompat = data->ioc_flags;
1434                 LNET_UNLOCK();
1435                 return 0;
1436
1437         case IOC_LIBCFS_PING:
1438                 id.nid = data->ioc_nid;
1439                 id.pid = data->ioc_u32[0];
1440                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
1441                                (lnet_process_id_t *)data->ioc_pbuf1,
1442                                data->ioc_plen1/sizeof(lnet_process_id_t));
1443                 if (rc < 0)
1444                         return rc;
1445                 data->ioc_count = rc;
1446                 return 0;
1447
1448         case IOC_LIBCFS_DEBUG_PEER: {
1449                 /* CAVEAT EMPTOR: this one designed for calling directly; not
1450                  * via an ioctl */
1451                 id = *((lnet_process_id_t *) arg);
1452
1453                 lnet_debug_peer(id.nid);
1454
1455                 ni = lnet_net2ni(LNET_NIDNET(id.nid));
1456                 if (ni == NULL) {
1457                         CDEBUG(D_WARNING, "No NI for %s\n", libcfs_id2str(id));
1458                 } else {
1459                         if (ni->ni_lnd->lnd_ctl == NULL) {
1460                                 CDEBUG(D_WARNING, "No ctl for %s\n",
1461                                        libcfs_id2str(id));
1462                         } else {
1463                                 (void)ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1464                         }
1465
1466                         lnet_ni_decref(ni);
1467                 }
1468                 return 0;
1469         }
1470
1471         default:
1472                 ni = lnet_net2ni(data->ioc_net);
1473                 if (ni == NULL)
1474                         return -EINVAL;
1475
1476                 if (ni->ni_lnd->lnd_ctl == NULL)
1477                         rc = -EINVAL;
1478                 else
1479                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1480
1481                 lnet_ni_decref(ni);
1482                 return rc;
1483         }
1484         /* not reached */
1485 }
1486
1487 /**
1488  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
1489  * all interfaces share a same PID, as requested by LNetNIInit().
1490  *
1491  * \param index Index of the interface to look up.
1492  * \param id On successful return, this location will hold the
1493  * lnet_process_id_t ID of the interface.
1494  *
1495  * \retval 0 If an interface exists at \a index.
1496  * \retval -ENOENT If no interface has been found.
1497  */
1498 int
1499 LNetGetId(unsigned int index, lnet_process_id_t *id)
1500 {
1501         lnet_ni_t        *ni;
1502         cfs_list_t       *tmp;
1503         int               rc = -ENOENT;
1504
1505         LASSERT (the_lnet.ln_init);
1506         LASSERT (the_lnet.ln_refcount > 0);
1507
1508         LNET_LOCK();
1509
1510         cfs_list_for_each(tmp, &the_lnet.ln_nis) {
1511                 if (index-- != 0)
1512                         continue;
1513
1514                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
1515
1516                 id->nid = ni->ni_nid;
1517                 id->pid = the_lnet.ln_pid;
1518                 rc = 0;
1519                 break;
1520         }
1521
1522         LNET_UNLOCK();
1523
1524         return rc;
1525 }
1526
1527 /**
1528  * Print a string representation of handle \a h into buffer \a str of
1529  * \a len bytes.
1530  */
1531 void
1532 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
1533 {
1534         snprintf(str, len, LPX64, h.cookie);
1535 }
1536
1537 static int
1538 lnet_create_ping_info(void)
1539 {
1540         int               i;
1541         int               n;
1542         int               rc;
1543         unsigned int      infosz;
1544         lnet_ni_t        *ni;
1545         lnet_process_id_t id;
1546         lnet_ping_info_t *pinfo;
1547
1548         for (n = 0; ; n++) {
1549                 rc = LNetGetId(n, &id);
1550                 if (rc == -ENOENT)
1551                         break;
1552
1553                 LASSERT (rc == 0);
1554         }
1555
1556         infosz = offsetof(lnet_ping_info_t, pi_ni[n]);
1557         LIBCFS_ALLOC(pinfo, infosz);
1558         if (pinfo == NULL) {
1559                 CERROR("Can't allocate ping info[%d]\n", n);
1560                 return -ENOMEM;
1561         }
1562
1563         pinfo->pi_nnis    = n;
1564         pinfo->pi_pid     = the_lnet.ln_pid;
1565         pinfo->pi_magic   = LNET_PROTO_PING_MAGIC;
1566         pinfo->pi_version = LNET_PROTO_PING_VERSION;
1567
1568         for (i = 0; i < n; i++) {
1569                 lnet_ni_status_t *ns = &pinfo->pi_ni[i];
1570
1571                 rc = LNetGetId(i, &id);
1572                 LASSERT (rc == 0);
1573
1574                 ns->ns_nid    = id.nid;
1575                 ns->ns_status = LNET_NI_STATUS_UP;
1576
1577                 LNET_LOCK();
1578
1579                 ni = lnet_nid2ni_locked(id.nid);
1580                 LASSERT (ni != NULL);
1581                 LASSERT (ni->ni_status == NULL);
1582                 ni->ni_status = ns;
1583                 lnet_ni_decref_locked(ni);
1584
1585                 LNET_UNLOCK();
1586         }
1587
1588         the_lnet.ln_ping_info = pinfo;
1589         return 0;
1590 }
1591
1592 static void
1593 lnet_destroy_ping_info(void)
1594 {
1595         lnet_ni_t *ni;
1596
1597         LNET_LOCK();
1598
1599         cfs_list_for_each_entry (ni, &the_lnet.ln_nis, ni_list) {
1600                 ni->ni_status = NULL;
1601         }
1602
1603         LNET_UNLOCK();
1604
1605         LIBCFS_FREE(the_lnet.ln_ping_info,
1606                     offsetof(lnet_ping_info_t,
1607                              pi_ni[the_lnet.ln_ping_info->pi_nnis]));
1608         the_lnet.ln_ping_info = NULL;
1609         return;
1610 }
1611
1612 int
1613 lnet_ping_target_init(void)
1614 {
1615         lnet_md_t         md = {0};
1616         lnet_handle_me_t  meh;
1617         lnet_process_id_t id;
1618         int               rc;
1619         int               rc2;
1620         int               infosz;
1621
1622         rc = lnet_create_ping_info();
1623         if (rc != 0)
1624                 return rc;
1625
1626         /* We can have a tiny EQ since we only need to see the unlink event on
1627          * teardown, which by definition is the last one! */
1628         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &the_lnet.ln_ping_target_eq);
1629         if (rc != 0) {
1630                 CERROR("Can't allocate ping EQ: %d\n", rc);
1631                 goto failed_0;
1632         }
1633
1634         memset(&id, 0, sizeof(lnet_process_id_t));
1635         id.nid = LNET_NID_ANY;
1636         id.pid = LNET_PID_ANY;
1637
1638         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1639                           LNET_PROTO_PING_MATCHBITS, 0,
1640                           LNET_UNLINK, LNET_INS_AFTER,
1641                           &meh);
1642         if (rc != 0) {
1643                 CERROR("Can't create ping ME: %d\n", rc);
1644                 goto failed_1;
1645         }
1646
1647         /* initialize md content */
1648         infosz = offsetof(lnet_ping_info_t,
1649                           pi_ni[the_lnet.ln_ping_info->pi_nnis]);
1650         md.start     = the_lnet.ln_ping_info;
1651         md.length    = infosz;
1652         md.threshold = LNET_MD_THRESH_INF;
1653         md.max_size  = 0;
1654         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1655                        LNET_MD_MANAGE_REMOTE;
1656         md.user_ptr  = NULL;
1657         md.eq_handle = the_lnet.ln_ping_target_eq;
1658
1659         rc = LNetMDAttach(meh, md,
1660                           LNET_RETAIN,
1661                           &the_lnet.ln_ping_target_md);
1662         if (rc != 0) {
1663                 CERROR("Can't attach ping MD: %d\n", rc);
1664                 goto failed_2;
1665         }
1666
1667         return 0;
1668
1669  failed_2:
1670         rc2 = LNetMEUnlink(meh);
1671         LASSERT (rc2 == 0);
1672  failed_1:
1673         rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1674         LASSERT (rc2 == 0);
1675  failed_0:
1676         lnet_destroy_ping_info();
1677         return rc;
1678 }
1679
1680 void
1681 lnet_ping_target_fini(void)
1682 {
1683         lnet_event_t    event;
1684         int             rc;
1685         int             which;
1686         int             timeout_ms = 1000;
1687         cfs_sigset_t    blocked = cfs_block_allsigs();
1688
1689         LNetMDUnlink(the_lnet.ln_ping_target_md);
1690         /* NB md could be busy; this just starts the unlink */
1691
1692         for (;;) {
1693                 rc = LNetEQPoll(&the_lnet.ln_ping_target_eq, 1,
1694                                 timeout_ms, &event, &which);
1695
1696                 /* I expect overflow... */
1697                 LASSERT (rc >= 0 || rc == -EOVERFLOW);
1698
1699                 if (rc == 0) {
1700                         /* timed out: provide a diagnostic */
1701                         CWARN("Still waiting for ping MD to unlink\n");
1702                         timeout_ms *= 2;
1703                         continue;
1704                 }
1705
1706                 /* Got a valid event */
1707                 if (event.unlinked)
1708                         break;
1709         }
1710
1711         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1712         LASSERT (rc == 0);
1713         lnet_destroy_ping_info();
1714         cfs_restore_sigs(blocked);
1715 }
1716
1717 int
1718 lnet_ping (lnet_process_id_t id, int timeout_ms, lnet_process_id_t *ids, int n_ids)
1719 {
1720         lnet_handle_eq_t     eqh;
1721         lnet_handle_md_t     mdh;
1722         lnet_event_t         event;
1723         lnet_md_t            md = {0};
1724         int                  which;
1725         int                  unlinked = 0;
1726         int                  replied = 0;
1727         const int            a_long_time = 60000; /* mS */
1728         int                  infosz = offsetof(lnet_ping_info_t, pi_ni[n_ids]);
1729         lnet_ping_info_t    *info;
1730         lnet_process_id_t    tmpid;
1731         int                  i;
1732         int                  nob;
1733         int                  rc;
1734         int                  rc2;
1735         cfs_sigset_t         blocked;
1736
1737         if (n_ids <= 0 ||
1738             id.nid == LNET_NID_ANY ||
1739             timeout_ms > 500000 ||              /* arbitrary limit! */
1740             n_ids > 20)                         /* arbitrary limit! */
1741                 return -EINVAL;
1742
1743         if (id.pid == LNET_PID_ANY)
1744                 id.pid = LUSTRE_SRV_LNET_PID;
1745
1746         LIBCFS_ALLOC(info, infosz);
1747         if (info == NULL)
1748                 return -ENOMEM;
1749
1750         /* NB 2 events max (including any unlink event) */
1751         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
1752         if (rc != 0) {
1753                 CERROR("Can't allocate EQ: %d\n", rc);
1754                 goto out_0;
1755         }
1756
1757         /* initialize md content */
1758         md.start     = info;
1759         md.length    = infosz;
1760         md.threshold = 2; /*GET/REPLY*/
1761         md.max_size  = 0;
1762         md.options   = LNET_MD_TRUNCATE;
1763         md.user_ptr  = NULL;
1764         md.eq_handle = eqh;
1765
1766         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
1767         if (rc != 0) {
1768                 CERROR("Can't bind MD: %d\n", rc);
1769                 goto out_1;
1770         }
1771
1772         rc = LNetGet(LNET_NID_ANY, mdh, id,
1773                      LNET_RESERVED_PORTAL,
1774                      LNET_PROTO_PING_MATCHBITS, 0);
1775
1776         if (rc != 0) {
1777                 /* Don't CERROR; this could be deliberate! */
1778
1779                 rc2 = LNetMDUnlink(mdh);
1780                 LASSERT (rc2 == 0);
1781
1782                 /* NB must wait for the UNLINK event below... */
1783                 unlinked = 1;
1784                 timeout_ms = a_long_time;
1785         }
1786
1787         do {
1788                 /* MUST block for unlink to complete */
1789                 if (unlinked)
1790                         blocked = cfs_block_allsigs();
1791
1792                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
1793
1794                 if (unlinked)
1795                         cfs_restore_sigs(blocked);
1796
1797                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
1798                        (rc2 <= 0) ? -1 : event.type,
1799                        (rc2 <= 0) ? -1 : event.status,
1800                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
1801
1802                 LASSERT (rc2 != -EOVERFLOW);     /* can't miss anything */
1803
1804                 if (rc2 <= 0 || event.status != 0) {
1805                         /* timeout or error */
1806                         if (!replied && rc == 0)
1807                                 rc = (rc2 < 0) ? rc2 :
1808                                      (rc2 == 0) ? -ETIMEDOUT :
1809                                      event.status;
1810
1811                         if (!unlinked) {
1812                                 /* Ensure completion in finite time... */
1813                                 LNetMDUnlink(mdh);
1814                                 /* No assertion (racing with network) */
1815                                 unlinked = 1;
1816                                 timeout_ms = a_long_time;
1817                         } else if (rc2 == 0) {
1818                                 /* timed out waiting for unlink */
1819                                 CWARN("ping %s: late network completion\n",
1820                                       libcfs_id2str(id));
1821                         }
1822                 } else if (event.type == LNET_EVENT_REPLY) {
1823                         replied = 1;
1824                         rc = event.mlength;
1825                 }
1826
1827         } while (rc2 <= 0 || !event.unlinked);
1828
1829         if (!replied) {
1830                 if (rc >= 0)
1831                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
1832                               libcfs_id2str(id));
1833                 rc = -EIO;
1834                 goto out_1;
1835         }
1836
1837         nob = rc;
1838         LASSERT (nob >= 0 && nob <= infosz);
1839
1840         rc = -EPROTO;                           /* if I can't parse... */
1841
1842         if (nob < 8) {
1843                 /* can't check magic/version */
1844                 CERROR("%s: ping info too short %d\n",
1845                        libcfs_id2str(id), nob);
1846                 goto out_1;
1847         }
1848
1849         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
1850                 lnet_swap_pinginfo(info);
1851         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
1852                 CERROR("%s: Unexpected magic %08x\n", 
1853                        libcfs_id2str(id), info->pi_magic);
1854                 goto out_1;
1855         }
1856
1857         if (info->pi_version != LNET_PROTO_PING_VERSION) {
1858                 CERROR("%s: Unexpected version 0x%x\n",
1859                        libcfs_id2str(id), info->pi_version);
1860                 goto out_1;
1861         }
1862
1863         if (nob < offsetof(lnet_ping_info_t, pi_ni[0])) {
1864                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
1865                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[0]));
1866                 goto out_1;
1867         }
1868
1869         if (info->pi_nnis < n_ids)
1870                 n_ids = info->pi_nnis;
1871
1872         if (nob < offsetof(lnet_ping_info_t, pi_ni[n_ids])) {
1873                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
1874                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[n_ids]));
1875                 goto out_1;
1876         }
1877
1878         rc = -EFAULT;                           /* If I SEGV... */
1879
1880         for (i = 0; i < n_ids; i++) {
1881                 tmpid.pid = info->pi_pid;
1882                 tmpid.nid = info->pi_ni[i].ns_nid;
1883 #ifdef __KERNEL__
1884                 if (cfs_copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
1885                         goto out_1;
1886 #else
1887                 ids[i] = tmpid;
1888 #endif
1889         }
1890         rc = info->pi_nnis;
1891
1892  out_1:
1893         rc2 = LNetEQFree(eqh);
1894         if (rc2 != 0)
1895                 CERROR("rc2 %d\n", rc2);
1896         LASSERT (rc2 == 0);
1897
1898  out_0:
1899         LIBCFS_FREE(info, infosz);
1900         return rc;
1901 }