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