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