Whamcloud - gitweb
82c37cfcb9104d6ba6a40b5f9dada34b4a120edd
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ldlm/ldlm_lockd.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #ifndef EXPORT_SYMTAB
43 # define EXPORT_SYMTAB
44 #endif
45 #define DEBUG_SUBSYSTEM S_LDLM
46
47 #ifdef __KERNEL__
48 # include <libcfs/libcfs.h>
49 #else
50 # include <liblustre.h>
51 #endif
52
53 #include <lustre_dlm.h>
54 #include <obd_class.h>
55 #include <libcfs/list.h>
56 #include "ldlm_internal.h"
57
58 #ifdef __KERNEL__
59 static int ldlm_num_threads;
60 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
61                 "number of DLM service threads to start");
62 #endif
63
64 extern cfs_mem_cache_t *ldlm_resource_slab;
65 extern cfs_mem_cache_t *ldlm_lock_slab;
66 static struct semaphore ldlm_ref_sem;
67 static int ldlm_refcount;
68
69 /* LDLM state */
70
71 static struct ldlm_state *ldlm_state;
72
73 inline cfs_time_t round_timeout(cfs_time_t timeout)
74 {
75         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
76 }
77
78 /* timeout for initial callback (AST) reply (bz10399) */
79 static inline unsigned int ldlm_get_rq_timeout(void)
80 {
81         /* Non-AT value */
82         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
83
84         return timeout < 1 ? 1 : timeout;
85 }
86
87 #ifdef __KERNEL__
88 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
89 static spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
90 static struct list_head waiting_locks_list;
91 static cfs_timer_t waiting_locks_timer;
92
93 static struct expired_lock_thread {
94         cfs_waitq_t               elt_waitq;
95         int                       elt_state;
96         int                       elt_dump;
97         struct list_head          elt_expired_locks;
98 } expired_lock_thread;
99 #endif
100
101 #define ELT_STOPPED   0
102 #define ELT_READY     1
103 #define ELT_TERMINATE 2
104
105 struct ldlm_bl_pool {
106         spinlock_t              blp_lock;
107
108         /*
109          * blp_prio_list is used for callbacks that should be handled
110          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
111          * see bug 13843
112          */
113         struct list_head        blp_prio_list;
114
115         /*
116          * blp_list is used for all other callbacks which are likely
117          * to take longer to process.
118          */
119         struct list_head        blp_list;
120
121         cfs_waitq_t             blp_waitq;
122         struct completion       blp_comp;
123         atomic_t                blp_num_threads;
124         atomic_t                blp_busy_threads;
125         int                     blp_min_threads;
126         int                     blp_max_threads;
127 };
128
129 struct ldlm_bl_work_item {
130         struct list_head        blwi_entry;
131         struct ldlm_namespace   *blwi_ns;
132         struct ldlm_lock_desc   blwi_ld;
133         struct ldlm_lock        *blwi_lock;
134         struct list_head        blwi_head;
135         int                     blwi_count;
136 };
137
138 #ifdef __KERNEL__
139
140 static inline int have_expired_locks(void)
141 {
142         int need_to_run;
143
144         ENTRY;
145         spin_lock_bh(&waiting_locks_spinlock);
146         need_to_run = !list_empty(&expired_lock_thread.elt_expired_locks);
147         spin_unlock_bh(&waiting_locks_spinlock);
148
149         RETURN(need_to_run);
150 }
151
152 static int expired_lock_main(void *arg)
153 {
154         struct list_head *expired = &expired_lock_thread.elt_expired_locks;
155         struct l_wait_info lwi = { 0 };
156         int do_dump;
157
158         ENTRY;
159         cfs_daemonize("ldlm_elt");
160
161         expired_lock_thread.elt_state = ELT_READY;
162         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
163
164         while (1) {
165                 l_wait_event(expired_lock_thread.elt_waitq,
166                              have_expired_locks() ||
167                              expired_lock_thread.elt_state == ELT_TERMINATE,
168                              &lwi);
169
170                 spin_lock_bh(&waiting_locks_spinlock);
171                 if (expired_lock_thread.elt_dump) {
172                         spin_unlock_bh(&waiting_locks_spinlock);
173
174                         /* from waiting_locks_callback, but not in timer */
175                         libcfs_debug_dumplog();
176                         libcfs_run_lbug_upcall(__FILE__,
177                                                 "waiting_locks_callback",
178                                                 expired_lock_thread.elt_dump);
179
180                         spin_lock_bh(&waiting_locks_spinlock);
181                         expired_lock_thread.elt_dump = 0;
182                 }
183
184                 do_dump = 0;
185
186                 while (!list_empty(expired)) {
187                         struct obd_export *export;
188                         struct ldlm_lock *lock;
189
190                         lock = list_entry(expired->next, struct ldlm_lock,
191                                           l_pending_chain);
192                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
193                             (void *)lock >= LP_POISON) {
194                                 spin_unlock_bh(&waiting_locks_spinlock);
195                                 CERROR("free lock on elt list %p\n", lock);
196                                 LBUG();
197                         }
198                         list_del_init(&lock->l_pending_chain);
199                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
200                             (void *)lock->l_export >= LP_POISON) {
201                                 CERROR("lock with free export on elt list %p\n",
202                                        lock->l_export);
203                                 lock->l_export = NULL;
204                                 LDLM_ERROR(lock, "free export");
205                                 /* release extra ref grabbed by
206                                  * ldlm_add_waiting_lock() or
207                                  * ldlm_failed_ast() */
208                                 LDLM_LOCK_RELEASE(lock);
209                                 continue;
210                         }
211                         export = class_export_get(lock->l_export);
212                         spin_unlock_bh(&waiting_locks_spinlock);
213
214                         /* release extra ref grabbed by ldlm_add_waiting_lock()
215                          * or ldlm_failed_ast() */
216                         LDLM_LOCK_RELEASE(lock);
217
218                         do_dump++;
219                         class_fail_export(export);
220                         class_export_put(export);
221                         spin_lock_bh(&waiting_locks_spinlock);
222                 }
223                 spin_unlock_bh(&waiting_locks_spinlock);
224
225                 if (do_dump && obd_dump_on_eviction) {
226                         CERROR("dump the log upon eviction\n");
227                         libcfs_debug_dumplog();
228                 }
229
230                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
231                         break;
232         }
233
234         expired_lock_thread.elt_state = ELT_STOPPED;
235         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
236         RETURN(0);
237 }
238
239 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
240
241 /**
242  * Check if there is a request in the export request list
243  * which prevents the lock canceling.
244  */
245 static int ldlm_lock_busy(struct ldlm_lock *lock)
246 {
247         struct ptlrpc_request *req;
248         int match = 0;
249         ENTRY;
250
251         if (lock->l_export == NULL)
252                 return 0;
253
254         spin_lock(&lock->l_export->exp_lock);
255         list_for_each_entry(req, &lock->l_export->exp_queued_rpc, rq_exp_list) {
256                 if (req->rq_ops->hpreq_lock_match) {
257                         match = req->rq_ops->hpreq_lock_match(req, lock);
258                         if (match)
259                                 break;
260                 }
261         }
262         spin_unlock(&lock->l_export->exp_lock);
263         RETURN(match);
264 }
265
266 /* This is called from within a timer interrupt and cannot schedule */
267 static void waiting_locks_callback(unsigned long unused)
268 {
269         struct ldlm_lock *lock, *last = NULL;
270
271 repeat:
272         spin_lock_bh(&waiting_locks_spinlock);
273         while (!list_empty(&waiting_locks_list)) {
274                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
275                                   l_pending_chain);
276                 if (cfs_time_after(lock->l_callback_timeout, cfs_time_current()) ||
277                     (lock->l_req_mode == LCK_GROUP))
278                         break;
279
280                 if (ptlrpc_check_suspend()) {
281                         /* there is a case when we talk to one mds, holding
282                          * lock from another mds. this way we easily can get
283                          * here, if second mds is being recovered. so, we
284                          * suspend timeouts. bug 6019 */
285
286                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
287                                    lock->l_export->exp_client_uuid.uuid,
288                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
289                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
290
291                         list_del_init(&lock->l_pending_chain);
292                         spin_unlock_bh(&waiting_locks_spinlock);
293                         ldlm_add_waiting_lock(lock);
294                         goto repeat;
295                 }
296
297                 /* if timeout overlaps the activation time of suspended timeouts
298                  * then extend it to give a chance for client to reconnect */
299                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
300                                                  cfs_time_seconds(obd_timeout)/2),
301                                     ptlrpc_suspend_wakeup_time())) {
302                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
303                                    lock->l_export->exp_client_uuid.uuid,
304                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
305                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
306
307                         list_del_init(&lock->l_pending_chain);
308                         spin_unlock_bh(&waiting_locks_spinlock);
309                         ldlm_add_waiting_lock(lock);
310                         goto repeat;
311                 }
312
313                 /* Check if we need to prolong timeout */
314                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
315                     ldlm_lock_busy(lock)) {
316                         int cont = 1;
317
318                         if (lock->l_pending_chain.next == &waiting_locks_list)
319                                 cont = 0;
320
321                         LDLM_LOCK_GET(lock);
322
323                         spin_unlock_bh(&waiting_locks_spinlock);
324                         LDLM_DEBUG(lock, "prolong the busy lock");
325                         ldlm_refresh_waiting_lock(lock,
326                                                   ldlm_get_enq_timeout(lock));
327                         spin_lock_bh(&waiting_locks_spinlock);
328
329                         if (!cont) {
330                                 LDLM_LOCK_RELEASE(lock);
331                                 break;
332                         }
333
334                         LDLM_LOCK_RELEASE(lock);
335                         continue;
336                 }
337                 lock->l_resource->lr_namespace->ns_timeouts++;
338                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
339                            "evicting client at %s ",
340                            cfs_time_current_sec()- lock->l_last_activity,
341                            libcfs_nid2str(
342                                    lock->l_export->exp_connection->c_peer.nid));
343
344                 last = lock;
345
346                 /* no needs to take an extra ref on the lock since it was in
347                  * the waiting_locks_list and ldlm_add_waiting_lock()
348                  * already grabbed a ref */
349                 list_del(&lock->l_pending_chain);
350                 list_add(&lock->l_pending_chain,
351                          &expired_lock_thread.elt_expired_locks);
352         }
353
354         if (!list_empty(&expired_lock_thread.elt_expired_locks)) {
355                 if (obd_dump_on_timeout)
356                         expired_lock_thread.elt_dump = __LINE__;
357
358                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
359         }
360
361         /*
362          * Make sure the timer will fire again if we have any locks
363          * left.
364          */
365         if (!list_empty(&waiting_locks_list)) {
366                 cfs_time_t timeout_rounded;
367                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
368                                   l_pending_chain);
369                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
370                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
371         }
372         spin_unlock_bh(&waiting_locks_spinlock);
373 }
374
375 /*
376  * Indicate that we're waiting for a client to call us back cancelling a given
377  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
378  * timer to fire appropriately.  (We round up to the next second, to avoid
379  * floods of timer firings during periods of high lock contention and traffic).
380  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
381  * if it has been added to the waiting list (1 is returned).
382  *
383  * Called with the namespace lock held.
384  */
385 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
386 {
387         cfs_time_t timeout;
388         cfs_time_t timeout_rounded;
389
390         if (!list_empty(&lock->l_pending_chain))
391                 return 0;
392
393         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
394             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
395                 seconds = 1;
396
397         timeout = cfs_time_shift(seconds);
398         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
399                 lock->l_callback_timeout = timeout;
400
401         timeout_rounded = round_timeout(lock->l_callback_timeout);
402
403         if (cfs_time_before(timeout_rounded,
404                             cfs_timer_deadline(&waiting_locks_timer)) ||
405             !cfs_timer_is_armed(&waiting_locks_timer)) {
406                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
407         }
408         /* if the new lock has a shorter timeout than something earlier on
409            the list, we'll wait the longer amount of time; no big deal. */
410         list_add_tail(&lock->l_pending_chain, &waiting_locks_list); /* FIFO */
411         return 1;
412 }
413
414 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
415 {
416         int ret;
417         int timeout = ldlm_get_enq_timeout(lock);
418
419         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
420
421         spin_lock_bh(&waiting_locks_spinlock);
422         if (lock->l_destroyed) {
423                 static cfs_time_t next;
424                 spin_unlock_bh(&waiting_locks_spinlock);
425                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
426                 if (cfs_time_after(cfs_time_current(), next)) {
427                         next = cfs_time_shift(14400);
428                         libcfs_debug_dumpstack(NULL);
429                 }
430                 return 0;
431         }
432
433         ret = __ldlm_add_waiting_lock(lock, timeout);
434         if (ret)
435                 /* grab ref on the lock if it has been added to the
436                  * waiting list */
437                 LDLM_LOCK_GET(lock);
438         spin_unlock_bh(&waiting_locks_spinlock);
439
440         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
441                    ret == 0 ? "not re-" : "", timeout,
442                    AT_OFF ? "off" : "on");
443         return ret;
444 }
445
446 /*
447  * Remove a lock from the pending list, likely because it had its cancellation
448  * callback arrive without incident.  This adjusts the lock-timeout timer if
449  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
450  * As done by ldlm_del_waiting_lock(), the caller must release the lock
451  * reference when the lock is removed from any list (1 is returned).
452  *
453  * Called with namespace lock held.
454  */
455 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
456 {
457         struct list_head *list_next;
458
459         if (list_empty(&lock->l_pending_chain))
460                 return 0;
461
462         list_next = lock->l_pending_chain.next;
463         if (lock->l_pending_chain.prev == &waiting_locks_list) {
464                 /* Removing the head of the list, adjust timer. */
465                 if (list_next == &waiting_locks_list) {
466                         /* No more, just cancel. */
467                         cfs_timer_disarm(&waiting_locks_timer);
468                 } else {
469                         struct ldlm_lock *next;
470                         next = list_entry(list_next, struct ldlm_lock,
471                                           l_pending_chain);
472                         cfs_timer_arm(&waiting_locks_timer,
473                                       round_timeout(next->l_callback_timeout));
474                 }
475         }
476         list_del_init(&lock->l_pending_chain);
477
478         return 1;
479 }
480
481 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
482 {
483         int ret;
484
485         if (lock->l_export == NULL) {
486                 /* We don't have a "waiting locks list" on clients. */
487                 LDLM_DEBUG(lock, "client lock: no-op");
488                 return 0;
489         }
490
491         spin_lock_bh(&waiting_locks_spinlock);
492         ret = __ldlm_del_waiting_lock(lock);
493         spin_unlock_bh(&waiting_locks_spinlock);
494         if (ret)
495                 /* release lock ref if it has indeed been removed
496                  * from a list */
497                 LDLM_LOCK_RELEASE(lock);
498
499         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
500         return ret;
501 }
502
503 /*
504  * Prolong the lock
505  *
506  * Called with namespace lock held.
507  */
508 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
509 {
510         if (lock->l_export == NULL) {
511                 /* We don't have a "waiting locks list" on clients. */
512                 LDLM_DEBUG(lock, "client lock: no-op");
513                 return 0;
514         }
515
516         spin_lock_bh(&waiting_locks_spinlock);
517
518         if (list_empty(&lock->l_pending_chain)) {
519                 spin_unlock_bh(&waiting_locks_spinlock);
520                 LDLM_DEBUG(lock, "wasn't waiting");
521                 return 0;
522         }
523
524         /* we remove/add the lock to the waiting list, so no needs to
525          * release/take a lock reference */
526         __ldlm_del_waiting_lock(lock);
527         __ldlm_add_waiting_lock(lock, timeout);
528         spin_unlock_bh(&waiting_locks_spinlock);
529
530         LDLM_DEBUG(lock, "refreshed");
531         return 1;
532 }
533 #else /* !__KERNEL__ */
534
535 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
536 {
537         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
538         RETURN(1);
539 }
540
541 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
542 {
543         RETURN(0);
544 }
545
546 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
547 {
548         RETURN(0);
549 }
550 #endif /* __KERNEL__ */
551
552 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
553                             const char *ast_type)
554 {
555         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
556                            "to a lock %s callback time out: rc %d\n",
557                            lock->l_export->exp_obd->obd_name,
558                            obd_export_nid2str(lock->l_export), ast_type, rc);
559
560         if (obd_dump_on_timeout)
561                 libcfs_debug_dumplog();
562 #ifdef __KERNEL__
563         spin_lock_bh(&waiting_locks_spinlock);
564         if (__ldlm_del_waiting_lock(lock) == 0)
565                 /* the lock was not in any list, grab an extra ref before adding
566                  * the lock to the expired list */
567                 LDLM_LOCK_GET(lock);
568         list_add(&lock->l_pending_chain, &expired_lock_thread.elt_expired_locks);
569         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
570         spin_unlock_bh(&waiting_locks_spinlock);
571 #else
572         class_fail_export(lock->l_export);
573 #endif
574 }
575
576 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
577                                  struct ptlrpc_request *req, int rc,
578                                  const char *ast_type)
579 {
580         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
581
582         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
583                 LASSERT(lock->l_export);
584                 if (lock->l_export->exp_libclient) {
585                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
586                                    " timeout, just cancelling lock", ast_type,
587                                    libcfs_nid2str(peer.nid));
588                         ldlm_lock_cancel(lock);
589                         rc = -ERESTART;
590                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
591                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
592                                    "cancel was received (AST reply lost?)",
593                                    ast_type, libcfs_nid2str(peer.nid));
594                         ldlm_lock_cancel(lock);
595                         rc = -ERESTART;
596                 } else {
597                         ldlm_del_waiting_lock(lock);
598                         ldlm_failed_ast(lock, rc, ast_type);
599                 }
600         } else if (rc) {
601                 if (rc == -EINVAL)
602                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
603                                " from %s AST - normal race",
604                                libcfs_nid2str(peer.nid),
605                                req->rq_repmsg ?
606                                lustre_msg_get_status(req->rq_repmsg) : -1,
607                                ast_type);
608                 else
609                         LDLM_ERROR(lock, "client (nid %s) returned %d "
610                                    "from %s AST", libcfs_nid2str(peer.nid),
611                                    (req->rq_repmsg != NULL) ?
612                                    lustre_msg_get_status(req->rq_repmsg) : 0,
613                                    ast_type);
614                 ldlm_lock_cancel(lock);
615                 /* Server-side AST functions are called from ldlm_reprocess_all,
616                  * which needs to be told to please restart its reprocessing. */
617                 rc = -ERESTART;
618         }
619
620         return rc;
621 }
622
623 static int ldlm_cb_interpret(const struct lu_env *env,
624                              struct ptlrpc_request *req, void *data, int rc)
625 {
626         struct ldlm_cb_set_arg *arg;
627         struct ldlm_lock *lock;
628         ENTRY;
629
630         LASSERT(data != NULL);
631
632         arg = req->rq_async_args.pointer_arg[0];
633         lock = req->rq_async_args.pointer_arg[1];
634         LASSERT(lock != NULL);
635         if (rc != 0) {
636                 /* If client canceled the lock but the cancel has not
637                  * been recieved yet, we need to update lvbo to have the
638                  * proper attributes cached. */
639                 if (rc == -EINVAL && arg->type == LDLM_BL_CALLBACK)
640                         ldlm_res_lvbo_update(lock->l_resource, NULL,
641                                              0, 1);
642                 rc = ldlm_handle_ast_error(lock, req, rc,
643                                            arg->type == LDLM_BL_CALLBACK
644                                            ? "blocking" : "completion");
645         }
646
647         LDLM_LOCK_RELEASE(lock);
648
649         if (rc == -ERESTART)
650                 atomic_set(&arg->restart, 1);
651
652         RETURN(0);
653 }
654
655 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
656                                           struct ldlm_cb_set_arg *arg,
657                                           struct ldlm_lock *lock,
658                                           int instant_cancel)
659 {
660         int rc = 0;
661         ENTRY;
662
663         if (unlikely(instant_cancel)) {
664                 rc = ptl_send_rpc(req, 1);
665                 ptlrpc_req_finished(req);
666                 if (rc == 0)
667                         /* If we cancelled the lock, we need to restart
668                          * ldlm_reprocess_queue */
669                         atomic_set(&arg->restart, 1);
670         } else {
671                 LDLM_LOCK_GET(lock);
672                 ptlrpc_set_add_req(arg->set, req);
673         }
674
675         RETURN(rc);
676 }
677
678 /**
679  * Check if there are requests in the export request list which prevent
680  * the lock canceling and make these requests high priority ones.
681  */
682 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
683 {
684         struct ptlrpc_request *req;
685         ENTRY;
686
687         if (lock->l_export == NULL) {
688                 LDLM_DEBUG(lock, "client lock: no-op");
689                 RETURN_EXIT;
690         }
691
692         spin_lock(&lock->l_export->exp_lock);
693         list_for_each_entry(req, &lock->l_export->exp_queued_rpc, rq_exp_list) {
694                 if (!req->rq_hp && req->rq_ops->hpreq_lock_match &&
695                     req->rq_ops->hpreq_lock_match(req, lock))
696                         ptlrpc_hpreq_reorder(req);
697         }
698         spin_unlock(&lock->l_export->exp_lock);
699         EXIT;
700 }
701
702 /*
703  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
704  * enqueued server lock conflicts with given one.
705  *
706  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
707  * to wait for client response.
708  */
709 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
710                              struct ldlm_lock_desc *desc,
711                              void *data, int flag)
712 {
713         struct ldlm_cb_set_arg *arg = data;
714         struct ldlm_request    *body;
715         struct ptlrpc_request  *req;
716         int                     instant_cancel = 0;
717         int                     rc = 0;
718         ENTRY;
719
720         if (flag == LDLM_CB_CANCELING)
721                 /* Don't need to do anything here. */
722                 RETURN(0);
723
724         LASSERT(lock);
725         LASSERT(data != NULL);
726         if (lock->l_export->exp_obd->obd_recovering != 0) {
727                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
728                 ldlm_lock_dump(D_ERROR, lock, 0);
729         }
730
731         ldlm_lock_reorder_req(lock);
732
733         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
734                                         &RQF_LDLM_BL_CALLBACK,
735                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
736         if (req == NULL)
737                 RETURN(-ENOMEM);
738
739         req->rq_async_args.pointer_arg[0] = arg;
740         req->rq_async_args.pointer_arg[1] = lock;
741         req->rq_interpret_reply = ldlm_cb_interpret;
742         req->rq_no_resend = 1;
743
744         lock_res(lock->l_resource);
745         if (lock->l_granted_mode != lock->l_req_mode) {
746                 /* this blocking AST will be communicated as part of the
747                  * completion AST instead */
748                 unlock_res(lock->l_resource);
749                 ptlrpc_req_finished(req);
750                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
751                 RETURN(0);
752         }
753
754         if (lock->l_destroyed) {
755                 /* What's the point? */
756                 unlock_res(lock->l_resource);
757                 ptlrpc_req_finished(req);
758                 RETURN(0);
759         }
760
761         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
762                 instant_cancel = 1;
763
764         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
765         body->lock_handle[0] = lock->l_remote_handle;
766         body->lock_desc = *desc;
767         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
768
769         LDLM_DEBUG(lock, "server preparing blocking AST");
770
771         ptlrpc_request_set_replen(req);
772         if (instant_cancel) {
773                 unlock_res(lock->l_resource);
774                 ldlm_lock_cancel(lock);
775         } else {
776                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
777                 ldlm_add_waiting_lock(lock);
778                 unlock_res(lock->l_resource);
779         }
780
781         req->rq_send_state = LUSTRE_IMP_FULL;
782         /* ptlrpc_prep_req already set timeout */
783         if (AT_OFF)
784                 req->rq_timeout = ldlm_get_rq_timeout();
785
786         if (lock->l_export && lock->l_export->exp_nid_stats &&
787             lock->l_export->exp_nid_stats->nid_ldlm_stats)
788                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
789                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
790
791         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
792
793         RETURN(rc);
794 }
795
796 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
797 {
798         struct ldlm_cb_set_arg *arg = data;
799         struct ldlm_request    *body;
800         struct ptlrpc_request  *req;
801         long                    total_enqueue_wait;
802         int                     instant_cancel = 0;
803         int                     rc = 0;
804         ENTRY;
805
806         LASSERT(lock != NULL);
807         LASSERT(data != NULL);
808
809         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
810                                           lock->l_last_activity);
811
812         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
813                                     &RQF_LDLM_CP_CALLBACK);
814         if (req == NULL)
815                 RETURN(-ENOMEM);
816
817         lock_res_and_lock(lock);
818         if (lock->l_resource->lr_lvb_len)
819                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
820                                       lock->l_resource->lr_lvb_len);
821         unlock_res_and_lock(lock);
822
823         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
824         if (rc) {
825                 ptlrpc_request_free(req);
826                 RETURN(rc);
827         }
828
829         req->rq_async_args.pointer_arg[0] = arg;
830         req->rq_async_args.pointer_arg[1] = lock;
831         req->rq_interpret_reply = ldlm_cb_interpret;
832         req->rq_no_resend = 1;
833         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
834
835         body->lock_handle[0] = lock->l_remote_handle;
836         body->lock_flags = flags;
837         ldlm_lock2desc(lock, &body->lock_desc);
838         if (lock->l_resource->lr_lvb_len) {
839                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
840
841                 lock_res_and_lock(lock);
842                 memcpy(lvb, lock->l_resource->lr_lvb_data,
843                        lock->l_resource->lr_lvb_len);
844                 unlock_res_and_lock(lock);
845         }
846
847         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
848                    total_enqueue_wait);
849
850         /* Server-side enqueue wait time estimate, used in
851             __ldlm_add_waiting_lock to set future enqueue timers */
852         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
853                 at_add(&lock->l_resource->lr_namespace->ns_at_estimate,
854                        total_enqueue_wait);
855         else
856                 /* bz18618. Don't add lock enqueue time we spend waiting for a
857                    previous callback to fail. Locks waiting legitimately will
858                    get extended by ldlm_refresh_waiting_lock regardless of the
859                    estimate, so it's okay to underestimate here. */
860                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
861                        "It is likely that a previous callback timed out.",
862                        total_enqueue_wait,
863                        at_get(&lock->l_resource->lr_namespace->ns_at_estimate));
864
865         ptlrpc_request_set_replen(req);
866
867         req->rq_send_state = LUSTRE_IMP_FULL;
868         /* ptlrpc_prep_req already set timeout */
869         if (AT_OFF)
870                 req->rq_timeout = ldlm_get_rq_timeout();
871
872         /* We only send real blocking ASTs after the lock is granted */
873         lock_res_and_lock(lock);
874         if (lock->l_flags & LDLM_FL_AST_SENT) {
875                 body->lock_flags |= LDLM_FL_AST_SENT;
876                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
877                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
878
879                 /* We might get here prior to ldlm_handle_enqueue setting
880                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
881                  * into waiting list, but this is safe and similar code in
882                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
883                  * that would not only cancel the lock, but will also remove
884                  * it from waiting list */
885                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
886                         unlock_res_and_lock(lock);
887                         ldlm_lock_cancel(lock);
888                         instant_cancel = 1;
889                         lock_res_and_lock(lock);
890                 } else {
891                         /* start the lock-timeout clock */
892                         ldlm_add_waiting_lock(lock);
893                 }
894         }
895         unlock_res_and_lock(lock);
896
897         if (lock->l_export && lock->l_export->exp_nid_stats &&
898             lock->l_export->exp_nid_stats->nid_ldlm_stats)
899                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
900                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
901
902         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
903
904         RETURN(rc);
905 }
906
907 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
908 {
909         struct ldlm_resource  *res = lock->l_resource;
910         struct ldlm_request   *body;
911         struct ptlrpc_request *req;
912         int                    rc;
913         ENTRY;
914
915         LASSERT(lock != NULL);
916
917         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
918                                         &RQF_LDLM_GL_CALLBACK,
919                                         LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK);
920
921         if (req == NULL)
922                 RETURN(-ENOMEM);
923
924         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
925         body->lock_handle[0] = lock->l_remote_handle;
926         ldlm_lock2desc(lock, &body->lock_desc);
927
928         lock_res_and_lock(lock);
929         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
930                              lock->l_resource->lr_lvb_len);
931         unlock_res_and_lock(lock);
932         res = lock->l_resource;
933         ptlrpc_request_set_replen(req);
934
935
936         req->rq_send_state = LUSTRE_IMP_FULL;
937         /* ptlrpc_prep_req already set timeout */
938         if (AT_OFF)
939                 req->rq_timeout = ldlm_get_rq_timeout();
940
941         if (lock->l_export && lock->l_export->exp_nid_stats &&
942             lock->l_export->exp_nid_stats->nid_ldlm_stats)
943                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
944                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
945
946         rc = ptlrpc_queue_wait(req);
947         if (rc == -ELDLM_NO_LOCK_DATA)
948                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
949         else if (rc != 0)
950                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
951         else
952                 rc = ldlm_res_lvbo_update(res, req->rq_repmsg,
953                                           REPLY_REC_OFF, 1);
954         ptlrpc_req_finished(req);
955         if (rc == -ERESTART)
956                 ldlm_reprocess_all(res);
957
958         RETURN(rc);
959 }
960
961 #ifdef __KERNEL__
962 extern unsigned long long lu_time_stamp_get(void);
963 #else
964 #define lu_time_stamp_get() time(NULL)
965 #endif
966
967 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
968                        struct lprocfs_stats *srv_stats)
969 {
970         int lock_type = 0, op = 0;
971
972         lock_type = dlm_req->lock_desc.l_resource.lr_type;
973
974         switch (lock_type) {
975         case LDLM_PLAIN:
976                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
977                 break;
978         case LDLM_EXTENT:
979                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
980                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
981                 else
982                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
983                 break;
984         case LDLM_FLOCK:
985                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
986                 break;
987         case LDLM_IBITS:
988                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
989                 break;
990         default:
991                 op = 0;
992                 break;
993         }
994
995         if (op)
996                 lprocfs_counter_incr(srv_stats, op);
997
998         return;
999 }
1000
1001 /*
1002  * Main server-side entry point into LDLM. This is called by ptlrpc service
1003  * threads to carry out client lock enqueueing requests.
1004  */
1005 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1006                          struct ptlrpc_request *req,
1007                          const struct ldlm_request *dlm_req,
1008                          const struct ldlm_callback_suite *cbs)
1009 {
1010         struct ldlm_reply *dlm_rep;
1011         __u32 flags;
1012         ldlm_error_t err = ELDLM_OK;
1013         struct ldlm_lock *lock = NULL;
1014         void *cookie = NULL;
1015         int rc = 0;
1016         ENTRY;
1017
1018         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1019
1020         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1021         flags = dlm_req->lock_flags;
1022
1023         LASSERT(req->rq_export);
1024
1025         if (req->rq_rqbd->rqbd_service->srv_stats)
1026                 ldlm_svc_get_eopc(dlm_req,
1027                                   req->rq_rqbd->rqbd_service->srv_stats);
1028
1029         if (req->rq_export && req->rq_export->exp_nid_stats &&
1030             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1031                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1032                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1033
1034         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1035                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1036                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1037                           dlm_req->lock_desc.l_resource.lr_type);
1038                 GOTO(out, rc = -EFAULT);
1039         }
1040
1041         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1042                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1043                      dlm_req->lock_desc.l_req_mode &
1044                      (dlm_req->lock_desc.l_req_mode-1))) {
1045                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1046                           dlm_req->lock_desc.l_req_mode);
1047                 GOTO(out, rc = -EFAULT);
1048         }
1049
1050         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1051                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1052                              LDLM_PLAIN)) {
1053                         DEBUG_REQ(D_ERROR, req,
1054                                   "PLAIN lock request from IBITS client?");
1055                         GOTO(out, rc = -EPROTO);
1056                 }
1057         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1058                             LDLM_IBITS)) {
1059                 DEBUG_REQ(D_ERROR, req,
1060                           "IBITS lock request from unaware client?");
1061                 GOTO(out, rc = -EPROTO);
1062         }
1063
1064 #if 0
1065         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1066            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1067            ibits for mgc/mgs) */
1068
1069         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1070          * inodebits lock if client does not support them. */
1071         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1072             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1073                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1074                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1075                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1076                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1077                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1078         }
1079 #endif
1080
1081         if (unlikely(flags & LDLM_FL_REPLAY)) {
1082                 /* Find an existing lock in the per-export lock hash */
1083                 lock = lustre_hash_lookup(req->rq_export->exp_lock_hash,
1084                                           (void *)&dlm_req->lock_handle[0]);
1085                 if (lock != NULL) {
1086                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1087                                   LPX64, lock->l_handle.h_cookie);
1088                         GOTO(existing_lock, rc = 0);
1089                 }
1090         }
1091
1092         /* The lock's callback data might be set in the policy function */
1093         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1094                                 dlm_req->lock_desc.l_resource.lr_type,
1095                                 dlm_req->lock_desc.l_req_mode,
1096                                 cbs, NULL, 0);
1097
1098         if (!lock)
1099                 GOTO(out, rc = -ENOMEM);
1100
1101         lock->l_last_activity = cfs_time_current_sec();
1102         lock->l_remote_handle = dlm_req->lock_handle[0];
1103         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1104
1105         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1106         /* Don't enqueue a lock onto the export if it has already
1107          * been evicted.  Cancel it now instead. (bug 3822) */
1108         if (req->rq_export->exp_failed) {
1109                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1110                 GOTO(out, rc = -ENOTCONN);
1111         }
1112         lock->l_export = class_export_get(req->rq_export);
1113
1114         if (lock->l_export->exp_lock_hash)
1115                 lustre_hash_add(lock->l_export->exp_lock_hash,
1116                                 &lock->l_remote_handle,
1117                                 &lock->l_exp_hash);
1118
1119 existing_lock:
1120
1121         if (flags & LDLM_FL_HAS_INTENT) {
1122                 /* In this case, the reply buffer is allocated deep in
1123                  * local_lock_enqueue by the policy function. */
1124                 cookie = req;
1125         } else {
1126                 lock_res_and_lock(lock);
1127                 if (lock->l_resource->lr_lvb_len) {
1128                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1129                                              RCL_SERVER,
1130                                              lock->l_resource->lr_lvb_len);
1131                 }
1132                 unlock_res_and_lock(lock);
1133
1134                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1135                         GOTO(out, rc = -ENOMEM);
1136
1137                 rc = req_capsule_server_pack(&req->rq_pill);
1138                 if (rc)
1139                         GOTO(out, rc);
1140         }
1141
1142         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1143                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1144         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1145                 lock->l_req_extent = lock->l_policy_data.l_extent;
1146
1147         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1148         if (err)
1149                 GOTO(out, err);
1150
1151         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1152         dlm_rep->lock_flags = flags;
1153
1154         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1155         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1156
1157         /* We never send a blocking AST until the lock is granted, but
1158          * we can tell it right now */
1159         lock_res_and_lock(lock);
1160
1161         /* Now take into account flags to be inherited from original lock
1162            request both in reply to client and in our own lock flags. */
1163         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1164         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1165
1166         /* Don't move a pending lock onto the export if it has already
1167          * been evicted.  Cancel it now instead. (bug 5683) */
1168         if (unlikely(req->rq_export->exp_failed ||
1169                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1170                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1171                 rc = -ENOTCONN;
1172         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1173                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1174                 if (lock->l_granted_mode == lock->l_req_mode) {
1175                         /*
1176                          * Only cancel lock if it was granted, because it would
1177                          * be destroyed immediatelly and would never be granted
1178                          * in the future, causing timeouts on client.  Not
1179                          * granted lock will be cancelled immediatelly after
1180                          * sending completion AST.
1181                          */
1182                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1183                                 unlock_res_and_lock(lock);
1184                                 ldlm_lock_cancel(lock);
1185                                 lock_res_and_lock(lock);
1186                         } else
1187                                 ldlm_add_waiting_lock(lock);
1188                 }
1189         }
1190         /* Make sure we never ever grant usual metadata locks to liblustre
1191            clients */
1192         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1193             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1194              req->rq_export->exp_libclient) {
1195                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1196                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1197                         CERROR("Granting sync lock to libclient. "
1198                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1199                                dlm_req->lock_flags, dlm_rep->lock_flags,
1200                                lock->l_flags);
1201                         LDLM_ERROR(lock, "sync lock");
1202                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1203                                 struct ldlm_intent *it;
1204
1205                                 it = req_capsule_client_get(&req->rq_pill,
1206                                                             &RMF_LDLM_INTENT);
1207                                 if (it != NULL) {
1208                                         CERROR("This is intent %s ("LPU64")\n",
1209                                                ldlm_it2str(it->opc), it->opc);
1210                                 }
1211                         }
1212                 }
1213         }
1214
1215         unlock_res_and_lock(lock);
1216
1217         EXIT;
1218  out:
1219         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1220         if (!req->rq_packed_final) {
1221                 err = lustre_pack_reply(req, 1, NULL, NULL);
1222                 if (rc == 0)
1223                         rc = err;
1224         }
1225
1226         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1227          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1228         if (lock) {
1229                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1230                            "(err=%d, rc=%d)", err, rc);
1231
1232                 lock_res_and_lock(lock);
1233                 if (rc == 0) {
1234                         if (lock->l_resource->lr_lvb_len > 0) {
1235                                 void *lvb;
1236
1237                                 lvb = req_capsule_server_get(&req->rq_pill,
1238                                                              &RMF_DLM_LVB);
1239                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1240                                          req, lock);
1241
1242                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1243                                        lock->l_resource->lr_lvb_len);
1244                         }
1245                 } else {
1246                         ldlm_resource_unlink_lock(lock);
1247                         ldlm_lock_destroy_nolock(lock);
1248                 }
1249                 unlock_res_and_lock(lock);
1250
1251                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1252                         ldlm_reprocess_all(lock->l_resource);
1253
1254                 LDLM_LOCK_RELEASE(lock);
1255         }
1256
1257         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1258                           lock, rc);
1259
1260         return rc;
1261 }
1262
1263 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1264                         ldlm_completion_callback completion_callback,
1265                         ldlm_blocking_callback blocking_callback,
1266                         ldlm_glimpse_callback glimpse_callback)
1267 {
1268         struct ldlm_request *dlm_req;
1269         struct ldlm_callback_suite cbs = {
1270                 .lcs_completion = completion_callback,
1271                 .lcs_blocking   = blocking_callback,
1272                 .lcs_glimpse    = glimpse_callback
1273         };
1274         int rc;
1275
1276         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1277         if (dlm_req != NULL) {
1278                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1279                                           req, dlm_req, &cbs);
1280         } else {
1281                 rc = -EFAULT;
1282         }
1283         return rc;
1284 }
1285
1286 int ldlm_handle_convert0(struct ptlrpc_request *req,
1287                          const struct ldlm_request *dlm_req)
1288 {
1289         struct ldlm_reply *dlm_rep;
1290         struct ldlm_lock *lock;
1291         int rc;
1292         ENTRY;
1293
1294         if (req->rq_export && req->rq_export->exp_nid_stats &&
1295             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1296                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1297                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1298
1299         rc = req_capsule_server_pack(&req->rq_pill);
1300         if (rc)
1301                 RETURN(rc);
1302
1303         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1304         dlm_rep->lock_flags = dlm_req->lock_flags;
1305
1306         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1307         if (!lock) {
1308                 req->rq_status = EINVAL;
1309         } else {
1310                 void *res = NULL;
1311
1312                 LDLM_DEBUG(lock, "server-side convert handler START");
1313
1314                 lock->l_last_activity = cfs_time_current_sec();
1315                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1316                                         &dlm_rep->lock_flags);
1317                 if (res) {
1318                         if (ldlm_del_waiting_lock(lock))
1319                                 LDLM_DEBUG(lock, "converted waiting lock");
1320                         req->rq_status = 0;
1321                 } else {
1322                         req->rq_status = EDEADLOCK;
1323                 }
1324         }
1325
1326         if (lock) {
1327                 if (!req->rq_status)
1328                         ldlm_reprocess_all(lock->l_resource);
1329                 LDLM_DEBUG(lock, "server-side convert handler END");
1330                 LDLM_LOCK_PUT(lock);
1331         } else
1332                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1333
1334         RETURN(0);
1335 }
1336
1337 int ldlm_handle_convert(struct ptlrpc_request *req)
1338 {
1339         int rc;
1340         struct ldlm_request *dlm_req;
1341
1342         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1343         if (dlm_req != NULL) {
1344                 rc = ldlm_handle_convert0(req, dlm_req);
1345         } else {
1346                 CERROR ("Can't unpack dlm_req\n");
1347                 rc = -EFAULT;
1348         }
1349         return rc;
1350 }
1351
1352 /* Cancel all the locks whos handles are packed into ldlm_request */
1353 int ldlm_request_cancel(struct ptlrpc_request *req,
1354                         const struct ldlm_request *dlm_req, int first)
1355 {
1356         struct ldlm_resource *res, *pres = NULL;
1357         struct ldlm_lock *lock;
1358         int i, count, done = 0;
1359         ENTRY;
1360
1361         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1362         if (first >= count)
1363                 RETURN(0);
1364
1365         /* There is no lock on the server at the replay time,
1366          * skip lock cancelling to make replay tests to pass. */
1367         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1368                 RETURN(0);
1369
1370         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1371                           "starting at %d", count, first);
1372
1373         for (i = first; i < count; i++) {
1374                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1375                 if (!lock) {
1376                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1377                                           "lock (cookie "LPU64")",
1378                                           dlm_req->lock_handle[i].cookie);
1379                         continue;
1380                 }
1381
1382                 res = lock->l_resource;
1383                 done++;
1384
1385                 if (res != pres) {
1386                         if (pres != NULL) {
1387                                 ldlm_reprocess_all(pres);
1388                                 LDLM_RESOURCE_DELREF(pres);
1389                                 ldlm_resource_putref(pres);
1390                         }
1391                         if (res != NULL) {
1392                                 ldlm_resource_getref(res);
1393                                 LDLM_RESOURCE_ADDREF(res);
1394                                 ldlm_res_lvbo_update(res, NULL, 0, 1);
1395                         }
1396                         pres = res;
1397                 }
1398                 ldlm_lock_cancel(lock);
1399                 LDLM_LOCK_PUT(lock);
1400         }
1401         if (pres != NULL) {
1402                 ldlm_reprocess_all(pres);
1403                 LDLM_RESOURCE_DELREF(pres);
1404                 ldlm_resource_putref(pres);
1405         }
1406         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1407         RETURN(done);
1408 }
1409
1410 int ldlm_handle_cancel(struct ptlrpc_request *req)
1411 {
1412         struct ldlm_request *dlm_req;
1413         int rc;
1414         ENTRY;
1415
1416         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1417         if (dlm_req == NULL) {
1418                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1419                 RETURN(-EFAULT);
1420         }
1421
1422         if (req->rq_export && req->rq_export->exp_nid_stats &&
1423             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1424                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1425                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1426
1427         rc = req_capsule_server_pack(&req->rq_pill);
1428         if (rc)
1429                 RETURN(rc);
1430
1431         if (!ldlm_request_cancel(req, dlm_req, 0))
1432                 req->rq_status = ESTALE;
1433
1434         if (ptlrpc_reply(req) != 0)
1435                 LBUG();
1436
1437         RETURN(0);
1438 }
1439
1440 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1441                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1442 {
1443         int do_ast;
1444         ENTRY;
1445
1446         LDLM_DEBUG(lock, "client blocking AST callback handler START");
1447
1448         lock_res_and_lock(lock);
1449         lock->l_flags |= LDLM_FL_CBPENDING;
1450
1451         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1452                 lock->l_flags |= LDLM_FL_CANCEL;
1453
1454         do_ast = (!lock->l_readers && !lock->l_writers);
1455         unlock_res_and_lock(lock);
1456
1457         if (do_ast) {
1458                 LDLM_DEBUG(lock, "already unused, calling "
1459                            "callback (%p)", lock->l_blocking_ast);
1460                 if (lock->l_blocking_ast != NULL)
1461                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1462                                              LDLM_CB_BLOCKING);
1463         } else {
1464                 LDLM_DEBUG(lock, "Lock still has references, will be"
1465                            " cancelled later");
1466         }
1467
1468         LDLM_DEBUG(lock, "client blocking callback handler END");
1469         LDLM_LOCK_RELEASE(lock);
1470         EXIT;
1471 }
1472
1473 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1474                                     struct ldlm_namespace *ns,
1475                                     struct ldlm_request *dlm_req,
1476                                     struct ldlm_lock *lock)
1477 {
1478         CFS_LIST_HEAD(ast_list);
1479         ENTRY;
1480
1481         LDLM_DEBUG(lock, "client completion callback handler START");
1482
1483         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1484                 int to = cfs_time_seconds(1);
1485                 while (to > 0) {
1486                         cfs_schedule_timeout(CFS_TASK_INTERRUPTIBLE, to);
1487                         if (lock->l_granted_mode == lock->l_req_mode ||
1488                             lock->l_destroyed)
1489                                 break;
1490                 }
1491         }
1492
1493         lock_res_and_lock(lock);
1494         if (lock->l_destroyed ||
1495             lock->l_granted_mode == lock->l_req_mode) {
1496                 /* bug 11300: the lock has already been granted */
1497                 unlock_res_and_lock(lock);
1498                 LDLM_DEBUG(lock, "Double grant race happened");
1499                 LDLM_LOCK_RELEASE(lock);
1500                 EXIT;
1501                 return;
1502         }
1503
1504         /* If we receive the completion AST before the actual enqueue returned,
1505          * then we might need to switch lock modes, resources, or extents. */
1506         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1507                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1508                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1509         }
1510
1511         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1512                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1513                 LDLM_DEBUG(lock, "completion AST, new policy data");
1514         }
1515
1516         ldlm_resource_unlink_lock(lock);
1517         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1518                    &lock->l_resource->lr_name,
1519                    sizeof(lock->l_resource->lr_name)) != 0) {
1520                 unlock_res_and_lock(lock);
1521                 if (ldlm_lock_change_resource(ns, lock,
1522                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1523                         LDLM_ERROR(lock, "Failed to allocate resource");
1524                         LDLM_LOCK_RELEASE(lock);
1525                         EXIT;
1526                         return;
1527                 }
1528                 LDLM_DEBUG(lock, "completion AST, new resource");
1529                 CERROR("change resource!\n");
1530                 lock_res_and_lock(lock);
1531         }
1532
1533         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1534                 /* BL_AST locks are not needed in lru.
1535                  * let ldlm_cancel_lru() be fast. */
1536                 ldlm_lock_remove_from_lru(lock);
1537                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1538                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1539         }
1540
1541         if (lock->l_lvb_len) {
1542                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1543                                          RCL_CLIENT) < lock->l_lvb_len) {
1544                         LDLM_ERROR(lock, "completion AST did not contain "
1545                                    "expected LVB!");
1546                 } else {
1547                         void *lvb = req_capsule_client_swab_get(&req->rq_pill,
1548                                                                 &RMF_DLM_LVB,
1549                                                   (void *)lock->l_lvb_swabber);
1550                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1551                 }
1552         }
1553
1554         ldlm_grant_lock(lock, &ast_list);
1555         unlock_res_and_lock(lock);
1556
1557         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1558
1559         ldlm_run_ast_work(&ast_list, LDLM_WORK_CP_AST);
1560
1561         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1562                           lock);
1563         LDLM_LOCK_RELEASE(lock);
1564         EXIT;
1565 }
1566
1567 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1568                                     struct ldlm_namespace *ns,
1569                                     struct ldlm_request *dlm_req,
1570                                     struct ldlm_lock *lock)
1571 {
1572         int rc = -ENOSYS;
1573         ENTRY;
1574
1575         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1576
1577         if (lock->l_glimpse_ast != NULL)
1578                 rc = lock->l_glimpse_ast(lock, req);
1579
1580         if (req->rq_repmsg != NULL) {
1581                 ptlrpc_reply(req);
1582         } else {
1583                 req->rq_status = rc;
1584                 ptlrpc_error(req);
1585         }
1586
1587         lock_res_and_lock(lock);
1588         if (lock->l_granted_mode == LCK_PW &&
1589             !lock->l_readers && !lock->l_writers &&
1590             cfs_time_after(cfs_time_current(),
1591                            cfs_time_add(lock->l_last_used,
1592                                         cfs_time_seconds(10)))) {
1593                 unlock_res_and_lock(lock);
1594                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1595                         ldlm_handle_bl_callback(ns, NULL, lock);
1596
1597                 EXIT;
1598                 return;
1599         }
1600         unlock_res_and_lock(lock);
1601         LDLM_LOCK_RELEASE(lock);
1602         EXIT;
1603 }
1604
1605 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1606 {
1607         if (req->rq_no_reply)
1608                 return 0;
1609
1610         req->rq_status = rc;
1611         if (!req->rq_packed_final) {
1612                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1613                 if (rc)
1614                         return rc;
1615         }
1616         return ptlrpc_reply(req);
1617 }
1618
1619 #ifdef __KERNEL__
1620 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1621                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1622                              struct list_head *cancels, int count)
1623 {
1624         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1625         struct ldlm_bl_work_item *blwi;
1626         ENTRY;
1627
1628         if (cancels && count == 0)
1629                 RETURN(0);
1630
1631         OBD_ALLOC(blwi, sizeof(*blwi));
1632         if (blwi == NULL)
1633                 RETURN(-ENOMEM);
1634
1635         blwi->blwi_ns = ns;
1636         if (ld != NULL)
1637                 blwi->blwi_ld = *ld;
1638         if (count) {
1639                 list_add(&blwi->blwi_head, cancels);
1640                 list_del_init(cancels);
1641                 blwi->blwi_count = count;
1642         } else {
1643                 blwi->blwi_lock = lock;
1644         }
1645         spin_lock(&blp->blp_lock);
1646         if (lock && lock->l_flags & LDLM_FL_DISCARD_DATA) {
1647                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1648                 list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1649         } else {
1650                 /* other blocking callbacks are added to the regular list */
1651                 list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1652         }
1653         cfs_waitq_signal(&blp->blp_waitq);
1654         spin_unlock(&blp->blp_lock);
1655
1656         RETURN(0);
1657 }
1658 #endif
1659
1660 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1661                            struct ldlm_lock *lock)
1662 {
1663 #ifdef __KERNEL__
1664         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0));
1665 #else
1666         RETURN(-ENOSYS);
1667 #endif
1668 }
1669
1670 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1671                            struct list_head *cancels, int count)
1672 {
1673 #ifdef __KERNEL__
1674         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count));
1675 #else
1676         RETURN(-ENOSYS);
1677 #endif
1678 }
1679
1680 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1681 static int ldlm_callback_handler(struct ptlrpc_request *req)
1682 {
1683         struct ldlm_namespace *ns;
1684         struct ldlm_request *dlm_req;
1685         struct ldlm_lock *lock;
1686         int rc;
1687         ENTRY;
1688
1689         /* Requests arrive in sender's byte order.  The ptlrpc service
1690          * handler has already checked and, if necessary, byte-swapped the
1691          * incoming request message body, but I am responsible for the
1692          * message buffers. */
1693
1694         /* do nothing for sec context finalize */
1695         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1696                 RETURN(0);
1697
1698         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1699
1700         if (req->rq_export == NULL) {
1701                 ldlm_callback_reply(req, -ENOTCONN);
1702                 RETURN(0);
1703         }
1704
1705         LASSERT(req->rq_export != NULL);
1706         LASSERT(req->rq_export->exp_obd != NULL);
1707
1708         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1709         case LDLM_BL_CALLBACK:
1710                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1711                         RETURN(0);
1712                 break;
1713         case LDLM_CP_CALLBACK:
1714                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1715                         RETURN(0);
1716                 break;
1717         case LDLM_GL_CALLBACK:
1718                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1719                         RETURN(0);
1720                 break;
1721         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1722                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1723                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1724                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1725                         RETURN(0);
1726                 rc = llog_origin_handle_cancel(req);
1727                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1728                         RETURN(0);
1729                 ldlm_callback_reply(req, rc);
1730                 RETURN(0);
1731         case OBD_QC_CALLBACK:
1732                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1733                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1734                         RETURN(0);
1735                 rc = target_handle_qc_callback(req);
1736                 ldlm_callback_reply(req, rc);
1737                 RETURN(0);
1738         case QUOTA_DQACQ:
1739         case QUOTA_DQREL:
1740                 /* reply in handler */
1741                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1742                 rc = target_handle_dqacq_callback(req);
1743                 RETURN(0);
1744         case LLOG_ORIGIN_HANDLE_CREATE:
1745                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1746                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1747                         RETURN(0);
1748                 rc = llog_origin_handle_create(req);
1749                 ldlm_callback_reply(req, rc);
1750                 RETURN(0);
1751         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1752                 req_capsule_set(&req->rq_pill,
1753                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1754                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1755                         RETURN(0);
1756                 rc = llog_origin_handle_next_block(req);
1757                 ldlm_callback_reply(req, rc);
1758                 RETURN(0);
1759         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1760                 req_capsule_set(&req->rq_pill,
1761                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1762                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1763                         RETURN(0);
1764                 rc = llog_origin_handle_read_header(req);
1765                 ldlm_callback_reply(req, rc);
1766                 RETURN(0);
1767         case LLOG_ORIGIN_HANDLE_CLOSE:
1768                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1769                         RETURN(0);
1770                 rc = llog_origin_handle_close(req);
1771                 ldlm_callback_reply(req, rc);
1772                 RETURN(0);
1773         default:
1774                 CERROR("unknown opcode %u\n",
1775                        lustre_msg_get_opc(req->rq_reqmsg));
1776                 ldlm_callback_reply(req, -EPROTO);
1777                 RETURN(0);
1778         }
1779
1780         ns = req->rq_export->exp_obd->obd_namespace;
1781         LASSERT(ns != NULL);
1782
1783         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1784
1785         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1786         if (dlm_req == NULL) {
1787                 ldlm_callback_reply(req, -EPROTO);
1788                 RETURN(0);
1789         }
1790
1791         /* Force a known safe race, send a cancel to the server for a lock
1792          * which the server has already started a blocking callback on. */
1793         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1794             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1795                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1796                 if (rc < 0)
1797                         CERROR("ldlm_cli_cancel: %d\n", rc);
1798         }
1799
1800         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1801         if (!lock) {
1802                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1803                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1804                 ldlm_callback_reply(req, -EINVAL);
1805                 RETURN(0);
1806         }
1807
1808         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1809             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1810                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1811
1812         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1813         lock_res_and_lock(lock);
1814         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1815         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1816                 /* If somebody cancels lock and cache is already droped,
1817                  * or lock is failed before cp_ast received on client,
1818                  * we can tell the server we have no lock. Otherwise, we
1819                  * should send cancel after dropping the cache. */
1820                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1821                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1822                     (lock->l_flags & LDLM_FL_FAILED)) {
1823                         LDLM_DEBUG(lock, "callback on lock "
1824                                    LPX64" - lock disappeared\n",
1825                                    dlm_req->lock_handle[0].cookie);
1826                         unlock_res_and_lock(lock);
1827                         LDLM_LOCK_RELEASE(lock);
1828                         ldlm_callback_reply(req, -EINVAL);
1829                         RETURN(0);
1830                 }
1831                 /* BL_AST locks are not needed in lru.
1832                  * let ldlm_cancel_lru() be fast. */
1833                 ldlm_lock_remove_from_lru(lock);
1834                 lock->l_flags |= LDLM_FL_BL_AST;
1835         }
1836         unlock_res_and_lock(lock);
1837
1838         /* We want the ost thread to get this reply so that it can respond
1839          * to ost requests (write cache writeback) that might be triggered
1840          * in the callback.
1841          *
1842          * But we'd also like to be able to indicate in the reply that we're
1843          * cancelling right now, because it's unused, or have an intent result
1844          * in the reply, so we might have to push the responsibility for sending
1845          * the reply down into the AST handlers, alas. */
1846
1847         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1848         case LDLM_BL_CALLBACK:
1849                 CDEBUG(D_INODE, "blocking ast\n");
1850                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
1851                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK))
1852                         ldlm_callback_reply(req, 0);
1853                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1854                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1855                 break;
1856         case LDLM_CP_CALLBACK:
1857                 CDEBUG(D_INODE, "completion ast\n");
1858                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
1859                 ldlm_callback_reply(req, 0);
1860                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1861                 break;
1862         case LDLM_GL_CALLBACK:
1863                 CDEBUG(D_INODE, "glimpse ast\n");
1864                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
1865                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1866                 break;
1867         default:
1868                 LBUG();                         /* checked above */
1869         }
1870
1871         RETURN(0);
1872 }
1873
1874 static int ldlm_cancel_handler(struct ptlrpc_request *req)
1875 {
1876         int rc;
1877         ENTRY;
1878
1879         /* Requests arrive in sender's byte order.  The ptlrpc service
1880          * handler has already checked and, if necessary, byte-swapped the
1881          * incoming request message body, but I am responsible for the
1882          * message buffers. */
1883
1884         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1885
1886         if (req->rq_export == NULL) {
1887                 struct ldlm_request *dlm_req;
1888
1889                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
1890                        lustre_msg_get_opc(req->rq_reqmsg),
1891                        libcfs_id2str(req->rq_peer),
1892                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1893
1894                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1895                 dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1896                 if (dlm_req != NULL)
1897                         ldlm_lock_dump_handle(D_ERROR,
1898                                               &dlm_req->lock_handle[0]);
1899                 ldlm_callback_reply(req, -ENOTCONN);
1900                 RETURN(0);
1901         }
1902
1903         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1904
1905         /* XXX FIXME move this back to mds/handler.c, bug 249 */
1906         case LDLM_CANCEL:
1907                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
1908                 CDEBUG(D_INODE, "cancel\n");
1909                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
1910                         RETURN(0);
1911                 rc = ldlm_handle_cancel(req);
1912                 if (rc)
1913                         break;
1914                 RETURN(0);
1915         case OBD_LOG_CANCEL:
1916                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1917                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1918                         RETURN(0);
1919                 rc = llog_origin_handle_cancel(req);
1920                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1921                         RETURN(0);
1922                 ldlm_callback_reply(req, rc);
1923                 RETURN(0);
1924         default:
1925                 CERROR("invalid opcode %d\n",
1926                        lustre_msg_get_opc(req->rq_reqmsg));
1927                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1928                 ldlm_callback_reply(req, -EINVAL);
1929         }
1930
1931         RETURN(0);
1932 }
1933
1934 void ldlm_revoke_lock_cb(void *obj, void *data)
1935 {
1936         struct list_head   *rpc_list = data;
1937         struct ldlm_lock   *lock = obj;
1938
1939         lock_res_and_lock(lock);
1940
1941         if (lock->l_req_mode != lock->l_granted_mode) {
1942                 unlock_res_and_lock(lock);
1943                 return;
1944         }
1945
1946         LASSERT(lock->l_resource);
1947         if (lock->l_resource->lr_type != LDLM_IBITS &&
1948             lock->l_resource->lr_type != LDLM_PLAIN) {
1949                 unlock_res_and_lock(lock);
1950                 return;
1951         }
1952
1953         if (lock->l_flags & LDLM_FL_AST_SENT) {
1954                 unlock_res_and_lock(lock);
1955                 return;
1956         }
1957
1958         LASSERT(lock->l_blocking_ast);
1959         LASSERT(!lock->l_blocking_lock);
1960
1961         lock->l_flags |= LDLM_FL_AST_SENT;
1962         if (lock->l_export && lock->l_export->exp_lock_hash &&
1963             !hlist_unhashed(&lock->l_exp_hash))
1964                 lustre_hash_del(lock->l_export->exp_lock_hash,
1965                                 &lock->l_remote_handle, &lock->l_exp_hash);
1966         list_add_tail(&lock->l_rk_ast, rpc_list);
1967         LDLM_LOCK_GET(lock);
1968
1969         unlock_res_and_lock(lock);
1970 }
1971
1972 void ldlm_revoke_export_locks(struct obd_export *exp)
1973 {
1974         struct list_head  rpc_list;
1975         ENTRY;
1976
1977         CFS_INIT_LIST_HEAD(&rpc_list);
1978         lustre_hash_for_each_empty(exp->exp_lock_hash,
1979                                    ldlm_revoke_lock_cb, &rpc_list);
1980         ldlm_run_ast_work(&rpc_list, LDLM_WORK_REVOKE_AST);
1981
1982         EXIT;
1983 }
1984
1985 #ifdef __KERNEL__
1986 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
1987 {
1988         struct ldlm_bl_work_item *blwi = NULL;
1989         static unsigned int num_bl = 0;
1990
1991         spin_lock(&blp->blp_lock);
1992         /* process a request from the blp_list at least every blp_num_threads */
1993         if (!list_empty(&blp->blp_list) &&
1994             (list_empty(&blp->blp_prio_list) || num_bl == 0))
1995                 blwi = list_entry(blp->blp_list.next,
1996                                   struct ldlm_bl_work_item, blwi_entry);
1997         else
1998                 if (!list_empty(&blp->blp_prio_list))
1999                         blwi = list_entry(blp->blp_prio_list.next,
2000                                           struct ldlm_bl_work_item, blwi_entry);
2001
2002         if (blwi) {
2003                 if (++num_bl >= atomic_read(&blp->blp_num_threads))
2004                         num_bl = 0;
2005                 list_del(&blwi->blwi_entry);
2006         }
2007         spin_unlock(&blp->blp_lock);
2008
2009         return blwi;
2010 }
2011
2012 /* This only contains temporary data until the thread starts */
2013 struct ldlm_bl_thread_data {
2014         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2015         struct ldlm_bl_pool     *bltd_blp;
2016         struct completion       bltd_comp;
2017         int                     bltd_num;
2018 };
2019
2020 static int ldlm_bl_thread_main(void *arg);
2021
2022 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2023 {
2024         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2025         int rc;
2026
2027         init_completion(&bltd.bltd_comp);
2028         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
2029         if (rc < 0) {
2030                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2031                        atomic_read(&blp->blp_num_threads), rc);
2032                 return rc;
2033         }
2034         wait_for_completion(&bltd.bltd_comp);
2035
2036         return 0;
2037 }
2038
2039 static int ldlm_bl_thread_main(void *arg)
2040 {
2041         struct ldlm_bl_pool *blp;
2042         ENTRY;
2043
2044         {
2045                 struct ldlm_bl_thread_data *bltd = arg;
2046
2047                 blp = bltd->bltd_blp;
2048
2049                 bltd->bltd_num = atomic_inc_return(&blp->blp_num_threads) - 1;
2050                 atomic_inc(&blp->blp_busy_threads);
2051
2052                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2053                         "ldlm_bl_%02d", bltd->bltd_num);
2054                 cfs_daemonize(bltd->bltd_name);
2055
2056                 complete(&bltd->bltd_comp);
2057                 /* cannot use bltd after this, it is only on caller's stack */
2058         }
2059
2060         while (1) {
2061                 struct l_wait_info lwi = { 0 };
2062                 struct ldlm_bl_work_item *blwi = NULL;
2063
2064                 blwi = ldlm_bl_get_work(blp);
2065
2066                 if (blwi == NULL) {
2067                         int busy;
2068
2069                         atomic_dec(&blp->blp_busy_threads);
2070                         l_wait_event_exclusive(blp->blp_waitq,
2071                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2072                                          &lwi);
2073                         busy = atomic_inc_return(&blp->blp_busy_threads);
2074
2075                         if (blwi->blwi_ns == NULL)
2076                                 /* added by ldlm_cleanup() */
2077                                 break;
2078
2079                         /* Not fatal if racy and have a few too many threads */
2080                         if (unlikely(busy < blp->blp_max_threads &&
2081                                     busy >= atomic_read(&blp->blp_num_threads)))
2082                                 /* discard the return value, we tried */
2083                                 ldlm_bl_thread_start(blp);
2084                 } else {
2085                         if (blwi->blwi_ns == NULL)
2086                                 /* added by ldlm_cleanup() */
2087                                 break;
2088                 }
2089
2090                 if (blwi->blwi_count) {
2091                         /* The special case when we cancel locks in lru
2092                          * asynchronously, we pass the list of locks here.
2093                          * Thus lock is marked LDLM_FL_CANCELING, and already
2094                          * canceled locally. */
2095                         ldlm_cli_cancel_list(&blwi->blwi_head,
2096                                              blwi->blwi_count, NULL, 0);
2097                 } else {
2098                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2099                                                 blwi->blwi_lock);
2100                 }
2101                 OBD_FREE(blwi, sizeof(*blwi));
2102         }
2103
2104         atomic_dec(&blp->blp_busy_threads);
2105         atomic_dec(&blp->blp_num_threads);
2106         complete(&blp->blp_comp);
2107         RETURN(0);
2108 }
2109
2110 #endif
2111
2112 static int ldlm_setup(void);
2113 static int ldlm_cleanup(void);
2114
2115 int ldlm_get_ref(void)
2116 {
2117         int rc = 0;
2118         ENTRY;
2119         mutex_down(&ldlm_ref_sem);
2120         if (++ldlm_refcount == 1) {
2121                 rc = ldlm_setup();
2122                 if (rc)
2123                         ldlm_refcount--;
2124         }
2125         mutex_up(&ldlm_ref_sem);
2126
2127         RETURN(rc);
2128 }
2129
2130 void ldlm_put_ref(void)
2131 {
2132         ENTRY;
2133         mutex_down(&ldlm_ref_sem);
2134         if (ldlm_refcount == 1) {
2135                 int rc = ldlm_cleanup();
2136                 if (rc)
2137                         CERROR("ldlm_cleanup failed: %d\n", rc);
2138                 else
2139                         ldlm_refcount--;
2140         } else {
2141                 ldlm_refcount--;
2142         }
2143         mutex_up(&ldlm_ref_sem);
2144
2145         EXIT;
2146 }
2147
2148 /*
2149  * Export handle<->lock hash operations.
2150  */
2151 static unsigned
2152 ldlm_export_lock_hash(lustre_hash_t *lh, void *key, unsigned mask)
2153 {
2154         return lh_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2155 }
2156
2157 static void *
2158 ldlm_export_lock_key(struct hlist_node *hnode)
2159 {
2160         struct ldlm_lock *lock;
2161         ENTRY;
2162
2163         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2164         RETURN(&lock->l_remote_handle);
2165 }
2166
2167 static int
2168 ldlm_export_lock_compare(void *key, struct hlist_node *hnode)
2169 {
2170         ENTRY;
2171         RETURN(lustre_handle_equal(ldlm_export_lock_key(hnode), key));
2172 }
2173
2174 static void *
2175 ldlm_export_lock_get(struct hlist_node *hnode)
2176 {
2177         struct ldlm_lock *lock;
2178         ENTRY;
2179
2180         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2181         LDLM_LOCK_GET(lock);
2182
2183         RETURN(lock);
2184 }
2185
2186 static void *
2187 ldlm_export_lock_put(struct hlist_node *hnode)
2188 {
2189         struct ldlm_lock *lock;
2190         ENTRY;
2191
2192         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2193         LDLM_LOCK_RELEASE(lock);
2194
2195         RETURN(lock);
2196 }
2197
2198 static lustre_hash_ops_t ldlm_export_lock_ops = {
2199         .lh_hash    = ldlm_export_lock_hash,
2200         .lh_key     = ldlm_export_lock_key,
2201         .lh_compare = ldlm_export_lock_compare,
2202         .lh_get     = ldlm_export_lock_get,
2203         .lh_put     = ldlm_export_lock_put
2204 };
2205
2206 int ldlm_init_export(struct obd_export *exp)
2207 {
2208         ENTRY;
2209
2210         exp->exp_lock_hash =
2211                 lustre_hash_init(obd_uuid2str(&exp->exp_client_uuid),
2212                                  7, 16, &ldlm_export_lock_ops, LH_REHASH);
2213
2214         if (!exp->exp_lock_hash)
2215                 RETURN(-ENOMEM);
2216
2217         RETURN(0);
2218 }
2219 EXPORT_SYMBOL(ldlm_init_export);
2220
2221 void ldlm_destroy_export(struct obd_export *exp)
2222 {
2223         ENTRY;
2224         lustre_hash_exit(exp->exp_lock_hash);
2225         exp->exp_lock_hash = NULL;
2226         EXIT;
2227 }
2228 EXPORT_SYMBOL(ldlm_destroy_export);
2229
2230 static int ldlm_setup(void)
2231 {
2232         struct ldlm_bl_pool *blp;
2233         int rc = 0;
2234         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
2235         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
2236 #ifdef __KERNEL__
2237         int i;
2238 #endif
2239         ENTRY;
2240
2241         if (ldlm_state != NULL)
2242                 RETURN(-EALREADY);
2243
2244         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2245         if (ldlm_state == NULL)
2246                 RETURN(-ENOMEM);
2247
2248 #ifdef LPROCFS
2249         rc = ldlm_proc_setup();
2250         if (rc != 0)
2251                 GOTO(out_free, rc);
2252 #endif
2253
2254 #ifdef __KERNEL__
2255         if (ldlm_num_threads) {
2256                 /* If ldlm_num_threads is set, it is the min and the max. */
2257                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
2258                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
2259                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
2260                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
2261                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
2262         }
2263 #endif
2264
2265         ldlm_state->ldlm_cb_service =
2266                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2267                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
2268                                 LDLM_CB_REPLY_PORTAL, 2,
2269                                 ldlm_callback_handler, "ldlm_cbd",
2270                                 ldlm_svc_proc_dir, NULL,
2271                                 ldlm_min_threads, ldlm_max_threads,
2272                                 "ldlm_cb",
2273                                 LCT_MD_THREAD|LCT_DT_THREAD, NULL);
2274
2275         if (!ldlm_state->ldlm_cb_service) {
2276                 CERROR("failed to start service\n");
2277                 GOTO(out_proc, rc = -ENOMEM);
2278         }
2279
2280         ldlm_state->ldlm_cancel_service =
2281                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2282                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
2283                                 LDLM_CANCEL_REPLY_PORTAL, 6,
2284                                 ldlm_cancel_handler, "ldlm_canceld",
2285                                 ldlm_svc_proc_dir, NULL,
2286                                 ldlm_min_threads, ldlm_max_threads,
2287                                 "ldlm_cn",
2288                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
2289                                 NULL);
2290
2291         if (!ldlm_state->ldlm_cancel_service) {
2292                 CERROR("failed to start service\n");
2293                 GOTO(out_proc, rc = -ENOMEM);
2294         }
2295
2296         OBD_ALLOC(blp, sizeof(*blp));
2297         if (blp == NULL)
2298                 GOTO(out_proc, rc = -ENOMEM);
2299         ldlm_state->ldlm_bl_pool = blp;
2300
2301         spin_lock_init(&blp->blp_lock);
2302         CFS_INIT_LIST_HEAD(&blp->blp_list);
2303         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2304         cfs_waitq_init(&blp->blp_waitq);
2305         atomic_set(&blp->blp_num_threads, 0);
2306         atomic_set(&blp->blp_busy_threads, 0);
2307         blp->blp_min_threads = ldlm_min_threads;
2308         blp->blp_max_threads = ldlm_max_threads;
2309
2310 #ifdef __KERNEL__
2311         for (i = 0; i < blp->blp_min_threads; i++) {
2312                 rc = ldlm_bl_thread_start(blp);
2313                 if (rc < 0)
2314                         GOTO(out_thread, rc);
2315         }
2316
2317         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
2318         if (rc)
2319                 GOTO(out_thread, rc);
2320
2321         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
2322         if (rc)
2323                 GOTO(out_thread, rc);
2324
2325         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2326         expired_lock_thread.elt_state = ELT_STOPPED;
2327         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2328
2329         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2330         spin_lock_init(&waiting_locks_spinlock);
2331         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2332
2333         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2334         if (rc < 0) {
2335                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2336                 GOTO(out_thread, rc);
2337         }
2338
2339         wait_event(expired_lock_thread.elt_waitq,
2340                    expired_lock_thread.elt_state == ELT_READY);
2341 #endif
2342
2343 #ifdef __KERNEL__
2344         rc = ldlm_pools_init();
2345         if (rc)
2346                 GOTO(out_thread, rc);
2347 #endif
2348         RETURN(0);
2349
2350 #ifdef __KERNEL__
2351  out_thread:
2352         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2353         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2354 #endif
2355
2356  out_proc:
2357 #ifdef LPROCFS
2358         ldlm_proc_cleanup();
2359  out_free:
2360 #endif
2361         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2362         ldlm_state = NULL;
2363         return rc;
2364 }
2365
2366 static int ldlm_cleanup(void)
2367 {
2368 #ifdef __KERNEL__
2369         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2370 #endif
2371         ENTRY;
2372
2373         if (!list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2374             !list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2375                 CERROR("ldlm still has namespaces; clean these up first.\n");
2376                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2377                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2378                 RETURN(-EBUSY);
2379         }
2380
2381 #ifdef __KERNEL__
2382         ldlm_pools_fini();
2383 #endif
2384
2385 #ifdef __KERNEL__
2386         while (atomic_read(&blp->blp_num_threads) > 0) {
2387                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2388
2389                 init_completion(&blp->blp_comp);
2390
2391                 spin_lock(&blp->blp_lock);
2392                 list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2393                 cfs_waitq_signal(&blp->blp_waitq);
2394                 spin_unlock(&blp->blp_lock);
2395
2396                 wait_for_completion(&blp->blp_comp);
2397         }
2398         OBD_FREE(blp, sizeof(*blp));
2399
2400         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2401         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2402         ldlm_proc_cleanup();
2403
2404         expired_lock_thread.elt_state = ELT_TERMINATE;
2405         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2406         wait_event(expired_lock_thread.elt_waitq,
2407                    expired_lock_thread.elt_state == ELT_STOPPED);
2408 #else
2409         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2410         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2411 #endif
2412
2413         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2414         ldlm_state = NULL;
2415
2416         RETURN(0);
2417 }
2418
2419 int __init ldlm_init(void)
2420 {
2421         init_mutex(&ldlm_ref_sem);
2422         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2423         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2424         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2425                                                sizeof(struct ldlm_resource), 0,
2426                                                SLAB_HWCACHE_ALIGN);
2427         if (ldlm_resource_slab == NULL)
2428                 return -ENOMEM;
2429
2430         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2431                                       sizeof(struct ldlm_lock), 0,
2432                                       SLAB_HWCACHE_ALIGN | SLAB_DESTROY_BY_RCU);
2433         if (ldlm_lock_slab == NULL) {
2434                 cfs_mem_cache_destroy(ldlm_resource_slab);
2435                 return -ENOMEM;
2436         }
2437
2438         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2439                                         sizeof(struct ldlm_interval),
2440                                         0, SLAB_HWCACHE_ALIGN);
2441         if (ldlm_interval_slab == NULL) {
2442                 cfs_mem_cache_destroy(ldlm_resource_slab);
2443                 cfs_mem_cache_destroy(ldlm_lock_slab);
2444                 return -ENOMEM;
2445         }
2446
2447         return 0;
2448 }
2449
2450 void __exit ldlm_exit(void)
2451 {
2452         int rc;
2453         if (ldlm_refcount)
2454                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2455         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2456         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2457 #ifdef __KERNEL__
2458         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2459          * synchronize_rcu() to wait a grace period elapsed, so that
2460          * ldlm_lock_free() get a chance to be called. */
2461         synchronize_rcu();
2462 #endif
2463         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2464         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2465         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2466         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2467 }
2468
2469 /* ldlm_extent.c */
2470 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2471
2472 /* ldlm_lock.c */
2473 EXPORT_SYMBOL(ldlm_get_processing_policy);
2474 EXPORT_SYMBOL(ldlm_lock2desc);
2475 EXPORT_SYMBOL(ldlm_register_intent);
2476 EXPORT_SYMBOL(ldlm_lockname);
2477 EXPORT_SYMBOL(ldlm_typename);
2478 EXPORT_SYMBOL(ldlm_lock2handle);
2479 EXPORT_SYMBOL(__ldlm_handle2lock);
2480 EXPORT_SYMBOL(ldlm_lock_get);
2481 EXPORT_SYMBOL(ldlm_lock_put);
2482 EXPORT_SYMBOL(ldlm_lock_match);
2483 EXPORT_SYMBOL(ldlm_lock_cancel);
2484 EXPORT_SYMBOL(ldlm_lock_addref);
2485 EXPORT_SYMBOL(ldlm_lock_addref_try);
2486 EXPORT_SYMBOL(ldlm_lock_decref);
2487 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2488 EXPORT_SYMBOL(ldlm_lock_change_resource);
2489 EXPORT_SYMBOL(ldlm_it2str);
2490 EXPORT_SYMBOL(ldlm_lock_dump);
2491 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2492 EXPORT_SYMBOL(ldlm_cancel_locks_for_export);
2493 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2494 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
2495 EXPORT_SYMBOL(ldlm_lock_allow_match);
2496 EXPORT_SYMBOL(ldlm_lock_downgrade);
2497 EXPORT_SYMBOL(ldlm_lock_convert);
2498
2499 /* ldlm_request.c */
2500 EXPORT_SYMBOL(ldlm_completion_ast_async);
2501 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
2502 EXPORT_SYMBOL(ldlm_completion_ast);
2503 EXPORT_SYMBOL(ldlm_blocking_ast);
2504 EXPORT_SYMBOL(ldlm_glimpse_ast);
2505 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2506 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2507 EXPORT_SYMBOL(ldlm_prep_elc_req);
2508 EXPORT_SYMBOL(ldlm_cli_convert);
2509 EXPORT_SYMBOL(ldlm_cli_enqueue);
2510 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2511 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2512 EXPORT_SYMBOL(ldlm_cli_cancel);
2513 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2514 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2515 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2516 EXPORT_SYMBOL(ldlm_replay_locks);
2517 EXPORT_SYMBOL(ldlm_resource_foreach);
2518 EXPORT_SYMBOL(ldlm_namespace_foreach);
2519 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2520 EXPORT_SYMBOL(ldlm_resource_iterate);
2521 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2522 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2523
2524 /* ldlm_lockd.c */
2525 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2526 EXPORT_SYMBOL(ldlm_server_completion_ast);
2527 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2528 EXPORT_SYMBOL(ldlm_handle_enqueue);
2529 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2530 EXPORT_SYMBOL(ldlm_handle_cancel);
2531 EXPORT_SYMBOL(ldlm_request_cancel);
2532 EXPORT_SYMBOL(ldlm_handle_convert);
2533 EXPORT_SYMBOL(ldlm_handle_convert0);
2534 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2535 EXPORT_SYMBOL(ldlm_get_ref);
2536 EXPORT_SYMBOL(ldlm_put_ref);
2537 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2538 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2539
2540 /* ldlm_resource.c */
2541 EXPORT_SYMBOL(ldlm_namespace_new);
2542 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2543 EXPORT_SYMBOL(ldlm_namespace_free);
2544 EXPORT_SYMBOL(ldlm_namespace_dump);
2545 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2546 EXPORT_SYMBOL(ldlm_resource_get);
2547 EXPORT_SYMBOL(ldlm_resource_putref);
2548 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2549
2550 /* ldlm_lib.c */
2551 EXPORT_SYMBOL(client_import_add_conn);
2552 EXPORT_SYMBOL(client_import_del_conn);
2553 EXPORT_SYMBOL(client_obd_setup);
2554 EXPORT_SYMBOL(client_obd_cleanup);
2555 EXPORT_SYMBOL(client_connect_import);
2556 EXPORT_SYMBOL(client_disconnect_export);
2557 EXPORT_SYMBOL(target_stop_recovery_thread);
2558 EXPORT_SYMBOL(target_handle_connect);
2559 EXPORT_SYMBOL(target_cleanup_recovery);
2560 EXPORT_SYMBOL(target_destroy_export);
2561 EXPORT_SYMBOL(target_cancel_recovery_timer);
2562 EXPORT_SYMBOL(target_send_reply);
2563 EXPORT_SYMBOL(target_queue_recovery_request);
2564 EXPORT_SYMBOL(target_handle_ping);
2565 EXPORT_SYMBOL(target_pack_pool_reply);
2566 EXPORT_SYMBOL(target_handle_disconnect);
2567
2568 /* l_lock.c */
2569 EXPORT_SYMBOL(lock_res_and_lock);
2570 EXPORT_SYMBOL(unlock_res_and_lock);