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