Whamcloud - gitweb
LU-1347 ldlm: makes EXPORT_SYMBOL follows function body
[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 cfs_mutex_t      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         cfs_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         cfs_completion_t        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         cfs_completion_t        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 cfs_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         cfs_spin_lock_bh(&waiting_locks_spinlock);
151         need_to_run = !cfs_list_empty(&expired_lock_thread.elt_expired_locks);
152         cfs_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                 cfs_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                         cfs_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                         cfs_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                                 cfs_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                         cfs_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                         cfs_spin_lock_bh(&waiting_locks_spinlock);
237                 }
238                 cfs_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         cfs_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         cfs_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         cfs_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                         cfs_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                         cfs_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         cfs_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         cfs_spin_lock_bh(&waiting_locks_spinlock);
458         if (lock->l_destroyed) {
459                 static cfs_time_t next;
460                 cfs_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         cfs_spin_unlock_bh(&waiting_locks_spinlock);
476
477         if (ret) {
478                 cfs_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                 cfs_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         cfs_spin_lock_bh(&waiting_locks_spinlock);
537         ret = __ldlm_del_waiting_lock(lock);
538         cfs_spin_unlock_bh(&waiting_locks_spinlock);
539
540         /* remove the lock out of export blocking list */
541         cfs_spin_lock_bh(&lock->l_export->exp_bl_list_lock);
542         cfs_list_del_init(&lock->l_exp_list);
543         cfs_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         cfs_spin_lock_bh(&waiting_locks_spinlock);
570
571         if (cfs_list_empty(&lock->l_pending_chain)) {
572                 cfs_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         cfs_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         cfs_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         cfs_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         cfs_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         cfs_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 |= (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, int 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         if (lvb_len > 0)
922                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
923                                       lvb_len);
924
925         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
926         if (rc) {
927                 ptlrpc_request_free(req);
928                 RETURN(rc);
929         }
930
931         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
932         ca = ptlrpc_req_async_args(req);
933         ca->ca_set_arg = arg;
934         ca->ca_lock = lock;
935
936         req->rq_interpret_reply = ldlm_cb_interpret;
937         req->rq_no_resend = 1;
938         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
939
940         body->lock_handle[0] = lock->l_remote_handle;
941         body->lock_flags = flags;
942         ldlm_lock2desc(lock, &body->lock_desc);
943         if (lvb_len > 0) {
944                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
945
946                 lvb_len = ldlm_lvbo_fill(lock, lvb, lvb_len);
947                 req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB,
948                                    lvb_len, RCL_CLIENT);
949         }
950
951         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
952                    total_enqueue_wait);
953
954         /* Server-side enqueue wait time estimate, used in
955             __ldlm_add_waiting_lock to set future enqueue timers */
956         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
957                 at_measured(ldlm_lock_to_ns_at(lock),
958                             total_enqueue_wait);
959         else
960                 /* bz18618. Don't add lock enqueue time we spend waiting for a
961                    previous callback to fail. Locks waiting legitimately will
962                    get extended by ldlm_refresh_waiting_lock regardless of the
963                    estimate, so it's okay to underestimate here. */
964                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
965                        "It is likely that a previous callback timed out.",
966                        total_enqueue_wait,
967                        at_get(ldlm_lock_to_ns_at(lock)));
968
969         ptlrpc_request_set_replen(req);
970
971         req->rq_send_state = LUSTRE_IMP_FULL;
972         /* ptlrpc_request_pack already set timeout */
973         if (AT_OFF)
974                 req->rq_timeout = ldlm_get_rq_timeout();
975
976         /* We only send real blocking ASTs after the lock is granted */
977         lock_res_and_lock(lock);
978         if (lock->l_flags & LDLM_FL_AST_SENT) {
979                 body->lock_flags |= LDLM_FL_AST_SENT;
980                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
981                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
982
983                 /* We might get here prior to ldlm_handle_enqueue setting
984                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
985                  * into waiting list, but this is safe and similar code in
986                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
987                  * that would not only cancel the lock, but will also remove
988                  * it from waiting list */
989                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
990                         unlock_res_and_lock(lock);
991                         ldlm_lock_cancel(lock);
992                         instant_cancel = 1;
993                         lock_res_and_lock(lock);
994                 } else {
995                         /* start the lock-timeout clock */
996                         ldlm_add_waiting_lock(lock);
997                 }
998         }
999         unlock_res_and_lock(lock);
1000
1001         if (lock->l_export && lock->l_export->exp_nid_stats &&
1002             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1003                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1004                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
1005
1006         rc = ldlm_ast_fini(req, arg, lock, instant_cancel);
1007
1008         RETURN(rc);
1009 }
1010 EXPORT_SYMBOL(ldlm_server_completion_ast);
1011
1012 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
1013 {
1014         struct ldlm_cb_set_arg          *arg = data;
1015         struct ldlm_request             *body;
1016         struct ptlrpc_request           *req;
1017         struct ldlm_cb_async_args       *ca;
1018         int                              rc;
1019         struct req_format               *req_fmt;
1020         ENTRY;
1021
1022         LASSERT(lock != NULL);
1023
1024         if (arg->gl_desc != NULL)
1025                 /* There is a glimpse descriptor to pack */
1026                 req_fmt = &RQF_LDLM_GL_DESC_CALLBACK;
1027         else
1028                 req_fmt = &RQF_LDLM_GL_CALLBACK;
1029
1030         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
1031                                         req_fmt, LUSTRE_DLM_VERSION,
1032                                         LDLM_GL_CALLBACK);
1033
1034         if (req == NULL)
1035                 RETURN(-ENOMEM);
1036
1037         if (arg->gl_desc != NULL) {
1038                 /* copy the GL descriptor */
1039                 union ldlm_gl_desc      *desc;
1040                 desc = req_capsule_client_get(&req->rq_pill, &RMF_DLM_GL_DESC);
1041                 *desc = *arg->gl_desc;
1042         }
1043
1044         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1045         body->lock_handle[0] = lock->l_remote_handle;
1046         ldlm_lock2desc(lock, &body->lock_desc);
1047
1048         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
1049         ca = ptlrpc_req_async_args(req);
1050         ca->ca_set_arg = arg;
1051         ca->ca_lock = lock;
1052
1053         /* server namespace, doesn't need lock */
1054         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
1055                              ldlm_lvbo_size(lock));
1056         ptlrpc_request_set_replen(req);
1057
1058         req->rq_send_state = LUSTRE_IMP_FULL;
1059         /* ptlrpc_request_alloc_pack already set timeout */
1060         if (AT_OFF)
1061                 req->rq_timeout = ldlm_get_rq_timeout();
1062
1063         req->rq_interpret_reply = ldlm_cb_interpret;
1064
1065         if (lock->l_export && lock->l_export->exp_nid_stats &&
1066             lock->l_export->exp_nid_stats->nid_ldlm_stats)
1067                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
1068                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
1069
1070         rc = ldlm_ast_fini(req, arg, lock, 0);
1071
1072         RETURN(rc);
1073 }
1074 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
1075
1076 int ldlm_glimpse_locks(struct ldlm_resource *res, cfs_list_t *gl_work_list)
1077 {
1078         int     rc;
1079         ENTRY;
1080
1081         rc = ldlm_run_ast_work(ldlm_res_to_ns(res), gl_work_list,
1082                                LDLM_WORK_GL_AST);
1083         if (rc == -ERESTART)
1084                 ldlm_reprocess_all(res);
1085
1086         RETURN(rc);
1087 }
1088 EXPORT_SYMBOL(ldlm_glimpse_locks);
1089
1090 /* return ldlm lock associated with a lock callback request */
1091 struct ldlm_lock *ldlm_request_lock(struct ptlrpc_request *req)
1092 {
1093         struct ldlm_cb_async_args       *ca;
1094         struct ldlm_lock                *lock;
1095         ENTRY;
1096
1097         ca = ptlrpc_req_async_args(req);
1098         lock = ca->ca_lock;
1099         if (lock == NULL)
1100                 RETURN(ERR_PTR(-EFAULT));
1101
1102         RETURN(lock);
1103 }
1104 EXPORT_SYMBOL(ldlm_request_lock);
1105
1106 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
1107                        struct lprocfs_stats *srv_stats)
1108 {
1109         int lock_type = 0, op = 0;
1110
1111         lock_type = dlm_req->lock_desc.l_resource.lr_type;
1112
1113         switch (lock_type) {
1114         case LDLM_PLAIN:
1115                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
1116                 break;
1117         case LDLM_EXTENT:
1118                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1119                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1120                 else
1121                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1122                 break;
1123         case LDLM_FLOCK:
1124                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1125                 break;
1126         case LDLM_IBITS:
1127                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1128                 break;
1129         default:
1130                 op = 0;
1131                 break;
1132         }
1133
1134         if (op)
1135                 lprocfs_counter_incr(srv_stats, op);
1136
1137         return;
1138 }
1139
1140 /*
1141  * Main server-side entry point into LDLM. This is called by ptlrpc service
1142  * threads to carry out client lock enqueueing requests.
1143  */
1144 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1145                          struct ptlrpc_request *req,
1146                          const struct ldlm_request *dlm_req,
1147                          const struct ldlm_callback_suite *cbs)
1148 {
1149         struct ldlm_reply *dlm_rep;
1150         __u32 flags;
1151         ldlm_error_t err = ELDLM_OK;
1152         struct ldlm_lock *lock = NULL;
1153         void *cookie = NULL;
1154         int rc = 0;
1155         ENTRY;
1156
1157         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1158
1159         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1160         flags = dlm_req->lock_flags;
1161
1162         LASSERT(req->rq_export);
1163
1164         if (ptlrpc_req2svc(req)->srv_stats != NULL)
1165                 ldlm_svc_get_eopc(dlm_req, ptlrpc_req2svc(req)->srv_stats);
1166
1167         if (req->rq_export && req->rq_export->exp_nid_stats &&
1168             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1169                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1170                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1171
1172         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1173                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1174                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1175                           dlm_req->lock_desc.l_resource.lr_type);
1176                 GOTO(out, rc = -EFAULT);
1177         }
1178
1179         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1180                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1181                      dlm_req->lock_desc.l_req_mode &
1182                      (dlm_req->lock_desc.l_req_mode-1))) {
1183                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1184                           dlm_req->lock_desc.l_req_mode);
1185                 GOTO(out, rc = -EFAULT);
1186         }
1187
1188         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1189                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1190                              LDLM_PLAIN)) {
1191                         DEBUG_REQ(D_ERROR, req,
1192                                   "PLAIN lock request from IBITS client?");
1193                         GOTO(out, rc = -EPROTO);
1194                 }
1195         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1196                             LDLM_IBITS)) {
1197                 DEBUG_REQ(D_ERROR, req,
1198                           "IBITS lock request from unaware client?");
1199                 GOTO(out, rc = -EPROTO);
1200         }
1201
1202 #if 0
1203         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1204            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1205            ibits for mgc/mgs) */
1206
1207         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1208          * inodebits lock if client does not support them. */
1209         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1210             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1211                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1212                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1213                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1214                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1215                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1216         }
1217 #endif
1218
1219         if (unlikely(flags & LDLM_FL_REPLAY)) {
1220                 /* Find an existing lock in the per-export lock hash */
1221                 /* In the function below, .hs_keycmp resolves to
1222                  * ldlm_export_lock_keycmp() */
1223                 /* coverity[overrun-buffer-val] */
1224                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1225                                        (void *)&dlm_req->lock_handle[0]);
1226                 if (lock != NULL) {
1227                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1228                                   LPX64, lock->l_handle.h_cookie);
1229                         GOTO(existing_lock, rc = 0);
1230                 }
1231         }
1232
1233         /* The lock's callback data might be set in the policy function */
1234         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1235                                 dlm_req->lock_desc.l_resource.lr_type,
1236                                 dlm_req->lock_desc.l_req_mode,
1237                                 cbs, NULL, 0);
1238
1239         if (!lock)
1240                 GOTO(out, rc = -ENOMEM);
1241
1242         lock->l_last_activity = cfs_time_current_sec();
1243         lock->l_remote_handle = dlm_req->lock_handle[0];
1244         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1245
1246         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1247         /* Don't enqueue a lock onto the export if it is been disonnected
1248          * due to eviction (bug 3822) or server umount (bug 24324).
1249          * Cancel it now instead. */
1250         if (req->rq_export->exp_disconnected) {
1251                 LDLM_ERROR(lock, "lock on disconnected export %p",
1252                            req->rq_export);
1253                 GOTO(out, rc = -ENOTCONN);
1254         }
1255
1256         lock->l_export = class_export_lock_get(req->rq_export, lock);
1257         if (lock->l_export->exp_lock_hash)
1258                 cfs_hash_add(lock->l_export->exp_lock_hash,
1259                              &lock->l_remote_handle,
1260                              &lock->l_exp_hash);
1261
1262 existing_lock:
1263
1264         if (flags & LDLM_FL_HAS_INTENT) {
1265                 /* In this case, the reply buffer is allocated deep in
1266                  * local_lock_enqueue by the policy function. */
1267                 cookie = req;
1268         } else {
1269                 /* based on the assumption that lvb size never changes during
1270                  * resource life time otherwise it need resource->lr_lock's
1271                  * protection */
1272                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1273                                      RCL_SERVER, ldlm_lvbo_size(lock));
1274
1275                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1276                         GOTO(out, rc = -ENOMEM);
1277
1278                 rc = req_capsule_server_pack(&req->rq_pill);
1279                 if (rc)
1280                         GOTO(out, rc);
1281         }
1282
1283         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1284                 ldlm_convert_policy_to_local(req->rq_export,
1285                                           dlm_req->lock_desc.l_resource.lr_type,
1286                                           &dlm_req->lock_desc.l_policy_data,
1287                                           &lock->l_policy_data);
1288         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1289                 lock->l_req_extent = lock->l_policy_data.l_extent;
1290
1291         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1292         if (err)
1293                 GOTO(out, err);
1294
1295         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1296         dlm_rep->lock_flags = flags;
1297
1298         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1299         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1300
1301         /* We never send a blocking AST until the lock is granted, but
1302          * we can tell it right now */
1303         lock_res_and_lock(lock);
1304
1305         /* Now take into account flags to be inherited from original lock
1306            request both in reply to client and in our own lock flags. */
1307         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1308         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1309
1310         /* Don't move a pending lock onto the export if it has already been
1311          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1312          * Cancel it now instead. */
1313         if (unlikely(req->rq_export->exp_disconnected ||
1314                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1315                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1316                 rc = -ENOTCONN;
1317         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1318                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1319                 if (lock->l_granted_mode == lock->l_req_mode) {
1320                         /*
1321                          * Only cancel lock if it was granted, because it would
1322                          * be destroyed immediately and would never be granted
1323                          * in the future, causing timeouts on client.  Not
1324                          * granted lock will be cancelled immediately after
1325                          * sending completion AST.
1326                          */
1327                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1328                                 unlock_res_and_lock(lock);
1329                                 ldlm_lock_cancel(lock);
1330                                 lock_res_and_lock(lock);
1331                         } else
1332                                 ldlm_add_waiting_lock(lock);
1333                 }
1334         }
1335         /* Make sure we never ever grant usual metadata locks to liblustre
1336            clients */
1337         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1338             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1339              req->rq_export->exp_libclient) {
1340                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1341                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1342                         CERROR("Granting sync lock to libclient. "
1343                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1344                                dlm_req->lock_flags, dlm_rep->lock_flags,
1345                                lock->l_flags);
1346                         LDLM_ERROR(lock, "sync lock");
1347                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1348                                 struct ldlm_intent *it;
1349
1350                                 it = req_capsule_client_get(&req->rq_pill,
1351                                                             &RMF_LDLM_INTENT);
1352                                 if (it != NULL) {
1353                                         CERROR("This is intent %s ("LPU64")\n",
1354                                                ldlm_it2str(it->opc), it->opc);
1355                                 }
1356                         }
1357                 }
1358         }
1359
1360         unlock_res_and_lock(lock);
1361
1362         EXIT;
1363  out:
1364         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1365         if (!req->rq_packed_final) {
1366                 err = lustre_pack_reply(req, 1, NULL, NULL);
1367                 if (rc == 0)
1368                         rc = err;
1369         }
1370
1371         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1372          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1373         if (lock) {
1374                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1375                            "(err=%d, rc=%d)", err, rc);
1376
1377                 if (rc == 0) {
1378                         int lvb_len = ldlm_lvbo_size(lock);
1379
1380                         if (lvb_len > 0) {
1381                                 void *buf;
1382                                 int buflen;
1383
1384                                 buf = req_capsule_server_get(&req->rq_pill,
1385                                                              &RMF_DLM_LVB);
1386                                 LASSERTF(buf != NULL, "req %p, lock %p\n",
1387                                          req, lock);
1388                                 buflen = req_capsule_get_size(&req->rq_pill,
1389                                                 &RMF_DLM_LVB, RCL_SERVER);
1390                                 buflen = ldlm_lvbo_fill(lock, buf, buflen);
1391                                 req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB,
1392                                                    buflen, RCL_SERVER);
1393                         }
1394                 } else {
1395                         lock_res_and_lock(lock);
1396                         ldlm_resource_unlink_lock(lock);
1397                         ldlm_lock_destroy_nolock(lock);
1398                         unlock_res_and_lock(lock);
1399                 }
1400
1401                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1402                         ldlm_reprocess_all(lock->l_resource);
1403
1404                 LDLM_LOCK_RELEASE(lock);
1405         }
1406
1407         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1408                           lock, rc);
1409
1410         return rc;
1411 }
1412 EXPORT_SYMBOL(ldlm_handle_enqueue0);
1413
1414 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1415                         ldlm_completion_callback completion_callback,
1416                         ldlm_blocking_callback blocking_callback,
1417                         ldlm_glimpse_callback glimpse_callback)
1418 {
1419         struct ldlm_request *dlm_req;
1420         struct ldlm_callback_suite cbs = {
1421                 .lcs_completion = completion_callback,
1422                 .lcs_blocking   = blocking_callback,
1423                 .lcs_glimpse    = glimpse_callback
1424         };
1425         int rc;
1426
1427         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1428         if (dlm_req != NULL) {
1429                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1430                                           req, dlm_req, &cbs);
1431         } else {
1432                 rc = -EFAULT;
1433         }
1434         return rc;
1435 }
1436 EXPORT_SYMBOL(ldlm_handle_enqueue);
1437
1438 int ldlm_handle_convert0(struct ptlrpc_request *req,
1439                          const struct ldlm_request *dlm_req)
1440 {
1441         struct ldlm_reply *dlm_rep;
1442         struct ldlm_lock *lock;
1443         int rc;
1444         ENTRY;
1445
1446         if (req->rq_export && req->rq_export->exp_nid_stats &&
1447             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1448                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1449                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1450
1451         rc = req_capsule_server_pack(&req->rq_pill);
1452         if (rc)
1453                 RETURN(rc);
1454
1455         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1456         dlm_rep->lock_flags = dlm_req->lock_flags;
1457
1458         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1459         if (!lock) {
1460                 req->rq_status = EINVAL;
1461         } else {
1462                 void *res = NULL;
1463
1464                 LDLM_DEBUG(lock, "server-side convert handler START");
1465
1466                 lock->l_last_activity = cfs_time_current_sec();
1467                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1468                                         &dlm_rep->lock_flags);
1469                 if (res) {
1470                         if (ldlm_del_waiting_lock(lock))
1471                                 LDLM_DEBUG(lock, "converted waiting lock");
1472                         req->rq_status = 0;
1473                 } else {
1474                         req->rq_status = EDEADLOCK;
1475                 }
1476         }
1477
1478         if (lock) {
1479                 if (!req->rq_status)
1480                         ldlm_reprocess_all(lock->l_resource);
1481                 LDLM_DEBUG(lock, "server-side convert handler END");
1482                 LDLM_LOCK_PUT(lock);
1483         } else
1484                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1485
1486         RETURN(0);
1487 }
1488 EXPORT_SYMBOL(ldlm_handle_convert0);
1489
1490 int ldlm_handle_convert(struct ptlrpc_request *req)
1491 {
1492         int rc;
1493         struct ldlm_request *dlm_req;
1494
1495         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1496         if (dlm_req != NULL) {
1497                 rc = ldlm_handle_convert0(req, dlm_req);
1498         } else {
1499                 CERROR ("Can't unpack dlm_req\n");
1500                 rc = -EFAULT;
1501         }
1502         return rc;
1503 }
1504 EXPORT_SYMBOL(ldlm_handle_convert);
1505
1506 /* Cancel all the locks whos handles are packed into ldlm_request */
1507 int ldlm_request_cancel(struct ptlrpc_request *req,
1508                         const struct ldlm_request *dlm_req, int first)
1509 {
1510         struct ldlm_resource *res, *pres = NULL;
1511         struct ldlm_lock *lock;
1512         int i, count, done = 0;
1513         ENTRY;
1514
1515         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1516         if (first >= count)
1517                 RETURN(0);
1518
1519         if (count == 1 && dlm_req->lock_handle[0].cookie == 0)
1520                 RETURN(0);
1521
1522         /* There is no lock on the server at the replay time,
1523          * skip lock cancelling to make replay tests to pass. */
1524         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1525                 RETURN(0);
1526
1527         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1528                           "starting at %d", count, first);
1529
1530         for (i = first; i < count; i++) {
1531                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1532                 if (!lock) {
1533                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1534                                           "lock (cookie "LPU64")",
1535                                           dlm_req->lock_handle[i].cookie);
1536                         continue;
1537                 }
1538
1539                 res = lock->l_resource;
1540                 done++;
1541
1542                 if (res != pres) {
1543                         if (pres != NULL) {
1544                                 ldlm_reprocess_all(pres);
1545                                 LDLM_RESOURCE_DELREF(pres);
1546                                 ldlm_resource_putref(pres);
1547                         }
1548                         if (res != NULL) {
1549                                 ldlm_resource_getref(res);
1550                                 LDLM_RESOURCE_ADDREF(res);
1551                                 ldlm_res_lvbo_update(res, NULL, 1);
1552                         }
1553                         pres = res;
1554                 }
1555                 ldlm_lock_cancel(lock);
1556                 LDLM_LOCK_PUT(lock);
1557         }
1558         if (pres != NULL) {
1559                 ldlm_reprocess_all(pres);
1560                 LDLM_RESOURCE_DELREF(pres);
1561                 ldlm_resource_putref(pres);
1562         }
1563         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1564         RETURN(done);
1565 }
1566 EXPORT_SYMBOL(ldlm_request_cancel);
1567
1568 int ldlm_handle_cancel(struct ptlrpc_request *req)
1569 {
1570         struct ldlm_request *dlm_req;
1571         int rc;
1572         ENTRY;
1573
1574         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1575         if (dlm_req == NULL) {
1576                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1577                 RETURN(-EFAULT);
1578         }
1579
1580         if (req->rq_export && req->rq_export->exp_nid_stats &&
1581             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1582                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1583                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1584
1585         rc = req_capsule_server_pack(&req->rq_pill);
1586         if (rc)
1587                 RETURN(rc);
1588
1589         if (!ldlm_request_cancel(req, dlm_req, 0))
1590                 req->rq_status = ESTALE;
1591
1592         RETURN(ptlrpc_reply(req));
1593 }
1594 EXPORT_SYMBOL(ldlm_handle_cancel);
1595 #endif /* HAVE_SERVER_SUPPORT */
1596
1597 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1598                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1599 {
1600         int do_ast;
1601         ENTRY;
1602
1603         LDLM_DEBUG(lock, "client blocking AST callback handler");
1604
1605         lock_res_and_lock(lock);
1606         lock->l_flags |= LDLM_FL_CBPENDING;
1607
1608         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1609                 lock->l_flags |= LDLM_FL_CANCEL;
1610
1611         do_ast = (!lock->l_readers && !lock->l_writers);
1612         unlock_res_and_lock(lock);
1613
1614         if (do_ast) {
1615                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1616                        lock, lock->l_blocking_ast);
1617                 if (lock->l_blocking_ast != NULL)
1618                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1619                                              LDLM_CB_BLOCKING);
1620         } else {
1621                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1622                        lock);
1623         }
1624
1625         LDLM_DEBUG(lock, "client blocking callback handler END");
1626         LDLM_LOCK_RELEASE(lock);
1627         EXIT;
1628 }
1629
1630 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1631                                     struct ldlm_namespace *ns,
1632                                     struct ldlm_request *dlm_req,
1633                                     struct ldlm_lock *lock)
1634 {
1635         int lvb_len;
1636         CFS_LIST_HEAD(ast_list);
1637         ENTRY;
1638
1639         LDLM_DEBUG(lock, "client completion callback handler START");
1640
1641         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1642                 int to = cfs_time_seconds(1);
1643                 while (to > 0) {
1644                         cfs_schedule_timeout_and_set_state(
1645                                 CFS_TASK_INTERRUPTIBLE, to);
1646                         if (lock->l_granted_mode == lock->l_req_mode ||
1647                             lock->l_destroyed)
1648                                 break;
1649                 }
1650         }
1651
1652         lvb_len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT);
1653         if (lvb_len > 0) {
1654                 if (lock->l_lvb_len > 0) {
1655                         /* for extent lock, lvb contains ost_lvb{}. */
1656                         LASSERT(lock->l_lvb_data != NULL);
1657                         LASSERTF(lock->l_lvb_len == lvb_len,
1658                                 "preallocated %d, actual %d.\n",
1659                                 lock->l_lvb_len, lvb_len);
1660                 } else { /* for layout lock, lvb has variable length */
1661                         void *lvb_data;
1662
1663                         OBD_ALLOC(lvb_data, lvb_len);
1664                         if (lvb_data == NULL)
1665                                 LDLM_ERROR(lock, "no memory.\n");
1666
1667                         lock_res_and_lock(lock);
1668                         if (lvb_data == NULL) {
1669                                 lock->l_flags |= LDLM_FL_FAILED;
1670                         } else {
1671                                 LASSERT(lock->l_lvb_data == NULL);
1672                                 lock->l_lvb_data = lvb_data;
1673                                 lock->l_lvb_len = lvb_len;
1674                         }
1675                         unlock_res_and_lock(lock);
1676                 }
1677         }
1678
1679         lock_res_and_lock(lock);
1680         if (lock->l_destroyed ||
1681             lock->l_granted_mode == lock->l_req_mode) {
1682                 /* bug 11300: the lock has already been granted */
1683                 unlock_res_and_lock(lock);
1684                 LDLM_DEBUG(lock, "Double grant race happened");
1685                 LDLM_LOCK_RELEASE(lock);
1686                 EXIT;
1687                 return;
1688         }
1689
1690         /* If we receive the completion AST before the actual enqueue returned,
1691          * then we might need to switch lock modes, resources, or extents. */
1692         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1693                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1694                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1695         }
1696
1697         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1698                 ldlm_convert_policy_to_local(req->rq_export,
1699                                           dlm_req->lock_desc.l_resource.lr_type,
1700                                           &dlm_req->lock_desc.l_policy_data,
1701                                           &lock->l_policy_data);
1702                 LDLM_DEBUG(lock, "completion AST, new policy data");
1703         }
1704
1705         ldlm_resource_unlink_lock(lock);
1706         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1707                    &lock->l_resource->lr_name,
1708                    sizeof(lock->l_resource->lr_name)) != 0) {
1709                 unlock_res_and_lock(lock);
1710                 if (ldlm_lock_change_resource(ns, lock,
1711                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1712                         LDLM_ERROR(lock, "Failed to allocate resource");
1713                         LDLM_LOCK_RELEASE(lock);
1714                         EXIT;
1715                         return;
1716                 }
1717                 LDLM_DEBUG(lock, "completion AST, new resource");
1718                 CERROR("change resource!\n");
1719                 lock_res_and_lock(lock);
1720         }
1721
1722         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1723                 /* BL_AST locks are not needed in lru.
1724                  * let ldlm_cancel_lru() be fast. */
1725                 ldlm_lock_remove_from_lru(lock);
1726                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1727                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1728         }
1729
1730         if (lock->l_lvb_len) {
1731                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1732                                          RCL_CLIENT) < lock->l_lvb_len) {
1733                         LDLM_ERROR(lock, "completion AST did not contain "
1734                                    "expected LVB!");
1735                 } else {
1736                         void *lvb = req_capsule_client_get(&req->rq_pill,
1737                                                            &RMF_DLM_LVB);
1738                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1739                 }
1740         }
1741
1742         ldlm_grant_lock(lock, &ast_list);
1743         unlock_res_and_lock(lock);
1744
1745         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1746
1747         /* Let Enqueue to call osc_lock_upcall() and initialize
1748          * l_ast_data */
1749         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1750
1751         ldlm_run_ast_work(ns, &ast_list, LDLM_WORK_CP_AST);
1752
1753         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1754                           lock);
1755         LDLM_LOCK_RELEASE(lock);
1756         EXIT;
1757 }
1758
1759 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1760                                     struct ldlm_namespace *ns,
1761                                     struct ldlm_request *dlm_req,
1762                                     struct ldlm_lock *lock)
1763 {
1764         int rc = -ENOSYS;
1765         ENTRY;
1766
1767         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1768
1769         if (lock->l_glimpse_ast != NULL)
1770                 rc = lock->l_glimpse_ast(lock, req);
1771
1772         if (req->rq_repmsg != NULL) {
1773                 ptlrpc_reply(req);
1774         } else {
1775                 req->rq_status = rc;
1776                 ptlrpc_error(req);
1777         }
1778
1779         lock_res_and_lock(lock);
1780         if (lock->l_granted_mode == LCK_PW &&
1781             !lock->l_readers && !lock->l_writers &&
1782             cfs_time_after(cfs_time_current(),
1783                            cfs_time_add(lock->l_last_used,
1784                                         cfs_time_seconds(10)))) {
1785                 unlock_res_and_lock(lock);
1786                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1787                         ldlm_handle_bl_callback(ns, NULL, lock);
1788
1789                 EXIT;
1790                 return;
1791         }
1792         unlock_res_and_lock(lock);
1793         LDLM_LOCK_RELEASE(lock);
1794         EXIT;
1795 }
1796
1797 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1798 {
1799         if (req->rq_no_reply)
1800                 return 0;
1801
1802         req->rq_status = rc;
1803         if (!req->rq_packed_final) {
1804                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1805                 if (rc)
1806                         return rc;
1807         }
1808         return ptlrpc_reply(req);
1809 }
1810
1811 #ifdef __KERNEL__
1812 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi, int mode)
1813 {
1814         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1815         ENTRY;
1816
1817         cfs_spin_lock(&blp->blp_lock);
1818         if (blwi->blwi_lock && blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1819                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1820                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1821         } else {
1822                 /* other blocking callbacks are added to the regular list */
1823                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1824         }
1825         cfs_spin_unlock(&blp->blp_lock);
1826
1827         cfs_waitq_signal(&blp->blp_waitq);
1828
1829         /* can not use blwi->blwi_mode as blwi could be already freed in
1830            LDLM_ASYNC mode */
1831         if (mode == LDLM_SYNC)
1832                 cfs_wait_for_completion(&blwi->blwi_comp);
1833
1834         RETURN(0);
1835 }
1836
1837 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1838                              struct ldlm_namespace *ns,
1839                              struct ldlm_lock_desc *ld,
1840                              cfs_list_t *cancels, int count,
1841                              struct ldlm_lock *lock,
1842                              int mode)
1843 {
1844         cfs_init_completion(&blwi->blwi_comp);
1845         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1846
1847         if (cfs_memory_pressure_get())
1848                 blwi->blwi_mem_pressure = 1;
1849
1850         blwi->blwi_ns = ns;
1851         blwi->blwi_mode = mode;
1852         if (ld != NULL)
1853                 blwi->blwi_ld = *ld;
1854         if (count) {
1855                 cfs_list_add(&blwi->blwi_head, cancels);
1856                 cfs_list_del_init(cancels);
1857                 blwi->blwi_count = count;
1858         } else {
1859                 blwi->blwi_lock = lock;
1860         }
1861 }
1862
1863 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1864                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1865                              cfs_list_t *cancels, int count, int mode)
1866 {
1867         ENTRY;
1868
1869         if (cancels && count == 0)
1870                 RETURN(0);
1871
1872         if (mode == LDLM_SYNC) {
1873                 /* if it is synchronous call do minimum mem alloc, as it could
1874                  * be triggered from kernel shrinker
1875                  */
1876                 struct ldlm_bl_work_item blwi;
1877                 memset(&blwi, 0, sizeof(blwi));
1878                 init_blwi(&blwi, ns, ld, cancels, count, lock, LDLM_SYNC);
1879                 RETURN(__ldlm_bl_to_thread(&blwi, LDLM_SYNC));
1880         } else {
1881                 struct ldlm_bl_work_item *blwi;
1882                 OBD_ALLOC(blwi, sizeof(*blwi));
1883                 if (blwi == NULL)
1884                         RETURN(-ENOMEM);
1885                 init_blwi(blwi, ns, ld, cancels, count, lock, LDLM_ASYNC);
1886
1887                 RETURN(__ldlm_bl_to_thread(blwi, LDLM_ASYNC));
1888         }
1889 }
1890
1891 #endif
1892
1893 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1894                            struct ldlm_lock *lock)
1895 {
1896 #ifdef __KERNEL__
1897         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1898 #else
1899         RETURN(-ENOSYS);
1900 #endif
1901 }
1902
1903 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1904                            cfs_list_t *cancels, int count, int mode)
1905 {
1906 #ifdef __KERNEL__
1907         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
1908 #else
1909         RETURN(-ENOSYS);
1910 #endif
1911 }
1912
1913 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1914 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1915 {
1916         struct obd_device *obd = req->rq_export->exp_obd;
1917         char *key;
1918         void *val;
1919         int keylen, vallen;
1920         int rc = -ENOSYS;
1921         ENTRY;
1922
1923         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1924
1925         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1926
1927         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1928         if (key == NULL) {
1929                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1930                 RETURN(-EFAULT);
1931         }
1932         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1933                                       RCL_CLIENT);
1934         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1935         if (val == NULL) {
1936                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1937                 RETURN(-EFAULT);
1938         }
1939         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1940                                       RCL_CLIENT);
1941
1942         /* We are responsible for swabbing contents of val */
1943
1944         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1945                 /* Pass it on to mdc (the "export" in this case) */
1946                 rc = obd_set_info_async(req->rq_svc_thread->t_env,
1947                                         req->rq_export,
1948                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1949                                         KEY_HSM_COPYTOOL_SEND,
1950                                         vallen, val, NULL);
1951         else
1952                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1953
1954         return rc;
1955 }
1956
1957 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1958                                         const char *msg, int rc,
1959                                         struct lustre_handle *handle)
1960 {
1961         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
1962                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
1963                   msg, libcfs_id2str(req->rq_peer), rc,
1964                   handle ? handle->cookie : 0);
1965         if (req->rq_no_reply)
1966                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1967         else if (rc)
1968                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1969 }
1970
1971 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1972 static int ldlm_callback_handler(struct ptlrpc_request *req)
1973 {
1974         struct ldlm_namespace *ns;
1975         struct ldlm_request *dlm_req;
1976         struct ldlm_lock *lock;
1977         int rc;
1978         ENTRY;
1979
1980         /* Requests arrive in sender's byte order.  The ptlrpc service
1981          * handler has already checked and, if necessary, byte-swapped the
1982          * incoming request message body, but I am responsible for the
1983          * message buffers. */
1984
1985         /* do nothing for sec context finalize */
1986         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1987                 RETURN(0);
1988
1989         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1990
1991         if (req->rq_export == NULL) {
1992                 rc = ldlm_callback_reply(req, -ENOTCONN);
1993                 ldlm_callback_errmsg(req, "Operate on unconnected server",
1994                                      rc, NULL);
1995                 RETURN(0);
1996         }
1997
1998         LASSERT(req->rq_export != NULL);
1999         LASSERT(req->rq_export->exp_obd != NULL);
2000
2001         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2002         case LDLM_BL_CALLBACK:
2003                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK_NET))
2004                         RETURN(0);
2005                 break;
2006         case LDLM_CP_CALLBACK:
2007                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK_NET))
2008                         RETURN(0);
2009                 break;
2010         case LDLM_GL_CALLBACK:
2011                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK_NET))
2012                         RETURN(0);
2013                 break;
2014         case LDLM_SET_INFO:
2015                 rc = ldlm_handle_setinfo(req);
2016                 ldlm_callback_reply(req, rc);
2017                 RETURN(0);
2018         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
2019                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
2020                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2021                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2022                         RETURN(0);
2023                 rc = llog_origin_handle_cancel(req);
2024                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2025                         RETURN(0);
2026                 ldlm_callback_reply(req, rc);
2027                 RETURN(0);
2028         case LLOG_ORIGIN_HANDLE_CREATE:
2029                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2030                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2031                         RETURN(0);
2032                 rc = llog_origin_handle_open(req);
2033                 ldlm_callback_reply(req, rc);
2034                 RETURN(0);
2035         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2036                 req_capsule_set(&req->rq_pill,
2037                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2038                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2039                         RETURN(0);
2040                 rc = llog_origin_handle_next_block(req);
2041                 ldlm_callback_reply(req, rc);
2042                 RETURN(0);
2043         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2044                 req_capsule_set(&req->rq_pill,
2045                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2046                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2047                         RETURN(0);
2048                 rc = llog_origin_handle_read_header(req);
2049                 ldlm_callback_reply(req, rc);
2050                 RETURN(0);
2051         case LLOG_ORIGIN_HANDLE_CLOSE:
2052                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
2053                         RETURN(0);
2054                 rc = llog_origin_handle_close(req);
2055                 ldlm_callback_reply(req, rc);
2056                 RETURN(0);
2057         default:
2058                 CERROR("unknown opcode %u\n",
2059                        lustre_msg_get_opc(req->rq_reqmsg));
2060                 ldlm_callback_reply(req, -EPROTO);
2061                 RETURN(0);
2062         }
2063
2064         ns = req->rq_export->exp_obd->obd_namespace;
2065         LASSERT(ns != NULL);
2066
2067         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2068
2069         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2070         if (dlm_req == NULL) {
2071                 rc = ldlm_callback_reply(req, -EPROTO);
2072                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
2073                                      NULL);
2074                 RETURN(0);
2075         }
2076
2077         /* Force a known safe race, send a cancel to the server for a lock
2078          * which the server has already started a blocking callback on. */
2079         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
2080             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2081                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
2082                 if (rc < 0)
2083                         CERROR("ldlm_cli_cancel: %d\n", rc);
2084         }
2085
2086         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
2087         if (!lock) {
2088                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
2089                        "disappeared\n", dlm_req->lock_handle[0].cookie);
2090                 rc = ldlm_callback_reply(req, -EINVAL);
2091                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
2092                                      &dlm_req->lock_handle[0]);
2093                 RETURN(0);
2094         }
2095
2096         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
2097             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
2098                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
2099
2100         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
2101         lock_res_and_lock(lock);
2102         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
2103         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
2104                 /* If somebody cancels lock and cache is already dropped,
2105                  * or lock is failed before cp_ast received on client,
2106                  * we can tell the server we have no lock. Otherwise, we
2107                  * should send cancel after dropping the cache. */
2108                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
2109                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
2110                     (lock->l_flags & LDLM_FL_FAILED)) {
2111                         LDLM_DEBUG(lock, "callback on lock "
2112                                    LPX64" - lock disappeared\n",
2113                                    dlm_req->lock_handle[0].cookie);
2114                         unlock_res_and_lock(lock);
2115                         LDLM_LOCK_RELEASE(lock);
2116                         rc = ldlm_callback_reply(req, -EINVAL);
2117                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
2118                                              &dlm_req->lock_handle[0]);
2119                         RETURN(0);
2120                 }
2121                 /* BL_AST locks are not needed in lru.
2122                  * let ldlm_cancel_lru() be fast. */
2123                 ldlm_lock_remove_from_lru(lock);
2124                 lock->l_flags |= LDLM_FL_BL_AST;
2125         }
2126         unlock_res_and_lock(lock);
2127
2128         /* We want the ost thread to get this reply so that it can respond
2129          * to ost requests (write cache writeback) that might be triggered
2130          * in the callback.
2131          *
2132          * But we'd also like to be able to indicate in the reply that we're
2133          * cancelling right now, because it's unused, or have an intent result
2134          * in the reply, so we might have to push the responsibility for sending
2135          * the reply down into the AST handlers, alas. */
2136
2137         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2138         case LDLM_BL_CALLBACK:
2139                 CDEBUG(D_INODE, "blocking ast\n");
2140                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
2141                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
2142                         rc = ldlm_callback_reply(req, 0);
2143                         if (req->rq_no_reply || rc)
2144                                 ldlm_callback_errmsg(req, "Normal process", rc,
2145                                                      &dlm_req->lock_handle[0]);
2146                 }
2147                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
2148                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2149                 break;
2150         case LDLM_CP_CALLBACK:
2151                 CDEBUG(D_INODE, "completion ast\n");
2152                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2153                 ldlm_callback_reply(req, 0);
2154                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2155                 break;
2156         case LDLM_GL_CALLBACK:
2157                 CDEBUG(D_INODE, "glimpse ast\n");
2158                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2159                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2160                 break;
2161         default:
2162                 LBUG();                         /* checked above */
2163         }
2164
2165         RETURN(0);
2166 }
2167
2168 #ifdef HAVE_SERVER_SUPPORT
2169 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2170 {
2171         int rc;
2172         ENTRY;
2173
2174         /* Requests arrive in sender's byte order.  The ptlrpc service
2175          * handler has already checked and, if necessary, byte-swapped the
2176          * incoming request message body, but I am responsible for the
2177          * message buffers. */
2178
2179         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2180
2181         if (req->rq_export == NULL) {
2182                 struct ldlm_request *dlm_req;
2183
2184                 CERROR("%s from %s arrived at %lu with bad export cookie "
2185                        LPU64"\n",
2186                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2187                        libcfs_nid2str(req->rq_peer.nid),
2188                        req->rq_arrival_time.tv_sec,
2189                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2190
2191                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2192                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2193                         dlm_req = req_capsule_client_get(&req->rq_pill,
2194                                                          &RMF_DLM_REQ);
2195                         if (dlm_req != NULL)
2196                                 ldlm_lock_dump_handle(D_ERROR,
2197                                                       &dlm_req->lock_handle[0]);
2198                 }
2199                 ldlm_callback_reply(req, -ENOTCONN);
2200                 RETURN(0);
2201         }
2202
2203         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2204
2205         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2206         case LDLM_CANCEL:
2207                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2208                 CDEBUG(D_INODE, "cancel\n");
2209                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_NET))
2210                         RETURN(0);
2211                 rc = ldlm_handle_cancel(req);
2212                 if (rc)
2213                         break;
2214                 RETURN(0);
2215         case OBD_LOG_CANCEL:
2216                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2217                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2218                         RETURN(0);
2219                 rc = llog_origin_handle_cancel(req);
2220                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2221                         RETURN(0);
2222                 ldlm_callback_reply(req, rc);
2223                 RETURN(0);
2224         default:
2225                 CERROR("invalid opcode %d\n",
2226                        lustre_msg_get_opc(req->rq_reqmsg));
2227                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2228                 ldlm_callback_reply(req, -EINVAL);
2229         }
2230
2231         RETURN(0);
2232 }
2233
2234 static int ldlm_cancel_hpreq_lock_match(struct ptlrpc_request *req,
2235                                         struct ldlm_lock *lock)
2236 {
2237         struct ldlm_request *dlm_req;
2238         struct lustre_handle lockh;
2239         int rc = 0;
2240         int i;
2241         ENTRY;
2242
2243         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2244         if (dlm_req == NULL)
2245                 RETURN(0);
2246
2247         ldlm_lock2handle(lock, &lockh);
2248         for (i = 0; i < dlm_req->lock_count; i++) {
2249                 if (lustre_handle_equal(&dlm_req->lock_handle[i],
2250                                         &lockh)) {
2251                         DEBUG_REQ(D_RPCTRACE, req,
2252                                   "Prio raised by lock "LPX64".", lockh.cookie);
2253
2254                         rc = 1;
2255                         break;
2256                 }
2257         }
2258
2259         RETURN(rc);
2260
2261 }
2262
2263 static int ldlm_cancel_hpreq_check(struct ptlrpc_request *req)
2264 {
2265         struct ldlm_request *dlm_req;
2266         int rc = 0;
2267         int i;
2268         ENTRY;
2269
2270         /* no prolong in recovery */
2271         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
2272                 RETURN(0);
2273
2274         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2275         if (dlm_req == NULL)
2276                 RETURN(-EFAULT);
2277
2278         for (i = 0; i < dlm_req->lock_count; i++) {
2279                 struct ldlm_lock *lock;
2280
2281                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
2282                 if (lock == NULL)
2283                         continue;
2284
2285                 rc = !!(lock->l_flags & LDLM_FL_AST_SENT);
2286                 if (rc)
2287                         LDLM_DEBUG(lock, "hpreq cancel lock");
2288                 LDLM_LOCK_PUT(lock);
2289
2290                 if (rc)
2291                         break;
2292         }
2293
2294         RETURN(rc);
2295 }
2296
2297 static struct ptlrpc_hpreq_ops ldlm_cancel_hpreq_ops = {
2298         .hpreq_lock_match = ldlm_cancel_hpreq_lock_match,
2299         .hpreq_check      = ldlm_cancel_hpreq_check,
2300         .hpreq_fini       = NULL,
2301 };
2302
2303 static int ldlm_hpreq_handler(struct ptlrpc_request *req)
2304 {
2305         ENTRY;
2306
2307         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2308
2309         if (req->rq_export == NULL)
2310                 RETURN(0);
2311
2312         if (LDLM_CANCEL == lustre_msg_get_opc(req->rq_reqmsg)) {
2313                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2314                 req->rq_ops = &ldlm_cancel_hpreq_ops;
2315         }
2316         RETURN(0);
2317 }
2318
2319 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2320                         cfs_hlist_node_t *hnode, void *data)
2321
2322 {
2323         cfs_list_t         *rpc_list = data;
2324         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2325
2326         lock_res_and_lock(lock);
2327
2328         if (lock->l_req_mode != lock->l_granted_mode) {
2329                 unlock_res_and_lock(lock);
2330                 return 0;
2331         }
2332
2333         LASSERT(lock->l_resource);
2334         if (lock->l_resource->lr_type != LDLM_IBITS &&
2335             lock->l_resource->lr_type != LDLM_PLAIN) {
2336                 unlock_res_and_lock(lock);
2337                 return 0;
2338         }
2339
2340         if (lock->l_flags & LDLM_FL_AST_SENT) {
2341                 unlock_res_and_lock(lock);
2342                 return 0;
2343         }
2344
2345         LASSERT(lock->l_blocking_ast);
2346         LASSERT(!lock->l_blocking_lock);
2347
2348         lock->l_flags |= LDLM_FL_AST_SENT;
2349         if (lock->l_export && lock->l_export->exp_lock_hash) {
2350                 /* NB: it's safe to call cfs_hash_del() even lock isn't
2351                  * in exp_lock_hash. */
2352                 /* In the function below, .hs_keycmp resolves to
2353                  * ldlm_export_lock_keycmp() */
2354                 /* coverity[overrun-buffer-val] */
2355                 cfs_hash_del(lock->l_export->exp_lock_hash,
2356                              &lock->l_remote_handle, &lock->l_exp_hash);
2357         }
2358
2359         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2360         LDLM_LOCK_GET(lock);
2361
2362         unlock_res_and_lock(lock);
2363         return 0;
2364 }
2365
2366 void ldlm_revoke_export_locks(struct obd_export *exp)
2367 {
2368         cfs_list_t  rpc_list;
2369         ENTRY;
2370
2371         CFS_INIT_LIST_HEAD(&rpc_list);
2372         cfs_hash_for_each_empty(exp->exp_lock_hash,
2373                                 ldlm_revoke_lock_cb, &rpc_list);
2374         ldlm_run_ast_work(exp->exp_obd->obd_namespace, &rpc_list,
2375                           LDLM_WORK_REVOKE_AST);
2376
2377         EXIT;
2378 }
2379 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2380 #endif /* HAVE_SERVER_SUPPORT */
2381
2382 #ifdef __KERNEL__
2383 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2384 {
2385         struct ldlm_bl_work_item *blwi = NULL;
2386         static unsigned int num_bl = 0;
2387
2388         cfs_spin_lock(&blp->blp_lock);
2389         /* process a request from the blp_list at least every blp_num_threads */
2390         if (!cfs_list_empty(&blp->blp_list) &&
2391             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2392                 blwi = cfs_list_entry(blp->blp_list.next,
2393                                       struct ldlm_bl_work_item, blwi_entry);
2394         else
2395                 if (!cfs_list_empty(&blp->blp_prio_list))
2396                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2397                                               struct ldlm_bl_work_item,
2398                                               blwi_entry);
2399
2400         if (blwi) {
2401                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2402                         num_bl = 0;
2403                 cfs_list_del(&blwi->blwi_entry);
2404         }
2405         cfs_spin_unlock(&blp->blp_lock);
2406
2407         return blwi;
2408 }
2409
2410 /* This only contains temporary data until the thread starts */
2411 struct ldlm_bl_thread_data {
2412         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2413         struct ldlm_bl_pool     *bltd_blp;
2414         cfs_completion_t        bltd_comp;
2415         int                     bltd_num;
2416 };
2417
2418 static int ldlm_bl_thread_main(void *arg);
2419
2420 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2421 {
2422         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2423         int rc;
2424
2425         cfs_init_completion(&bltd.bltd_comp);
2426         rc = cfs_create_thread(ldlm_bl_thread_main, &bltd, 0);
2427         if (rc < 0) {
2428                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2429                        cfs_atomic_read(&blp->blp_num_threads), rc);
2430                 return rc;
2431         }
2432         cfs_wait_for_completion(&bltd.bltd_comp);
2433
2434         return 0;
2435 }
2436
2437 static int ldlm_bl_thread_main(void *arg)
2438 {
2439         struct ldlm_bl_pool *blp;
2440         ENTRY;
2441
2442         {
2443                 struct ldlm_bl_thread_data *bltd = arg;
2444
2445                 blp = bltd->bltd_blp;
2446
2447                 bltd->bltd_num =
2448                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2449                 cfs_atomic_inc(&blp->blp_busy_threads);
2450
2451                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2452                         "ldlm_bl_%02d", bltd->bltd_num);
2453                 cfs_daemonize(bltd->bltd_name);
2454
2455                 cfs_complete(&bltd->bltd_comp);
2456                 /* cannot use bltd after this, it is only on caller's stack */
2457         }
2458
2459         while (1) {
2460                 struct l_wait_info lwi = { 0 };
2461                 struct ldlm_bl_work_item *blwi = NULL;
2462                 int busy;
2463
2464                 blwi = ldlm_bl_get_work(blp);
2465
2466                 if (blwi == NULL) {
2467                         cfs_atomic_dec(&blp->blp_busy_threads);
2468                         l_wait_event_exclusive(blp->blp_waitq,
2469                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2470                                          &lwi);
2471                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2472                 } else {
2473                         busy = cfs_atomic_read(&blp->blp_busy_threads);
2474                 }
2475
2476                 if (blwi->blwi_ns == NULL)
2477                         /* added by ldlm_cleanup() */
2478                         break;
2479
2480                 /* Not fatal if racy and have a few too many threads */
2481                 if (unlikely(busy < blp->blp_max_threads &&
2482                              busy >= cfs_atomic_read(&blp->blp_num_threads) &&
2483                              !blwi->blwi_mem_pressure))
2484                         /* discard the return value, we tried */
2485                         ldlm_bl_thread_start(blp);
2486
2487                 if (blwi->blwi_mem_pressure)
2488                         cfs_memory_pressure_set();
2489
2490                 if (blwi->blwi_count) {
2491                         int count;
2492                         /* The special case when we cancel locks in lru
2493                          * asynchronously, we pass the list of locks here.
2494                          * Thus locks are marked LDLM_FL_CANCELING, but NOT
2495                          * canceled locally yet. */
2496                         count = ldlm_cli_cancel_list_local(&blwi->blwi_head,
2497                                                            blwi->blwi_count,
2498                                                            LCF_BL_AST);
2499                         ldlm_cli_cancel_list(&blwi->blwi_head, count, NULL, 0);
2500                 } else {
2501                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2502                                                 blwi->blwi_lock);
2503                 }
2504                 if (blwi->blwi_mem_pressure)
2505                         cfs_memory_pressure_clr();
2506
2507                 if (blwi->blwi_mode == LDLM_ASYNC)
2508                         OBD_FREE(blwi, sizeof(*blwi));
2509                 else
2510                         cfs_complete(&blwi->blwi_comp);
2511         }
2512
2513         cfs_atomic_dec(&blp->blp_busy_threads);
2514         cfs_atomic_dec(&blp->blp_num_threads);
2515         cfs_complete(&blp->blp_comp);
2516         RETURN(0);
2517 }
2518
2519 #endif
2520
2521 static int ldlm_setup(void);
2522 static int ldlm_cleanup(void);
2523
2524 int ldlm_get_ref(void)
2525 {
2526         int rc = 0;
2527         ENTRY;
2528         cfs_mutex_lock(&ldlm_ref_mutex);
2529         if (++ldlm_refcount == 1) {
2530                 rc = ldlm_setup();
2531                 if (rc)
2532                         ldlm_refcount--;
2533         }
2534         cfs_mutex_unlock(&ldlm_ref_mutex);
2535
2536         RETURN(rc);
2537 }
2538 EXPORT_SYMBOL(ldlm_get_ref);
2539
2540 void ldlm_put_ref(void)
2541 {
2542         ENTRY;
2543         cfs_mutex_lock(&ldlm_ref_mutex);
2544         if (ldlm_refcount == 1) {
2545                 int rc = ldlm_cleanup();
2546                 if (rc)
2547                         CERROR("ldlm_cleanup failed: %d\n", rc);
2548                 else
2549                         ldlm_refcount--;
2550         } else {
2551                 ldlm_refcount--;
2552         }
2553         cfs_mutex_unlock(&ldlm_ref_mutex);
2554
2555         EXIT;
2556 }
2557 EXPORT_SYMBOL(ldlm_put_ref);
2558
2559 /*
2560  * Export handle<->lock hash operations.
2561  */
2562 static unsigned
2563 ldlm_export_lock_hash(cfs_hash_t *hs, const void *key, unsigned mask)
2564 {
2565         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2566 }
2567
2568 static void *
2569 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2570 {
2571         struct ldlm_lock *lock;
2572
2573         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2574         return &lock->l_remote_handle;
2575 }
2576
2577 static void
2578 ldlm_export_lock_keycpy(cfs_hlist_node_t *hnode, void *key)
2579 {
2580         struct ldlm_lock     *lock;
2581
2582         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2583         lock->l_remote_handle = *(struct lustre_handle *)key;
2584 }
2585
2586 static int
2587 ldlm_export_lock_keycmp(const void *key, cfs_hlist_node_t *hnode)
2588 {
2589         return lustre_handle_equal(ldlm_export_lock_key(hnode), key);
2590 }
2591
2592 static void *
2593 ldlm_export_lock_object(cfs_hlist_node_t *hnode)
2594 {
2595         return cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2596 }
2597
2598 static void
2599 ldlm_export_lock_get(cfs_hash_t *hs, cfs_hlist_node_t *hnode)
2600 {
2601         struct ldlm_lock *lock;
2602
2603         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2604         LDLM_LOCK_GET(lock);
2605 }
2606
2607 static void
2608 ldlm_export_lock_put(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_RELEASE(lock);
2614 }
2615
2616 static cfs_hash_ops_t ldlm_export_lock_ops = {
2617         .hs_hash        = ldlm_export_lock_hash,
2618         .hs_key         = ldlm_export_lock_key,
2619         .hs_keycmp      = ldlm_export_lock_keycmp,
2620         .hs_keycpy      = ldlm_export_lock_keycpy,
2621         .hs_object      = ldlm_export_lock_object,
2622         .hs_get         = ldlm_export_lock_get,
2623         .hs_put         = ldlm_export_lock_put,
2624         .hs_put_locked  = ldlm_export_lock_put,
2625 };
2626
2627 int ldlm_init_export(struct obd_export *exp)
2628 {
2629         ENTRY;
2630
2631         exp->exp_lock_hash =
2632                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2633                                 HASH_EXP_LOCK_CUR_BITS,
2634                                 HASH_EXP_LOCK_MAX_BITS,
2635                                 HASH_EXP_LOCK_BKT_BITS, 0,
2636                                 CFS_HASH_MIN_THETA, CFS_HASH_MAX_THETA,
2637                                 &ldlm_export_lock_ops,
2638                                 CFS_HASH_DEFAULT | CFS_HASH_REHASH_KEY |
2639                                 CFS_HASH_NBLK_CHANGE);
2640
2641         if (!exp->exp_lock_hash)
2642                 RETURN(-ENOMEM);
2643
2644         RETURN(0);
2645 }
2646 EXPORT_SYMBOL(ldlm_init_export);
2647
2648 void ldlm_destroy_export(struct obd_export *exp)
2649 {
2650         ENTRY;
2651         cfs_hash_putref(exp->exp_lock_hash);
2652         exp->exp_lock_hash = NULL;
2653
2654         ldlm_destroy_flock_export(exp);
2655         EXIT;
2656 }
2657 EXPORT_SYMBOL(ldlm_destroy_export);
2658
2659 static int ldlm_setup(void)
2660 {
2661         static struct ptlrpc_service_conf       conf;
2662         struct ldlm_bl_pool                     *blp = NULL;
2663         int rc = 0;
2664 #ifdef __KERNEL__
2665         int i;
2666 #endif
2667         ENTRY;
2668
2669         if (ldlm_state != NULL)
2670                 RETURN(-EALREADY);
2671
2672         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2673         if (ldlm_state == NULL)
2674                 RETURN(-ENOMEM);
2675
2676 #ifdef LPROCFS
2677         rc = ldlm_proc_setup();
2678         if (rc != 0)
2679                 GOTO(out, rc);
2680 #endif
2681
2682         memset(&conf, 0, sizeof(conf));
2683         conf = (typeof(conf)) {
2684                 .psc_name               = "ldlm_cbd",
2685                 .psc_watchdog_factor    = 2,
2686                 .psc_buf                = {
2687                         .bc_nbufs               = LDLM_NBUFS,
2688                         .bc_buf_size            = LDLM_BUFSIZE,
2689                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2690                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2691                         .bc_req_portal          = LDLM_CB_REQUEST_PORTAL,
2692                         .bc_rep_portal          = LDLM_CB_REPLY_PORTAL,
2693                 },
2694                 .psc_thr                = {
2695                         .tc_thr_name            = "ldlm_cb",
2696                         .tc_thr_factor          = LDLM_THR_FACTOR,
2697                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2698                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2699                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2700                         .tc_nthrs_user          = ldlm_num_threads,
2701                         .tc_cpu_affinity        = 1,
2702                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD,
2703                 },
2704                 .psc_cpt                = {
2705                         .cc_pattern             = ldlm_cpts,
2706                 },
2707                 .psc_ops                = {
2708                         .so_req_handler         = ldlm_callback_handler,
2709                 },
2710         };
2711         ldlm_state->ldlm_cb_service = \
2712                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2713         if (IS_ERR(ldlm_state->ldlm_cb_service)) {
2714                 CERROR("failed to start service\n");
2715                 rc = PTR_ERR(ldlm_state->ldlm_cb_service);
2716                 ldlm_state->ldlm_cb_service = NULL;
2717                 GOTO(out, rc);
2718         }
2719
2720 #ifdef HAVE_SERVER_SUPPORT
2721         memset(&conf, 0, sizeof(conf));
2722         conf = (typeof(conf)) {
2723                 .psc_name               = "ldlm_canceld",
2724                 .psc_watchdog_factor    = 6,
2725                 .psc_buf                = {
2726                         .bc_nbufs               = LDLM_NBUFS,
2727                         .bc_buf_size            = LDLM_BUFSIZE,
2728                         .bc_req_max_size        = LDLM_MAXREQSIZE,
2729                         .bc_rep_max_size        = LDLM_MAXREPSIZE,
2730                         .bc_req_portal          = LDLM_CANCEL_REQUEST_PORTAL,
2731                         .bc_rep_portal          = LDLM_CANCEL_REPLY_PORTAL,
2732
2733                 },
2734                 .psc_thr                = {
2735                         .tc_thr_name            = "ldlm_cn",
2736                         .tc_thr_factor          = LDLM_THR_FACTOR,
2737                         .tc_nthrs_init          = LDLM_NTHRS_INIT,
2738                         .tc_nthrs_base          = LDLM_NTHRS_BASE,
2739                         .tc_nthrs_max           = LDLM_NTHRS_MAX,
2740                         .tc_nthrs_user          = ldlm_num_threads,
2741                         .tc_cpu_affinity        = 1,
2742                         .tc_ctx_tags            = LCT_MD_THREAD | \
2743                                                   LCT_DT_THREAD | \
2744                                                   LCT_CL_THREAD,
2745                 },
2746                 .psc_cpt                = {
2747                         .cc_pattern             = ldlm_cpts,
2748                 },
2749                 .psc_ops                = {
2750                         .so_req_handler         = ldlm_cancel_handler,
2751                         .so_hpreq_handler       = ldlm_hpreq_handler,
2752                 },
2753         };
2754         ldlm_state->ldlm_cancel_service = \
2755                         ptlrpc_register_service(&conf, ldlm_svc_proc_dir);
2756         if (IS_ERR(ldlm_state->ldlm_cancel_service)) {
2757                 CERROR("failed to start service\n");
2758                 rc = PTR_ERR(ldlm_state->ldlm_cancel_service);
2759                 ldlm_state->ldlm_cancel_service = NULL;
2760                 GOTO(out, rc);
2761         }
2762 #endif
2763
2764         OBD_ALLOC(blp, sizeof(*blp));
2765         if (blp == NULL)
2766                 GOTO(out, rc = -ENOMEM);
2767         ldlm_state->ldlm_bl_pool = blp;
2768
2769         cfs_spin_lock_init(&blp->blp_lock);
2770         CFS_INIT_LIST_HEAD(&blp->blp_list);
2771         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2772         cfs_waitq_init(&blp->blp_waitq);
2773         cfs_atomic_set(&blp->blp_num_threads, 0);
2774         cfs_atomic_set(&blp->blp_busy_threads, 0);
2775
2776 #ifdef __KERNEL__
2777         if (ldlm_num_threads == 0) {
2778                 blp->blp_min_threads = LDLM_NTHRS_INIT;
2779                 blp->blp_max_threads = LDLM_NTHRS_MAX;
2780         } else {
2781                 blp->blp_min_threads = blp->blp_max_threads = \
2782                         min_t(int, LDLM_NTHRS_MAX, max_t(int, LDLM_NTHRS_INIT,
2783                                                          ldlm_num_threads));
2784         }
2785
2786         for (i = 0; i < blp->blp_min_threads; i++) {
2787                 rc = ldlm_bl_thread_start(blp);
2788                 if (rc < 0)
2789                         GOTO(out, rc);
2790         }
2791
2792 # ifdef HAVE_SERVER_SUPPORT
2793         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2794         expired_lock_thread.elt_state = ELT_STOPPED;
2795         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2796
2797         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2798         cfs_spin_lock_init(&waiting_locks_spinlock);
2799         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2800
2801         rc = cfs_create_thread(expired_lock_main, NULL, CFS_DAEMON_FLAGS);
2802         if (rc < 0) {
2803                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2804                 GOTO(out, rc);
2805         }
2806
2807         cfs_wait_event(expired_lock_thread.elt_waitq,
2808                        expired_lock_thread.elt_state == ELT_READY);
2809 # endif /* HAVE_SERVER_SUPPORT */
2810
2811         rc = ldlm_pools_init();
2812         if (rc) {
2813                 CERROR("Failed to initialize LDLM pools: %d\n", rc);
2814                 GOTO(out, rc);
2815         }
2816 #endif
2817         RETURN(0);
2818
2819  out:
2820         ldlm_cleanup();
2821         RETURN(rc);
2822 }
2823
2824 static int ldlm_cleanup(void)
2825 {
2826         ENTRY;
2827
2828         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2829             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2830                 CERROR("ldlm still has namespaces; clean these up first.\n");
2831                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2832                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2833                 RETURN(-EBUSY);
2834         }
2835
2836 #ifdef __KERNEL__
2837         ldlm_pools_fini();
2838
2839         if (ldlm_state->ldlm_bl_pool != NULL) {
2840                 struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2841
2842                 while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2843                         struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2844
2845                         cfs_init_completion(&blp->blp_comp);
2846
2847                         cfs_spin_lock(&blp->blp_lock);
2848                         cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2849                         cfs_waitq_signal(&blp->blp_waitq);
2850                         cfs_spin_unlock(&blp->blp_lock);
2851
2852                         cfs_wait_for_completion(&blp->blp_comp);
2853                 }
2854
2855                 OBD_FREE(blp, sizeof(*blp));
2856         }
2857 #endif /* __KERNEL__ */
2858
2859         if (ldlm_state->ldlm_cb_service != NULL)
2860                 ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2861 # ifdef HAVE_SERVER_SUPPORT
2862         if (ldlm_state->ldlm_cancel_service != NULL)
2863                 ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2864 # endif
2865
2866 #ifdef __KERNEL__
2867         ldlm_proc_cleanup();
2868
2869 # ifdef HAVE_SERVER_SUPPORT
2870         if (expired_lock_thread.elt_state != ELT_STOPPED) {
2871                 expired_lock_thread.elt_state = ELT_TERMINATE;
2872                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2873                 cfs_wait_event(expired_lock_thread.elt_waitq,
2874                                expired_lock_thread.elt_state == ELT_STOPPED);
2875         }
2876 # endif
2877 #endif /* __KERNEL__ */
2878
2879         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2880         ldlm_state = NULL;
2881
2882         RETURN(0);
2883 }
2884
2885 int ldlm_init(void)
2886 {
2887         cfs_mutex_init(&ldlm_ref_mutex);
2888         cfs_mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2889         cfs_mutex_init(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2890         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2891                                                sizeof(struct ldlm_resource), 0,
2892                                                CFS_SLAB_HWCACHE_ALIGN);
2893         if (ldlm_resource_slab == NULL)
2894                 return -ENOMEM;
2895
2896         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2897                               sizeof(struct ldlm_lock), 0,
2898                               CFS_SLAB_HWCACHE_ALIGN | SLAB_DESTROY_BY_RCU);
2899         if (ldlm_lock_slab == NULL) {
2900                 cfs_mem_cache_destroy(ldlm_resource_slab);
2901                 return -ENOMEM;
2902         }
2903
2904         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2905                                         sizeof(struct ldlm_interval),
2906                                         0, CFS_SLAB_HWCACHE_ALIGN);
2907         if (ldlm_interval_slab == NULL) {
2908                 cfs_mem_cache_destroy(ldlm_resource_slab);
2909                 cfs_mem_cache_destroy(ldlm_lock_slab);
2910                 return -ENOMEM;
2911         }
2912 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2913         class_export_dump_hook = ldlm_dump_export_locks;
2914 #endif
2915         return 0;
2916 }
2917
2918 void ldlm_exit(void)
2919 {
2920         int rc;
2921         if (ldlm_refcount)
2922                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2923         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2924         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2925 #ifdef __KERNEL__
2926         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2927          * synchronize_rcu() to wait a grace period elapsed, so that
2928          * ldlm_lock_free() get a chance to be called. */
2929         synchronize_rcu();
2930 #endif
2931         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2932         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2933         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2934         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2935 }