Whamcloud - gitweb
LU-2675 build: assume __linux__ and __KERNEL__
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2010, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ldlm/ldlm_lockd.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #define DEBUG_SUBSYSTEM S_LDLM
43
44 #include <libcfs/libcfs.h>
45 #include <lustre_dlm.h>
46 #include <obd_class.h>
47 #include <libcfs/list.h>
48 #include "ldlm_internal.h"
49
50 static int ldlm_num_threads;
51 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
52                 "number of DLM service threads to start");
53
54 static char *ldlm_cpts;
55 CFS_MODULE_PARM(ldlm_cpts, "s", charp, 0444,
56                 "CPU partitions ldlm threads should run on");
57
58 extern struct kmem_cache *ldlm_resource_slab;
59 extern struct kmem_cache *ldlm_lock_slab;
60 static struct mutex     ldlm_ref_mutex;
61 static int ldlm_refcount;
62
63 struct ldlm_cb_async_args {
64         struct ldlm_cb_set_arg *ca_set_arg;
65         struct ldlm_lock       *ca_lock;
66 };
67
68 /* LDLM state */
69
70 static struct ldlm_state *ldlm_state;
71
72 inline cfs_time_t round_timeout(cfs_time_t timeout)
73 {
74         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
75 }
76
77 /* timeout for initial callback (AST) reply (bz10399) */
78 static inline unsigned int ldlm_get_rq_timeout(void)
79 {
80         /* Non-AT value */
81         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
82
83         return timeout < 1 ? 1 : timeout;
84 }
85
86 #define ELT_STOPPED   0
87 #define ELT_READY     1
88 #define ELT_TERMINATE 2
89
90 struct ldlm_bl_pool {
91         spinlock_t              blp_lock;
92
93         /*
94          * blp_prio_list is used for callbacks that should be handled
95          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
96          * see bug 13843
97          */
98         struct list_head              blp_prio_list;
99
100         /*
101          * blp_list is used for all other callbacks which are likely
102          * to take longer to process.
103          */
104         struct list_head              blp_list;
105
106         wait_queue_head_t       blp_waitq;
107         struct completion       blp_comp;
108         atomic_t            blp_num_threads;
109         atomic_t            blp_busy_threads;
110         int                     blp_min_threads;
111         int                     blp_max_threads;
112 };
113
114 struct ldlm_bl_work_item {
115         struct list_head              blwi_entry;
116         struct ldlm_namespace  *blwi_ns;
117         struct ldlm_lock_desc   blwi_ld;
118         struct ldlm_lock       *blwi_lock;
119         struct list_head              blwi_head;
120         int                     blwi_count;
121         struct completion        blwi_comp;
122         ldlm_cancel_flags_t     blwi_flags;
123         int                     blwi_mem_pressure;
124 };
125
126 #ifdef HAVE_SERVER_SUPPORT
127
128 /**
129  * Protects both waiting_locks_list and expired_lock_thread.
130  */
131 static spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
132
133 /**
134  * List for contended locks.
135  *
136  * As soon as a lock is contended, it gets placed on this list and
137  * expected time to get a response is filled in the lock. A special
138  * thread walks the list looking for locks that should be released and
139  * schedules client evictions for those that have not been released in
140  * time.
141  *
142  * All access to it should be under waiting_locks_spinlock.
143  */
144 static struct list_head waiting_locks_list;
145 static struct timer_list waiting_locks_timer;
146
147 static struct expired_lock_thread {
148         wait_queue_head_t       elt_waitq;
149         int                     elt_state;
150         int                     elt_dump;
151         struct list_head                elt_expired_locks;
152 } expired_lock_thread;
153
154 static inline int have_expired_locks(void)
155 {
156         int need_to_run;
157
158         ENTRY;
159         spin_lock_bh(&waiting_locks_spinlock);
160         need_to_run = !list_empty(&expired_lock_thread.elt_expired_locks);
161         spin_unlock_bh(&waiting_locks_spinlock);
162
163         RETURN(need_to_run);
164 }
165
166 /**
167  * Check expired lock list for expired locks and time them out.
168  */
169 static int expired_lock_main(void *arg)
170 {
171         struct list_head *expired = &expired_lock_thread.elt_expired_locks;
172         struct l_wait_info lwi = { 0 };
173         int do_dump;
174
175         ENTRY;
176
177         expired_lock_thread.elt_state = ELT_READY;
178         wake_up(&expired_lock_thread.elt_waitq);
179
180         while (1) {
181                 l_wait_event(expired_lock_thread.elt_waitq,
182                              have_expired_locks() ||
183                              expired_lock_thread.elt_state == ELT_TERMINATE,
184                              &lwi);
185
186                 spin_lock_bh(&waiting_locks_spinlock);
187                 if (expired_lock_thread.elt_dump) {
188                         struct libcfs_debug_msg_data msgdata = {
189                                 .msg_file = __FILE__,
190                                 .msg_fn = "waiting_locks_callback",
191                                 .msg_line = expired_lock_thread.elt_dump };
192                         spin_unlock_bh(&waiting_locks_spinlock);
193
194                         /* from waiting_locks_callback, but not in timer */
195                         libcfs_debug_dumplog();
196                         libcfs_run_lbug_upcall(&msgdata);
197
198                         spin_lock_bh(&waiting_locks_spinlock);
199                         expired_lock_thread.elt_dump = 0;
200                 }
201
202                 do_dump = 0;
203
204                 while (!list_empty(expired)) {
205                         struct obd_export *export;
206                         struct ldlm_lock *lock;
207
208                         lock = list_entry(expired->next, struct ldlm_lock,
209                                           l_pending_chain);
210                         if ((void *)lock < LP_POISON + PAGE_CACHE_SIZE &&
211                             (void *)lock >= LP_POISON) {
212                                 spin_unlock_bh(&waiting_locks_spinlock);
213                                 CERROR("free lock on elt list %p\n", lock);
214                                 LBUG();
215                         }
216                         list_del_init(&lock->l_pending_chain);
217                         if ((void *)lock->l_export <
218                              LP_POISON + PAGE_CACHE_SIZE &&
219                             (void *)lock->l_export >= LP_POISON) {
220                                 CERROR("lock with free export on elt list %p\n",
221                                        lock->l_export);
222                                 lock->l_export = NULL;
223                                 LDLM_ERROR(lock, "free export");
224                                 /* release extra ref grabbed by
225                                  * ldlm_add_waiting_lock() or
226                                  * ldlm_failed_ast() */
227                                 LDLM_LOCK_RELEASE(lock);
228                                 continue;
229                         }
230
231                         if (ldlm_is_destroyed(lock)) {
232                                 /* release the lock refcount where
233                                  * waiting_locks_callback() founds */
234                                 LDLM_LOCK_RELEASE(lock);
235                                 continue;
236                         }
237                         export = class_export_lock_get(lock->l_export, lock);
238                         spin_unlock_bh(&waiting_locks_spinlock);
239
240                         do_dump++;
241                         class_fail_export(export);
242                         class_export_lock_put(export, lock);
243
244                         /* release extra ref grabbed by ldlm_add_waiting_lock()
245                          * or ldlm_failed_ast() */
246                         LDLM_LOCK_RELEASE(lock);
247
248                         spin_lock_bh(&waiting_locks_spinlock);
249                 }
250                 spin_unlock_bh(&waiting_locks_spinlock);
251
252                 if (do_dump && obd_dump_on_eviction) {
253                         CERROR("dump the log upon eviction\n");
254                         libcfs_debug_dumplog();
255                 }
256
257                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
258                         break;
259         }
260
261         expired_lock_thread.elt_state = ELT_STOPPED;
262         wake_up(&expired_lock_thread.elt_waitq);
263         RETURN(0);
264 }
265
266 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
267 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds);
268
269 /**
270  * Check if there is a request in the export request list
271  * which prevents the lock canceling.
272  */
273 static int ldlm_lock_busy(struct ldlm_lock *lock)
274 {
275         struct ptlrpc_request *req;
276         int match = 0;
277         ENTRY;
278
279         if (lock->l_export == NULL)
280                 return 0;
281
282         spin_lock_bh(&lock->l_export->exp_rpc_lock);
283         list_for_each_entry(req, &lock->l_export->exp_hp_rpcs,
284                                 rq_exp_list) {
285                 if (req->rq_ops->hpreq_lock_match) {
286                         match = req->rq_ops->hpreq_lock_match(req, lock);
287                         if (match)
288                                 break;
289                 }
290         }
291         spin_unlock_bh(&lock->l_export->exp_rpc_lock);
292         RETURN(match);
293 }
294
295 /* This is called from within a timer interrupt and cannot schedule */
296 static void waiting_locks_callback(unsigned long unused)
297 {
298         struct ldlm_lock        *lock;
299         int                     need_dump = 0;
300
301         spin_lock_bh(&waiting_locks_spinlock);
302         while (!list_empty(&waiting_locks_list)) {
303                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
304                                       l_pending_chain);
305                 if (cfs_time_after(lock->l_callback_timeout,
306                                    cfs_time_current()) ||
307                     (lock->l_req_mode == LCK_GROUP))
308                         break;
309
310                 /* Check if we need to prolong timeout */
311                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
312                     ldlm_lock_busy(lock)) {
313                         int cont = 1;
314
315                         if (lock->l_pending_chain.next == &waiting_locks_list)
316                                 cont = 0;
317
318                         LDLM_LOCK_GET(lock);
319
320                         spin_unlock_bh(&waiting_locks_spinlock);
321                         LDLM_DEBUG(lock, "prolong the busy lock");
322                         ldlm_refresh_waiting_lock(lock,
323                                                   ldlm_get_enq_timeout(lock));
324                         spin_lock_bh(&waiting_locks_spinlock);
325
326                         if (!cont) {
327                                 LDLM_LOCK_RELEASE(lock);
328                                 break;
329                         }
330
331                         LDLM_LOCK_RELEASE(lock);
332                         continue;
333                 }
334                 ldlm_lock_to_ns(lock)->ns_timeouts++;
335                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
336                            "evicting client at %s ",
337                            cfs_time_current_sec() - lock->l_last_activity,
338                            libcfs_nid2str(
339                                    lock->l_export->exp_connection->c_peer.nid));
340
341                 /* no needs to take an extra ref on the lock since it was in
342                  * the waiting_locks_list and ldlm_add_waiting_lock()
343                  * already grabbed a ref */
344                 list_del(&lock->l_pending_chain);
345                 list_add(&lock->l_pending_chain,
346                              &expired_lock_thread.elt_expired_locks);
347                 need_dump = 1;
348         }
349
350         if (!list_empty(&expired_lock_thread.elt_expired_locks)) {
351                 if (obd_dump_on_timeout && need_dump)
352                         expired_lock_thread.elt_dump = __LINE__;
353
354                 wake_up(&expired_lock_thread.elt_waitq);
355         }
356
357         /*
358          * Make sure the timer will fire again if we have any locks
359          * left.
360          */
361         if (!list_empty(&waiting_locks_list)) {
362                 cfs_time_t timeout_rounded;
363                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
364                                       l_pending_chain);
365                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
366                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
367         }
368         spin_unlock_bh(&waiting_locks_spinlock);
369 }
370
371 /**
372  * Add lock to the list of contended locks.
373  *
374  * Indicate that we're waiting for a client to call us back cancelling a given
375  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
376  * timer to fire appropriately.  (We round up to the next second, to avoid
377  * floods of timer firings during periods of high lock contention and traffic).
378  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
379  * if it has been added to the waiting list (1 is returned).
380  *
381  * Called with the namespace lock held.
382  */
383 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
384 {
385         cfs_time_t timeout;
386         cfs_time_t timeout_rounded;
387
388         if (!list_empty(&lock->l_pending_chain))
389                 return 0;
390
391         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
392             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
393                 seconds = 1;
394
395         timeout = cfs_time_shift(seconds);
396         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
397                 lock->l_callback_timeout = timeout;
398
399         timeout_rounded = round_timeout(lock->l_callback_timeout);
400
401         if (cfs_time_before(timeout_rounded,
402                             cfs_timer_deadline(&waiting_locks_timer)) ||
403             !cfs_timer_is_armed(&waiting_locks_timer)) {
404                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
405         }
406         /* if the new lock has a shorter timeout than something earlier on
407            the list, we'll wait the longer amount of time; no big deal. */
408         /* FIFO */
409         list_add_tail(&lock->l_pending_chain, &waiting_locks_list);
410         return 1;
411 }
412
413 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
414 {
415         int ret;
416         int timeout = ldlm_get_enq_timeout(lock);
417
418         /* NB: must be called with hold of lock_res_and_lock() */
419         LASSERT(ldlm_is_res_locked(lock));
420         ldlm_set_waited(lock);
421
422         LASSERT(!ldlm_is_cancel_on_block(lock));
423
424         spin_lock_bh(&waiting_locks_spinlock);
425         if (ldlm_is_destroyed(lock)) {
426                 static cfs_time_t next;
427                 spin_unlock_bh(&waiting_locks_spinlock);
428                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
429                 if (cfs_time_after(cfs_time_current(), next)) {
430                         next = cfs_time_shift(14400);
431                         libcfs_debug_dumpstack(NULL);
432                 }
433                 return 0;
434         }
435
436         ret = __ldlm_add_waiting_lock(lock, timeout);
437         if (ret) {
438                 /* grab ref on the lock if it has been added to the
439                  * waiting list */
440                 LDLM_LOCK_GET(lock);
441         }
442         spin_unlock_bh(&waiting_locks_spinlock);
443
444         if (ret) {
445                 spin_lock_bh(&lock->l_export->exp_bl_list_lock);
446                 if (list_empty(&lock->l_exp_list))
447                         list_add(&lock->l_exp_list,
448                                      &lock->l_export->exp_bl_list);
449                 spin_unlock_bh(&lock->l_export->exp_bl_list_lock);
450         }
451
452         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
453                    ret == 0 ? "not re-" : "", timeout,
454                    AT_OFF ? "off" : "on");
455         return ret;
456 }
457
458 /**
459  * Remove a lock from the pending list, likely because it had its cancellation
460  * callback arrive without incident.  This adjusts the lock-timeout timer if
461  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
462  * As done by ldlm_del_waiting_lock(), the caller must release the lock
463  * reference when the lock is removed from any list (1 is returned).
464  *
465  * Called with namespace lock held.
466  */
467 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
468 {
469         struct list_head *list_next;
470
471         if (list_empty(&lock->l_pending_chain))
472                 return 0;
473
474         list_next = lock->l_pending_chain.next;
475         if (lock->l_pending_chain.prev == &waiting_locks_list) {
476                 /* Removing the head of the list, adjust timer. */
477                 if (list_next == &waiting_locks_list) {
478                         /* No more, just cancel. */
479                         cfs_timer_disarm(&waiting_locks_timer);
480                 } else {
481                         struct ldlm_lock *next;
482                         next = list_entry(list_next, struct ldlm_lock,
483                                               l_pending_chain);
484                         cfs_timer_arm(&waiting_locks_timer,
485                                       round_timeout(next->l_callback_timeout));
486                 }
487         }
488         list_del_init(&lock->l_pending_chain);
489
490         return 1;
491 }
492
493 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
494 {
495         int ret;
496
497         if (lock->l_export == NULL) {
498                 /* We don't have a "waiting locks list" on clients. */
499                 CDEBUG(D_DLMTRACE, "Client lock %p : no-op\n", lock);
500                 return 0;
501         }
502
503         spin_lock_bh(&waiting_locks_spinlock);
504         ret = __ldlm_del_waiting_lock(lock);
505         spin_unlock_bh(&waiting_locks_spinlock);
506
507         /* remove the lock out of export blocking list */
508         spin_lock_bh(&lock->l_export->exp_bl_list_lock);
509         list_del_init(&lock->l_exp_list);
510         spin_unlock_bh(&lock->l_export->exp_bl_list_lock);
511
512         if (ret) {
513                 /* release lock ref if it has indeed been removed
514                  * from a list */
515                 LDLM_LOCK_RELEASE(lock);
516         }
517
518         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
519         return ret;
520 }
521 EXPORT_SYMBOL(ldlm_del_waiting_lock);
522
523 /**
524  * Prolong the contended lock waiting time.
525  *
526  * Called with namespace lock held.
527  */
528 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
529 {
530         if (lock->l_export == NULL) {
531                 /* We don't have a "waiting locks list" on clients. */
532                 LDLM_DEBUG(lock, "client lock: no-op");
533                 return 0;
534         }
535
536         spin_lock_bh(&waiting_locks_spinlock);
537
538         if (list_empty(&lock->l_pending_chain)) {
539                 spin_unlock_bh(&waiting_locks_spinlock);
540                 LDLM_DEBUG(lock, "wasn't waiting");
541                 return 0;
542         }
543
544         /* we remove/add the lock to the waiting list, so no needs to
545          * release/take a lock reference */
546         __ldlm_del_waiting_lock(lock);
547         __ldlm_add_waiting_lock(lock, timeout);
548         spin_unlock_bh(&waiting_locks_spinlock);
549
550         LDLM_DEBUG(lock, "refreshed");
551         return 1;
552 }
553 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
554
555 #else /* HAVE_SERVER_SUPPORT */
556
557 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
558 {
559         RETURN(0);
560 }
561
562 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
563 {
564         RETURN(0);
565 }
566
567 #endif /* !HAVE_SERVER_SUPPORT */
568
569 #ifdef HAVE_SERVER_SUPPORT
570
571 /**
572  * Perform lock cleanup if AST sending failed.
573  */
574 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
575                             const char *ast_type)
576 {
577         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
578                            "to a lock %s callback time out: rc %d\n",
579                            lock->l_export->exp_obd->obd_name,
580                            obd_export_nid2str(lock->l_export), ast_type, rc);
581
582         if (obd_dump_on_timeout)
583                 libcfs_debug_dumplog();
584         spin_lock_bh(&waiting_locks_spinlock);
585         if (__ldlm_del_waiting_lock(lock) == 0)
586                 /* the lock was not in any list, grab an extra ref before adding
587                  * the lock to the expired list */
588                 LDLM_LOCK_GET(lock);
589         list_add(&lock->l_pending_chain,
590                      &expired_lock_thread.elt_expired_locks);
591         wake_up(&expired_lock_thread.elt_waitq);
592         spin_unlock_bh(&waiting_locks_spinlock);
593 }
594
595 /**
596  * Perform lock cleanup if AST reply came with error.
597  */
598 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
599                                  struct ptlrpc_request *req, int rc,
600                                  const char *ast_type)
601 {
602         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
603
604         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
605                 LASSERT(lock->l_export);
606                 if (lock->l_export->exp_libclient) {
607                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
608                                    " timeout, just cancelling lock", ast_type,
609                                    libcfs_nid2str(peer.nid));
610                         ldlm_lock_cancel(lock);
611                         rc = -ERESTART;
612                 } else if (ldlm_is_cancel(lock)) {
613                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
614                                    "cancel was received (AST reply lost?)",
615                                    ast_type, libcfs_nid2str(peer.nid));
616                         ldlm_lock_cancel(lock);
617                         rc = -ERESTART;
618                 } else {
619                         ldlm_del_waiting_lock(lock);
620                         ldlm_failed_ast(lock, rc, ast_type);
621                 }
622         } else if (rc) {
623                 if (rc == -EINVAL) {
624                         struct ldlm_resource *res = lock->l_resource;
625                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
626                                " from %s AST - normal race",
627                                libcfs_nid2str(peer.nid),
628                                req->rq_repmsg ?
629                                lustre_msg_get_status(req->rq_repmsg) : -1,
630                                ast_type);
631                         if (res) {
632                                 /* update lvbo to return proper attributes.
633                                  * see bug 23174 */
634                                 ldlm_resource_getref(res);
635                                 ldlm_res_lvbo_update(res, NULL, 1);
636                                 ldlm_resource_putref(res);
637                         }
638
639                 } else {
640                         LDLM_ERROR(lock, "client (nid %s) returned %d "
641                                    "from %s AST", libcfs_nid2str(peer.nid),
642                                    (req->rq_repmsg != NULL) ?
643                                    lustre_msg_get_status(req->rq_repmsg) : 0,
644                                    ast_type);
645                 }
646                 ldlm_lock_cancel(lock);
647                 /* Server-side AST functions are called from ldlm_reprocess_all,
648                  * which needs to be told to please restart its reprocessing. */
649                 rc = -ERESTART;
650         }
651
652         return rc;
653 }
654
655 static int ldlm_cb_interpret(const struct lu_env *env,
656                              struct ptlrpc_request *req, void *data, int rc)
657 {
658         struct ldlm_cb_async_args *ca   = data;
659         struct ldlm_lock          *lock = ca->ca_lock;
660         struct ldlm_cb_set_arg    *arg  = ca->ca_set_arg;
661         ENTRY;
662
663         LASSERT(lock != NULL);
664
665         switch (arg->type) {
666         case LDLM_GL_CALLBACK:
667                 /* Update the LVB from disk if the AST failed
668                  * (this is a legal race)
669                  *
670                  * - Glimpse callback of local lock just returns
671                  *   -ELDLM_NO_LOCK_DATA.
672                  * - Glimpse callback of remote lock might return
673                  *   -ELDLM_NO_LOCK_DATA when inode is cleared. LU-274
674                  */
675                 if (rc == -ELDLM_NO_LOCK_DATA) {
676                         LDLM_DEBUG(lock, "lost race - client has a lock but no "
677                                    "inode");
678                         ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
679                 } else if (rc != 0) {
680                         rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
681                 } else {
682                         rc = ldlm_res_lvbo_update(lock->l_resource, req, 1);
683                 }
684                 break;
685         case LDLM_BL_CALLBACK:
686                 if (rc != 0)
687                         rc = ldlm_handle_ast_error(lock, req, rc, "blocking");
688                 break;
689         case LDLM_CP_CALLBACK:
690                 if (rc != 0)
691                         rc = ldlm_handle_ast_error(lock, req, rc, "completion");
692                 break;
693         default:
694                 LDLM_ERROR(lock, "invalid opcode for lock callback %d",
695                            arg->type);
696                 LBUG();
697         }
698
699         /* release extra reference taken in ldlm_ast_fini() */
700         LDLM_LOCK_RELEASE(lock);
701
702         if (rc == -ERESTART)
703                 atomic_inc(&arg->restart);
704
705         RETURN(0);
706 }
707
708 static inline int ldlm_ast_fini(struct ptlrpc_request *req,
709                                 struct ldlm_cb_set_arg *arg,
710                                 struct ldlm_lock *lock,
711                                 int instant_cancel)
712 {
713         int rc = 0;
714         ENTRY;
715
716         if (unlikely(instant_cancel)) {
717                 rc = ptl_send_rpc(req, 1);
718                 ptlrpc_req_finished(req);
719                 if (rc == 0)
720                         atomic_inc(&arg->restart);
721         } else {
722                 LDLM_LOCK_GET(lock);
723                 ptlrpc_set_add_req(arg->set, req);
724         }
725
726         RETURN(rc);
727 }
728
729 /**
730  * Check if there are requests in the export request list which prevent
731  * the lock canceling and make these requests high priority ones.
732  */
733 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
734 {
735         struct ptlrpc_request *req;
736         ENTRY;
737
738         if (lock->l_export == NULL) {
739                 LDLM_DEBUG(lock, "client lock: no-op");
740                 RETURN_EXIT;
741         }
742
743         spin_lock_bh(&lock->l_export->exp_rpc_lock);
744         list_for_each_entry(req, &lock->l_export->exp_hp_rpcs,
745                             rq_exp_list) {
746                 /* Do not process requests that were not yet added to there
747                  * incoming queue or were already removed from there for
748                  * processing. We evaluate ptlrpc_nrs_req_can_move() without
749                  * holding svcpt->scp_req_lock, and then redo the check with
750                  * the lock held once we need to obtain a reliable result.
751                  */
752                 if (ptlrpc_nrs_req_can_move(req) &&
753                     req->rq_ops->hpreq_lock_match &&
754                     req->rq_ops->hpreq_lock_match(req, lock))
755                         ptlrpc_nrs_req_hp_move(req);
756         }
757         spin_unlock_bh(&lock->l_export->exp_rpc_lock);
758         EXIT;
759 }
760
761 /**
762  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
763  * enqueued server lock conflicts with given one.
764  *
765  * Sends blocking AST RPC to the client owning that lock; arms timeout timer
766  * to wait for client response.
767  */
768 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
769                              struct ldlm_lock_desc *desc,
770                              void *data, int flag)
771 {
772         struct ldlm_cb_async_args *ca;
773         struct ldlm_cb_set_arg *arg = data;
774         struct ldlm_request    *body;
775         struct ptlrpc_request  *req;
776         int                     instant_cancel = 0;
777         int                     rc = 0;
778         ENTRY;
779
780         if (flag == LDLM_CB_CANCELING)
781                 /* Don't need to do anything here. */
782                 RETURN(0);
783
784         LASSERT(lock);
785         LASSERT(data != NULL);
786         if (lock->l_export->exp_obd->obd_recovering != 0)
787                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
788
789         ldlm_lock_reorder_req(lock);
790
791         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
792                                         &RQF_LDLM_BL_CALLBACK,
793                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
794         if (req == NULL)
795                 RETURN(-ENOMEM);
796
797         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
798         ca = ptlrpc_req_async_args(req);
799         ca->ca_set_arg = arg;
800         ca->ca_lock = lock;
801
802         req->rq_interpret_reply = ldlm_cb_interpret;
803         req->rq_no_resend = 1;
804
805         lock_res_and_lock(lock);
806         if (lock->l_granted_mode != lock->l_req_mode) {
807                 /* this blocking AST will be communicated as part of the
808                  * completion AST instead */
809                 unlock_res_and_lock(lock);
810
811                 ptlrpc_req_finished(req);
812                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
813                 RETURN(0);
814         }
815
816         if (ldlm_is_destroyed(lock)) {
817                 /* What's the point? */
818                 unlock_res_and_lock(lock);
819                 ptlrpc_req_finished(req);
820                 RETURN(0);
821         }
822
823         if (ldlm_is_cancel_on_block(lock))
824                 instant_cancel = 1;
825
826         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
827         body->lock_handle[0] = lock->l_remote_handle;
828         body->lock_desc = *desc;
829         body->lock_flags |= ldlm_flags_to_wire(lock->l_flags & LDLM_FL_AST_MASK);
830
831         LDLM_DEBUG(lock, "server preparing blocking AST");
832
833         ptlrpc_request_set_replen(req);
834         if (instant_cancel) {
835                 unlock_res_and_lock(lock);
836                 ldlm_lock_cancel(lock);
837         } else {
838                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
839                 ldlm_add_waiting_lock(lock);
840                 unlock_res_and_lock(lock);
841         }
842
843         req->rq_send_state = LUSTRE_IMP_FULL;
844         /* ptlrpc_request_alloc_pack already set timeout */
845         if (AT_OFF)
846                 req->rq_timeout = ldlm_get_rq_timeout();
847
848         lock->l_last_activity = cfs_time_current_sec();
849
850         if (lock->l_export && lock->l_export->exp_nid_stats &&
851             lock->l_export->exp_nid_stats->nid_ldlm_stats)
852                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
853                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
854
855         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
856
857         RETURN(rc);
858 }
859 EXPORT_SYMBOL(ldlm_server_blocking_ast);
860
861 /**
862  * ->l_completion_ast callback for a remote lock in server namespace.
863  *
864  *  Sends AST to the client notifying it of lock granting.  If initial
865  *  lock response was not sent yet, instead of sending another RPC, just
866  *  mark the lock as granted and client will understand
867  */
868 int ldlm_server_completion_ast(struct ldlm_lock *lock, __u64 flags, void *data)
869 {
870         struct ldlm_cb_set_arg *arg = data;
871         struct ldlm_request    *body;
872         struct ptlrpc_request  *req;
873         struct ldlm_cb_async_args *ca;
874         long                    total_enqueue_wait;
875         int                     instant_cancel = 0;
876         int                     rc = 0;
877         int                     lvb_len;
878         ENTRY;
879
880         LASSERT(lock != NULL);
881         LASSERT(data != NULL);
882
883         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
884                                           lock->l_last_activity);
885
886         if (OBD_FAIL_PRECHECK(OBD_FAIL_OST_LDLM_REPLY_NET)) {
887                 LDLM_DEBUG(lock, "dropping CP AST");
888                 RETURN(0);
889         }
890
891         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
892                                     &RQF_LDLM_CP_CALLBACK);
893         if (req == NULL)
894                 RETURN(-ENOMEM);
895
896         /* server namespace, doesn't need lock */
897         lvb_len = ldlm_lvbo_size(lock);
898         /* LU-3124 & LU-2187: to not return layout in completion AST because
899          * it may deadlock for LU-2187, or client may not have enough space
900          * for large layout. The layout will be returned to client with an
901          * extra RPC to fetch xattr.lov */
902         if (ldlm_has_layout(lock))
903                 lvb_len = 0;
904
905         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT, lvb_len);
906         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
907         if (rc) {
908                 ptlrpc_request_free(req);
909                 RETURN(rc);
910         }
911
912         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
913         ca = ptlrpc_req_async_args(req);
914         ca->ca_set_arg = arg;
915         ca->ca_lock = lock;
916
917         req->rq_interpret_reply = ldlm_cb_interpret;
918         req->rq_no_resend = 1;
919         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
920
921         body->lock_handle[0] = lock->l_remote_handle;
922         body->lock_flags = ldlm_flags_to_wire(flags);
923         ldlm_lock2desc(lock, &body->lock_desc);
924         if (lvb_len > 0) {
925                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
926
927                 lvb_len = ldlm_lvbo_fill(lock, lvb, lvb_len);
928                 if (lvb_len < 0) {
929                         /* We still need to send the RPC to wake up the blocked
930                          * enqueue thread on the client.
931                          *
932                          * Consider old client, there is no better way to notify
933                          * the failure, just zero-sized the LVB, then the client
934                          * will fail out as "-EPROTO". */
935                         req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB, 0,
936                                            RCL_CLIENT);
937                         instant_cancel = 1;
938                 } else {
939                         req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB, lvb_len,
940                                            RCL_CLIENT);
941                 }
942         }
943
944         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
945                    total_enqueue_wait);
946
947         lock->l_last_activity = cfs_time_current_sec();
948
949         /* Server-side enqueue wait time estimate, used in
950             __ldlm_add_waiting_lock to set future enqueue timers */
951         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
952                 at_measured(ldlm_lock_to_ns_at(lock),
953                             total_enqueue_wait);
954         else
955                 /* bz18618. Don't add lock enqueue time we spend waiting for a
956                    previous callback to fail. Locks waiting legitimately will
957                    get extended by ldlm_refresh_waiting_lock regardless of the
958                    estimate, so it's okay to underestimate here. */
959                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
960                        "It is likely that a previous callback timed out.",
961                        total_enqueue_wait,
962                        at_get(ldlm_lock_to_ns_at(lock)));
963
964         ptlrpc_request_set_replen(req);
965
966         req->rq_send_state = LUSTRE_IMP_FULL;
967         /* ptlrpc_request_pack already set timeout */
968         if (AT_OFF)
969                 req->rq_timeout = ldlm_get_rq_timeout();
970
971         /* We only send real blocking ASTs after the lock is granted */
972         lock_res_and_lock(lock);
973         if (ldlm_is_ast_sent(lock)) {
974                 body->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
975                 /* Copy AST flags like LDLM_FL_DISCARD_DATA. */
976                 body->lock_flags |= ldlm_flags_to_wire(lock->l_flags &
977                                                        LDLM_FL_AST_MASK);
978
979                 /* We might get here prior to ldlm_handle_enqueue setting
980                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
981                  * into waiting list, but this is safe and similar code in
982                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
983                  * that would not only cancel the lock, but will also remove
984                  * it from waiting list */
985                 if (ldlm_is_cancel_on_block(lock)) {
986                         unlock_res_and_lock(lock);
987                         ldlm_lock_cancel(lock);
988                         instant_cancel = 1;
989                         lock_res_and_lock(lock);
990                 } else {
991                         /* start the lock-timeout clock */
992                         ldlm_add_waiting_lock(lock);
993                 }
994         }
995         unlock_res_and_lock(lock);
996
997         if (lock->l_export && lock->l_export->exp_nid_stats &&
998             lock->l_export->exp_nid_stats->nid_ldlm_stats)
999                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1000                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
1001
1002         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
1003
1004         RETURN(lvb_len < 0 ? lvb_len : rc);
1005 }
1006 EXPORT_SYMBOL(ldlm_server_completion_ast);
1007
1008 /**
1009  * Server side ->l_glimpse_ast handler for client locks.
1010  *
1011  * Sends glimpse AST to the client and waits for reply. Then updates
1012  * lvbo with the result.
1013  */
1014 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
1015 {
1016         struct ldlm_cb_set_arg          *arg = data;
1017         struct ldlm_request             *body;
1018         struct ptlrpc_request           *req;
1019         struct ldlm_cb_async_args       *ca;
1020         int                              rc;
1021         struct req_format               *req_fmt;
1022         ENTRY;
1023
1024         LASSERT(lock != NULL);
1025
1026         if (arg->gl_desc != NULL)
1027                 /* There is a glimpse descriptor to pack */
1028                 req_fmt = &RQF_LDLM_GL_DESC_CALLBACK;
1029         else
1030                 req_fmt = &RQF_LDLM_GL_CALLBACK;
1031
1032         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
1033                                         req_fmt, LUSTRE_DLM_VERSION,
1034                                         LDLM_GL_CALLBACK);
1035
1036         if (req == NULL)
1037                 RETURN(-ENOMEM);
1038
1039         if (arg->gl_desc != NULL) {
1040                 /* copy the GL descriptor */
1041                 union ldlm_gl_desc      *desc;
1042                 desc = req_capsule_client_get(&req->rq_pill, &RMF_DLM_GL_DESC);
1043                 *desc = *arg->gl_desc;
1044         }
1045
1046         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1047         body->lock_handle[0] = lock->l_remote_handle;
1048         ldlm_lock2desc(lock, &body->lock_desc);
1049
1050         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
1051         ca = ptlrpc_req_async_args(req);
1052         ca->ca_set_arg = arg;
1053         ca->ca_lock = lock;
1054
1055         /* server namespace, doesn't need lock */
1056         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
1057                              ldlm_lvbo_size(lock));
1058         ptlrpc_request_set_replen(req);
1059
1060         req->rq_send_state = LUSTRE_IMP_FULL;
1061         /* ptlrpc_request_alloc_pack already set timeout */
1062         if (AT_OFF)
1063                 req->rq_timeout = ldlm_get_rq_timeout();
1064
1065         lock->l_last_activity = cfs_time_current_sec();
1066
1067         req->rq_interpret_reply = ldlm_cb_interpret;
1068
1069         if (lock->l_export && lock->l_export->exp_nid_stats &&
1070             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1071                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1072                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
1073
1074         rc = ldlm_ast_fini(req, arg, lock, 0);
1075
1076         RETURN(rc);
1077 }
1078 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
1079
1080 int ldlm_glimpse_locks(struct ldlm_resource *res,
1081                        struct list_head *gl_work_list)
1082 {
1083         int     rc;
1084         ENTRY;
1085
1086         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), gl_work_list,
1087                                LDLM_WORK_GL_AST);
1088         if (rc == -ERESTART)
1089                 ldlm_reprocess_all(res);
1090
1091         RETURN(rc);
1092 }
1093 EXPORT_SYMBOL(ldlm_glimpse_locks);
1094
1095 /* return LDLM lock associated with a lock callback request */
1096 struct ldlm_lock *ldlm_request_lock(struct ptlrpc_request *req)
1097 {
1098         struct ldlm_cb_async_args       *ca;
1099         struct ldlm_lock                *lock;
1100         ENTRY;
1101
1102         ca = ptlrpc_req_async_args(req);
1103         lock = ca->ca_lock;
1104         if (lock == NULL)
1105                 RETURN(ERR_PTR(-EFAULT));
1106
1107         RETURN(lock);
1108 }
1109 EXPORT_SYMBOL(ldlm_request_lock);
1110
1111 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
1112                        struct lprocfs_stats *srv_stats)
1113 {
1114         int lock_type = 0, op = 0;
1115
1116         lock_type = dlm_req->lock_desc.l_resource.lr_type;
1117
1118         switch (lock_type) {
1119         case LDLM_PLAIN:
1120                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
1121                 break;
1122         case LDLM_EXTENT:
1123                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1124                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1125                 else
1126                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1127                 break;
1128         case LDLM_FLOCK:
1129                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1130                 break;
1131         case LDLM_IBITS:
1132                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1133                 break;
1134         default:
1135                 op = 0;
1136                 break;
1137         }
1138
1139         if (op)
1140                 lprocfs_counter_incr(srv_stats, op);
1141
1142         return;
1143 }
1144
1145 /**
1146  * Main server-side entry point into LDLM for enqueue. This is called by ptlrpc
1147  * service threads to carry out client lock enqueueing requests.
1148  */
1149 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1150                          struct ptlrpc_request *req,
1151                          const struct ldlm_request *dlm_req,
1152                          const struct ldlm_callback_suite *cbs)
1153 {
1154         struct ldlm_reply *dlm_rep;
1155         __u64 flags;
1156         ldlm_error_t err = ELDLM_OK;
1157         struct ldlm_lock *lock = NULL;
1158         void *cookie = NULL;
1159         int rc = 0;
1160         struct ldlm_resource *res = NULL;
1161         ENTRY;
1162
1163         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1164
1165         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1166         flags = ldlm_flags_from_wire(dlm_req->lock_flags);
1167
1168         LASSERT(req->rq_export);
1169
1170         if (ptlrpc_req2svc(req)->srv_stats != NULL)
1171                 ldlm_svc_get_eopc(dlm_req, ptlrpc_req2svc(req)->srv_stats);
1172
1173         if (req->rq_export && req->rq_export->exp_nid_stats &&
1174             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1175                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1176                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1177
1178         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1179                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1180                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1181                           dlm_req->lock_desc.l_resource.lr_type);
1182                 GOTO(out, rc = -EFAULT);
1183         }
1184
1185         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1186                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1187                      dlm_req->lock_desc.l_req_mode &
1188                      (dlm_req->lock_desc.l_req_mode-1))) {
1189                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1190                           dlm_req->lock_desc.l_req_mode);
1191                 GOTO(out, rc = -EFAULT);
1192         }
1193
1194         if (exp_connect_flags(req->rq_export) & OBD_CONNECT_IBITS) {
1195                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1196                              LDLM_PLAIN)) {
1197                         DEBUG_REQ(D_ERROR, req,
1198                                   "PLAIN lock request from IBITS client?");
1199                         GOTO(out, rc = -EPROTO);
1200                 }
1201         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1202                             LDLM_IBITS)) {
1203                 DEBUG_REQ(D_ERROR, req,
1204                           "IBITS lock request from unaware client?");
1205                 GOTO(out, rc = -EPROTO);
1206         }
1207
1208 #if 0
1209         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1210            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1211            ibits for mgc/mgs) */
1212
1213         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1214          * inodebits lock if client does not support them. */
1215         if (!(exp_connect_flags(req->rq_export) & OBD_CONNECT_IBITS) &&
1216             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1217                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1218                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1219                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1220                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1221                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1222         }
1223 #endif
1224
1225         if (unlikely((flags & LDLM_FL_REPLAY) ||
1226                      (lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))) {
1227                 /* Find an existing lock in the per-export lock hash */
1228                 /* In the function below, .hs_keycmp resolves to
1229                  * ldlm_export_lock_keycmp() */
1230                 /* coverity[overrun-buffer-val] */
1231                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1232                                        (void *)&dlm_req->lock_handle[0]);
1233                 if (lock != NULL) {
1234                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1235                                   LPX64, lock->l_handle.h_cookie);
1236                         flags |= LDLM_FL_RESENT;
1237                         GOTO(existing_lock, rc = 0);
1238                 }
1239         }
1240
1241         /* The lock's callback data might be set in the policy function */
1242         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1243                                 dlm_req->lock_desc.l_resource.lr_type,
1244                                 dlm_req->lock_desc.l_req_mode,
1245                                 cbs, NULL, 0, LVB_T_NONE);
1246         if (IS_ERR(lock)) {
1247                 rc = PTR_ERR(lock);
1248                 lock = NULL;
1249                 GOTO(out, rc);
1250         }
1251
1252         lock->l_last_activity = cfs_time_current_sec();
1253         lock->l_remote_handle = dlm_req->lock_handle[0];
1254         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1255
1256         /* Initialize resource lvb but not for a lock being replayed since
1257          * Client already got lvb sent in this case.
1258          * This must occur early since some policy methods assume resource
1259          * lvb is available (lr_lvb_data != NULL).
1260          */
1261         res = lock->l_resource;
1262         if (!(flags & LDLM_FL_REPLAY)) {
1263                 /* non-replayed lock, delayed lvb init may need to be done */
1264                 rc = ldlm_lvbo_init(res);
1265                 if (rc < 0) {
1266                         LDLM_ERROR(lock, "delayed lvb init failed (rc %d)", rc);
1267                         GOTO(out, rc);
1268                 }
1269         }
1270
1271         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1272         /* Don't enqueue a lock onto the export if it is been disonnected
1273          * due to eviction (bug 3822) or server umount (bug 24324).
1274          * Cancel it now instead. */
1275         if (req->rq_export->exp_disconnected) {
1276                 LDLM_ERROR(lock, "lock on disconnected export %p",
1277                            req->rq_export);
1278                 GOTO(out, rc = -ENOTCONN);
1279         }
1280
1281         lock->l_export = class_export_lock_get(req->rq_export, lock);
1282         if (lock->l_export->exp_lock_hash)
1283                 cfs_hash_add(lock->l_export->exp_lock_hash,
1284                              &lock->l_remote_handle,
1285                              &lock->l_exp_hash);
1286
1287 existing_lock:
1288
1289         if (flags & LDLM_FL_HAS_INTENT) {
1290                 /* In this case, the reply buffer is allocated deep in
1291                  * local_lock_enqueue by the policy function. */
1292                 cookie = req;
1293         } else {
1294                 /* based on the assumption that lvb size never changes during
1295                  * resource life time otherwise it need resource->lr_lock's
1296                  * protection */
1297                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1298                                      RCL_SERVER, ldlm_lvbo_size(lock));
1299
1300                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1301                         GOTO(out, rc = -ENOMEM);
1302
1303                 rc = req_capsule_server_pack(&req->rq_pill);
1304                 if (rc)
1305                         GOTO(out, rc);
1306         }
1307
1308         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1309                 ldlm_convert_policy_to_local(req->rq_export,
1310                                           dlm_req->lock_desc.l_resource.lr_type,
1311                                           &dlm_req->lock_desc.l_policy_data,
1312                                           &lock->l_policy_data);
1313         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1314                 lock->l_req_extent = lock->l_policy_data.l_extent;
1315
1316         err = ldlm_lock_enqueue(ns, &lock, cookie, &flags);
1317         if (err) {
1318                 if ((int)err < 0)
1319                         rc = (int)err;
1320                 GOTO(out, err);
1321         }
1322
1323         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1324         dlm_rep->lock_flags = ldlm_flags_to_wire(flags);
1325
1326         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1327         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1328
1329         /* We never send a blocking AST until the lock is granted, but
1330          * we can tell it right now */
1331         lock_res_and_lock(lock);
1332
1333         /* Now take into account flags to be inherited from original lock
1334            request both in reply to client and in our own lock flags. */
1335         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_FL_INHERIT_MASK;
1336         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
1337                                               LDLM_FL_INHERIT_MASK);
1338
1339         /* Don't move a pending lock onto the export if it has already been
1340          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1341          * Cancel it now instead. */
1342         if (unlikely(req->rq_export->exp_disconnected ||
1343                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1344                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1345                 rc = -ENOTCONN;
1346         } else if (ldlm_is_ast_sent(lock)) {
1347                 dlm_rep->lock_flags |= ldlm_flags_to_wire(LDLM_FL_AST_SENT);
1348                 if (lock->l_granted_mode == lock->l_req_mode) {
1349                         /*
1350                          * Only cancel lock if it was granted, because it would
1351                          * be destroyed immediately and would never be granted
1352                          * in the future, causing timeouts on client.  Not
1353                          * granted lock will be cancelled immediately after
1354                          * sending completion AST.
1355                          */
1356                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1357                                 unlock_res_and_lock(lock);
1358                                 ldlm_lock_cancel(lock);
1359                                 lock_res_and_lock(lock);
1360                         } else
1361                                 ldlm_add_waiting_lock(lock);
1362                 }
1363         }
1364         /* Make sure we never ever grant usual metadata locks to liblustre
1365            clients */
1366         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1367             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1368              req->rq_export->exp_libclient) {
1369                 if (unlikely(!ldlm_is_cancel_on_block(lock) ||
1370                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1371                         CERROR("Granting sync lock to libclient. "
1372                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1373                                dlm_req->lock_flags, dlm_rep->lock_flags,
1374                                lock->l_flags);
1375                         LDLM_ERROR(lock, "sync lock");
1376                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1377                                 struct ldlm_intent *it;
1378
1379                                 it = req_capsule_client_get(&req->rq_pill,
1380                                                             &RMF_LDLM_INTENT);
1381                                 if (it != NULL) {
1382                                         CERROR("This is intent %s ("LPU64")\n",
1383                                                ldlm_it2str(it->opc), it->opc);
1384                                 }
1385                         }
1386                 }
1387         }
1388
1389         unlock_res_and_lock(lock);
1390
1391         EXIT;
1392  out:
1393         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1394         if (!req->rq_packed_final) {
1395                 err = lustre_pack_reply(req, 1, NULL, NULL);
1396                 if (rc == 0)
1397                         rc = err;
1398         }
1399
1400         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1401          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1402         if (lock != NULL) {
1403                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1404                            "(err=%d, rc=%d)", err, rc);
1405
1406                 if (rc == 0) {
1407                         if (req_capsule_has_field(&req->rq_pill, &RMF_DLM_LVB,
1408                                                   RCL_SERVER) &&
1409                             ldlm_lvbo_size(lock) > 0) {
1410                                 void *buf;
1411                                 int buflen;
1412
1413                                 buf = req_capsule_server_get(&req->rq_pill,
1414                                                              &RMF_DLM_LVB);
1415                                 LASSERTF(buf != NULL, "req %p, lock %p\n",
1416                                          req, lock);
1417                                 buflen = req_capsule_get_size(&req->rq_pill,
1418                                                 &RMF_DLM_LVB, RCL_SERVER);
1419                                 /* non-replayed lock, delayed lvb init may
1420                                  * need to be occur now */
1421                                 if ((buflen > 0) && !(flags & LDLM_FL_REPLAY)) {
1422                                         buflen = ldlm_lvbo_fill(lock, buf,
1423                                                                 buflen);
1424                                         if (buflen >= 0)
1425                                                 req_capsule_shrink(
1426                                                         &req->rq_pill,
1427                                                         &RMF_DLM_LVB,
1428                                                         buflen, RCL_SERVER);
1429                                         else
1430                                                 rc = buflen;
1431                                 } else if (flags & LDLM_FL_REPLAY) {
1432                                         /* no LVB resend upon replay */
1433                                         if (buflen > 0)
1434                                                 req_capsule_shrink(
1435                                                         &req->rq_pill,
1436                                                         &RMF_DLM_LVB,
1437                                                         0, RCL_SERVER);
1438                                         else
1439                                                 rc = buflen;
1440                                 } else {
1441                                         rc = buflen;
1442                                 }
1443                         }
1444                 }
1445
1446                 if (rc != 0) {
1447                         lock_res_and_lock(lock);
1448                         ldlm_resource_unlink_lock(lock);
1449                         ldlm_lock_destroy_nolock(lock);
1450                         unlock_res_and_lock(lock);
1451                 }
1452
1453                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1454                         ldlm_reprocess_all(lock->l_resource);
1455
1456                 LDLM_LOCK_RELEASE(lock);
1457         }
1458
1459         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1460                           lock, rc);
1461
1462         return rc;
1463 }
1464 EXPORT_SYMBOL(ldlm_handle_enqueue0);
1465
1466 /**
1467  * Old-style LDLM main entry point for server code enqueue.
1468  */
1469 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1470                         ldlm_completion_callback completion_callback,
1471                         ldlm_blocking_callback blocking_callback,
1472                         ldlm_glimpse_callback glimpse_callback)
1473 {
1474         struct ldlm_request *dlm_req;
1475         struct ldlm_callback_suite cbs = {
1476                 .lcs_completion = completion_callback,
1477                 .lcs_blocking   = blocking_callback,
1478                 .lcs_glimpse    = glimpse_callback
1479         };
1480         int rc;
1481
1482         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1483         if (dlm_req != NULL) {
1484                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1485                                           req, dlm_req, &cbs);
1486         } else {
1487                 rc = -EFAULT;
1488         }
1489         return rc;
1490 }
1491 EXPORT_SYMBOL(ldlm_handle_enqueue);
1492
1493 /**
1494  * Main LDLM entry point for server code to process lock conversion requests.
1495  */
1496 int ldlm_handle_convert0(struct ptlrpc_request *req,
1497                          const struct ldlm_request *dlm_req)
1498 {
1499         struct ldlm_reply *dlm_rep;
1500         struct ldlm_lock *lock;
1501         int rc;
1502         ENTRY;
1503
1504         if (req->rq_export && req->rq_export->exp_nid_stats &&
1505             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1506                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1507                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1508
1509         rc = req_capsule_server_pack(&req->rq_pill);
1510         if (rc)
1511                 RETURN(rc);
1512
1513         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1514         dlm_rep->lock_flags = dlm_req->lock_flags;
1515
1516         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1517         if (!lock) {
1518                 req->rq_status = LUSTRE_EINVAL;
1519         } else {
1520                 void *res = NULL;
1521
1522                 LDLM_DEBUG(lock, "server-side convert handler START");
1523
1524                 lock->l_last_activity = cfs_time_current_sec();
1525                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1526                                         &dlm_rep->lock_flags);
1527                 if (res) {
1528                         if (ldlm_del_waiting_lock(lock))
1529                                 LDLM_DEBUG(lock, "converted waiting lock");
1530                         req->rq_status = 0;
1531                 } else {
1532                         req->rq_status = LUSTRE_EDEADLK;
1533                 }
1534         }
1535
1536         if (lock) {
1537                 if (!req->rq_status)
1538                         ldlm_reprocess_all(lock->l_resource);
1539                 LDLM_DEBUG(lock, "server-side convert handler END");
1540                 LDLM_LOCK_PUT(lock);
1541         } else
1542                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1543
1544         RETURN(0);
1545 }
1546 EXPORT_SYMBOL(ldlm_handle_convert0);
1547
1548 /**
1549  * Old-style main LDLM entry point for server code to process lock conversion
1550  * requests.
1551  */
1552 int ldlm_handle_convert(struct ptlrpc_request *req)
1553 {
1554         int rc;
1555         struct ldlm_request *dlm_req;
1556
1557         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1558         if (dlm_req != NULL) {
1559                 rc = ldlm_handle_convert0(req, dlm_req);
1560         } else {
1561                 CERROR ("Can't unpack dlm_req\n");
1562                 rc = -EFAULT;
1563         }
1564         return rc;
1565 }
1566 EXPORT_SYMBOL(ldlm_handle_convert);
1567
1568 /**
1569  * Cancel all the locks whose handles are packed into ldlm_request
1570  *
1571  * Called by server code expecting such combined cancel activity
1572  * requests.
1573  */
1574 int ldlm_request_cancel(struct ptlrpc_request *req,
1575                         const struct ldlm_request *dlm_req, int first)
1576 {
1577         struct ldlm_resource *res, *pres = NULL;
1578         struct ldlm_lock *lock;
1579         int i, count, done = 0;
1580         ENTRY;
1581
1582         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1583         if (first >= count)
1584                 RETURN(0);
1585
1586         if (count == 1 && dlm_req->lock_handle[0].cookie == 0)
1587                 RETURN(0);
1588
1589         /* There is no lock on the server at the replay time,
1590          * skip lock cancelling to make replay tests to pass. */
1591         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1592                 RETURN(0);
1593
1594         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1595                           "starting at %d", count, first);
1596
1597         for (i = first; i < count; i++) {
1598                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1599                 if (!lock) {
1600                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1601                                           "lock (cookie "LPU64")",
1602                                           dlm_req->lock_handle[i].cookie);
1603                         continue;
1604                 }
1605
1606                 res = lock->l_resource;
1607                 done++;
1608
1609                 /* This code is an optimization to only attempt lock
1610                  * granting on the resource (that could be CPU-expensive)
1611                  * after we are done cancelling lock in that resource. */
1612                 if (res != pres) {
1613                         if (pres != NULL) {
1614                                 ldlm_reprocess_all(pres);
1615                                 LDLM_RESOURCE_DELREF(pres);
1616                                 ldlm_resource_putref(pres);
1617                         }
1618                         if (res != NULL) {
1619                                 ldlm_resource_getref(res);
1620                                 LDLM_RESOURCE_ADDREF(res);
1621                                 ldlm_res_lvbo_update(res, NULL, 1);
1622                         }
1623                         pres = res;
1624                 }
1625                 ldlm_lock_cancel(lock);
1626                 LDLM_LOCK_PUT(lock);
1627         }
1628         if (pres != NULL) {
1629                 ldlm_reprocess_all(pres);
1630                 LDLM_RESOURCE_DELREF(pres);
1631                 ldlm_resource_putref(pres);
1632         }
1633         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1634         RETURN(done);
1635 }
1636 EXPORT_SYMBOL(ldlm_request_cancel);
1637
1638 /**
1639  * Main LDLM entry point for server code to cancel locks.
1640  *
1641  * Typically gets called from service handler on LDLM_CANCEL opc.
1642  */
1643 int ldlm_handle_cancel(struct ptlrpc_request *req)
1644 {
1645         struct ldlm_request *dlm_req;
1646         int rc;
1647         ENTRY;
1648
1649         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1650         if (dlm_req == NULL) {
1651                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1652                 RETURN(-EFAULT);
1653         }
1654
1655         if (req->rq_export && req->rq_export->exp_nid_stats &&
1656             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1657                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1658                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1659
1660         rc = req_capsule_server_pack(&req->rq_pill);
1661         if (rc)
1662                 RETURN(rc);
1663
1664         if (!ldlm_request_cancel(req, dlm_req, 0))
1665                 req->rq_status = LUSTRE_ESTALE;
1666
1667         RETURN(ptlrpc_reply(req));
1668 }
1669 EXPORT_SYMBOL(ldlm_handle_cancel);
1670 #endif /* HAVE_SERVER_SUPPORT */
1671
1672 /**
1673  * Callback handler for receiving incoming blocking ASTs.
1674  *
1675  * This can only happen on client side.
1676  */
1677 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1678                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1679 {
1680         int do_ast;
1681         ENTRY;
1682
1683         LDLM_DEBUG(lock, "client blocking AST callback handler");
1684
1685         lock_res_and_lock(lock);
1686         ldlm_set_cbpending(lock);
1687
1688         if (ldlm_is_cancel_on_block(lock))
1689                 ldlm_set_cancel(lock);
1690
1691         do_ast = (!lock->l_readers && !lock->l_writers);
1692         unlock_res_and_lock(lock);
1693
1694         if (do_ast) {
1695                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1696                        lock, lock->l_blocking_ast);
1697                 if (lock->l_blocking_ast != NULL)
1698                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1699                                              LDLM_CB_BLOCKING);
1700         } else {
1701                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1702                        lock);
1703         }
1704
1705         LDLM_DEBUG(lock, "client blocking callback handler END");
1706         LDLM_LOCK_RELEASE(lock);
1707         EXIT;
1708 }
1709
1710 /**
1711  * Callback handler for receiving incoming completion ASTs.
1712  *
1713  * This only can happen on client side.
1714  */
1715 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1716                                     struct ldlm_namespace *ns,
1717                                     struct ldlm_request *dlm_req,
1718                                     struct ldlm_lock *lock)
1719 {
1720         struct list_head ast_list;
1721         int lvb_len;
1722         int rc = 0;
1723         ENTRY;
1724
1725         LDLM_DEBUG(lock, "client completion callback handler START");
1726
1727         INIT_LIST_HEAD(&ast_list);
1728         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1729                 int to = cfs_time_seconds(1);
1730                 while (to > 0) {
1731                         schedule_timeout_and_set_state(
1732                                 TASK_INTERRUPTIBLE, to);
1733                         if (lock->l_granted_mode == lock->l_req_mode ||
1734                             ldlm_is_destroyed(lock))
1735                                 break;
1736                 }
1737         }
1738
1739         lvb_len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT);
1740         if (lvb_len < 0) {
1741                 LDLM_ERROR(lock, "Fail to get lvb_len, rc = %d", lvb_len);
1742                 GOTO(out, rc = lvb_len);
1743         } else if (lvb_len > 0) {
1744                 if (lock->l_lvb_len > 0) {
1745                         /* for extent lock, lvb contains ost_lvb{}. */
1746                         LASSERT(lock->l_lvb_data != NULL);
1747
1748                         if (unlikely(lock->l_lvb_len < lvb_len)) {
1749                                 LDLM_ERROR(lock, "Replied LVB is larger than "
1750                                            "expectation, expected = %d, "
1751                                            "replied = %d",
1752                                            lock->l_lvb_len, lvb_len);
1753                                 GOTO(out, rc = -EINVAL);
1754                         }
1755                 } else if (ldlm_has_layout(lock)) { /* for layout lock, lvb has
1756                                                      * variable length */
1757                         void *lvb_data;
1758
1759                         OBD_ALLOC_LARGE(lvb_data, lvb_len);
1760                         if (lvb_data == NULL) {
1761                                 LDLM_ERROR(lock, "No memory: %d.\n", lvb_len);
1762                                 GOTO(out, rc = -ENOMEM);
1763                         }
1764
1765                         lock_res_and_lock(lock);
1766                         LASSERT(lock->l_lvb_data == NULL);
1767                         lock->l_lvb_type = LVB_T_LAYOUT;
1768                         lock->l_lvb_data = lvb_data;
1769                         lock->l_lvb_len = lvb_len;
1770                         unlock_res_and_lock(lock);
1771                 }
1772         }
1773
1774         lock_res_and_lock(lock);
1775         if (ldlm_is_destroyed(lock) ||
1776             lock->l_granted_mode == lock->l_req_mode) {
1777                 /* bug 11300: the lock has already been granted */
1778                 unlock_res_and_lock(lock);
1779                 LDLM_DEBUG(lock, "Double grant race happened");
1780                 GOTO(out, rc = 0);
1781         }
1782
1783         /* If we receive the completion AST before the actual enqueue returned,
1784          * then we might need to switch lock modes, resources, or extents. */
1785         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1786                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1787                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1788         }
1789
1790         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1791                 ldlm_convert_policy_to_local(req->rq_export,
1792                                           dlm_req->lock_desc.l_resource.lr_type,
1793                                           &dlm_req->lock_desc.l_policy_data,
1794                                           &lock->l_policy_data);
1795                 LDLM_DEBUG(lock, "completion AST, new policy data");
1796         }
1797
1798         ldlm_resource_unlink_lock(lock);
1799         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1800                    &lock->l_resource->lr_name,
1801                    sizeof(lock->l_resource->lr_name)) != 0) {
1802                 unlock_res_and_lock(lock);
1803                 rc = ldlm_lock_change_resource(ns, lock,
1804                                 &dlm_req->lock_desc.l_resource.lr_name);
1805                 if (rc < 0) {
1806                         LDLM_ERROR(lock, "Failed to allocate resource");
1807                         GOTO(out, rc);
1808                 }
1809                 LDLM_DEBUG(lock, "completion AST, new resource");
1810                 CERROR("change resource!\n");
1811                 lock_res_and_lock(lock);
1812         }
1813
1814         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1815                 /* BL_AST locks are not needed in LRU.
1816                  * Let ldlm_cancel_lru() be fast. */
1817                 ldlm_lock_remove_from_lru(lock);
1818                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1819                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1820         }
1821
1822         if (lock->l_lvb_len > 0) {
1823                 rc = ldlm_fill_lvb(lock, &req->rq_pill, RCL_CLIENT,
1824                                    lock->l_lvb_data, lvb_len);
1825                 if (rc < 0) {
1826                         unlock_res_and_lock(lock);
1827                         GOTO(out, rc);
1828                 }
1829         }
1830
1831         ldlm_grant_lock(lock, &ast_list);
1832         unlock_res_and_lock(lock);
1833
1834         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1835
1836         /* Let Enqueue to call osc_lock_upcall() and initialize
1837          * l_ast_data */
1838         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1839
1840         ldlm_run_ast_work(ns, &ast_list, LDLM_WORK_CP_AST);
1841
1842         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1843                           lock);
1844         GOTO(out, rc);
1845
1846 out:
1847         if (rc < 0) {
1848                 lock_res_and_lock(lock);
1849                 ldlm_set_failed(lock);
1850                 unlock_res_and_lock(lock);
1851                 wake_up(&lock->l_waitq);
1852         }
1853         LDLM_LOCK_RELEASE(lock);
1854 }
1855
1856 /**
1857  * Callback handler for receiving incoming glimpse ASTs.
1858  *
1859  * This only can happen on client side.  After handling the glimpse AST
1860  * we also consider dropping the lock here if it is unused locally for a
1861  * long time.
1862  */
1863 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1864                                     struct ldlm_namespace *ns,
1865                                     struct ldlm_request *dlm_req,
1866                                     struct ldlm_lock *lock)
1867 {
1868         int rc = -ENOSYS;
1869         ENTRY;
1870
1871         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1872
1873         if (lock->l_glimpse_ast != NULL)
1874                 rc = lock->l_glimpse_ast(lock, req);
1875
1876         if (req->rq_repmsg != NULL) {
1877                 ptlrpc_reply(req);
1878         } else {
1879                 req->rq_status = rc;
1880                 ptlrpc_error(req);
1881         }
1882
1883         lock_res_and_lock(lock);
1884         if (lock->l_granted_mode == LCK_PW &&
1885             !lock->l_readers && !lock->l_writers &&
1886             cfs_time_after(cfs_time_current(),
1887                            cfs_time_add(lock->l_last_used,
1888                                         cfs_time_seconds(10)))) {
1889                 unlock_res_and_lock(lock);
1890                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1891                         ldlm_handle_bl_callback(ns, NULL, lock);
1892
1893                 EXIT;
1894                 return;
1895         }
1896         unlock_res_and_lock(lock);
1897         LDLM_LOCK_RELEASE(lock);
1898         EXIT;
1899 }
1900
1901 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1902 {
1903         if (req->rq_no_reply)
1904                 return 0;
1905
1906         req->rq_status = rc;
1907         if (!req->rq_packed_final) {
1908                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1909                 if (rc)
1910                         return rc;
1911         }
1912         return ptlrpc_reply(req);
1913 }
1914
1915 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi,
1916                                ldlm_cancel_flags_t cancel_flags)
1917 {
1918         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1919         ENTRY;
1920
1921         spin_lock(&blp->blp_lock);
1922         if (blwi->blwi_lock &&
1923             ldlm_is_discard_data(blwi->blwi_lock)) {
1924                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1925                 list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1926         } else {
1927                 /* other blocking callbacks are added to the regular list */
1928                 list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1929         }
1930         spin_unlock(&blp->blp_lock);
1931
1932         wake_up(&blp->blp_waitq);
1933
1934         /* can not check blwi->blwi_flags as blwi could be already freed in
1935            LCF_ASYNC mode */
1936         if (!(cancel_flags & LCF_ASYNC))
1937                 wait_for_completion(&blwi->blwi_comp);
1938
1939         RETURN(0);
1940 }
1941
1942 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1943                              struct ldlm_namespace *ns,
1944                              struct ldlm_lock_desc *ld,
1945                              struct list_head *cancels, int count,
1946                              struct ldlm_lock *lock,
1947                              ldlm_cancel_flags_t cancel_flags)
1948 {
1949         init_completion(&blwi->blwi_comp);
1950         INIT_LIST_HEAD(&blwi->blwi_head);
1951
1952         if (memory_pressure_get())
1953                 blwi->blwi_mem_pressure = 1;
1954
1955         blwi->blwi_ns = ns;
1956         blwi->blwi_flags = cancel_flags;
1957         if (ld != NULL)
1958                 blwi->blwi_ld = *ld;
1959         if (count) {
1960                 list_add(&blwi->blwi_head, cancels);
1961                 list_del_init(cancels);
1962                 blwi->blwi_count = count;
1963         } else {
1964                 blwi->blwi_lock = lock;
1965         }
1966 }
1967
1968 /**
1969  * Queues a list of locks \a cancels containing \a count locks
1970  * for later processing by a blocking thread.  If \a count is zero,
1971  * then the lock referenced as \a lock is queued instead.
1972  *
1973  * The blocking thread would then call ->l_blocking_ast callback in the lock.
1974  * If list addition fails an error is returned and caller is supposed to
1975  * call ->l_blocking_ast itself.
1976  */
1977 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1978                              struct ldlm_lock_desc *ld,
1979                              struct ldlm_lock *lock,
1980                              struct list_head *cancels, int count,
1981                              ldlm_cancel_flags_t cancel_flags)
1982 {
1983         ENTRY;
1984
1985         if (cancels && count == 0)
1986                 RETURN(0);
1987
1988         if (cancel_flags & LCF_ASYNC) {
1989                 struct ldlm_bl_work_item *blwi;
1990
1991                 OBD_ALLOC(blwi, sizeof(*blwi));
1992                 if (blwi == NULL)
1993                         RETURN(-ENOMEM);
1994                 init_blwi(blwi, ns, ld, cancels, count, lock, cancel_flags);
1995
1996                 RETURN(__ldlm_bl_to_thread(blwi, cancel_flags));
1997         } else {
1998                 /* if it is synchronous call do minimum mem alloc, as it could
1999                  * be triggered from kernel shrinker
2000                  */
2001                 struct ldlm_bl_work_item blwi;
2002
2003                 memset(&blwi, 0, sizeof(blwi));
2004                 init_blwi(&blwi, ns, ld, cancels, count, lock, cancel_flags);
2005                 RETURN(__ldlm_bl_to_thread(&blwi, cancel_flags));
2006         }
2007 }
2008
2009
2010 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
2011                            struct ldlm_lock *lock)
2012 {
2013         return ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LCF_ASYNC);
2014 }
2015
2016 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
2017                            struct list_head *cancels, int count,
2018                            ldlm_cancel_flags_t cancel_flags)
2019 {
2020         return ldlm_bl_to_thread(ns, ld, NULL, cancels, count, cancel_flags);
2021 }
2022
2023 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
2024 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
2025 {
2026         struct obd_device *obd = req->rq_export->exp_obd;
2027         char *key;
2028         void *val;
2029         int keylen, vallen;
2030         int rc = -ENOSYS;
2031         ENTRY;
2032
2033         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
2034
2035         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
2036
2037         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
2038         if (key == NULL) {
2039                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
2040                 RETURN(-EFAULT);
2041         }
2042         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
2043                                       RCL_CLIENT);
2044         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
2045         if (val == NULL) {
2046                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
2047                 RETURN(-EFAULT);
2048         }
2049         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
2050                                       RCL_CLIENT);
2051
2052         /* We are responsible for swabbing contents of val */
2053
2054         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
2055                 /* Pass it on to mdc (the "export" in this case) */
2056                 rc = obd_set_info_async(req->rq_svc_thread->t_env,
2057                                         req->rq_export,
2058                                         sizeof(KEY_HSM_COPYTOOL_SEND),
2059                                         KEY_HSM_COPYTOOL_SEND,
2060                                         vallen, val, NULL);
2061         else
2062                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
2063
2064         return rc;
2065 }
2066
2067 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
2068                                         const char *msg, int rc,
2069                                         struct lustre_handle *handle)
2070 {
2071         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
2072                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
2073                   msg, libcfs_id2str(req->rq_peer), rc,
2074                   handle ? handle->cookie : 0);
2075         if (req->rq_no_reply)
2076                 CWARN("No reply was sent, maybe cause bug 21636.\n");
2077         else if (rc)
2078                 CWARN("Send reply failed, maybe cause bug 21636.\n");
2079 }
2080
2081 static int ldlm_handle_qc_callback(struct ptlrpc_request *req)
2082 {
2083         struct obd_quotactl *oqctl;
2084         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2085
2086         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2087         if (oqctl == NULL) {
2088                 CERROR("Can't unpack obd_quotactl\n");
2089                 RETURN(-EPROTO);
2090         }
2091
2092         oqctl->qc_stat = ptlrpc_status_ntoh(oqctl->qc_stat);
2093
2094         cli->cl_qchk_stat = oqctl->qc_stat;
2095         return 0;
2096 }
2097
2098 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
2099 static int ldlm_callback_handler(struct ptlrpc_request *req)
2100 {
2101         struct ldlm_namespace *ns;
2102         struct ldlm_request *dlm_req;
2103         struct ldlm_lock *lock;
2104         int rc;
2105         ENTRY;
2106
2107         /* Requests arrive in sender's byte order.  The ptlrpc service
2108          * handler has already checked and, if necessary, byte-swapped the
2109          * incoming request message body, but I am responsible for the
2110          * message buffers. */
2111
2112         /* do nothing for sec context finalize */
2113         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
2114                 RETURN(0);
2115
2116         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2117
2118         if (req->rq_export == NULL) {
2119                 rc = ldlm_callback_reply(req, -ENOTCONN);
2120                 ldlm_callback_errmsg(req, "Operate on unconnected server",
2121                                      rc, NULL);
2122                 RETURN(0);
2123         }
2124
2125         LASSERT(req->rq_export != NULL);
2126         LASSERT(req->rq_export->exp_obd != NULL);
2127
2128         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2129         case LDLM_BL_CALLBACK:
2130                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK_NET))
2131                         RETURN(0);
2132                 break;
2133         case LDLM_CP_CALLBACK:
2134                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK_NET))
2135                         RETURN(0);
2136                 break;
2137         case LDLM_GL_CALLBACK:
2138                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK_NET))
2139                         RETURN(0);
2140                 break;
2141         case LDLM_SET_INFO:
2142                 rc = ldlm_handle_setinfo(req);
2143                 ldlm_callback_reply(req, rc);
2144                 RETURN(0);
2145         case LLOG_ORIGIN_HANDLE_CREATE:
2146                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2147                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2148                         RETURN(0);
2149                 rc = llog_origin_handle_open(req);
2150                 ldlm_callback_reply(req, rc);
2151                 RETURN(0);
2152         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2153                 req_capsule_set(&req->rq_pill,
2154                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2155                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2156                         RETURN(0);
2157                 rc = llog_origin_handle_next_block(req);
2158                 ldlm_callback_reply(req, rc);
2159                 RETURN(0);
2160         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2161                 req_capsule_set(&req->rq_pill,
2162                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2163                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2164                         RETURN(0);
2165                 rc = llog_origin_handle_read_header(req);
2166                 ldlm_callback_reply(req, rc);
2167                 RETURN(0);
2168         case LLOG_ORIGIN_HANDLE_CLOSE:
2169                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2170                         RETURN(0);
2171                 rc = llog_origin_handle_close(req);
2172                 ldlm_callback_reply(req, rc);
2173                 RETURN(0);
2174         case OBD_QC_CALLBACK:
2175                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
2176                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
2177                         RETURN(0);
2178                 rc = ldlm_handle_qc_callback(req);
2179                 ldlm_callback_reply(req, rc);
2180                 RETURN(0);
2181         default:
2182                 CERROR("unknown opcode %u\n",
2183                        lustre_msg_get_opc(req->rq_reqmsg));
2184                 ldlm_callback_reply(req, -EPROTO);
2185                 RETURN(0);
2186         }
2187
2188         ns = req->rq_export->exp_obd->obd_namespace;
2189         LASSERT(ns != NULL);
2190
2191         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2192
2193         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2194         if (dlm_req == NULL) {
2195                 rc = ldlm_callback_reply(req, -EPROTO);
2196                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
2197                                      NULL);
2198                 RETURN(0);
2199         }
2200
2201         /* Force a known safe race, send a cancel to the server for a lock
2202          * which the server has already started a blocking callback on. */
2203         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
2204             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2205                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0], 0);
2206                 if (rc < 0)
2207                         CERROR("ldlm_cli_cancel: %d\n", rc);
2208         }
2209
2210         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
2211         if (!lock) {
2212                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
2213                        "disappeared\n", dlm_req->lock_handle[0].cookie);
2214                 rc = ldlm_callback_reply(req, -EINVAL);
2215                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
2216                                      &dlm_req->lock_handle[0]);
2217                 RETURN(0);
2218         }
2219
2220         if (ldlm_is_fail_loc(lock) &&
2221             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
2222                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
2223
2224         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
2225         lock_res_and_lock(lock);
2226         lock->l_flags |= ldlm_flags_from_wire(dlm_req->lock_flags &
2227                                               LDLM_FL_AST_MASK);
2228         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2229                 /* If somebody cancels lock and cache is already dropped,
2230                  * or lock is failed before cp_ast received on client,
2231                  * we can tell the server we have no lock. Otherwise, we
2232                  * should send cancel after dropping the cache. */
2233                 if ((ldlm_is_canceling(lock) && ldlm_is_bl_done(lock)) ||
2234                     ldlm_is_failed(lock)) {
2235                         LDLM_DEBUG(lock, "callback on lock "
2236                                    LPX64" - lock disappeared\n",
2237                                    dlm_req->lock_handle[0].cookie);
2238                         unlock_res_and_lock(lock);
2239                         LDLM_LOCK_RELEASE(lock);
2240                         rc = ldlm_callback_reply(req, -EINVAL);
2241                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
2242                                              &dlm_req->lock_handle[0]);
2243                         RETURN(0);
2244                 }
2245                 /* BL_AST locks are not needed in LRU.
2246                  * Let ldlm_cancel_lru() be fast. */
2247                 ldlm_lock_remove_from_lru(lock);
2248                 ldlm_set_bl_ast(lock);
2249         }
2250         unlock_res_and_lock(lock);
2251
2252         /* We want the ost thread to get this reply so that it can respond
2253          * to ost requests (write cache writeback) that might be triggered
2254          * in the callback.
2255          *
2256          * But we'd also like to be able to indicate in the reply that we're
2257          * cancelling right now, because it's unused, or have an intent result
2258          * in the reply, so we might have to push the responsibility for sending
2259          * the reply down into the AST handlers, alas. */
2260
2261         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2262         case LDLM_BL_CALLBACK:
2263                 CDEBUG(D_INODE, "blocking ast\n");
2264                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
2265                 if (!ldlm_is_cancel_on_block(lock)) {
2266                         rc = ldlm_callback_reply(req, 0);
2267                         if (req->rq_no_reply || rc)
2268                                 ldlm_callback_errmsg(req, "Normal process", rc,
2269                                                      &dlm_req->lock_handle[0]);
2270                 }
2271                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
2272                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2273                 break;
2274         case LDLM_CP_CALLBACK:
2275                 CDEBUG(D_INODE, "completion ast\n");
2276                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2277                 ldlm_callback_reply(req, 0);
2278                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2279                 break;
2280         case LDLM_GL_CALLBACK:
2281                 CDEBUG(D_INODE, "glimpse ast\n");
2282                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2283                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2284                 break;
2285         default:
2286                 LBUG();                         /* checked above */
2287         }
2288
2289         RETURN(0);
2290 }
2291
2292 #ifdef HAVE_SERVER_SUPPORT
2293 /**
2294  * Main handler for canceld thread.
2295  *
2296  * Separated into its own thread to avoid deadlocks.
2297  */
2298 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2299 {
2300         int rc;
2301         ENTRY;
2302
2303         /* Requests arrive in sender's byte order.  The ptlrpc service
2304          * handler has already checked and, if necessary, byte-swapped the
2305          * incoming request message body, but I am responsible for the
2306          * message buffers. */
2307
2308         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2309
2310         if (req->rq_export == NULL) {
2311                 struct ldlm_request *dlm_req;
2312
2313                 CERROR("%s from %s arrived at %lu with bad export cookie "
2314                        LPU64"\n",
2315                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2316                        libcfs_nid2str(req->rq_peer.nid),
2317                        req->rq_arrival_time.tv_sec,
2318                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2319
2320                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2321                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2322                         dlm_req = req_capsule_client_get(&req->rq_pill,
2323                                                          &RMF_DLM_REQ);
2324                         if (dlm_req != NULL)
2325                                 ldlm_lock_dump_handle(D_ERROR,
2326                                                       &dlm_req->lock_handle[0]);
2327                 }
2328                 ldlm_callback_reply(req, -ENOTCONN);
2329                 RETURN(0);
2330         }
2331
2332         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2333
2334         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2335         case LDLM_CANCEL:
2336                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2337                 CDEBUG(D_INODE, "cancel\n");
2338                 if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_NET) ||
2339                     CFS_FAIL_CHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))
2340                         RETURN(0);
2341                 rc = ldlm_handle_cancel(req);
2342                 if (rc)
2343                         break;
2344                 RETURN(0);
2345         default:
2346                 CERROR("invalid opcode %d\n",
2347                        lustre_msg_get_opc(req->rq_reqmsg));
2348                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2349                 ldlm_callback_reply(req, -EINVAL);
2350         }
2351
2352         RETURN(0);
2353 }
2354
2355 static int ldlm_cancel_hpreq_lock_match(struct ptlrpc_request *req,
2356                                         struct ldlm_lock *lock)
2357 {
2358         struct ldlm_request *dlm_req;
2359         struct lustre_handle lockh;
2360         int rc = 0;
2361         int i;
2362         ENTRY;
2363
2364         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2365         if (dlm_req == NULL)
2366                 RETURN(0);
2367
2368         ldlm_lock2handle(lock, &lockh);
2369         for (i = 0; i < dlm_req->lock_count; i++) {
2370                 if (lustre_handle_equal(&dlm_req->lock_handle[i],
2371                                         &lockh)) {
2372                         DEBUG_REQ(D_RPCTRACE, req,
2373                                   "Prio raised by lock "LPX64".", lockh.cookie);
2374
2375                         rc = 1;
2376                         break;
2377                 }
2378         }
2379
2380         RETURN(rc);
2381
2382 }
2383
2384 static int ldlm_cancel_hpreq_check(struct ptlrpc_request *req)
2385 {
2386         struct ldlm_request *dlm_req;
2387         int rc = 0;
2388         int i;
2389         ENTRY;
2390
2391         /* no prolong in recovery */
2392         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
2393                 RETURN(0);
2394
2395         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2396         if (dlm_req == NULL)
2397                 RETURN(-EFAULT);
2398
2399         for (i = 0; i < dlm_req->lock_count; i++) {
2400                 struct ldlm_lock *lock;
2401
2402                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
2403                 if (lock == NULL)
2404                         continue;
2405
2406                 rc = ldlm_is_ast_sent(lock) ? 1 : 0;
2407                 if (rc)
2408                         LDLM_DEBUG(lock, "hpreq cancel lock");
2409                 LDLM_LOCK_PUT(lock);
2410
2411                 if (rc)
2412                         break;
2413         }
2414
2415         RETURN(rc);
2416 }
2417
2418 static struct ptlrpc_hpreq_ops ldlm_cancel_hpreq_ops = {
2419         .hpreq_lock_match = ldlm_cancel_hpreq_lock_match,
2420         .hpreq_check      = ldlm_cancel_hpreq_check,
2421         .hpreq_fini       = NULL,
2422 };
2423
2424 static int ldlm_hpreq_handler(struct ptlrpc_request *req)
2425 {
2426         ENTRY;
2427
2428         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2429
2430         if (req->rq_export == NULL)
2431                 RETURN(0);
2432
2433         if (LDLM_CANCEL == lustre_msg_get_opc(req->rq_reqmsg)) {
2434                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2435                 req->rq_ops = &ldlm_cancel_hpreq_ops;
2436         }
2437         RETURN(0);
2438 }
2439
2440 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2441                         struct hlist_node *hnode, void *data)
2442
2443 {
2444         struct list_head         *rpc_list = data;
2445         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2446
2447         lock_res_and_lock(lock);
2448
2449         if (lock->l_req_mode != lock->l_granted_mode) {
2450                 unlock_res_and_lock(lock);
2451                 return 0;
2452         }
2453
2454         LASSERT(lock->l_resource);
2455         if (lock->l_resource->lr_type != LDLM_IBITS &&
2456             lock->l_resource->lr_type != LDLM_PLAIN) {
2457                 unlock_res_and_lock(lock);
2458                 return 0;
2459         }
2460
2461         if (ldlm_is_ast_sent(lock)) {
2462                 unlock_res_and_lock(lock);
2463                 return 0;
2464         }
2465
2466         LASSERT(lock->l_blocking_ast);
2467         LASSERT(!lock->l_blocking_lock);
2468
2469         ldlm_set_ast_sent(lock);
2470         if (lock->l_export && lock->l_export->exp_lock_hash) {
2471                 /* NB: it's safe to call cfs_hash_del() even lock isn't
2472                  * in exp_lock_hash. */
2473                 /* In the function below, .hs_keycmp resolves to
2474                  * ldlm_export_lock_keycmp() */
2475                 /* coverity[overrun-buffer-val] */
2476                 cfs_hash_del(lock->l_export->exp_lock_hash,
2477                              &lock->l_remote_handle, &lock->l_exp_hash);
2478         }
2479
2480         list_add_tail(&lock->l_rk_ast, rpc_list);
2481         LDLM_LOCK_GET(lock);
2482
2483         unlock_res_and_lock(lock);
2484         return 0;
2485 }
2486
2487 void ldlm_revoke_export_locks(struct obd_export *exp)
2488 {
2489         struct list_head  rpc_list;
2490         ENTRY;
2491
2492         INIT_LIST_HEAD(&rpc_list);
2493         cfs_hash_for_each_empty(exp->exp_lock_hash,
2494                                 ldlm_revoke_lock_cb, &rpc_list);
2495         ldlm_run_ast_work(exp->exp_obd->obd_namespace, &rpc_list,
2496                           LDLM_WORK_REVOKE_AST);
2497
2498         EXIT;
2499 }
2500 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2501 #endif /* HAVE_SERVER_SUPPORT */
2502
2503 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2504 {
2505         struct ldlm_bl_work_item *blwi = NULL;
2506         static unsigned int num_bl = 0;
2507
2508         spin_lock(&blp->blp_lock);
2509         /* process a request from the blp_list at least every blp_num_threads */
2510         if (!list_empty(&blp->blp_list) &&
2511             (list_empty(&blp->blp_prio_list) || num_bl == 0))
2512                 blwi = list_entry(blp->blp_list.next,
2513                                   struct ldlm_bl_work_item, blwi_entry);
2514         else
2515                 if (!list_empty(&blp->blp_prio_list))
2516                         blwi = list_entry(blp->blp_prio_list.next,
2517                                           struct ldlm_bl_work_item,
2518                                           blwi_entry);
2519
2520         if (blwi) {
2521                 if (++num_bl >= atomic_read(&blp->blp_num_threads))
2522                         num_bl = 0;
2523                 list_del(&blwi->blwi_entry);
2524         }
2525         spin_unlock(&blp->blp_lock);
2526
2527         return blwi;
2528 }
2529
2530 /* This only contains temporary data until the thread starts */
2531 struct ldlm_bl_thread_data {
2532         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2533         struct ldlm_bl_pool     *bltd_blp;
2534         struct completion       bltd_comp;
2535         int                     bltd_num;
2536 };
2537
2538 static int ldlm_bl_thread_main(void *arg);
2539
2540 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2541 {
2542         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2543         struct task_struct *task;
2544
2545         init_completion(&bltd.bltd_comp);
2546         bltd.bltd_num = atomic_read(&blp->blp_num_threads);
2547         snprintf(bltd.bltd_name, sizeof(bltd.bltd_name) - 1,
2548                 "ldlm_bl_%02d", bltd.bltd_num);
2549         task = kthread_run(ldlm_bl_thread_main, &bltd, bltd.bltd_name);
2550         if (IS_ERR(task)) {
2551                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %ld\n",
2552                        atomic_read(&blp->blp_num_threads), PTR_ERR(task));
2553                 return PTR_ERR(task);
2554         }
2555         wait_for_completion(&bltd.bltd_comp);
2556
2557         return 0;
2558 }
2559
2560 /**
2561  * Main blocking requests processing thread.
2562  *
2563  * Callers put locks into its queue by calling ldlm_bl_to_thread.
2564  * This thread in the end ends up doing actual call to ->l_blocking_ast
2565  * for queued locks.
2566  */
2567 static int ldlm_bl_thread_main(void *arg)
2568 {
2569         struct ldlm_bl_pool *blp;
2570         struct ldlm_bl_thread_data *bltd = arg;
2571         ENTRY;
2572
2573         blp = bltd->bltd_blp;
2574
2575         atomic_inc(&blp->blp_num_threads);
2576         atomic_inc(&blp->blp_busy_threads);
2577
2578         complete(&bltd->bltd_comp);
2579         /* cannot use bltd after this, it is only on caller's stack */
2580
2581         while (1) {
2582                 struct l_wait_info lwi = { 0 };
2583                 struct ldlm_bl_work_item *blwi = NULL;
2584                 int busy;
2585
2586                 blwi = ldlm_bl_get_work(blp);
2587
2588                 if (blwi == NULL) {
2589                         atomic_dec(&blp->blp_busy_threads);
2590                         l_wait_event_exclusive(blp->blp_waitq,
2591                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2592                                          &lwi);
2593                         busy = atomic_inc_return(&blp->blp_busy_threads);
2594                 } else {
2595                         busy = atomic_read(&blp->blp_busy_threads);
2596                 }
2597
2598                 if (blwi->blwi_ns == NULL)
2599                         /* added by ldlm_cleanup() */
2600                         break;
2601
2602                 /* Not fatal if racy and have a few too many threads */
2603                 if (unlikely(busy < blp->blp_max_threads &&
2604                              busy >= atomic_read(&blp->blp_num_threads) &&
2605                              !blwi->blwi_mem_pressure))
2606                         /* discard the return value, we tried */
2607                         ldlm_bl_thread_start(blp);
2608
2609                 if (blwi->blwi_mem_pressure)
2610                         memory_pressure_set();
2611
2612                 OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL2, 4);
2613
2614                 if (blwi->blwi_count) {
2615                         int count;
2616                         /* The special case when we cancel locks in LRU
2617                          * asynchronously, we pass the list of locks here.
2618                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2619                          * canceled locally yet. */
2620                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2621                                                            blwi->blwi_count,
2622                                                            LCF_BL_AST);
2623                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL,
2624                                              blwi->blwi_flags);
2625                 } else {
2626                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2627                                                 blwi->blwi_lock);
2628                 }
2629                 if (blwi->blwi_mem_pressure)
2630                         memory_pressure_clr();
2631
2632                 if (blwi->blwi_flags & LCF_ASYNC)
2633                         OBD_FREE(blwi, sizeof(*blwi));
2634                 else
2635                         complete(&blwi->blwi_comp);
2636         }
2637
2638         atomic_dec(&blp->blp_busy_threads);
2639         atomic_dec(&blp->blp_num_threads);
2640         complete(&blp->blp_comp);
2641         RETURN(0);
2642 }
2643
2644
2645 static int ldlm_setup(void);
2646 static int ldlm_cleanup(void);
2647
2648 int ldlm_get_ref(void)
2649 {
2650         int rc = 0;
2651         ENTRY;
2652         mutex_lock(&ldlm_ref_mutex);
2653         if (++ldlm_refcount == 1) {
2654                 rc = ldlm_setup();
2655                 if (rc)
2656                         ldlm_refcount--;
2657         }
2658         mutex_unlock(&ldlm_ref_mutex);
2659
2660         RETURN(rc);
2661 }
2662 EXPORT_SYMBOL(ldlm_get_ref);
2663
2664 void ldlm_put_ref(void)
2665 {
2666         ENTRY;
2667         mutex_lock(&ldlm_ref_mutex);
2668         if (ldlm_refcount == 1) {
2669                 int rc = ldlm_cleanup();
2670                 if (rc)
2671                         CERROR("ldlm_cleanup failed: %d\n", rc);
2672                 else
2673                         ldlm_refcount--;
2674         } else {
2675                 ldlm_refcount--;
2676         }
2677         mutex_unlock(&ldlm_ref_mutex);
2678
2679         EXIT;
2680 }
2681 EXPORT_SYMBOL(ldlm_put_ref);
2682
2683 /*
2684  * Export handle<->lock hash operations.
2685  */
2686 static unsigned
2687 ldlm_export_lock_hash(cfs_hash_t *hs, const void *key, unsigned mask)
2688 {
2689         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2690 }
2691
2692 static void *
2693 ldlm_export_lock_key(struct hlist_node *hnode)
2694 {
2695         struct ldlm_lock *lock;
2696
2697         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2698         return &lock->l_remote_handle;
2699 }
2700
2701 static void
2702 ldlm_export_lock_keycpy(struct hlist_node *hnode, void *key)
2703 {
2704         struct ldlm_lock     *lock;
2705
2706         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2707         lock->l_remote_handle = *(struct lustre_handle *)key;
2708 }
2709
2710 static int
2711 ldlm_export_lock_keycmp(const void *key, struct hlist_node *hnode)
2712 {
2713         return lustre_handle_equal(ldlm_export_lock_key(hnode), key);
2714 }
2715
2716 static void *
2717 ldlm_export_lock_object(struct hlist_node *hnode)
2718 {
2719         return hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2720 }
2721
2722 static void
2723 ldlm_export_lock_get(cfs_hash_t *hs, struct hlist_node *hnode)
2724 {
2725         struct ldlm_lock *lock;
2726
2727         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2728         LDLM_LOCK_GET(lock);
2729 }
2730
2731 static void
2732 ldlm_export_lock_put(cfs_hash_t *hs, struct hlist_node *hnode)
2733 {
2734         struct ldlm_lock *lock;
2735
2736         lock = hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2737         LDLM_LOCK_RELEASE(lock);
2738 }
2739
2740 static cfs_hash_ops_t ldlm_export_lock_ops = {
2741         .hs_hash        = ldlm_export_lock_hash,
2742         .hs_key         = ldlm_export_lock_key,
2743         .hs_keycmp      = ldlm_export_lock_keycmp,
2744         .hs_keycpy      = ldlm_export_lock_keycpy,
2745         .hs_object      = ldlm_export_lock_object,
2746         .hs_get         = ldlm_export_lock_get,
2747         .hs_put         = ldlm_export_lock_put,
2748         .hs_put_locked  = ldlm_export_lock_put,
2749 };
2750
2751 int ldlm_init_export(struct obd_export *exp)
2752 {
2753         int rc;
2754         ENTRY;
2755
2756         exp->exp_lock_hash =
2757                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2758                                 HASH_EXP_LOCK_CUR_BITS,
2759                                 HASH_EXP_LOCK_MAX_BITS,
2760                                 HASH_EXP_LOCK_BKT_BITS, 0,
2761                                 CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
2762                                 &ldlm_export_lock_ops,
2763                                 CFS_HASH_DEFAULT | CFS_HASH_REHASH_KEY |
2764                                 CFS_HASH_NBLK_CHANGE);
2765
2766         if (!exp->exp_lock_hash)
2767                 RETURN(-ENOMEM);
2768
2769         rc = ldlm_init_flock_export(exp);
2770         if (rc)
2771                 GOTO(err, rc);
2772
2773         RETURN(0);
2774 err:
2775         ldlm_destroy_export(exp);
2776         RETURN(rc);
2777 }
2778 EXPORT_SYMBOL(ldlm_init_export);
2779
2780 void ldlm_destroy_export(struct obd_export *exp)
2781 {
2782         ENTRY;
2783         cfs_hash_putref(exp->exp_lock_hash);
2784         exp->exp_lock_hash = NULL;
2785
2786         ldlm_destroy_flock_export(exp);
2787         EXIT;
2788 }
2789 EXPORT_SYMBOL(ldlm_destroy_export);
2790
2791 static int ldlm_setup(void)
2792 {
2793         static struct ptlrpc_service_conf       conf;
2794         struct ldlm_bl_pool                    *blp = NULL;
2795 #ifdef HAVE_SERVER_SUPPORT
2796         struct task_struct *task;
2797 #endif /* HAVE_SERVER_SUPPORT */
2798         int i;
2799         int rc = 0;
2800
2801         ENTRY;
2802
2803         if (ldlm_state != NULL)
2804                 RETURN(-EALREADY);
2805
2806         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2807         if (ldlm_state == NULL)
2808                 RETURN(-ENOMEM);
2809
2810 #ifdef LPROCFS
2811         rc = ldlm_proc_setup();
2812         if (rc != 0)
2813                 GOTO(out, rc);
2814 #endif /* LPROCFS */
2815
2816         memset(&conf, 0, sizeof(conf));
2817         conf = (typeof(conf)) {
2818                 .psc_name               = "ldlm_cbd",
2819                 .psc_watchdog_factor    = 2,
2820                 .psc_buf                = {
2821                         .bc_nbufs               = LDLM_CLIENT_NBUFS,
2822                         .bc_buf_size            = LDLM_BUFSIZE,
2823                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2824                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2825                         .bc_req_portal          = LDLM_CB_REQUEST_PORTAL,
2826                         .bc_rep_portal          = LDLM_CB_REPLY_PORTAL,
2827                 },
2828                 .psc_thr                = {
2829                         .tc_thr_name            = "ldlm_cb",
2830                         .tc_thr_factor          = LDLM_THR_FACTOR,
2831                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2832                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2833                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2834                         .tc_nthrs_user          = ldlm_num_threads,
2835                         .tc_cpu_affinity        = 1,
2836                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD,
2837                 },
2838                 .psc_cpt                = {
2839                         .cc_pattern             = ldlm_cpts,
2840                 },
2841                 .psc_ops                = {
2842                         .so_req_handler         = ldlm_callback_handler,
2843                 },
2844         };
2845         ldlm_state->ldlm_cb_service = \
2846                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2847         if (IS_ERR(ldlm_state->ldlm_cb_service)) {
2848                 CERROR("failed to start service\n");
2849                 rc = PTR_ERR(ldlm_state->ldlm_cb_service);
2850                 ldlm_state->ldlm_cb_service = NULL;
2851                 GOTO(out, rc);
2852         }
2853
2854 #ifdef HAVE_SERVER_SUPPORT
2855         memset(&conf, 0, sizeof(conf));
2856         conf = (typeof(conf)) {
2857                 .psc_name               = "ldlm_canceld",
2858                 .psc_watchdog_factor    = 6,
2859                 .psc_buf                = {
2860                         .bc_nbufs               = LDLM_SERVER_NBUFS,
2861                         .bc_buf_size            = LDLM_BUFSIZE,
2862                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2863                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2864                         .bc_req_portal          = LDLM_CANCEL_REQUEST_PORTAL,
2865                         .bc_rep_portal          = LDLM_CANCEL_REPLY_PORTAL,
2866
2867                 },
2868                 .psc_thr                = {
2869                         .tc_thr_name            = "ldlm_cn",
2870                         .tc_thr_factor          = LDLM_THR_FACTOR,
2871                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2872                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2873                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2874                         .tc_nthrs_user          = ldlm_num_threads,
2875                         .tc_cpu_affinity        = 1,
2876                         .tc_ctx_tags            = LCT_MD_THREAD | \
2877                                                   LCT_DT_THREAD | \
2878                                                   LCT_CL_THREAD,
2879                 },
2880                 .psc_cpt                = {
2881                         .cc_pattern             = ldlm_cpts,
2882                 },
2883                 .psc_ops                = {
2884                         .so_req_handler         = ldlm_cancel_handler,
2885                         .so_hpreq_handler       = ldlm_hpreq_handler,
2886                 },
2887         };
2888         ldlm_state->ldlm_cancel_service = \
2889                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2890         if (IS_ERR(ldlm_state->ldlm_cancel_service)) {
2891                 CERROR("failed to start service\n");
2892                 rc = PTR_ERR(ldlm_state->ldlm_cancel_service);
2893                 ldlm_state->ldlm_cancel_service = NULL;
2894                 GOTO(out, rc);
2895         }
2896 #endif /* HAVE_SERVER_SUPPORT */
2897
2898         OBD_ALLOC(blp, sizeof(*blp));
2899         if (blp == NULL)
2900                 GOTO(out, rc = -ENOMEM);
2901         ldlm_state->ldlm_bl_pool = blp;
2902
2903         spin_lock_init(&blp->blp_lock);
2904         INIT_LIST_HEAD(&blp->blp_list);
2905         INIT_LIST_HEAD(&blp->blp_prio_list);
2906         init_waitqueue_head(&blp->blp_waitq);
2907         atomic_set(&blp->blp_num_threads, 0);
2908         atomic_set(&blp->blp_busy_threads, 0);
2909
2910         if (ldlm_num_threads == 0) {
2911                 blp->blp_min_threads = LDLM_NTHRS_INIT;
2912                 blp->blp_max_threads = LDLM_NTHRS_MAX;
2913         } else {
2914                 blp->blp_min_threads = blp->blp_max_threads = \
2915                         min_t(int, LDLM_NTHRS_MAX, max_t(int, LDLM_NTHRS_INIT,
2916                                                          ldlm_num_threads));
2917         }
2918
2919         for (i = 0; i < blp->blp_min_threads; i++) {
2920                 rc = ldlm_bl_thread_start(blp);
2921                 if (rc < 0)
2922                         GOTO(out, rc);
2923         }
2924
2925 #ifdef HAVE_SERVER_SUPPORT
2926         INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2927         expired_lock_thread.elt_state = ELT_STOPPED;
2928         init_waitqueue_head(&expired_lock_thread.elt_waitq);
2929
2930         INIT_LIST_HEAD(&waiting_locks_list);
2931         spin_lock_init(&waiting_locks_spinlock);
2932         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2933
2934         task = kthread_run(expired_lock_main, NULL, "ldlm_elt");
2935         if (IS_ERR(task)) {
2936                 rc = PTR_ERR(task);
2937                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2938                 GOTO(out, rc);
2939         }
2940
2941         wait_event(expired_lock_thread.elt_waitq,
2942                        expired_lock_thread.elt_state == ELT_READY);
2943 #endif /* HAVE_SERVER_SUPPORT */
2944
2945         rc = ldlm_pools_init();
2946         if (rc) {
2947                 CERROR("Failed to initialize LDLM pools: %d\n", rc);
2948                 GOTO(out, rc);
2949         }
2950         RETURN(0);
2951
2952  out:
2953         ldlm_cleanup();
2954         RETURN(rc);
2955 }
2956
2957 static int ldlm_cleanup(void)
2958 {
2959         ENTRY;
2960
2961         if (!list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2962             !list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2963                 CERROR("ldlm still has namespaces; clean these up first.\n");
2964                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2965                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2966                 RETURN(-EBUSY);
2967         }
2968
2969         ldlm_pools_fini();
2970
2971         if (ldlm_state->ldlm_bl_pool != NULL) {
2972                 struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2973
2974                 while (atomic_read(&blp->blp_num_threads) > 0) {
2975                         struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2976
2977                         init_completion(&blp->blp_comp);
2978
2979                         spin_lock(&blp->blp_lock);
2980                         list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2981                         wake_up(&blp->blp_waitq);
2982                         spin_unlock(&blp->blp_lock);
2983
2984                         wait_for_completion(&blp->blp_comp);
2985                 }
2986
2987                 OBD_FREE(blp, sizeof(*blp));
2988         }
2989
2990         if (ldlm_state->ldlm_cb_service != NULL)
2991                 ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2992 #ifdef HAVE_SERVER_SUPPORT
2993         if (ldlm_state->ldlm_cancel_service != NULL)
2994                 ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2995 #endif
2996
2997         ldlm_proc_cleanup();
2998
2999 #ifdef HAVE_SERVER_SUPPORT
3000         if (expired_lock_thread.elt_state != ELT_STOPPED) {
3001                 expired_lock_thread.elt_state = ELT_TERMINATE;
3002                 wake_up(&expired_lock_thread.elt_waitq);
3003                 wait_event(expired_lock_thread.elt_waitq,
3004                                expired_lock_thread.elt_state == ELT_STOPPED);
3005         }
3006 #endif
3007
3008         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
3009         ldlm_state = NULL;
3010
3011         RETURN(0);
3012 }
3013
3014 int ldlm_init(void)
3015 {
3016         mutex_init(&ldlm_ref_mutex);
3017         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
3018         mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
3019
3020         INIT_LIST_HEAD(&ldlm_srv_namespace_list);
3021         INIT_LIST_HEAD(&ldlm_cli_active_namespace_list);
3022         INIT_LIST_HEAD(&ldlm_cli_inactive_namespace_list);
3023
3024         ldlm_resource_slab = kmem_cache_create("ldlm_resources",
3025                                                sizeof(struct ldlm_resource), 0,
3026                                                SLAB_HWCACHE_ALIGN, NULL);
3027         if (ldlm_resource_slab == NULL)
3028                 return -ENOMEM;
3029
3030         ldlm_lock_slab = kmem_cache_create("ldlm_locks",
3031                               sizeof(struct ldlm_lock), 0,
3032                               SLAB_HWCACHE_ALIGN | SLAB_DESTROY_BY_RCU, NULL);
3033         if (ldlm_lock_slab == NULL) {
3034                 kmem_cache_destroy(ldlm_resource_slab);
3035                 return -ENOMEM;
3036         }
3037
3038         ldlm_interval_slab = kmem_cache_create("interval_node",
3039                                         sizeof(struct ldlm_interval),
3040                                         0, SLAB_HWCACHE_ALIGN, NULL);
3041         if (ldlm_interval_slab == NULL) {
3042                 kmem_cache_destroy(ldlm_resource_slab);
3043                 kmem_cache_destroy(ldlm_lock_slab);
3044                 return -ENOMEM;
3045         }
3046 #if LUSTRE_TRACKS_LOCK_EXP_REFS
3047         class_export_dump_hook = ldlm_dump_export_locks;
3048 #endif
3049         return 0;
3050 }
3051
3052 void ldlm_exit(void)
3053 {
3054         if (ldlm_refcount)
3055                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
3056         kmem_cache_destroy(ldlm_resource_slab);
3057         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
3058          * synchronize_rcu() to wait a grace period elapsed, so that
3059          * ldlm_lock_free() get a chance to be called. */
3060         synchronize_rcu();
3061         kmem_cache_destroy(ldlm_lock_slab);
3062         kmem_cache_destroy(ldlm_interval_slab);
3063 }