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