Whamcloud - gitweb
LU-1346 libcfs: cleanup waitq related primitives
[fs/lustre-release.git] / lustre / ptlrpc / events.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) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 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_RPC
38
39 #ifndef __KERNEL__
40 # include <liblustre.h>
41 #else
42 # include <libcfs/libcfs.h>
43 # ifdef __mips64__
44 #  include <linux/kernel.h>
45 # endif
46 #endif
47
48 #include <obd_class.h>
49 #include <lustre_net.h>
50 #include <lustre_sec.h>
51 #include "ptlrpc_internal.h"
52
53 lnet_handle_eq_t   ptlrpc_eq_h;
54
55 /*
56  *  Client's outgoing request callback
57  */
58 void request_out_callback(lnet_event_t *ev)
59 {
60         struct ptlrpc_cb_id   *cbid = ev->md.user_ptr;
61         struct ptlrpc_request *req = cbid->cbid_arg;
62         ENTRY;
63
64         LASSERT (ev->type == LNET_EVENT_SEND ||
65                  ev->type == LNET_EVENT_UNLINK);
66         LASSERT (ev->unlinked);
67
68         DEBUG_REQ(D_NET, req, "type %d, status %d", ev->type, ev->status);
69
70         sptlrpc_request_out_callback(req);
71         req->rq_real_sent = cfs_time_current_sec();
72
73         if (ev->type == LNET_EVENT_UNLINK || ev->status != 0) {
74
75                 /* Failed send: make it seem like the reply timed out, just
76                  * like failing sends in client.c does currently...  */
77
78                 spin_lock(&req->rq_lock);
79                 req->rq_net_err = 1;
80                 spin_unlock(&req->rq_lock);
81
82                 ptlrpc_client_wake_req(req);
83         }
84
85         ptlrpc_req_finished(req);
86
87         EXIT;
88 }
89
90 /*
91  * Client's incoming reply callback
92  */
93 void reply_in_callback(lnet_event_t *ev)
94 {
95         struct ptlrpc_cb_id   *cbid = ev->md.user_ptr;
96         struct ptlrpc_request *req = cbid->cbid_arg;
97         ENTRY;
98
99         DEBUG_REQ(D_NET, req, "type %d, status %d", ev->type, ev->status);
100
101         LASSERT (ev->type == LNET_EVENT_PUT || ev->type == LNET_EVENT_UNLINK);
102         LASSERT (ev->md.start == req->rq_repbuf);
103         LASSERT (ev->offset + ev->mlength <= req->rq_repbuf_len);
104         /* We've set LNET_MD_MANAGE_REMOTE for all outgoing requests
105            for adaptive timeouts' early reply. */
106         LASSERT((ev->md.options & LNET_MD_MANAGE_REMOTE) != 0);
107
108         spin_lock(&req->rq_lock);
109
110         req->rq_receiving_reply = 0;
111         req->rq_early = 0;
112         if (ev->unlinked)
113                 req->rq_must_unlink = 0;
114
115         if (ev->status)
116                 goto out_wake;
117
118         if (ev->type == LNET_EVENT_UNLINK) {
119                 LASSERT(ev->unlinked);
120                 DEBUG_REQ(D_NET, req, "unlink");
121                 goto out_wake;
122         }
123
124         if (ev->mlength < ev->rlength ) {
125                 CDEBUG(D_RPCTRACE, "truncate req %p rpc %d - %d+%d\n", req,
126                        req->rq_replen, ev->rlength, ev->offset);
127                 req->rq_reply_truncate = 1;
128                 req->rq_replied = 1;
129                 req->rq_status = -EOVERFLOW;
130                 req->rq_nob_received = ev->rlength + ev->offset;
131                 goto out_wake;
132         }
133
134         if ((ev->offset == 0) &&
135             ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT))) {
136                 /* Early reply */
137                 DEBUG_REQ(D_ADAPTTO, req,
138                           "Early reply received: mlen=%u offset=%d replen=%d "
139                           "replied=%d unlinked=%d", ev->mlength, ev->offset,
140                           req->rq_replen, req->rq_replied, ev->unlinked);
141
142                 req->rq_early_count++; /* number received, client side */
143
144                 if (req->rq_replied)   /* already got the real reply */
145                         goto out_wake;
146
147                 req->rq_early = 1;
148                 req->rq_reply_off = ev->offset;
149                 req->rq_nob_received = ev->mlength;
150                 /* And we're still receiving */
151                 req->rq_receiving_reply = 1;
152         } else {
153                 /* Real reply */
154                 req->rq_rep_swab_mask = 0;
155                 req->rq_replied = 1;
156                 req->rq_reply_off = ev->offset;
157                 req->rq_nob_received = ev->mlength;
158                 /* LNetMDUnlink can't be called under the LNET_LOCK,
159                    so we must unlink in ptlrpc_unregister_reply */
160                 DEBUG_REQ(D_INFO, req,
161                           "reply in flags=%x mlen=%u offset=%d replen=%d",
162                           lustre_msg_get_flags(req->rq_reqmsg),
163                           ev->mlength, ev->offset, req->rq_replen);
164         }
165
166         req->rq_import->imp_last_reply_time = cfs_time_current_sec();
167
168 out_wake:
169         /* NB don't unlock till after wakeup; req can disappear under us
170          * since we don't have our own ref */
171         ptlrpc_client_wake_req(req);
172         spin_unlock(&req->rq_lock);
173         EXIT;
174 }
175
176 /*
177  * Client's bulk has been written/read
178  */
179 void client_bulk_callback (lnet_event_t *ev)
180 {
181         struct ptlrpc_cb_id     *cbid = ev->md.user_ptr;
182         struct ptlrpc_bulk_desc *desc = cbid->cbid_arg;
183         struct ptlrpc_request   *req;
184         ENTRY;
185
186         LASSERT ((desc->bd_type == BULK_PUT_SINK &&
187                   ev->type == LNET_EVENT_PUT) ||
188                  (desc->bd_type == BULK_GET_SOURCE &&
189                   ev->type == LNET_EVENT_GET) ||
190                  ev->type == LNET_EVENT_UNLINK);
191         LASSERT (ev->unlinked);
192
193         if (CFS_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_CLIENT_BULK_CB, CFS_FAIL_ONCE))
194                 ev->status = -EIO;
195
196         if (CFS_FAIL_CHECK_ORSET(OBD_FAIL_PTLRPC_CLIENT_BULK_CB2,CFS_FAIL_ONCE))
197                 ev->status = -EIO;
198
199         CDEBUG((ev->status == 0) ? D_NET : D_ERROR,
200                "event type %d, status %d, desc %p\n",
201                ev->type, ev->status, desc);
202
203         spin_lock(&desc->bd_lock);
204         req = desc->bd_req;
205         LASSERT(desc->bd_md_count > 0);
206         desc->bd_md_count--;
207
208         if (ev->type != LNET_EVENT_UNLINK && ev->status == 0) {
209                 desc->bd_nob_transferred += ev->mlength;
210                 desc->bd_sender = ev->sender;
211         } else {
212                 /* start reconnect and resend if network error hit */
213                 spin_lock(&req->rq_lock);
214                 req->rq_net_err = 1;
215                 spin_unlock(&req->rq_lock);
216         }
217
218         if (ev->status != 0)
219                 desc->bd_failure = 1;
220
221         /* NB don't unlock till after wakeup; desc can disappear under us
222          * otherwise */
223         if (desc->bd_md_count == 0)
224                 ptlrpc_client_wake_req(desc->bd_req);
225
226         spin_unlock(&desc->bd_lock);
227         EXIT;
228 }
229
230 /*
231  * We will have percpt request history list for ptlrpc service in upcoming
232  * patches because we don't want to be serialized by current per-service
233  * history operations. So we require history ID can (somehow) show arriving
234  * order w/o grabbing global lock, and user can sort them in userspace.
235  *
236  * This is how we generate history ID for ptlrpc_request:
237  * ----------------------------------------------------
238  * |  32 bits  |  16 bits  | (16 - X)bits  |  X bits  |
239  * ----------------------------------------------------
240  * |  seconds  | usec / 16 |   sequence    | CPT id   |
241  * ----------------------------------------------------
242  *
243  * it might not be precise but should be good enough.
244  */
245
246 #define REQS_CPT_BITS(svcpt)    ((svcpt)->scp_service->srv_cpt_bits)
247
248 #define REQS_SEC_SHIFT          32
249 #define REQS_USEC_SHIFT         16
250 #define REQS_SEQ_SHIFT(svcpt)   REQS_CPT_BITS(svcpt)
251
252 static void ptlrpc_req_add_history(struct ptlrpc_service_part *svcpt,
253                                    struct ptlrpc_request *req)
254 {
255         __u64   sec = req->rq_arrival_time.tv_sec;
256         __u32   usec = req->rq_arrival_time.tv_usec >> 4; /* usec / 16 */
257         __u64   new_seq;
258
259         /* set sequence ID for request and add it to history list,
260          * it must be called with hold svcpt::scp_lock */
261
262         new_seq = (sec << REQS_SEC_SHIFT) |
263                   (usec << REQS_USEC_SHIFT) |
264                   (svcpt->scp_cpt < 0 ? 0 : svcpt->scp_cpt);
265
266         if (new_seq > svcpt->scp_hist_seq) {
267                 /* This handles the initial case of scp_hist_seq == 0 or
268                  * we just jumped into a new time window */
269                 svcpt->scp_hist_seq = new_seq;
270         } else {
271                 LASSERT(REQS_SEQ_SHIFT(svcpt) < REQS_USEC_SHIFT);
272                 /* NB: increase sequence number in current usec bucket,
273                  * however, it's possible that we used up all bits for
274                  * sequence and jumped into the next usec bucket (future time),
275                  * then we hope there will be less RPCs per bucket at some
276                  * point, and sequence will catch up again */
277                 svcpt->scp_hist_seq += (1U << REQS_SEQ_SHIFT(svcpt));
278                 new_seq = svcpt->scp_hist_seq;
279         }
280
281         req->rq_history_seq = new_seq;
282
283         cfs_list_add_tail(&req->rq_history_list, &svcpt->scp_hist_reqs);
284 }
285
286 /*
287  * Server's incoming request callback
288  */
289 void request_in_callback(lnet_event_t *ev)
290 {
291         struct ptlrpc_cb_id               *cbid = ev->md.user_ptr;
292         struct ptlrpc_request_buffer_desc *rqbd = cbid->cbid_arg;
293         struct ptlrpc_service_part        *svcpt = rqbd->rqbd_svcpt;
294         struct ptlrpc_service             *service = svcpt->scp_service;
295         struct ptlrpc_request             *req;
296         ENTRY;
297
298         LASSERT (ev->type == LNET_EVENT_PUT ||
299                  ev->type == LNET_EVENT_UNLINK);
300         LASSERT ((char *)ev->md.start >= rqbd->rqbd_buffer);
301         LASSERT ((char *)ev->md.start + ev->offset + ev->mlength <=
302                  rqbd->rqbd_buffer + service->srv_buf_size);
303
304         CDEBUG((ev->status == 0) ? D_NET : D_ERROR,
305                "event type %d, status %d, service %s\n",
306                ev->type, ev->status, service->srv_name);
307
308         if (ev->unlinked) {
309                 /* If this is the last request message to fit in the
310                  * request buffer we can use the request object embedded in
311                  * rqbd.  Note that if we failed to allocate a request,
312                  * we'd have to re-post the rqbd, which we can't do in this
313                  * context. */
314                 req = &rqbd->rqbd_req;
315                 memset(req, 0, sizeof (*req));
316         } else {
317                 LASSERT (ev->type == LNET_EVENT_PUT);
318                 if (ev->status != 0) {
319                         /* We moaned above already... */
320                         return;
321                 }
322                 req = ptlrpc_request_cache_alloc(ALLOC_ATOMIC_TRY);
323                 if (req == NULL) {
324                         CERROR("Can't allocate incoming request descriptor: "
325                                "Dropping %s RPC from %s\n",
326                                service->srv_name,
327                                libcfs_id2str(ev->initiator));
328                         return;
329                 }
330         }
331
332         /* NB we ABSOLUTELY RELY on req being zeroed, so pointers are NULL,
333          * flags are reset and scalars are zero.  We only set the message
334          * size to non-zero if this was a successful receive. */
335         req->rq_xid = ev->match_bits;
336         req->rq_reqbuf = ev->md.start + ev->offset;
337         if (ev->type == LNET_EVENT_PUT && ev->status == 0)
338                 req->rq_reqdata_len = ev->mlength;
339         do_gettimeofday(&req->rq_arrival_time);
340         req->rq_peer = ev->initiator;
341         req->rq_self = ev->target.nid;
342         req->rq_rqbd = rqbd;
343         req->rq_phase = RQ_PHASE_NEW;
344         spin_lock_init(&req->rq_lock);
345         CFS_INIT_LIST_HEAD(&req->rq_timed_list);
346         CFS_INIT_LIST_HEAD(&req->rq_exp_list);
347         cfs_atomic_set(&req->rq_refcount, 1);
348         if (ev->type == LNET_EVENT_PUT)
349                 CDEBUG(D_INFO, "incoming req@%p x"LPU64" msgsize %u\n",
350                        req, req->rq_xid, ev->mlength);
351
352         CDEBUG(D_RPCTRACE, "peer: %s\n", libcfs_id2str(req->rq_peer));
353
354         spin_lock(&svcpt->scp_lock);
355
356         ptlrpc_req_add_history(svcpt, req);
357
358         if (ev->unlinked) {
359                 svcpt->scp_nrqbds_posted--;
360                 CDEBUG(D_INFO, "Buffer complete: %d buffers still posted\n",
361                        svcpt->scp_nrqbds_posted);
362
363                 /* Normally, don't complain about 0 buffers posted; LNET won't
364                  * drop incoming reqs since we set the portal lazy */
365                 if (test_req_buffer_pressure &&
366                     ev->type != LNET_EVENT_UNLINK &&
367                     svcpt->scp_nrqbds_posted == 0)
368                         CWARN("All %s request buffers busy\n",
369                               service->srv_name);
370
371                 /* req takes over the network's ref on rqbd */
372         } else {
373                 /* req takes a ref on rqbd */
374                 rqbd->rqbd_refcount++;
375         }
376
377         cfs_list_add_tail(&req->rq_list, &svcpt->scp_req_incoming);
378         svcpt->scp_nreqs_incoming++;
379
380         /* NB everything can disappear under us once the request
381          * has been queued and we unlock, so do the wake now... */
382         wake_up(&svcpt->scp_waitq);
383
384         spin_unlock(&svcpt->scp_lock);
385         EXIT;
386 }
387
388 /*
389  *  Server's outgoing reply callback
390  */
391 void reply_out_callback(lnet_event_t *ev)
392 {
393         struct ptlrpc_cb_id       *cbid = ev->md.user_ptr;
394         struct ptlrpc_reply_state *rs = cbid->cbid_arg;
395         struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
396         ENTRY;
397
398         LASSERT (ev->type == LNET_EVENT_SEND ||
399                  ev->type == LNET_EVENT_ACK ||
400                  ev->type == LNET_EVENT_UNLINK);
401
402         if (!rs->rs_difficult) {
403                 /* 'Easy' replies have no further processing so I drop the
404                  * net's ref on 'rs' */
405                 LASSERT (ev->unlinked);
406                 ptlrpc_rs_decref(rs);
407                 EXIT;
408                 return;
409         }
410
411         LASSERT (rs->rs_on_net);
412
413         if (ev->unlinked) {
414                 /* Last network callback. The net's ref on 'rs' stays put
415                  * until ptlrpc_handle_rs() is done with it */
416                 spin_lock(&svcpt->scp_rep_lock);
417                 spin_lock(&rs->rs_lock);
418
419                 rs->rs_on_net = 0;
420                 if (!rs->rs_no_ack ||
421                     rs->rs_transno <=
422                     rs->rs_export->exp_obd->obd_last_committed)
423                         ptlrpc_schedule_difficult_reply(rs);
424
425                 spin_unlock(&rs->rs_lock);
426                 spin_unlock(&svcpt->scp_rep_lock);
427         }
428         EXIT;
429 }
430
431 #ifdef HAVE_SERVER_SUPPORT
432 /*
433  * Server's bulk completion callback
434  */
435 void server_bulk_callback (lnet_event_t *ev)
436 {
437         struct ptlrpc_cb_id     *cbid = ev->md.user_ptr;
438         struct ptlrpc_bulk_desc *desc = cbid->cbid_arg;
439         ENTRY;
440
441         LASSERT(ev->type == LNET_EVENT_SEND ||
442                 ev->type == LNET_EVENT_UNLINK ||
443                 (desc->bd_type == BULK_PUT_SOURCE &&
444                  ev->type == LNET_EVENT_ACK) ||
445                 (desc->bd_type == BULK_GET_SINK &&
446                  ev->type == LNET_EVENT_REPLY));
447
448         CDEBUG((ev->status == 0) ? D_NET : D_ERROR,
449                "event type %d, status %d, desc %p\n",
450                ev->type, ev->status, desc);
451
452         spin_lock(&desc->bd_lock);
453
454         LASSERT(desc->bd_md_count > 0);
455
456         if ((ev->type == LNET_EVENT_ACK ||
457              ev->type == LNET_EVENT_REPLY) &&
458             ev->status == 0) {
459                 /* We heard back from the peer, so even if we get this
460                  * before the SENT event (oh yes we can), we know we
461                  * read/wrote the peer buffer and how much... */
462                 desc->bd_nob_transferred += ev->mlength;
463                 desc->bd_sender = ev->sender;
464         }
465
466         if (ev->status != 0)
467                 desc->bd_failure = 1;
468
469         if (ev->unlinked) {
470                 desc->bd_md_count--;
471                 /* This is the last callback no matter what... */
472                 if (desc->bd_md_count == 0)
473                         wake_up(&desc->bd_waitq);
474         }
475
476         spin_unlock(&desc->bd_lock);
477         EXIT;
478 }
479 #endif
480
481 static void ptlrpc_master_callback(lnet_event_t *ev)
482 {
483         struct ptlrpc_cb_id *cbid = ev->md.user_ptr;
484         void (*callback)(lnet_event_t *ev) = cbid->cbid_fn;
485
486         /* Honestly, it's best to find out early. */
487         LASSERT (cbid->cbid_arg != LP_POISON);
488         LASSERT (callback == request_out_callback ||
489                  callback == reply_in_callback ||
490                  callback == client_bulk_callback ||
491                  callback == request_in_callback ||
492                  callback == reply_out_callback
493 #ifdef HAVE_SERVER_SUPPORT
494                  || callback == server_bulk_callback
495 #endif
496                  );
497
498         callback (ev);
499 }
500
501 int ptlrpc_uuid_to_peer (struct obd_uuid *uuid,
502                          lnet_process_id_t *peer, lnet_nid_t *self)
503 {
504         int               best_dist = 0;
505         __u32             best_order = 0;
506         int               count = 0;
507         int               rc = -ENOENT;
508         int               portals_compatibility;
509         int               dist;
510         __u32             order;
511         lnet_nid_t        dst_nid;
512         lnet_nid_t        src_nid;
513
514         portals_compatibility = LNetCtl(IOC_LIBCFS_PORTALS_COMPATIBILITY, NULL);
515
516         peer->pid = LUSTRE_SRV_LNET_PID;
517
518         /* Choose the matching UUID that's closest */
519         while (lustre_uuid_to_peer(uuid->uuid, &dst_nid, count++) == 0) {
520                 dist = LNetDist(dst_nid, &src_nid, &order);
521                 if (dist < 0)
522                         continue;
523
524                 if (dist == 0) {                /* local! use loopback LND */
525                         peer->nid = *self = LNET_MKNID(LNET_MKNET(LOLND, 0), 0);
526                         rc = 0;
527                         break;
528                 }
529
530                 if (rc < 0 ||
531                     dist < best_dist ||
532                     (dist == best_dist && order < best_order)) {
533                         best_dist = dist;
534                         best_order = order;
535
536                         if (portals_compatibility > 1) {
537                                 /* Strong portals compatibility: Zero the nid's
538                                  * NET, so if I'm reading new config logs, or
539                                  * getting configured by (new) lconf I can
540                                  * still talk to old servers. */
541                                 dst_nid = LNET_MKNID(0, LNET_NIDADDR(dst_nid));
542                                 src_nid = LNET_MKNID(0, LNET_NIDADDR(src_nid));
543                         }
544                         peer->nid = dst_nid;
545                         *self = src_nid;
546                         rc = 0;
547                 }
548         }
549
550         CDEBUG(D_NET,"%s->%s\n", uuid->uuid, libcfs_id2str(*peer));
551         return rc;
552 }
553
554 void ptlrpc_ni_fini(void)
555 {
556         wait_queue_head_t         waitq;
557         struct l_wait_info  lwi;
558         int                 rc;
559         int                 retries;
560
561         /* Wait for the event queue to become idle since there may still be
562          * messages in flight with pending events (i.e. the fire-and-forget
563          * messages == client requests and "non-difficult" server
564          * replies */
565
566         for (retries = 0;; retries++) {
567                 rc = LNetEQFree(ptlrpc_eq_h);
568                 switch (rc) {
569                 default:
570                         LBUG();
571
572                 case 0:
573                         LNetNIFini();
574                         return;
575
576                 case -EBUSY:
577                         if (retries != 0)
578                                 CWARN("Event queue still busy\n");
579
580                         /* Wait for a bit */
581                         init_waitqueue_head(&waitq);
582                         lwi = LWI_TIMEOUT(cfs_time_seconds(2), NULL, NULL);
583                         l_wait_event(waitq, 0, &lwi);
584                         break;
585                 }
586         }
587         /* notreached */
588 }
589
590 lnet_pid_t ptl_get_pid(void)
591 {
592         lnet_pid_t        pid;
593
594 #ifndef  __KERNEL__
595         pid = getpid();
596 #else
597         pid = LUSTRE_SRV_LNET_PID;
598 #endif
599         return pid;
600 }
601
602 int ptlrpc_ni_init(void)
603 {
604         int              rc;
605         lnet_pid_t       pid;
606
607         pid = ptl_get_pid();
608         CDEBUG(D_NET, "My pid is: %x\n", pid);
609
610         /* We're not passing any limits yet... */
611         rc = LNetNIInit(pid);
612         if (rc < 0) {
613                 CDEBUG (D_NET, "Can't init network interface: %d\n", rc);
614                 return (-ENOENT);
615         }
616
617         /* CAVEAT EMPTOR: how we process portals events is _radically_
618          * different depending on... */
619 #ifdef __KERNEL__
620         /* kernel LNet calls our master callback when there are new event,
621          * because we are guaranteed to get every event via callback,
622          * so we just set EQ size to 0 to avoid overhread of serializing
623          * enqueue/dequeue operations in LNet. */
624         rc = LNetEQAlloc(0, ptlrpc_master_callback, &ptlrpc_eq_h);
625 #else
626         /* liblustre calls the master callback when it removes events from the
627          * event queue.  The event queue has to be big enough not to drop
628          * anything */
629         rc = LNetEQAlloc(10240, LNET_EQ_HANDLER_NONE, &ptlrpc_eq_h);
630 #endif
631         if (rc == 0)
632                 return 0;
633
634         CERROR ("Failed to allocate event queue: %d\n", rc);
635         LNetNIFini();
636
637         return (-ENOMEM);
638 }
639
640 #ifndef __KERNEL__
641 CFS_LIST_HEAD(liblustre_wait_callbacks);
642 CFS_LIST_HEAD(liblustre_idle_callbacks);
643 void *liblustre_services_callback;
644
645 void *
646 liblustre_register_waitidle_callback (cfs_list_t *callback_list,
647                                       const char *name,
648                                       int (*fn)(void *arg), void *arg)
649 {
650         struct liblustre_wait_callback *llwc;
651
652         OBD_ALLOC(llwc, sizeof(*llwc));
653         LASSERT (llwc != NULL);
654
655         llwc->llwc_name = name;
656         llwc->llwc_fn = fn;
657         llwc->llwc_arg = arg;
658         cfs_list_add_tail(&llwc->llwc_list, callback_list);
659
660         return (llwc);
661 }
662
663 void
664 liblustre_deregister_waitidle_callback (void *opaque)
665 {
666         struct liblustre_wait_callback *llwc = opaque;
667
668         cfs_list_del(&llwc->llwc_list);
669         OBD_FREE(llwc, sizeof(*llwc));
670 }
671
672 void *
673 liblustre_register_wait_callback (const char *name,
674                                   int (*fn)(void *arg), void *arg)
675 {
676         return liblustre_register_waitidle_callback(&liblustre_wait_callbacks,
677                                                     name, fn, arg);
678 }
679
680 void
681 liblustre_deregister_wait_callback (void *opaque)
682 {
683         liblustre_deregister_waitidle_callback(opaque);
684 }
685
686 void *
687 liblustre_register_idle_callback (const char *name,
688                                   int (*fn)(void *arg), void *arg)
689 {
690         return liblustre_register_waitidle_callback(&liblustre_idle_callbacks,
691                                                     name, fn, arg);
692 }
693
694 void
695 liblustre_deregister_idle_callback (void *opaque)
696 {
697         liblustre_deregister_waitidle_callback(opaque);
698 }
699
700 int
701 liblustre_check_events (int timeout)
702 {
703         lnet_event_t ev;
704         int         rc;
705         int         i;
706         ENTRY;
707
708         rc = LNetEQPoll(&ptlrpc_eq_h, 1, timeout * 1000, &ev, &i);
709         if (rc == 0)
710                 RETURN(0);
711
712         LASSERT (rc == -EOVERFLOW || rc == 1);
713
714         /* liblustre: no asynch callback so we can't afford to miss any
715          * events... */
716         if (rc == -EOVERFLOW) {
717                 CERROR ("Dropped an event!!!\n");
718                 abort();
719         }
720
721         ptlrpc_master_callback (&ev);
722         RETURN(1);
723 }
724
725 int liblustre_waiting = 0;
726
727 int
728 liblustre_wait_event (int timeout)
729 {
730         cfs_list_t                     *tmp;
731         struct liblustre_wait_callback *llwc;
732         int                             found_something = 0;
733
734         /* single threaded recursion check... */
735         liblustre_waiting = 1;
736
737         for (;;) {
738                 /* Deal with all pending events */
739                 while (liblustre_check_events(0))
740                         found_something = 1;
741
742                 /* Give all registered callbacks a bite at the cherry */
743                 cfs_list_for_each(tmp, &liblustre_wait_callbacks) {
744                         llwc = cfs_list_entry(tmp,
745                                               struct liblustre_wait_callback,
746                                               llwc_list);
747
748                         if (llwc->llwc_fn(llwc->llwc_arg))
749                                 found_something = 1;
750                 }
751
752                 if (found_something || timeout == 0)
753                         break;
754
755                 /* Nothing so far, but I'm allowed to block... */
756                 found_something = liblustre_check_events(timeout);
757                 if (!found_something)           /* still nothing */
758                         break;                  /* I timed out */
759         }
760
761         liblustre_waiting = 0;
762
763         return found_something;
764 }
765
766 void
767 liblustre_wait_idle(void)
768 {
769         static int recursed = 0;
770
771         cfs_list_t                     *tmp;
772         struct liblustre_wait_callback *llwc;
773         int                             idle = 0;
774
775         LASSERT(!recursed);
776         recursed = 1;
777
778         do {
779                 liblustre_wait_event(0);
780
781                 idle = 1;
782
783                 cfs_list_for_each(tmp, &liblustre_idle_callbacks) {
784                         llwc = cfs_list_entry(tmp,
785                                               struct liblustre_wait_callback,
786                                               llwc_list);
787
788                         if (!llwc->llwc_fn(llwc->llwc_arg)) {
789                                 idle = 0;
790                                 break;
791                         }
792                 }
793
794         } while (!idle);
795
796         recursed = 0;
797 }
798
799 #endif /* __KERNEL__ */
800
801 int ptlrpc_init_portals(void)
802 {
803         int   rc = ptlrpc_ni_init();
804
805         if (rc != 0) {
806                 CERROR("network initialisation failed\n");
807                 return -EIO;
808         }
809 #ifndef __KERNEL__
810         liblustre_services_callback =
811                 liblustre_register_wait_callback("liblustre_check_services",
812                                                  &liblustre_check_services,
813                                                  NULL);
814         init_completion_module(liblustre_wait_event);
815 #endif
816         rc = ptlrpcd_addref();
817         if (rc == 0)
818                 return 0;
819
820         CERROR("rpcd initialisation failed\n");
821 #ifndef __KERNEL__
822         liblustre_deregister_wait_callback(liblustre_services_callback);
823 #endif
824         ptlrpc_ni_fini();
825         return rc;
826 }
827
828 void ptlrpc_exit_portals(void)
829 {
830 #ifndef __KERNEL__
831         liblustre_deregister_wait_callback(liblustre_services_callback);
832 #endif
833         ptlrpcd_decref();
834         ptlrpc_ni_fini();
835 }