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