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