Whamcloud - gitweb
b=23179 MDS node unresponsive
[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                 LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
1032                 lnd = lnet_find_lnd_by_type(lnd_type);
1033
1034 #ifdef __KERNEL__
1035                 if (lnd == NULL) {
1036                         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1037                         rc = cfs_request_module("%s",
1038                                                 libcfs_lnd2modname(lnd_type));
1039                         LNET_MUTEX_DOWN(&the_lnet.ln_lnd_mutex);
1040
1041                         lnd = lnet_find_lnd_by_type(lnd_type);
1042                         if (lnd == NULL) {
1043                                 LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1044                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
1045                                        libcfs_lnd2str(lnd_type),
1046                                        libcfs_lnd2modname(lnd_type), rc);
1047 #ifndef HAVE_MODULE_LOADING_SUPPORT
1048                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
1049                                          "compiled with kernel module "
1050                                          "loading support.");
1051 #endif
1052                                 goto failed;
1053                         }
1054                 }
1055 #else
1056                 if (lnd == NULL) {
1057                         LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1058                         CERROR("LND %s not supported\n",
1059                                libcfs_lnd2str(lnd_type));
1060                         goto failed;
1061                 }
1062 #endif
1063
1064                 ni->ni_refcount = 1;
1065
1066                 LNET_LOCK();
1067                 lnd->lnd_refcount++;
1068                 LNET_UNLOCK();
1069
1070                 ni->ni_lnd = lnd;
1071
1072                 rc = (lnd->lnd_startup)(ni);
1073
1074                 LNET_MUTEX_UP(&the_lnet.ln_lnd_mutex);
1075
1076                 if (rc != 0) {
1077                         LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s"
1078                                            "\n",
1079                                            rc, libcfs_lnd2str(lnd->lnd_type));
1080                         LNET_LOCK();
1081                         lnd->lnd_refcount--;
1082                         LNET_UNLOCK();
1083                         goto failed;
1084                 }
1085
1086                 LASSERT (ni->ni_peertimeout <= 0 || lnd->lnd_query != NULL);
1087
1088                 cfs_list_del(&ni->ni_list);
1089
1090                 LNET_LOCK();
1091                 cfs_list_add_tail(&ni->ni_list, &the_lnet.ln_nis);
1092                 LNET_UNLOCK();
1093
1094                 if (lnd->lnd_type == LOLND) {
1095                         lnet_ni_addref(ni);
1096                         LASSERT (the_lnet.ln_loni == NULL);
1097                         the_lnet.ln_loni = ni;
1098                         continue;
1099                 }
1100
1101 #ifndef __KERNEL__
1102                 if (lnd->lnd_wait != NULL) {
1103                         if (the_lnet.ln_eqwaitni == NULL) {
1104                                 lnet_ni_addref(ni);
1105                                 the_lnet.ln_eqwaitni = ni;
1106                         }
1107                 } else {
1108 # ifndef HAVE_LIBPTHREAD
1109                         LCONSOLE_ERROR_MSG(0x106, "LND %s not supported in a "
1110                                            "single-threaded runtime\n",
1111                                            libcfs_lnd2str(lnd_type));
1112                         goto failed;
1113 # endif
1114                 }
1115 #endif
1116                 if (ni->ni_peertxcredits == 0 ||
1117                     ni->ni_maxtxcredits == 0) {
1118                         LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
1119                                            libcfs_lnd2str(lnd->lnd_type),
1120                                            ni->ni_peertxcredits == 0 ?
1121                                            "" : "per-peer ");
1122                         goto failed;
1123                 }
1124
1125                 ni->ni_txcredits = ni->ni_mintxcredits = ni->ni_maxtxcredits;
1126
1127                 CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
1128                        libcfs_nid2str(ni->ni_nid),
1129                        ni->ni_peertxcredits, ni->ni_txcredits,
1130                        ni->ni_peerrtrcredits, ni->ni_peertimeout);
1131
1132                 nicount++;
1133         }
1134
1135         if (the_lnet.ln_eqwaitni != NULL && nicount > 1) {
1136                 lnd_type = the_lnet.ln_eqwaitni->ni_lnd->lnd_type;
1137                 LCONSOLE_ERROR_MSG(0x109, "LND %s can only run single-network"
1138                                    "\n",
1139                                    libcfs_lnd2str(lnd_type));
1140                 goto failed;
1141         }
1142
1143         return 0;
1144
1145  failed:
1146         lnet_shutdown_lndnis();
1147
1148         while (!cfs_list_empty(&nilist)) {
1149                 ni = cfs_list_entry(nilist.next, lnet_ni_t, ni_list);
1150                 cfs_list_del(&ni->ni_list);
1151                 LIBCFS_FREE(ni, sizeof(*ni));
1152         }
1153
1154         return -ENETDOWN;
1155 }
1156
1157 /**
1158  * Initialize LNet library.
1159  *
1160  * Only userspace program needs to call this function - it's automatically
1161  * called in the kernel at module loading time. Caller has to call LNetFini()
1162  * after a call to LNetInit(), if and only if the latter returned 0. It must
1163  * be called exactly once.
1164  *
1165  * \return 0 on success, and -ve on failures.
1166  */
1167 int
1168 LNetInit(void)
1169 {
1170         lnet_assert_wire_constants ();
1171         LASSERT (!the_lnet.ln_init);
1172
1173         memset(&the_lnet, 0, sizeof(the_lnet));
1174
1175         lnet_init_locks();
1176         the_lnet.ln_refcount = 0;
1177         the_lnet.ln_init = 1;
1178         LNetInvalidateHandle(&the_lnet.ln_rc_eqh);
1179         CFS_INIT_LIST_HEAD(&the_lnet.ln_lnds);
1180         CFS_INIT_LIST_HEAD(&the_lnet.ln_zombie_rcd);
1181
1182 #ifdef __KERNEL__
1183         /* All LNDs apart from the LOLND are in separate modules.  They
1184          * register themselves when their module loads, and unregister
1185          * themselves when their module is unloaded. */
1186 #else
1187         /* Register LNDs
1188          * NB the order here determines default 'networks=' order */
1189 # ifdef CRAY_XT3
1190         LNET_REGISTER_ULND(the_ptllnd);
1191 # endif
1192 # ifdef HAVE_LIBPTHREAD
1193         LNET_REGISTER_ULND(the_tcplnd);
1194 # endif
1195 #endif
1196         lnet_register_lnd(&the_lolnd);
1197         return 0;
1198 }
1199
1200 /**
1201  * Finalize LNet library.
1202  *
1203  * Only userspace program needs to call this function. It can be called
1204  * at most once.
1205  *
1206  * \pre LNetInit() called with success.
1207  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
1208  */
1209 void
1210 LNetFini(void)
1211 {
1212         LASSERT (the_lnet.ln_init);
1213         LASSERT (the_lnet.ln_refcount == 0);
1214
1215         while (!cfs_list_empty(&the_lnet.ln_lnds))
1216                 lnet_unregister_lnd(cfs_list_entry(the_lnet.ln_lnds.next,
1217                                                    lnd_t, lnd_list));
1218         lnet_fini_locks();
1219
1220         the_lnet.ln_init = 0;
1221 }
1222
1223 /**
1224  * Set LNet PID and start LNet interfaces, routing, and forwarding.
1225  *
1226  * Userspace program should call this after a successful call to LNetInit().
1227  * Users must call this function at least once before any other functions.
1228  * For each successful call there must be a corresponding call to
1229  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
1230  * ignored.
1231  *
1232  * The PID used by LNet may be different from the one requested.
1233  * See LNetGetId().
1234  *
1235  * \param requested_pid PID requested by the caller.
1236  *
1237  * \return 0 on success, and non-zero error code on failures.
1238  */
1239 int
1240 LNetNIInit(lnet_pid_t requested_pid)
1241 {
1242         int         im_a_router = 0;
1243         int         rc;
1244
1245         LNET_MUTEX_DOWN(&the_lnet.ln_api_mutex);
1246
1247         LASSERT (the_lnet.ln_init);
1248         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
1249
1250         if (the_lnet.ln_refcount > 0) {
1251                 rc = the_lnet.ln_refcount++;
1252                 goto out;
1253         }
1254
1255         lnet_get_tunables();
1256
1257         if (requested_pid == LNET_PID_ANY) {
1258                 /* Don't instantiate LNET just for me */
1259                 rc = -ENETDOWN;
1260                 goto failed0;
1261         }
1262
1263         rc = lnet_prepare(requested_pid);
1264         if (rc != 0)
1265                 goto failed0;
1266
1267         rc = lnet_startup_lndnis();
1268         if (rc != 0)
1269                 goto failed1;
1270
1271         rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
1272         if (rc != 0)
1273                 goto failed2;
1274
1275         rc = lnet_check_routes();
1276         if (rc != 0)
1277                 goto failed2;
1278
1279         rc = lnet_alloc_rtrpools(im_a_router);
1280         if (rc != 0)
1281                 goto failed2;
1282
1283         rc = lnet_acceptor_start();
1284         if (rc != 0)
1285                 goto failed2;
1286
1287         the_lnet.ln_refcount = 1;
1288         /* Now I may use my own API functions... */
1289
1290         /* NB router checker needs the_lnet.ln_ping_info in
1291          * lnet_router_checker -> lnet_update_ni_status */
1292         rc = lnet_ping_target_init();
1293         if (rc != 0)
1294                 goto failed3;
1295
1296         rc = lnet_router_checker_start();
1297         if (rc != 0)
1298                 goto failed4;
1299
1300         lnet_proc_init();
1301         goto out;
1302
1303  failed4:
1304         lnet_ping_target_fini();
1305  failed3:
1306         the_lnet.ln_refcount = 0;
1307         lnet_acceptor_stop();
1308  failed2:
1309         lnet_destroy_routes();
1310         lnet_shutdown_lndnis();
1311  failed1:
1312         lnet_unprepare();
1313  failed0:
1314         LASSERT (rc < 0);
1315  out:
1316         LNET_MUTEX_UP(&the_lnet.ln_api_mutex);
1317         return rc;
1318 }
1319
1320 /**
1321  * Stop LNet interfaces, routing, and forwarding.
1322  *
1323  * Users must call this function once for each successful call to LNetNIInit().
1324  * Once the LNetNIFini() operation has been started, the results of pending
1325  * API operations are undefined.
1326  *
1327  * \return always 0 for current implementation.
1328  */
1329 int
1330 LNetNIFini()
1331 {
1332         LNET_MUTEX_DOWN(&the_lnet.ln_api_mutex);
1333
1334         LASSERT (the_lnet.ln_init);
1335         LASSERT (the_lnet.ln_refcount > 0);
1336
1337         if (the_lnet.ln_refcount != 1) {
1338                 the_lnet.ln_refcount--;
1339         } else {
1340                 LASSERT (!the_lnet.ln_niinit_self);
1341
1342                 lnet_proc_fini();
1343                 lnet_router_checker_stop();
1344                 lnet_ping_target_fini();
1345
1346                 /* Teardown fns that use my own API functions BEFORE here */
1347                 the_lnet.ln_refcount = 0;
1348
1349                 lnet_acceptor_stop();
1350                 lnet_destroy_routes();
1351                 lnet_shutdown_lndnis();
1352                 lnet_unprepare();
1353         }
1354
1355         LNET_MUTEX_UP(&the_lnet.ln_api_mutex);
1356         return 0;
1357 }
1358
1359 /**
1360  * This is an ugly hack to export IOC_LIBCFS_DEBUG_PEER and
1361  * IOC_LIBCFS_PORTALS_COMPATIBILITY commands to users, by tweaking the LNet
1362  * internal ioctl handler.
1363  *
1364  * IOC_LIBCFS_PORTALS_COMPATIBILITY is now deprecated, don't use it.
1365  *
1366  * \param cmd IOC_LIBCFS_DEBUG_PEER to print debugging data about a peer.
1367  * The data will be printed to system console. Don't use it excessively.
1368  * \param arg A pointer to lnet_process_id_t, process ID of the peer.
1369  *
1370  * \return Always return 0 when called by users directly (i.e., not via ioctl).
1371  */
1372 int
1373 LNetCtl(unsigned int cmd, void *arg)
1374 {
1375         struct libcfs_ioctl_data *data = arg;
1376         lnet_process_id_t         id = {0};
1377         lnet_ni_t                *ni;
1378         int                       rc;
1379
1380         LASSERT (the_lnet.ln_init);
1381         LASSERT (the_lnet.ln_refcount > 0);
1382
1383         switch (cmd) {
1384         case IOC_LIBCFS_GET_NI:
1385                 rc = LNetGetId(data->ioc_count, &id);
1386                 data->ioc_nid = id.nid;
1387                 return rc;
1388
1389         case IOC_LIBCFS_FAIL_NID:
1390                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
1391
1392         case IOC_LIBCFS_ADD_ROUTE:
1393                 rc = lnet_add_route(data->ioc_net, data->ioc_count,
1394                                     data->ioc_nid);
1395                 return (rc != 0) ? rc : lnet_check_routes();
1396
1397         case IOC_LIBCFS_DEL_ROUTE:
1398                 return lnet_del_route(data->ioc_net, data->ioc_nid);
1399
1400         case IOC_LIBCFS_GET_ROUTE:
1401                 return lnet_get_route(data->ioc_count,
1402                                       &data->ioc_net, &data->ioc_count,
1403                                       &data->ioc_nid, &data->ioc_flags);
1404         case IOC_LIBCFS_NOTIFY_ROUTER:
1405                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
1406                                    cfs_time_current() -
1407                                    cfs_time_seconds(cfs_time_current_sec() -
1408                                                     (time_t)data->ioc_u64[0]));
1409
1410         case IOC_LIBCFS_PORTALS_COMPATIBILITY:
1411                 /* This can be removed once lustre stops calling it */
1412                 return 0;
1413
1414         case IOC_LIBCFS_LNET_DIST:
1415                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
1416                 if (rc < 0 && rc != -EHOSTUNREACH)
1417                         return rc;
1418
1419                 data->ioc_u32[0] = rc;
1420                 return 0;
1421
1422         case IOC_LIBCFS_TESTPROTOCOMPAT:
1423                 LNET_LOCK();
1424                 the_lnet.ln_testprotocompat = data->ioc_flags;
1425                 LNET_UNLOCK();
1426                 return 0;
1427
1428         case IOC_LIBCFS_PING:
1429                 id.nid = data->ioc_nid;
1430                 id.pid = data->ioc_u32[0];
1431                 rc = lnet_ping(id, data->ioc_u32[1], /* timeout */
1432                                (lnet_process_id_t *)data->ioc_pbuf1,
1433                                data->ioc_plen1/sizeof(lnet_process_id_t));
1434                 if (rc < 0)
1435                         return rc;
1436                 data->ioc_count = rc;
1437                 return 0;
1438
1439         case IOC_LIBCFS_DEBUG_PEER: {
1440                 /* CAVEAT EMPTOR: this one designed for calling directly; not
1441                  * via an ioctl */
1442                 id = *((lnet_process_id_t *) arg);
1443
1444                 lnet_debug_peer(id.nid);
1445
1446                 ni = lnet_net2ni(LNET_NIDNET(id.nid));
1447                 if (ni == NULL) {
1448                         CDEBUG(D_WARNING, "No NI for %s\n", libcfs_id2str(id));
1449                 } else {
1450                         if (ni->ni_lnd->lnd_ctl == NULL) {
1451                                 CDEBUG(D_WARNING, "No ctl for %s\n",
1452                                        libcfs_id2str(id));
1453                         } else {
1454                                 (void)ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1455                         }
1456
1457                         lnet_ni_decref(ni);
1458                 }
1459                 return 0;
1460         }
1461
1462         default:
1463                 ni = lnet_net2ni(data->ioc_net);
1464                 if (ni == NULL)
1465                         return -EINVAL;
1466
1467                 if (ni->ni_lnd->lnd_ctl == NULL)
1468                         rc = -EINVAL;
1469                 else
1470                         rc = ni->ni_lnd->lnd_ctl(ni, cmd, arg);
1471
1472                 lnet_ni_decref(ni);
1473                 return rc;
1474         }
1475         /* not reached */
1476 }
1477
1478 /**
1479  * Retrieve the lnet_process_id_t ID of LNet interface at \a index. Note that
1480  * all interfaces share a same PID, as requested by LNetNIInit().
1481  *
1482  * \param index Index of the interface to look up.
1483  * \param id On successful return, this location will hold the
1484  * lnet_process_id_t ID of the interface.
1485  *
1486  * \retval 0 If an interface exists at \a index.
1487  * \retval -ENOENT If no interface has been found.
1488  */
1489 int
1490 LNetGetId(unsigned int index, lnet_process_id_t *id)
1491 {
1492         lnet_ni_t        *ni;
1493         cfs_list_t       *tmp;
1494         int               rc = -ENOENT;
1495
1496         LASSERT (the_lnet.ln_init);
1497         LASSERT (the_lnet.ln_refcount > 0);
1498
1499         LNET_LOCK();
1500
1501         cfs_list_for_each(tmp, &the_lnet.ln_nis) {
1502                 if (index-- != 0)
1503                         continue;
1504
1505                 ni = cfs_list_entry(tmp, lnet_ni_t, ni_list);
1506
1507                 id->nid = ni->ni_nid;
1508                 id->pid = the_lnet.ln_pid;
1509                 rc = 0;
1510                 break;
1511         }
1512
1513         LNET_UNLOCK();
1514
1515         return rc;
1516 }
1517
1518 /**
1519  * Print a string representation of handle \a h into buffer \a str of
1520  * \a len bytes.
1521  */
1522 void
1523 LNetSnprintHandle(char *str, int len, lnet_handle_any_t h)
1524 {
1525         snprintf(str, len, LPX64, h.cookie);
1526 }
1527
1528 static int
1529 lnet_create_ping_info(void)
1530 {
1531         int               i;
1532         int               n;
1533         int               rc;
1534         unsigned int      infosz;
1535         lnet_ni_t        *ni;
1536         lnet_process_id_t id;
1537         lnet_ping_info_t *pinfo;
1538
1539         for (n = 0; ; n++) {
1540                 rc = LNetGetId(n, &id);
1541                 if (rc == -ENOENT)
1542                         break;
1543
1544                 LASSERT (rc == 0);
1545         }
1546
1547         infosz = offsetof(lnet_ping_info_t, pi_ni[n]);
1548         LIBCFS_ALLOC(pinfo, infosz);
1549         if (pinfo == NULL) {
1550                 CERROR("Can't allocate ping info[%d]\n", n);
1551                 return -ENOMEM;
1552         }
1553
1554         pinfo->pi_nnis    = n;
1555         pinfo->pi_pid     = the_lnet.ln_pid;
1556         pinfo->pi_magic   = LNET_PROTO_PING_MAGIC;
1557         pinfo->pi_version = LNET_PROTO_PING_VERSION;
1558
1559         for (i = 0; i < n; i++) {
1560                 lnet_ni_status_t *ns = &pinfo->pi_ni[i];
1561
1562                 rc = LNetGetId(i, &id);
1563                 LASSERT (rc == 0);
1564
1565                 ns->ns_nid    = id.nid;
1566                 ns->ns_status = LNET_NI_STATUS_UP;
1567
1568                 LNET_LOCK();
1569
1570                 ni = lnet_nid2ni_locked(id.nid);
1571                 LASSERT (ni != NULL);
1572                 LASSERT (ni->ni_status == NULL);
1573                 ni->ni_status = ns;
1574                 lnet_ni_decref_locked(ni);
1575
1576                 LNET_UNLOCK();
1577         }
1578
1579         the_lnet.ln_ping_info = pinfo;
1580         return 0;
1581 }
1582
1583 static void
1584 lnet_destroy_ping_info(void)
1585 {
1586         lnet_ni_t *ni;
1587
1588         LNET_LOCK();
1589
1590         cfs_list_for_each_entry (ni, &the_lnet.ln_nis, ni_list) {
1591                 ni->ni_status = NULL;
1592         }
1593
1594         LNET_UNLOCK();
1595
1596         LIBCFS_FREE(the_lnet.ln_ping_info,
1597                     offsetof(lnet_ping_info_t,
1598                              pi_ni[the_lnet.ln_ping_info->pi_nnis]));
1599         the_lnet.ln_ping_info = NULL;
1600         return;
1601 }
1602
1603 int
1604 lnet_ping_target_init(void)
1605 {
1606         lnet_md_t         md = {0};
1607         lnet_handle_me_t  meh;
1608         lnet_process_id_t id;
1609         int               rc;
1610         int               rc2;
1611         int               infosz;
1612
1613         rc = lnet_create_ping_info();
1614         if (rc != 0)
1615                 return rc;
1616
1617         /* We can have a tiny EQ since we only need to see the unlink event on
1618          * teardown, which by definition is the last one! */
1619         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &the_lnet.ln_ping_target_eq);
1620         if (rc != 0) {
1621                 CERROR("Can't allocate ping EQ: %d\n", rc);
1622                 goto failed_0;
1623         }
1624
1625         memset(&id, 0, sizeof(lnet_process_id_t));
1626         id.nid = LNET_NID_ANY;
1627         id.pid = LNET_PID_ANY;
1628
1629         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1630                           LNET_PROTO_PING_MATCHBITS, 0,
1631                           LNET_UNLINK, LNET_INS_AFTER,
1632                           &meh);
1633         if (rc != 0) {
1634                 CERROR("Can't create ping ME: %d\n", rc);
1635                 goto failed_1;
1636         }
1637
1638         /* initialize md content */
1639         infosz = offsetof(lnet_ping_info_t,
1640                           pi_ni[the_lnet.ln_ping_info->pi_nnis]);
1641         md.start     = the_lnet.ln_ping_info;
1642         md.length    = infosz;
1643         md.threshold = LNET_MD_THRESH_INF;
1644         md.max_size  = 0;
1645         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1646                        LNET_MD_MANAGE_REMOTE;
1647         md.user_ptr  = NULL;
1648         md.eq_handle = the_lnet.ln_ping_target_eq;
1649
1650         rc = LNetMDAttach(meh, md,
1651                           LNET_RETAIN,
1652                           &the_lnet.ln_ping_target_md);
1653         if (rc != 0) {
1654                 CERROR("Can't attach ping MD: %d\n", rc);
1655                 goto failed_2;
1656         }
1657
1658         return 0;
1659
1660  failed_2:
1661         rc2 = LNetMEUnlink(meh);
1662         LASSERT (rc2 == 0);
1663  failed_1:
1664         rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1665         LASSERT (rc2 == 0);
1666  failed_0:
1667         lnet_destroy_ping_info();
1668         return rc;
1669 }
1670
1671 void
1672 lnet_ping_target_fini(void)
1673 {
1674         lnet_event_t    event;
1675         int             rc;
1676         int             which;
1677         int             timeout_ms = 1000;
1678         cfs_sigset_t    blocked = cfs_block_allsigs();
1679
1680         LNetMDUnlink(the_lnet.ln_ping_target_md);
1681         /* NB md could be busy; this just starts the unlink */
1682
1683         for (;;) {
1684                 rc = LNetEQPoll(&the_lnet.ln_ping_target_eq, 1,
1685                                 timeout_ms, &event, &which);
1686
1687                 /* I expect overflow... */
1688                 LASSERT (rc >= 0 || rc == -EOVERFLOW);
1689
1690                 if (rc == 0) {
1691                         /* timed out: provide a diagnostic */
1692                         CWARN("Still waiting for ping MD to unlink\n");
1693                         timeout_ms *= 2;
1694                         continue;
1695                 }
1696
1697                 /* Got a valid event */
1698                 if (event.unlinked)
1699                         break;
1700         }
1701
1702         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1703         LASSERT (rc == 0);
1704         lnet_destroy_ping_info();
1705         cfs_restore_sigs(blocked);
1706 }
1707
1708 int
1709 lnet_ping (lnet_process_id_t id, int timeout_ms, lnet_process_id_t *ids, int n_ids)
1710 {
1711         lnet_handle_eq_t     eqh;
1712         lnet_handle_md_t     mdh;
1713         lnet_event_t         event;
1714         lnet_md_t            md = {0};
1715         int                  which;
1716         int                  unlinked = 0;
1717         int                  replied = 0;
1718         const int            a_long_time = 60000; /* mS */
1719         int                  infosz = offsetof(lnet_ping_info_t, pi_ni[n_ids]);
1720         lnet_ping_info_t    *info;
1721         lnet_process_id_t    tmpid;
1722         int                  i;
1723         int                  nob;
1724         int                  rc;
1725         int                  rc2;
1726         cfs_sigset_t         blocked;
1727
1728         if (n_ids <= 0 ||
1729             id.nid == LNET_NID_ANY ||
1730             timeout_ms > 500000 ||              /* arbitrary limit! */
1731             n_ids > 20)                         /* arbitrary limit! */
1732                 return -EINVAL;
1733
1734         if (id.pid == LNET_PID_ANY)
1735                 id.pid = LUSTRE_SRV_LNET_PID;
1736
1737         LIBCFS_ALLOC(info, infosz);
1738         if (info == NULL)
1739                 return -ENOMEM;
1740
1741         /* NB 2 events max (including any unlink event) */
1742         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
1743         if (rc != 0) {
1744                 CERROR("Can't allocate EQ: %d\n", rc);
1745                 goto out_0;
1746         }
1747
1748         /* initialize md content */
1749         md.start     = info;
1750         md.length    = infosz;
1751         md.threshold = 2; /*GET/REPLY*/
1752         md.max_size  = 0;
1753         md.options   = LNET_MD_TRUNCATE;
1754         md.user_ptr  = NULL;
1755         md.eq_handle = eqh;
1756
1757         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
1758         if (rc != 0) {
1759                 CERROR("Can't bind MD: %d\n", rc);
1760                 goto out_1;
1761         }
1762
1763         rc = LNetGet(LNET_NID_ANY, mdh, id,
1764                      LNET_RESERVED_PORTAL,
1765                      LNET_PROTO_PING_MATCHBITS, 0);
1766
1767         if (rc != 0) {
1768                 /* Don't CERROR; this could be deliberate! */
1769
1770                 rc2 = LNetMDUnlink(mdh);
1771                 LASSERT (rc2 == 0);
1772
1773                 /* NB must wait for the UNLINK event below... */
1774                 unlinked = 1;
1775                 timeout_ms = a_long_time;
1776         }
1777
1778         do {
1779                 /* MUST block for unlink to complete */
1780                 if (unlinked)
1781                         blocked = cfs_block_allsigs();
1782
1783                 rc2 = LNetEQPoll(&eqh, 1, timeout_ms, &event, &which);
1784
1785                 if (unlinked)
1786                         cfs_restore_sigs(blocked);
1787
1788                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
1789                        (rc2 <= 0) ? -1 : event.type,
1790                        (rc2 <= 0) ? -1 : event.status,
1791                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
1792
1793                 LASSERT (rc2 != -EOVERFLOW);     /* can't miss anything */
1794
1795                 if (rc2 <= 0 || event.status != 0) {
1796                         /* timeout or error */
1797                         if (!replied && rc == 0)
1798                                 rc = (rc2 < 0) ? rc2 :
1799                                      (rc2 == 0) ? -ETIMEDOUT :
1800                                      event.status;
1801
1802                         if (!unlinked) {
1803                                 /* Ensure completion in finite time... */
1804                                 LNetMDUnlink(mdh);
1805                                 /* No assertion (racing with network) */
1806                                 unlinked = 1;
1807                                 timeout_ms = a_long_time;
1808                         } else if (rc2 == 0) {
1809                                 /* timed out waiting for unlink */
1810                                 CWARN("ping %s: late network completion\n",
1811                                       libcfs_id2str(id));
1812                         }
1813                 } else if (event.type == LNET_EVENT_REPLY) {
1814                         replied = 1;
1815                         rc = event.mlength;
1816                 }
1817
1818         } while (rc2 <= 0 || !event.unlinked);
1819
1820         if (!replied) {
1821                 if (rc >= 0)
1822                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
1823                               libcfs_id2str(id));
1824                 rc = -EIO;
1825                 goto out_1;
1826         }
1827
1828         nob = rc;
1829         LASSERT (nob >= 0 && nob <= infosz);
1830
1831         rc = -EPROTO;                           /* if I can't parse... */
1832
1833         if (nob < 8) {
1834                 /* can't check magic/version */
1835                 CERROR("%s: ping info too short %d\n",
1836                        libcfs_id2str(id), nob);
1837                 goto out_1;
1838         }
1839
1840         if (info->pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
1841                 lnet_swap_pinginfo(info);
1842         } else if (info->pi_magic != LNET_PROTO_PING_MAGIC) {
1843                 CERROR("%s: Unexpected magic %08x\n", 
1844                        libcfs_id2str(id), info->pi_magic);
1845                 goto out_1;
1846         }
1847
1848         if (info->pi_version != LNET_PROTO_PING_VERSION) {
1849                 CERROR("%s: Unexpected version 0x%x\n",
1850                        libcfs_id2str(id), info->pi_version);
1851                 goto out_1;
1852         }
1853
1854         if (nob < offsetof(lnet_ping_info_t, pi_ni[0])) {
1855                 CERROR("%s: Short reply %d(%d min)\n", libcfs_id2str(id),
1856                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[0]));
1857                 goto out_1;
1858         }
1859
1860         if (info->pi_nnis < n_ids)
1861                 n_ids = info->pi_nnis;
1862
1863         if (nob < offsetof(lnet_ping_info_t, pi_ni[n_ids])) {
1864                 CERROR("%s: Short reply %d(%d expected)\n", libcfs_id2str(id),
1865                        nob, (int)offsetof(lnet_ping_info_t, pi_ni[n_ids]));
1866                 goto out_1;
1867         }
1868
1869         rc = -EFAULT;                           /* If I SEGV... */
1870
1871         for (i = 0; i < n_ids; i++) {
1872                 tmpid.pid = info->pi_pid;
1873                 tmpid.nid = info->pi_ni[i].ns_nid;
1874 #ifdef __KERNEL__
1875                 if (cfs_copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
1876                         goto out_1;
1877 #else
1878                 ids[i] = tmpid;
1879 #endif
1880         }
1881         rc = info->pi_nnis;
1882
1883  out_1:
1884         rc2 = LNetEQFree(eqh);
1885         if (rc2 != 0)
1886                 CERROR("rc2 %d\n", rc2);
1887         LASSERT (rc2 == 0);
1888
1889  out_0:
1890         LIBCFS_FREE(info, infosz);
1891         return rc;
1892 }