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