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