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