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