Whamcloud - gitweb
94aacc8d25dfee4dbfaedcfa8a4601fa2b86b5dc
[fs/lustre-release.git] / lustre / ldlm / ldlm_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2010, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32 /**
33  * This file contains Asynchronous System Trap (AST) handlers and related
34  * LDLM request-processing routines.
35  *
36  * An AST is a callback issued on a lock when its state is changed. There are
37  * several different types of ASTs (callbacks) registered for each lock:
38  *
39  * - completion AST: when a lock is enqueued by some process, but cannot be
40  *   granted immediately due to other conflicting locks on the same resource,
41  *   the completion AST is sent to notify the caller when the lock is
42  *   eventually granted
43  *
44  * - blocking AST: when a lock is granted to some process, if another process
45  *   enqueues a conflicting (blocking) lock on a resource, a blocking AST is
46  *   sent to notify the holder(s) of the lock(s) of the conflicting lock
47  *   request. The lock holder(s) must release their lock(s) on that resource in
48  *   a timely manner or be evicted by the server.
49  *
50  * - glimpse AST: this is used when a process wants information about a lock
51  *   (i.e. the lock value block (LVB)) but does not necessarily require holding
52  *   the lock. If the resource is locked, the lock holder(s) are sent glimpse
53  *   ASTs and the LVB is returned to the caller, and lock holder(s) may CANCEL
54  *   their lock(s) if they are idle. If the resource is not locked, the server
55  *   may grant the lock.
56  */
57
58 #define DEBUG_SUBSYSTEM S_LDLM
59
60 #include <lustre/lustre_errno.h>
61
62 #include <lustre_dlm.h>
63 #include <obd_class.h>
64 #include <obd.h>
65
66 #include "ldlm_internal.h"
67
68 unsigned int ldlm_enqueue_min = OBD_TIMEOUT_DEFAULT;
69 module_param(ldlm_enqueue_min, uint, 0644);
70 MODULE_PARM_DESC(ldlm_enqueue_min, "lock enqueue timeout minimum");
71
72 /* in client side, whether the cached locks will be canceled before replay */
73 unsigned int ldlm_cancel_unused_locks_before_replay = 1;
74
75 static void interrupted_completion_wait(void *data)
76 {
77 }
78
79 struct lock_wait_data {
80         struct ldlm_lock *lwd_lock;
81         __u32             lwd_conn_cnt;
82 };
83
84 struct ldlm_async_args {
85         struct lustre_handle lock_handle;
86 };
87
88 /**
89  * ldlm_request_bufsize
90  *
91  * If opcode=LDLM_ENQUEUE, 1 slot is already occupied,
92  * LDLM_LOCKREQ_HANDLE -1 slots are available.
93  * Otherwise, LDLM_LOCKREQ_HANDLE slots are available.
94  *
95  * \param[in] count
96  * \param[in] type
97  *
98  * \retval size of the request buffer
99  */
100
101 int ldlm_request_bufsize(int count, int type)
102 {
103         int avail = LDLM_LOCKREQ_HANDLES;
104         if (type == LDLM_ENQUEUE)
105                 avail -= LDLM_ENQUEUE_CANCEL_OFF;
106
107         if (count > avail)
108                 avail = (count - avail) * sizeof(struct lustre_handle);
109         else
110                 avail = 0;
111
112         return sizeof(struct ldlm_request) + avail;
113 }
114
115 int ldlm_expired_completion_wait(void *data)
116 {
117         struct lock_wait_data *lwd = data;
118         struct ldlm_lock *lock = lwd->lwd_lock;
119         struct obd_import *imp;
120         struct obd_device *obd;
121
122         ENTRY;
123         if (lock->l_conn_export == NULL) {
124                 static cfs_time_t next_dump = 0, last_dump = 0;
125
126                 LDLM_ERROR(lock, "lock timed out (enqueued at %lld, %llds ago); "
127                            "not entering recovery in server code, just going back to sleep",
128                            (s64)lock->l_last_activity,
129                            (s64)(ktime_get_real_seconds() -
130                                  lock->l_last_activity));
131                 if (cfs_time_after(cfs_time_current(), next_dump)) {
132                         last_dump = next_dump;
133                         next_dump = cfs_time_shift(300);
134                         ldlm_namespace_dump(D_DLMTRACE,
135                                             ldlm_lock_to_ns(lock));
136                         if (last_dump == 0)
137                                 libcfs_debug_dumplog();
138                 }
139                 RETURN(0);
140         }
141
142         obd = lock->l_conn_export->exp_obd;
143         imp = obd->u.cli.cl_import;
144         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
145         LDLM_ERROR(lock, "lock timed out (enqueued at %lld, %llds ago), entering recovery for %s@%s",
146                   (s64)lock->l_last_activity,
147                   (s64)(ktime_get_real_seconds() - lock->l_last_activity),
148                   obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
149
150         RETURN(0);
151 }
152
153 /**
154  * Calculate the Completion timeout (covering enqueue, BL AST, data flush,
155  * lock cancel, and their replies). Used for lock completion timeout on the
156  * client side.
157  *
158  * \param[in] lock        lock which is waiting the completion callback
159  *
160  * \retval            timeout in seconds to wait for the server reply
161  */
162
163 /* We use the same basis for both server side and client side functions
164    from a single node. */
165 static unsigned int ldlm_cp_timeout(struct ldlm_lock *lock)
166 {
167         unsigned int timeout;
168
169         if (AT_OFF)
170                 return obd_timeout;
171
172         /* Wait a long time for enqueue - server may have to callback a
173          * lock from another client.  Server will evict the other client if it
174          * doesn't respond reasonably, and then give us the lock. */
175         timeout = at_get(ldlm_lock_to_ns_at(lock));
176         return max(3 * timeout, ldlm_enqueue_min);
177 }
178
179 /**
180  * Helper function for ldlm_completion_ast(), updating timings when lock is
181  * actually granted.
182  */
183 static int ldlm_completion_tail(struct ldlm_lock *lock, void *data)
184 {
185         time64_t delay;
186         int result = 0;
187
188         if (ldlm_is_destroyed(lock) || ldlm_is_failed(lock)) {
189                 LDLM_DEBUG(lock, "client-side enqueue: destroyed");
190                 result = -EIO;
191         } else if (data == NULL) {
192                 LDLM_DEBUG(lock, "client-side enqueue: granted");
193         } else {
194                 /* Take into AT only CP RPC, not immediately granted locks */
195                 delay = ktime_get_real_seconds() - lock->l_last_activity;
196                 LDLM_DEBUG(lock, "client-side enqueue: granted after %llds",
197                            (s64)delay);
198
199                 /* Update our time estimate */
200                 at_measured(ldlm_lock_to_ns_at(lock), delay);
201         }
202         return result;
203 }
204
205 /**
206  * Implementation of ->l_completion_ast() for a client, that doesn't wait
207  * until lock is granted. Suitable for locks enqueued through ptlrpcd, of
208  * other threads that cannot block for long.
209  */
210 int ldlm_completion_ast_async(struct ldlm_lock *lock, __u64 flags, void *data)
211 {
212         ENTRY;
213
214         if (flags == LDLM_FL_WAIT_NOREPROC) {
215                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
216                 RETURN(0);
217         }
218
219         if (!(flags & LDLM_FL_BLOCKED_MASK)) {
220                 wake_up(&lock->l_waitq);
221                 RETURN(ldlm_completion_tail(lock, data));
222         }
223
224         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
225                    "going forward");
226         ldlm_reprocess_all(lock->l_resource);
227         RETURN(0);
228 }
229 EXPORT_SYMBOL(ldlm_completion_ast_async);
230
231 /**
232  * Generic LDLM "completion" AST. This is called in several cases:
233  *
234  *     - when a reply to an ENQUEUE RPC is received from the server
235  *       (ldlm_cli_enqueue_fini()). Lock might be granted or not granted at
236  *       this point (determined by flags);
237  *
238  *     - when LDLM_CP_CALLBACK RPC comes to client to notify it that lock has
239  *       been granted;
240  *
241  *     - when ldlm_lock_match(LDLM_FL_LVB_READY) is about to wait until lock
242  *       gets correct lvb;
243  *
244  *     - to force all locks when resource is destroyed (cleanup_resource());
245  *
246  *     - during lock conversion (not used currently).
247  *
248  * If lock is not granted in the first case, this function waits until second
249  * or penultimate cases happen in some other thread.
250  *
251  */
252 int ldlm_completion_ast(struct ldlm_lock *lock, __u64 flags, void *data)
253 {
254         /* XXX ALLOCATE - 160 bytes */
255         struct lock_wait_data lwd;
256         struct obd_device *obd;
257         struct obd_import *imp = NULL;
258         struct l_wait_info lwi;
259         __u32 timeout;
260         int rc = 0;
261         ENTRY;
262
263         if (flags == LDLM_FL_WAIT_NOREPROC) {
264                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
265                 goto noreproc;
266         }
267
268         if (!(flags & LDLM_FL_BLOCKED_MASK)) {
269                 wake_up(&lock->l_waitq);
270                 RETURN(0);
271         }
272
273         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, "
274                    "sleeping");
275
276 noreproc:
277
278         obd = class_exp2obd(lock->l_conn_export);
279
280         /* if this is a local lock, then there is no import */
281         if (obd != NULL) {
282                 imp = obd->u.cli.cl_import;
283         }
284
285         timeout = ldlm_cp_timeout(lock);
286
287         lwd.lwd_lock = lock;
288         lock->l_last_activity = cfs_time_current_sec();
289
290         if (ldlm_is_no_timeout(lock)) {
291                 LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
292                 lwi = LWI_INTR(interrupted_completion_wait, &lwd);
293         } else {
294                 lwi = LWI_TIMEOUT_INTR(cfs_time_seconds(timeout),
295                                        ldlm_expired_completion_wait,
296                                        interrupted_completion_wait, &lwd);
297         }
298
299         if (imp != NULL) {
300                 spin_lock(&imp->imp_lock);
301                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
302                 spin_unlock(&imp->imp_lock);
303         }
304
305         if (ns_is_client(ldlm_lock_to_ns(lock)) &&
306             OBD_FAIL_CHECK_RESET(OBD_FAIL_LDLM_INTR_CP_AST,
307                                  OBD_FAIL_LDLM_CP_BL_RACE | OBD_FAIL_ONCE)) {
308                 ldlm_set_fail_loc(lock);
309                 rc = -EINTR;
310         } else {
311                 /* Go to sleep until the lock is granted or cancelled. */
312                 rc = l_wait_event(lock->l_waitq,
313                                   is_granted_or_cancelled(lock), &lwi);
314         }
315
316         if (rc) {
317                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
318                            rc);
319                 RETURN(rc);
320         }
321
322         RETURN(ldlm_completion_tail(lock, data));
323 }
324 EXPORT_SYMBOL(ldlm_completion_ast);
325
326 /**
327  * A helper to build a blocking AST function
328  *
329  * Perform a common operation for blocking ASTs:
330  * defferred lock cancellation.
331  *
332  * \param lock the lock blocking or canceling AST was called on
333  * \retval 0
334  * \see mdt_blocking_ast
335  * \see ldlm_blocking_ast
336  */
337 int ldlm_blocking_ast_nocheck(struct ldlm_lock *lock)
338 {
339         int do_ast;
340         ENTRY;
341
342         ldlm_set_cbpending(lock);
343         do_ast = (!lock->l_readers && !lock->l_writers);
344         unlock_res_and_lock(lock);
345
346         if (do_ast) {
347                 struct lustre_handle lockh;
348                 int rc;
349
350                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
351                 ldlm_lock2handle(lock, &lockh);
352                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
353                 if (rc < 0)
354                         CERROR("ldlm_cli_cancel: %d\n", rc);
355         } else {
356                 LDLM_DEBUG(lock, "Lock still has references, will be "
357                            "cancelled later");
358         }
359         RETURN(0);
360 }
361 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
362
363 /**
364  * Server blocking AST
365  *
366  * ->l_blocking_ast() callback for LDLM locks acquired by server-side
367  * OBDs.
368  *
369  * \param lock the lock which blocks a request or cancelling lock
370  * \param desc unused
371  * \param data unused
372  * \param flag indicates whether this cancelling or blocking callback
373  * \retval 0
374  * \see ldlm_blocking_ast_nocheck
375  */
376 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
377                       void *data, int flag)
378 {
379         ENTRY;
380
381         if (flag == LDLM_CB_CANCELING) {
382                 /* Don't need to do anything here. */
383                 RETURN(0);
384         }
385
386         lock_res_and_lock(lock);
387         /* Get this: if ldlm_blocking_ast is racing with intent_policy, such
388          * that ldlm_blocking_ast is called just before intent_policy method
389          * takes the lr_lock, then by the time we get the lock, we might not
390          * be the correct blocking function anymore.  So check, and return
391          * early, if so. */
392         if (lock->l_blocking_ast != ldlm_blocking_ast) {
393                 unlock_res_and_lock(lock);
394                 RETURN(0);
395         }
396         RETURN(ldlm_blocking_ast_nocheck(lock));
397 }
398 EXPORT_SYMBOL(ldlm_blocking_ast);
399
400 /**
401  * Implements ldlm_lock::l_glimpse_ast for extent locks acquired on the server.
402  *
403  * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for that is
404  * rather subtle: with OST-side locking, it may so happen that _all_ extent
405  * locks are held by the OST. If client wants to obtain the current file size
406  * it calls ll_glimpse_size(), and (as all locks are held only on the server),
407  * this dummy glimpse callback fires and does nothing. The client still
408  * receives the correct file size due to the following fragment of code in
409  * ldlm_cb_interpret():
410  *
411  *      if (rc == -ELDLM_NO_LOCK_DATA) {
412  *              LDLM_DEBUG(lock, "lost race - client has a lock but no"
413  *                         "inode");
414  *              ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
415  *      }
416  *
417  * That is, after the glimpse returns this error, ofd_lvbo_update() is called
418  * and returns the updated file attributes from the inode to the client.
419  *
420  * See also comment in ofd_intent_policy() on why servers must set a non-NULL
421  * l_glimpse_ast when grabbing DLM locks.  Otherwise, the server will assume
422  * that the object is in the process of being destroyed.
423  *
424  * \param[in] lock      DLM lock being glimpsed, unused
425  * \param[in] reqp      pointer to ptlrpc_request, unused
426  *
427  * \retval              -ELDLM_NO_LOCK_DATA to get attributes from disk object
428  */
429 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
430 {
431         return -ELDLM_NO_LOCK_DATA;
432 }
433
434 /**
435  * Enqueue a local lock (typically on a server).
436  */
437 int ldlm_cli_enqueue_local(struct ldlm_namespace *ns,
438                            const struct ldlm_res_id *res_id,
439                            enum ldlm_type type, union ldlm_policy_data *policy,
440                            enum ldlm_mode mode, __u64 *flags,
441                            ldlm_blocking_callback blocking,
442                            ldlm_completion_callback completion,
443                            ldlm_glimpse_callback glimpse,
444                            void *data, __u32 lvb_len, enum lvb_type lvb_type,
445                            const __u64 *client_cookie,
446                            struct lustre_handle *lockh)
447 {
448         struct ldlm_lock *lock;
449         int err;
450         const struct ldlm_callback_suite cbs = { .lcs_completion = completion,
451                                                  .lcs_blocking   = blocking,
452                                                  .lcs_glimpse    = glimpse,
453         };
454         ENTRY;
455
456         LASSERT(!(*flags & LDLM_FL_REPLAY));
457         if (unlikely(ns_is_client(ns))) {
458                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
459                 LBUG();
460         }
461
462         lock = ldlm_lock_create(ns, res_id, type, mode, &cbs, data, lvb_len,
463                                 lvb_type);
464         if (IS_ERR(lock))
465                 GOTO(out_nolock, err = PTR_ERR(lock));
466
467         err = ldlm_lvbo_init(lock->l_resource);
468         if (err < 0) {
469                 LDLM_ERROR(lock, "delayed lvb init failed (rc %d)", err);
470                 GOTO(out, err);
471         }
472
473         ldlm_lock2handle(lock, lockh);
474
475         /* NB: we don't have any lock now (lock_res_and_lock)
476          * because it's a new lock */
477         ldlm_lock_addref_internal_nolock(lock, mode);
478         ldlm_set_local(lock);
479         if (*flags & LDLM_FL_ATOMIC_CB)
480                 ldlm_set_atomic_cb(lock);
481
482         if (policy != NULL)
483                 lock->l_policy_data = *policy;
484         if (client_cookie != NULL)
485                 lock->l_client_cookie = *client_cookie;
486         if (type == LDLM_EXTENT) {
487                 /* extent lock without policy is a bug */
488                 if (policy == NULL)
489                         LBUG();
490
491                 lock->l_req_extent = policy->l_extent;
492         }
493
494         err = ldlm_lock_enqueue(ns, &lock, policy, flags);
495         if (unlikely(err != ELDLM_OK))
496                 GOTO(out, err);
497
498         if (policy != NULL)
499                 *policy = lock->l_policy_data;
500
501         if (lock->l_completion_ast)
502                 lock->l_completion_ast(lock, *flags, NULL);
503
504         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
505         EXIT;
506  out:
507         LDLM_LOCK_RELEASE(lock);
508  out_nolock:
509         return err;
510 }
511 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
512
513 static void failed_lock_cleanup(struct ldlm_namespace *ns,
514                                 struct ldlm_lock *lock, int mode)
515 {
516         int need_cancel = 0;
517
518         /* Set a flag to prevent us from sending a CANCEL (bug 407) */
519         lock_res_and_lock(lock);
520         /* Check that lock is not granted or failed, we might race. */
521         if ((lock->l_req_mode != lock->l_granted_mode) &&
522             !ldlm_is_failed(lock)) {
523                 /* Make sure that this lock will not be found by raced
524                  * bl_ast and -EINVAL reply is sent to server anyways.
525                  * b=17645*/
526                 lock->l_flags |= LDLM_FL_LOCAL_ONLY | LDLM_FL_FAILED |
527                                  LDLM_FL_ATOMIC_CB | LDLM_FL_CBPENDING;
528                 need_cancel = 1;
529         }
530         unlock_res_and_lock(lock);
531
532         if (need_cancel)
533                 LDLM_DEBUG(lock,
534                            "setting FL_LOCAL_ONLY | LDLM_FL_FAILED | "
535                            "LDLM_FL_ATOMIC_CB | LDLM_FL_CBPENDING");
536         else
537                 LDLM_DEBUG(lock, "lock was granted or failed in race");
538
539         /* XXX - HACK because we shouldn't call ldlm_lock_destroy()
540          *       from llite/file.c/ll_file_flock(). */
541         /* This code makes for the fact that we do not have blocking handler on
542          * a client for flock locks. As such this is the place where we must
543          * completely kill failed locks. (interrupted and those that
544          * were waiting to be granted when server evicted us. */
545         if (lock->l_resource->lr_type == LDLM_FLOCK) {
546                 lock_res_and_lock(lock);
547                 if (!ldlm_is_destroyed(lock)) {
548                         ldlm_resource_unlink_lock(lock);
549                         ldlm_lock_decref_internal_nolock(lock, mode);
550                         ldlm_lock_destroy_nolock(lock);
551                 }
552                 unlock_res_and_lock(lock);
553         } else {
554                 ldlm_lock_decref_internal(lock, mode);
555         }
556 }
557
558 /**
559  * Finishing portion of client lock enqueue code.
560  *
561  * Called after receiving reply from server.
562  */
563 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct ptlrpc_request *req,
564                           enum ldlm_type type, __u8 with_policy,
565                           enum ldlm_mode mode, __u64 *flags, void *lvb,
566                           __u32 lvb_len, const struct lustre_handle *lockh,
567                           int rc)
568 {
569         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
570         int is_replay = *flags & LDLM_FL_REPLAY;
571         struct ldlm_lock *lock;
572         struct ldlm_reply *reply;
573         int cleanup_phase = 1;
574         ENTRY;
575
576         lock = ldlm_handle2lock(lockh);
577         /* ldlm_cli_enqueue is holding a reference on this lock. */
578         if (!lock) {
579                 LASSERT(type == LDLM_FLOCK);
580                 RETURN(-ENOLCK);
581         }
582
583         LASSERTF(ergo(lvb_len != 0, lvb_len == lock->l_lvb_len),
584                  "lvb_len = %d, l_lvb_len = %d\n", lvb_len, lock->l_lvb_len);
585
586         if (rc != ELDLM_OK) {
587                 LASSERT(!is_replay);
588                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
589                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
590
591                 if (rc != ELDLM_LOCK_ABORTED)
592                         GOTO(cleanup, rc);
593         }
594
595         /* Before we return, swab the reply */
596         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
597         if (reply == NULL)
598                 GOTO(cleanup, rc = -EPROTO);
599
600         if (lvb_len > 0) {
601                 int size = 0;
602
603                 size = req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
604                                             RCL_SERVER);
605                 if (size < 0) {
606                         LDLM_ERROR(lock, "Fail to get lvb_len, rc = %d", size);
607                         GOTO(cleanup, rc = size);
608                 } else if (unlikely(size > lvb_len)) {
609                         LDLM_ERROR(lock, "Replied LVB is larger than "
610                                    "expectation, expected = %d, replied = %d",
611                                    lvb_len, size);
612                         GOTO(cleanup, rc = -EINVAL);
613                 }
614                 lvb_len = size;
615         }
616
617         if (rc == ELDLM_LOCK_ABORTED) {
618                 if (lvb_len > 0 && lvb != NULL)
619                         rc = ldlm_fill_lvb(lock, &req->rq_pill, RCL_SERVER,
620                                            lvb, lvb_len);
621                 GOTO(cleanup, rc = rc ? : ELDLM_LOCK_ABORTED);
622         }
623
624         /* lock enqueued on the server */
625         cleanup_phase = 0;
626
627         lock_res_and_lock(lock);
628         /* Key change rehash lock in per-export hash with new key */
629         if (exp->exp_lock_hash) {
630                 /* In the function below, .hs_keycmp resolves to
631                  * ldlm_export_lock_keycmp() */
632                 /* coverity[overrun-buffer-val] */
633                 cfs_hash_rehash_key(exp->exp_lock_hash,
634                                     &lock->l_remote_handle,
635                                     &reply->lock_handle,
636                                     &lock->l_exp_hash);
637         } else {
638                 lock->l_remote_handle = reply->lock_handle;
639         }
640
641         *flags = ldlm_flags_from_wire(reply->lock_flags);
642         lock->l_flags |= ldlm_flags_from_wire(reply->lock_flags &
643                                               LDLM_FL_INHERIT_MASK);
644         unlock_res_and_lock(lock);
645
646         CDEBUG(D_INFO, "local: %p, remote cookie: %#llx, flags: %#llx\n",
647                lock, reply->lock_handle.cookie, *flags);
648
649         /* If enqueue returned a blocked lock but the completion handler has
650          * already run, then it fixed up the resource and we don't need to do it
651          * again. */
652         if ((*flags) & LDLM_FL_LOCK_CHANGED) {
653                 int newmode = reply->lock_desc.l_req_mode;
654                 LASSERT(!is_replay);
655                 if (newmode && newmode != lock->l_req_mode) {
656                         LDLM_DEBUG(lock, "server returned different mode %s",
657                                    ldlm_lockname[newmode]);
658                         lock->l_req_mode = newmode;
659                 }
660
661                 if (!ldlm_res_eq(&reply->lock_desc.l_resource.lr_name,
662                                  &lock->l_resource->lr_name)) {
663                         CDEBUG(D_INFO, "remote intent success, locking "DLDLMRES
664                                        " instead of "DLDLMRES"\n",
665                                PLDLMRES(&reply->lock_desc.l_resource),
666                                PLDLMRES(lock->l_resource));
667
668                         rc = ldlm_lock_change_resource(ns, lock,
669                                         &reply->lock_desc.l_resource.lr_name);
670                         if (rc || lock->l_resource == NULL)
671                                 GOTO(cleanup, rc = -ENOMEM);
672                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
673                 }
674                 if (with_policy)
675                         if (!(type == LDLM_IBITS &&
676                               !(exp_connect_flags(exp) & OBD_CONNECT_IBITS)))
677                                 /* We assume lock type cannot change on server*/
678                                 ldlm_convert_policy_to_local(exp,
679                                                 lock->l_resource->lr_type,
680                                                 &reply->lock_desc.l_policy_data,
681                                                 &lock->l_policy_data);
682                 if (type != LDLM_PLAIN)
683                         LDLM_DEBUG(lock,"client-side enqueue, new policy data");
684         }
685
686         if ((*flags) & LDLM_FL_AST_SENT) {
687                 lock_res_and_lock(lock);
688                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
689                 unlock_res_and_lock(lock);
690                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
691         }
692
693         /* If the lock has already been granted by a completion AST, don't
694          * clobber the LVB with an older one. */
695         if (lvb_len > 0) {
696                 /* We must lock or a racing completion might update lvb without
697                  * letting us know and we'll clobber the correct value.
698                  * Cannot unlock after the check either, a that still leaves
699                  * a tiny window for completion to get in */
700                 lock_res_and_lock(lock);
701                 if (lock->l_req_mode != lock->l_granted_mode)
702                         rc = ldlm_fill_lvb(lock, &req->rq_pill, RCL_SERVER,
703                                            lock->l_lvb_data, lvb_len);
704                 unlock_res_and_lock(lock);
705                 if (rc < 0) {
706                         cleanup_phase = 1;
707                         GOTO(cleanup, rc);
708                 }
709         }
710
711         if (!is_replay) {
712                 rc = ldlm_lock_enqueue(ns, &lock, NULL, flags);
713                 if (lock->l_completion_ast != NULL) {
714                         int err = lock->l_completion_ast(lock, *flags, NULL);
715                         if (!rc)
716                                 rc = err;
717                         if (rc)
718                                 cleanup_phase = 1;
719                 }
720         }
721
722         if (lvb_len > 0 && lvb != NULL) {
723                 /* Copy the LVB here, and not earlier, because the completion
724                  * AST (if any) can override what we got in the reply */
725                 memcpy(lvb, lock->l_lvb_data, lvb_len);
726         }
727
728         LDLM_DEBUG(lock, "client-side enqueue END");
729         EXIT;
730 cleanup:
731         if (cleanup_phase == 1 && rc)
732                 failed_lock_cleanup(ns, lock, mode);
733         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
734         LDLM_LOCK_PUT(lock);
735         LDLM_LOCK_RELEASE(lock);
736         return rc;
737 }
738 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
739
740 /**
741  * Estimate number of lock handles that would fit into request of given
742  * size.  PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
743  * a single page on the send/receive side. XXX: 512 should be changed to
744  * more adequate value.
745  */
746 static inline int ldlm_req_handles_avail(int req_size, int off)
747 {
748         int avail;
749
750         avail = min_t(int, LDLM_MAXREQSIZE, PAGE_SIZE - 512) - req_size;
751         if (likely(avail >= 0))
752                 avail /= (int)sizeof(struct lustre_handle);
753         else
754                 avail = 0;
755         avail += LDLM_LOCKREQ_HANDLES - off;
756
757         return avail;
758 }
759
760 static inline int ldlm_capsule_handles_avail(struct req_capsule *pill,
761                                              enum req_location loc,
762                                              int off)
763 {
764         __u32 size = req_capsule_msg_size(pill, loc);
765         return ldlm_req_handles_avail(size, off);
766 }
767
768 static inline int ldlm_format_handles_avail(struct obd_import *imp,
769                                             const struct req_format *fmt,
770                                             enum req_location loc, int off)
771 {
772         __u32 size = req_capsule_fmt_size(imp->imp_msg_magic, fmt, loc);
773         return ldlm_req_handles_avail(size, off);
774 }
775
776 /**
777  * Cancel LRU locks and pack them into the enqueue request. Pack there the given
778  * \a count locks in \a cancels.
779  *
780  * This is to be called by functions preparing their own requests that
781  * might contain lists of locks to cancel in addition to actual operation
782  * that needs to be performed.
783  */
784 int ldlm_prep_elc_req(struct obd_export *exp, struct ptlrpc_request *req,
785                       int version, int opc, int canceloff,
786                       struct list_head *cancels, int count)
787         {
788         struct ldlm_namespace   *ns = exp->exp_obd->obd_namespace;
789         struct req_capsule      *pill = &req->rq_pill;
790         struct ldlm_request     *dlm = NULL;
791         struct list_head        head = LIST_HEAD_INIT(head);
792         enum ldlm_lru_flags lru_flags;
793         int avail, to_free, pack = 0;
794         int rc;
795         ENTRY;
796
797         if (cancels == NULL)
798                 cancels = &head;
799         if (ns_connect_cancelset(ns)) {
800                 /* Estimate the amount of available space in the request. */
801                 req_capsule_filled_sizes(pill, RCL_CLIENT);
802                 avail = ldlm_capsule_handles_avail(pill, RCL_CLIENT, canceloff);
803
804                 lru_flags = LDLM_LRU_FLAG_NO_WAIT | (ns_connect_lru_resize(ns) ?
805                         LDLM_LRU_FLAG_LRUR : LDLM_LRU_FLAG_AGED);
806                 to_free = !ns_connect_lru_resize(ns) &&
807                         opc == LDLM_ENQUEUE ? 1 : 0;
808
809                 /* Cancel LRU locks here _only_ if the server supports
810                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
811                  * RPC, which will make us slower. */
812                 if (avail > count)
813                         count += ldlm_cancel_lru_local(ns, cancels, to_free,
814                                                        avail - count, 0,
815                                                        lru_flags);
816                 if (avail > count)
817                         pack = count;
818                 else
819                         pack = avail;
820                 req_capsule_set_size(pill, &RMF_DLM_REQ, RCL_CLIENT,
821                                      ldlm_request_bufsize(pack, opc));
822         }
823
824         rc = ptlrpc_request_pack(req, version, opc);
825         if (rc) {
826                 ldlm_lock_list_put(cancels, l_bl_ast, count);
827                 RETURN(rc);
828         }
829
830         if (ns_connect_cancelset(ns)) {
831                 if (canceloff) {
832                         dlm = req_capsule_client_get(pill, &RMF_DLM_REQ);
833                         LASSERT(dlm);
834                         /* Skip first lock handler in ldlm_request_pack(),
835                          * this method will increment @lock_count according
836                          * to the lock handle amount actually written to
837                          * the buffer. */
838                         dlm->lock_count = canceloff;
839                 }
840                 /* Pack into the request @pack lock handles. */
841                 ldlm_cli_cancel_list(cancels, pack, req, 0);
842                 /* Prepare and send separate cancel RPC for others. */
843                 ldlm_cli_cancel_list(cancels, count - pack, NULL, 0);
844         } else {
845                 ldlm_lock_list_put(cancels, l_bl_ast, count);
846         }
847         RETURN(0);
848 }
849 EXPORT_SYMBOL(ldlm_prep_elc_req);
850
851 int ldlm_prep_enqueue_req(struct obd_export *exp, struct ptlrpc_request *req,
852                           struct list_head *cancels, int count)
853 {
854         return ldlm_prep_elc_req(exp, req, LUSTRE_DLM_VERSION, LDLM_ENQUEUE,
855                                  LDLM_ENQUEUE_CANCEL_OFF, cancels, count);
856 }
857 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
858
859 struct ptlrpc_request *ldlm_enqueue_pack(struct obd_export *exp, int lvb_len)
860 {
861         struct ptlrpc_request *req;
862         int rc;
863         ENTRY;
864
865         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LDLM_ENQUEUE);
866         if (req == NULL)
867                 RETURN(ERR_PTR(-ENOMEM));
868
869         rc = ldlm_prep_enqueue_req(exp, req, NULL, 0);
870         if (rc) {
871                 ptlrpc_request_free(req);
872                 RETURN(ERR_PTR(rc));
873         }
874
875         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, lvb_len);
876         ptlrpc_request_set_replen(req);
877         RETURN(req);
878 }
879 EXPORT_SYMBOL(ldlm_enqueue_pack);
880
881 /**
882  * Client-side lock enqueue.
883  *
884  * If a request has some specific initialisation it is passed in \a reqp,
885  * otherwise it is created in ldlm_cli_enqueue.
886  *
887  * Supports sync and async requests, pass \a async flag accordingly. If a
888  * request was created in ldlm_cli_enqueue and it is the async request,
889  * pass it to the caller in \a reqp.
890  */
891 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
892                      struct ldlm_enqueue_info *einfo,
893                      const struct ldlm_res_id *res_id,
894                      union ldlm_policy_data const *policy, __u64 *flags,
895                      void *lvb, __u32 lvb_len, enum lvb_type lvb_type,
896                      struct lustre_handle *lockh, int async)
897 {
898         struct ldlm_namespace *ns;
899         struct ldlm_lock      *lock;
900         struct ldlm_request   *body;
901         int                    is_replay = *flags & LDLM_FL_REPLAY;
902         int                    req_passed_in = 1;
903         int                    rc, err;
904         struct ptlrpc_request *req;
905         ENTRY;
906
907         LASSERT(exp != NULL);
908
909         ns = exp->exp_obd->obd_namespace;
910
911         /* If we're replaying this lock, just check some invariants.
912          * If we're creating a new lock, get everything all setup nice. */
913         if (is_replay) {
914                 lock = ldlm_handle2lock_long(lockh, 0);
915                 LASSERT(lock != NULL);
916                 LDLM_DEBUG(lock, "client-side enqueue START");
917                 LASSERT(exp == lock->l_conn_export);
918         } else {
919                 const struct ldlm_callback_suite cbs = {
920                         .lcs_completion = einfo->ei_cb_cp,
921                         .lcs_blocking   = einfo->ei_cb_bl,
922                         .lcs_glimpse    = einfo->ei_cb_gl
923                 };
924                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
925                                         einfo->ei_mode, &cbs, einfo->ei_cbdata,
926                                         lvb_len, lvb_type);
927                 if (IS_ERR(lock))
928                         RETURN(PTR_ERR(lock));
929                 /* for the local lock, add the reference */
930                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
931                 ldlm_lock2handle(lock, lockh);
932                 if (policy != NULL)
933                         lock->l_policy_data = *policy;
934
935                 if (einfo->ei_type == LDLM_EXTENT) {
936                         /* extent lock without policy is a bug */
937                         if (policy == NULL)
938                                 LBUG();
939
940                         lock->l_req_extent = policy->l_extent;
941                 }
942                 LDLM_DEBUG(lock, "client-side enqueue START, flags %#llx",
943                            *flags);
944         }
945
946         lock->l_conn_export = exp;
947         lock->l_export = NULL;
948         lock->l_blocking_ast = einfo->ei_cb_bl;
949         lock->l_flags |= (*flags & (LDLM_FL_NO_LRU | LDLM_FL_EXCL));
950         lock->l_last_activity = cfs_time_current_sec();
951
952         /* lock not sent to server yet */
953         if (reqp == NULL || *reqp == NULL) {
954                 req = ldlm_enqueue_pack(exp, lvb_len);
955                 if (IS_ERR(req)) {
956                         failed_lock_cleanup(ns, lock, einfo->ei_mode);
957                         LDLM_LOCK_RELEASE(lock);
958                         RETURN(PTR_ERR(req));
959                 }
960
961                 req_passed_in = 0;
962                 if (reqp)
963                         *reqp = req;
964         } else {
965                 int len;
966
967                 req = *reqp;
968                 len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ,
969                                            RCL_CLIENT);
970                 LASSERTF(len >= sizeof(*body), "buflen[%d] = %d, not %d\n",
971                          DLM_LOCKREQ_OFF, len, (int)sizeof(*body));
972         }
973
974         /* Dump lock data into the request buffer */
975         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
976         ldlm_lock2desc(lock, &body->lock_desc);
977         body->lock_flags = ldlm_flags_to_wire(*flags);
978         body->lock_handle[0] = *lockh;
979
980         if (async) {
981                 LASSERT(reqp != NULL);
982                 RETURN(0);
983         }
984
985         LDLM_DEBUG(lock, "sending request");
986
987         rc = ptlrpc_queue_wait(req);
988
989         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
990                                     einfo->ei_mode, flags, lvb, lvb_len,
991                                     lockh, rc);
992
993         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
994          * one reference that we took */
995         if (err == -ENOLCK)
996                 LDLM_LOCK_RELEASE(lock);
997         else
998                 rc = err;
999
1000         if (!req_passed_in && req != NULL) {
1001                 ptlrpc_req_finished(req);
1002                 if (reqp)
1003                         *reqp = NULL;
1004         }
1005
1006         RETURN(rc);
1007 }
1008 EXPORT_SYMBOL(ldlm_cli_enqueue);
1009
1010 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
1011                                   __u32 *flags)
1012 {
1013         struct ldlm_resource *res;
1014         int rc;
1015         ENTRY;
1016         if (ns_is_client(ldlm_lock_to_ns(lock))) {
1017                 CERROR("Trying to cancel local lock\n");
1018                 LBUG();
1019         }
1020         LDLM_DEBUG(lock, "client-side local convert");
1021
1022         res = ldlm_lock_convert(lock, new_mode, flags);
1023         if (res) {
1024                 ldlm_reprocess_all(res);
1025                 rc = 0;
1026         } else {
1027                 rc = LUSTRE_EDEADLK;
1028         }
1029         LDLM_DEBUG(lock, "client-side local convert handler END");
1030         LDLM_LOCK_PUT(lock);
1031         RETURN(rc);
1032 }
1033
1034 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
1035  * conversion of locks which are on the waiting or converting queue */
1036 /* Caller of this code is supposed to take care of lock readers/writers
1037    accounting */
1038 int ldlm_cli_convert(const struct lustre_handle *lockh, int new_mode,
1039                      __u32 *flags)
1040 {
1041         struct ldlm_request   *body;
1042         struct ldlm_reply     *reply;
1043         struct ldlm_lock      *lock;
1044         struct ldlm_resource  *res;
1045         struct ptlrpc_request *req;
1046         int                    rc;
1047         ENTRY;
1048
1049         lock = ldlm_handle2lock(lockh);
1050         if (!lock) {
1051                 LBUG();
1052                 RETURN(-EINVAL);
1053         }
1054         *flags = 0;
1055
1056         if (lock->l_conn_export == NULL)
1057                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
1058
1059         LDLM_DEBUG(lock, "client-side convert");
1060
1061         req = ptlrpc_request_alloc_pack(class_exp2cliimp(lock->l_conn_export),
1062                                         &RQF_LDLM_CONVERT, LUSTRE_DLM_VERSION,
1063                                         LDLM_CONVERT);
1064         if (req == NULL) {
1065                 LDLM_LOCK_PUT(lock);
1066                 RETURN(-ENOMEM);
1067         }
1068
1069         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1070         body->lock_handle[0] = lock->l_remote_handle;
1071
1072         body->lock_desc.l_req_mode = new_mode;
1073         body->lock_flags = ldlm_flags_to_wire(*flags);
1074
1075
1076         ptlrpc_request_set_replen(req);
1077         rc = ptlrpc_queue_wait(req);
1078         if (rc != ELDLM_OK)
1079                 GOTO(out, rc);
1080
1081         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1082         if (reply == NULL)
1083                 GOTO(out, rc = -EPROTO);
1084
1085         if (req->rq_status)
1086                 GOTO(out, rc = req->rq_status);
1087
1088         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
1089         if (res != NULL) {
1090                 ldlm_reprocess_all(res);
1091                 /* Go to sleep until the lock is granted. */
1092                 /* FIXME: or cancelled. */
1093                 if (lock->l_completion_ast) {
1094                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
1095                                                     NULL);
1096                         if (rc)
1097                                 GOTO(out, rc);
1098                 }
1099         } else {
1100                 rc = LUSTRE_EDEADLK;
1101         }
1102         EXIT;
1103  out:
1104         LDLM_LOCK_PUT(lock);
1105         ptlrpc_req_finished(req);
1106         return rc;
1107 }
1108
1109 /**
1110  * Cancel locks locally.
1111  * Returns:
1112  * \retval LDLM_FL_LOCAL_ONLY if there is no need for a CANCEL RPC to the server
1113  * \retval LDLM_FL_CANCELING otherwise;
1114  * \retval LDLM_FL_BL_AST if there is a need for a separate CANCEL RPC.
1115  */
1116 static __u64 ldlm_cli_cancel_local(struct ldlm_lock *lock)
1117 {
1118         __u64 rc = LDLM_FL_LOCAL_ONLY;
1119         ENTRY;
1120
1121         if (lock->l_conn_export) {
1122                 bool local_only;
1123
1124                 LDLM_DEBUG(lock, "client-side cancel");
1125                 /* Set this flag to prevent others from getting new references*/
1126                 lock_res_and_lock(lock);
1127                 ldlm_set_cbpending(lock);
1128                 local_only = !!(lock->l_flags &
1129                                 (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
1130                 ldlm_cancel_callback(lock);
1131                 rc = (ldlm_is_bl_ast(lock)) ?
1132                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
1133                 unlock_res_and_lock(lock);
1134
1135                 if (local_only) {
1136                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
1137                                "instruction)\n");
1138                         rc = LDLM_FL_LOCAL_ONLY;
1139                 }
1140                 ldlm_lock_cancel(lock);
1141         } else {
1142                 if (ns_is_client(ldlm_lock_to_ns(lock))) {
1143                         LDLM_ERROR(lock, "Trying to cancel local lock");
1144                         LBUG();
1145                 }
1146                 LDLM_DEBUG(lock, "server-side local cancel");
1147                 ldlm_lock_cancel(lock);
1148                 ldlm_reprocess_all(lock->l_resource);
1149         }
1150
1151         RETURN(rc);
1152 }
1153
1154 /**
1155  * Pack \a count locks in \a head into ldlm_request buffer of request \a req.
1156  */
1157 static void ldlm_cancel_pack(struct ptlrpc_request *req,
1158                              struct list_head *head, int count)
1159 {
1160         struct ldlm_request *dlm;
1161         struct ldlm_lock *lock;
1162         int max, packed = 0;
1163         ENTRY;
1164
1165         dlm = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1166         LASSERT(dlm != NULL);
1167
1168         /* Check the room in the request buffer. */
1169         max = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT) -
1170                 sizeof(struct ldlm_request);
1171         max /= sizeof(struct lustre_handle);
1172         max += LDLM_LOCKREQ_HANDLES;
1173         LASSERT(max >= dlm->lock_count + count);
1174
1175         /* XXX: it would be better to pack lock handles grouped by resource.
1176          * so that the server cancel would call filter_lvbo_update() less
1177          * frequently. */
1178         list_for_each_entry(lock, head, l_bl_ast) {
1179                 if (!count--)
1180                         break;
1181                 LASSERT(lock->l_conn_export);
1182                 /* Pack the lock handle to the given request buffer. */
1183                 LDLM_DEBUG(lock, "packing");
1184                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
1185                 packed++;
1186         }
1187         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
1188         EXIT;
1189 }
1190
1191 /**
1192  * Prepare and send a batched cancel RPC. It will include \a count lock
1193  * handles of locks given in \a cancels list. */
1194 int ldlm_cli_cancel_req(struct obd_export *exp, struct list_head *cancels,
1195                         int count, enum ldlm_cancel_flags flags)
1196 {
1197         struct ptlrpc_request *req = NULL;
1198         struct obd_import *imp;
1199         int free, sent = 0;
1200         int rc = 0;
1201         ENTRY;
1202
1203         LASSERT(exp != NULL);
1204         LASSERT(count > 0);
1205
1206         CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL, cfs_fail_val);
1207
1208         if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
1209                 RETURN(count);
1210
1211         free = ldlm_format_handles_avail(class_exp2cliimp(exp),
1212                                          &RQF_LDLM_CANCEL, RCL_CLIENT, 0);
1213         if (count > free)
1214                 count = free;
1215
1216         while (1) {
1217                 imp = class_exp2cliimp(exp);
1218                 if (imp == NULL || imp->imp_invalid) {
1219                         CDEBUG(D_DLMTRACE,
1220                                "skipping cancel on invalid import %p\n", imp);
1221                         RETURN(count);
1222                 }
1223
1224                 req = ptlrpc_request_alloc(imp, &RQF_LDLM_CANCEL);
1225                 if (req == NULL)
1226                         GOTO(out, rc = -ENOMEM);
1227
1228                 req_capsule_filled_sizes(&req->rq_pill, RCL_CLIENT);
1229                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT,
1230                                      ldlm_request_bufsize(count, LDLM_CANCEL));
1231
1232                 rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CANCEL);
1233                 if (rc) {
1234                         ptlrpc_request_free(req);
1235                         GOTO(out, rc);
1236                 }
1237
1238                 /* If OSP want cancel cross-MDT lock, let's not block it in
1239                  * in recovery, otherwise the lock will not released, if
1240                  * the remote target is also in recovery, and it also need
1241                  * this lock, it might cause deadlock. */
1242                 if (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS &&
1243                     exp->exp_obd->obd_lu_dev != NULL &&
1244                     exp->exp_obd->obd_lu_dev->ld_site != NULL) {
1245                         struct lu_device *top_dev;
1246
1247                         top_dev = exp->exp_obd->obd_lu_dev->ld_site->ls_top_dev;
1248                         if (top_dev != NULL &&
1249                             top_dev->ld_obd->obd_recovering)
1250                                 req->rq_allow_replay = 1;
1251                 }
1252
1253                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1254                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1255                 ptlrpc_at_set_req_timeout(req);
1256
1257                 ldlm_cancel_pack(req, cancels, count);
1258
1259                 ptlrpc_request_set_replen(req);
1260                 if (flags & LCF_ASYNC) {
1261                         ptlrpcd_add_req(req);
1262                         sent = count;
1263                         GOTO(out, 0);
1264                 }
1265
1266                 rc = ptlrpc_queue_wait(req);
1267                 if (rc == LUSTRE_ESTALE) {
1268                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
1269                                "out of sync -- not fatal\n",
1270                                libcfs_nid2str(req->rq_import->
1271                                               imp_connection->c_peer.nid));
1272                         rc = 0;
1273                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1274                            req->rq_import_generation == imp->imp_generation) {
1275                         ptlrpc_req_finished(req);
1276                         continue;
1277                 } else if (rc != ELDLM_OK) {
1278                         /* -ESHUTDOWN is common on umount */
1279                         CDEBUG_LIMIT(rc == -ESHUTDOWN ? D_DLMTRACE : D_ERROR,
1280                                      "Got rc %d from cancel RPC: "
1281                                      "canceling anyway\n", rc);
1282                         break;
1283                 }
1284                 sent = count;
1285                 break;
1286         }
1287
1288         ptlrpc_req_finished(req);
1289         EXIT;
1290 out:
1291         return sent ? sent : rc;
1292 }
1293
1294 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1295 {
1296         LASSERT(imp != NULL);
1297         return &imp->imp_obd->obd_namespace->ns_pool;
1298 }
1299
1300 /**
1301  * Update client's OBD pool related fields with new SLV and Limit from \a req.
1302  */
1303 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1304 {
1305         struct obd_device *obd;
1306         __u64 new_slv;
1307         __u32 new_limit;
1308         ENTRY;
1309         if (unlikely(!req->rq_import || !req->rq_import->imp_obd ||
1310                      !imp_connect_lru_resize(req->rq_import)))
1311         {
1312                 /*
1313                  * Do nothing for corner cases.
1314                  */
1315                 RETURN(0);
1316         }
1317
1318         /* In some cases RPC may contain SLV and limit zeroed out. This
1319          * is the case when server does not support LRU resize feature.
1320          * This is also possible in some recovery cases when server-side
1321          * reqs have no reference to the OBD export and thus access to
1322          * server-side namespace is not possible. */
1323         if (lustre_msg_get_slv(req->rq_repmsg) == 0 ||
1324             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1325                 DEBUG_REQ(D_HA, req, "Zero SLV or Limit found "
1326                           "(SLV: %llu, Limit: %u)",
1327                           lustre_msg_get_slv(req->rq_repmsg),
1328                           lustre_msg_get_limit(req->rq_repmsg));
1329                 RETURN(0);
1330         }
1331
1332         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1333         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1334         obd = req->rq_import->imp_obd;
1335
1336         /* Set new SLV and limit in OBD fields to make them accessible
1337          * to the pool thread. We do not access obd_namespace and pool
1338          * directly here as there is no reliable way to make sure that
1339          * they are still alive at cleanup time. Evil races are possible
1340          * which may cause Oops at that time. */
1341         write_lock(&obd->obd_pool_lock);
1342         obd->obd_pool_slv = new_slv;
1343         obd->obd_pool_limit = new_limit;
1344         write_unlock(&obd->obd_pool_lock);
1345
1346         RETURN(0);
1347 }
1348
1349 /**
1350  * Client side lock cancel.
1351  *
1352  * Lock must not have any readers or writers by this time.
1353  */
1354 int ldlm_cli_cancel(const struct lustre_handle *lockh,
1355                     enum ldlm_cancel_flags cancel_flags)
1356 {
1357         struct obd_export *exp;
1358         enum ldlm_lru_flags lru_flags;
1359         int avail, count = 1;
1360         __u64 rc = 0;
1361         struct ldlm_namespace *ns;
1362         struct ldlm_lock *lock;
1363         struct list_head cancels = LIST_HEAD_INIT(cancels);
1364         ENTRY;
1365
1366         lock = ldlm_handle2lock_long(lockh, 0);
1367         if (lock == NULL) {
1368                 LDLM_DEBUG_NOLOCK("lock is already being destroyed");
1369                 RETURN(0);
1370         }
1371
1372         lock_res_and_lock(lock);
1373         /* Lock is being canceled and the caller doesn't want to wait */
1374         if (ldlm_is_canceling(lock)) {
1375                 if (cancel_flags & LCF_ASYNC) {
1376                         unlock_res_and_lock(lock);
1377                 } else {
1378                         struct l_wait_info lwi = { 0 };
1379
1380                         unlock_res_and_lock(lock);
1381                         l_wait_event(lock->l_waitq, is_bl_done(lock), &lwi);
1382                 }
1383                 LDLM_LOCK_RELEASE(lock);
1384                 RETURN(0);
1385         }
1386
1387         ldlm_set_canceling(lock);
1388         unlock_res_and_lock(lock);
1389
1390         rc = ldlm_cli_cancel_local(lock);
1391         if (rc == LDLM_FL_LOCAL_ONLY || cancel_flags & LCF_LOCAL) {
1392                 LDLM_LOCK_RELEASE(lock);
1393                 RETURN(0);
1394         }
1395         /* Even if the lock is marked as LDLM_FL_BL_AST, this is a LDLM_CANCEL
1396          * RPC which goes to canceld portal, so we can cancel other LRU locks
1397          * here and send them all as one LDLM_CANCEL RPC. */
1398         LASSERT(list_empty(&lock->l_bl_ast));
1399         list_add(&lock->l_bl_ast, &cancels);
1400
1401         exp = lock->l_conn_export;
1402         if (exp_connect_cancelset(exp)) {
1403                 avail = ldlm_format_handles_avail(class_exp2cliimp(exp),
1404                                                   &RQF_LDLM_CANCEL,
1405                                                   RCL_CLIENT, 0);
1406                 LASSERT(avail > 0);
1407
1408                 ns = ldlm_lock_to_ns(lock);
1409                 lru_flags = ns_connect_lru_resize(ns) ?
1410                         LDLM_LRU_FLAG_LRUR : LDLM_LRU_FLAG_AGED;
1411                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1412                                                LCF_BL_AST, lru_flags);
1413         }
1414         ldlm_cli_cancel_list(&cancels, count, NULL, cancel_flags);
1415         RETURN(0);
1416 }
1417 EXPORT_SYMBOL(ldlm_cli_cancel);
1418
1419 /**
1420  * Locally cancel up to \a count locks in list \a cancels.
1421  * Return the number of cancelled locks.
1422  */
1423 int ldlm_cli_cancel_list_local(struct list_head *cancels, int count,
1424                                enum ldlm_cancel_flags cancel_flags)
1425 {
1426         struct list_head head = LIST_HEAD_INIT(head);
1427         struct ldlm_lock *lock, *next;
1428         int left = 0, bl_ast = 0;
1429         __u64 rc;
1430
1431         left = count;
1432         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1433                 if (left-- == 0)
1434                         break;
1435
1436                 if (cancel_flags & LCF_LOCAL) {
1437                         rc = LDLM_FL_LOCAL_ONLY;
1438                         ldlm_lock_cancel(lock);
1439                 } else {
1440                         rc = ldlm_cli_cancel_local(lock);
1441                 }
1442                 /* Until we have compound requests and can send LDLM_CANCEL
1443                  * requests batched with generic RPCs, we need to send cancels
1444                  * with the LDLM_FL_BL_AST flag in a separate RPC from
1445                  * the one being generated now. */
1446                 if (!(cancel_flags & LCF_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1447                         LDLM_DEBUG(lock, "Cancel lock separately");
1448                         list_del_init(&lock->l_bl_ast);
1449                         list_add(&lock->l_bl_ast, &head);
1450                         bl_ast++;
1451                         continue;
1452                 }
1453                 if (rc == LDLM_FL_LOCAL_ONLY) {
1454                         /* CANCEL RPC should not be sent to server. */
1455                         list_del_init(&lock->l_bl_ast);
1456                         LDLM_LOCK_RELEASE(lock);
1457                         count--;
1458                 }
1459         }
1460         if (bl_ast > 0) {
1461                 count -= bl_ast;
1462                 ldlm_cli_cancel_list(&head, bl_ast, NULL, 0);
1463         }
1464
1465         RETURN(count);
1466 }
1467
1468 /**
1469  * Cancel as many locks as possible w/o sending any RPCs (e.g. to write back
1470  * dirty data, to close a file, ...) or waiting for any RPCs in-flight (e.g.
1471  * readahead requests, ...)
1472  */
1473 static enum ldlm_policy_res
1474 ldlm_cancel_no_wait_policy(struct ldlm_namespace *ns, struct ldlm_lock *lock,
1475                            int unused, int added, int count)
1476 {
1477         enum ldlm_policy_res result = LDLM_POLICY_CANCEL_LOCK;
1478
1479         /* don't check added & count since we want to process all locks
1480          * from unused list.
1481          * It's fine to not take lock to access lock->l_resource since
1482          * the lock has already been granted so it won't change. */
1483         switch (lock->l_resource->lr_type) {
1484                 case LDLM_EXTENT:
1485                 case LDLM_IBITS:
1486                         if (ns->ns_cancel != NULL && ns->ns_cancel(lock) != 0)
1487                                 break;
1488                 default:
1489                         result = LDLM_POLICY_SKIP_LOCK;
1490                         break;
1491         }
1492
1493         RETURN(result);
1494 }
1495
1496 /**
1497  * Callback function for LRU-resize policy. Decides whether to keep
1498  * \a lock in LRU for current \a LRU size \a unused, added in current
1499  * scan \a added and number of locks to be preferably canceled \a count.
1500  *
1501  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1502  *
1503  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1504  */
1505 static enum ldlm_policy_res ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1506                                                     struct ldlm_lock *lock,
1507                                                     int unused, int added,
1508                                                     int count)
1509 {
1510         ktime_t cur = ktime_get();
1511         struct ldlm_pool *pl = &ns->ns_pool;
1512         u64 slv, lvf, lv;
1513         s64 la;
1514
1515         /* Stop LRU processing when we reach past @count or have checked all
1516          * locks in LRU. */
1517         if (count && added >= count)
1518                 return LDLM_POLICY_KEEP_LOCK;
1519
1520         /* Despite of the LV, It doesn't make sense to keep the lock which
1521          * is unused for ns_max_age time.
1522          */
1523         if (ktime_after(ktime_get(),
1524                         ktime_add(lock->l_last_used, ns->ns_max_age)))
1525                 return LDLM_POLICY_CANCEL_LOCK;
1526
1527         slv = ldlm_pool_get_slv(pl);
1528         lvf = ldlm_pool_get_lvf(pl);
1529         la = ktime_to_ns(ktime_sub(cur, lock->l_last_used)) / NSEC_PER_SEC;
1530         lv = lvf * la * unused;
1531
1532         /* Inform pool about current CLV to see it via proc. */
1533         ldlm_pool_set_clv(pl, lv);
1534
1535         /* Stop when SLV is not yet come from server or lv is smaller than
1536          * it is. */
1537         if (slv == 0 || lv < slv)
1538                 return LDLM_POLICY_KEEP_LOCK;
1539
1540         return LDLM_POLICY_CANCEL_LOCK;
1541 }
1542
1543 static enum ldlm_policy_res
1544 ldlm_cancel_lrur_no_wait_policy(struct ldlm_namespace *ns,
1545                                 struct ldlm_lock *lock,
1546                                 int unused, int added,
1547                                 int count)
1548 {
1549         enum ldlm_policy_res result;
1550
1551         result = ldlm_cancel_lrur_policy(ns, lock, unused, added, count);
1552         if (result == LDLM_POLICY_KEEP_LOCK)
1553                 return result;
1554
1555         return ldlm_cancel_no_wait_policy(ns, lock, unused, added, count);
1556 }
1557
1558 /**
1559  * Callback function for proc used policy. Makes decision whether to keep
1560  * \a lock in LRU for current \a LRU size \a unused, added in current scan \a
1561  * added and number of locks to be preferably canceled \a count.
1562  *
1563  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1564  *
1565  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1566  */
1567 static enum ldlm_policy_res ldlm_cancel_passed_policy(struct ldlm_namespace *ns,
1568                                                       struct ldlm_lock *lock,
1569                                                       int unused, int added,
1570                                                       int count)
1571 {
1572         /* Stop LRU processing when we reach past @count or have checked all
1573          * locks in LRU. */
1574         return (added >= count) ?
1575                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1576 }
1577
1578 /**
1579  * Callback function for aged policy. Makes decision whether to keep \a lock in
1580  * LRU for current LRU size \a unused, added in current scan \a added and
1581  * number of locks to be preferably canceled \a count.
1582  *
1583  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1584  *
1585  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1586  */
1587 static enum ldlm_policy_res ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1588                                                     struct ldlm_lock *lock,
1589                                                     int unused, int added,
1590                                                     int count)
1591 {
1592         if ((added >= count) &&
1593             ktime_before(ktime_get(),
1594                          ktime_add(lock->l_last_used, ns->ns_max_age)))
1595                 return LDLM_POLICY_KEEP_LOCK;
1596
1597         return LDLM_POLICY_CANCEL_LOCK;
1598 }
1599
1600 static enum ldlm_policy_res
1601 ldlm_cancel_aged_no_wait_policy(struct ldlm_namespace *ns,
1602                                 struct ldlm_lock *lock,
1603                                 int unused, int added, int count)
1604 {
1605         enum ldlm_policy_res result;
1606
1607         result = ldlm_cancel_aged_policy(ns, lock, unused, added, count);
1608         if (result == LDLM_POLICY_KEEP_LOCK)
1609                 return result;
1610
1611         return ldlm_cancel_no_wait_policy(ns, lock, unused, added, count);
1612 }
1613
1614 /**
1615  * Callback function for default policy. Makes decision whether to keep \a lock
1616  * in LRU for current LRU size \a unused, added in current scan \a added and
1617  * number of locks to be preferably canceled \a count.
1618  *
1619  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1620  *
1621  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1622  */
1623 static
1624 enum ldlm_policy_res ldlm_cancel_default_policy(struct ldlm_namespace *ns,
1625                                                 struct ldlm_lock *lock,
1626                                                 int unused, int added,
1627                                                 int count)
1628 {
1629         /* Stop LRU processing when we reach past count or have checked all
1630          * locks in LRU. */
1631         return (added >= count) ?
1632                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1633 }
1634
1635 typedef enum ldlm_policy_res
1636 (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *ns, struct ldlm_lock *lock,
1637                             int unused, int added, int count);
1638
1639 static ldlm_cancel_lru_policy_t
1640 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, enum ldlm_lru_flags lru_flags)
1641 {
1642         if (ns_connect_lru_resize(ns)) {
1643                 if (lru_flags & LDLM_LRU_FLAG_SHRINK)
1644                         /* We kill passed number of old locks. */
1645                         return ldlm_cancel_passed_policy;
1646                 if (lru_flags & LDLM_LRU_FLAG_LRUR) {
1647                         if (lru_flags & LDLM_LRU_FLAG_NO_WAIT)
1648                                 return ldlm_cancel_lrur_no_wait_policy;
1649                         else
1650                                 return ldlm_cancel_lrur_policy;
1651                 }
1652                 if (lru_flags & LDLM_LRU_FLAG_PASSED)
1653                         return ldlm_cancel_passed_policy;
1654         } else {
1655                 if (lru_flags & LDLM_LRU_FLAG_AGED) {
1656                         if (lru_flags & LDLM_LRU_FLAG_NO_WAIT)
1657                                 return ldlm_cancel_aged_no_wait_policy;
1658                         else
1659                                 return ldlm_cancel_aged_policy;
1660                 }
1661         }
1662         if (lru_flags & LDLM_LRU_FLAG_NO_WAIT)
1663                 return ldlm_cancel_no_wait_policy;
1664
1665         return ldlm_cancel_default_policy;
1666 }
1667
1668 /**
1669  * - Free space in LRU for \a count new locks,
1670  *   redundant unused locks are canceled locally;
1671  * - also cancel locally unused aged locks;
1672  * - do not cancel more than \a max locks;
1673  * - GET the found locks and add them into the \a cancels list.
1674  *
1675  * A client lock can be added to the l_bl_ast list only when it is
1676  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing
1677  * CANCEL.  There are the following use cases:
1678  * ldlm_cancel_resource_local(), ldlm_cancel_lru_local() and
1679  * ldlm_cli_cancel(), which check and set this flag properly. As any
1680  * attempt to cancel a lock rely on this flag, l_bl_ast list is accessed
1681  * later without any special locking.
1682  *
1683  * Calling policies for enabled LRU resize:
1684  * ----------------------------------------
1685  * flags & LDLM_LRU_FLAG_LRUR - use LRU resize policy (SLV from server) to
1686  *                              cancel not more than \a count locks;
1687  *
1688  * flags & LDLM_LRU_FLAG_PASSED - cancel \a count number of old locks (located
1689  *                              at the beginning of LRU list);
1690  *
1691  * flags & LDLM_LRU_FLAG_SHRINK - cancel not more than \a count locks according
1692  *                              to memory pressre policy function;
1693  *
1694  * flags & LDLM_LRU_FLAG_AGED - cancel \a count locks according to "aged policy"
1695  *
1696  * flags & LDLM_LRU_FLAG_NO_WAIT - cancel as many unused locks as possible
1697  *                              (typically before replaying locks) w/o
1698  *                              sending any RPCs or waiting for any
1699  *                              outstanding RPC to complete.
1700  *
1701  * flags & LDLM_CANCEL_CLEANUP - when cancelling read locks, do not check for
1702  *                              other read locks covering the same pages, just
1703  *                              discard those pages.
1704  */
1705 static int ldlm_prepare_lru_list(struct ldlm_namespace *ns,
1706                                  struct list_head *cancels, int count, int max,
1707                                  enum ldlm_lru_flags lru_flags)
1708 {
1709         ldlm_cancel_lru_policy_t pf;
1710         int added = 0;
1711         int no_wait = lru_flags & LDLM_LRU_FLAG_NO_WAIT;
1712
1713         ENTRY;
1714
1715         if (!ns_connect_lru_resize(ns))
1716                 count += ns->ns_nr_unused - ns->ns_max_unused;
1717
1718         pf = ldlm_cancel_lru_policy(ns, lru_flags);
1719         LASSERT(pf != NULL);
1720
1721         /* For any flags, stop scanning if @max is reached. */
1722         while (!list_empty(&ns->ns_unused_list) && (max == 0 || added < max)) {
1723                 struct ldlm_lock *lock;
1724                 struct list_head *item, *next;
1725                 enum ldlm_policy_res result;
1726                 ktime_t last_use = ktime_set(0, 0);
1727
1728                 spin_lock(&ns->ns_lock);
1729                 item = no_wait ? ns->ns_last_pos : &ns->ns_unused_list;
1730                 for (item = item->next, next = item->next;
1731                      item != &ns->ns_unused_list;
1732                      item = next, next = item->next) {
1733                         lock = list_entry(item, struct ldlm_lock, l_lru);
1734
1735                         /* No locks which got blocking requests. */
1736                         LASSERT(!ldlm_is_bl_ast(lock));
1737
1738                         if (!ldlm_is_canceling(lock))
1739                                 break;
1740
1741                         /* Somebody is already doing CANCEL. No need for this
1742                          * lock in LRU, do not traverse it again. */
1743                         ldlm_lock_remove_from_lru_nolock(lock);
1744                 }
1745                 if (item == &ns->ns_unused_list) {
1746                         spin_unlock(&ns->ns_lock);
1747                         break;
1748                 }
1749
1750                 last_use = lock->l_last_used;
1751
1752                 LDLM_LOCK_GET(lock);
1753                 spin_unlock(&ns->ns_lock);
1754                 lu_ref_add(&lock->l_reference, __FUNCTION__, current);
1755
1756                 /* Pass the lock through the policy filter and see if it
1757                  * should stay in LRU.
1758                  *
1759                  * Even for shrinker policy we stop scanning if
1760                  * we find a lock that should stay in the cache.
1761                  * We should take into account lock age anyway
1762                  * as a new lock is a valuable resource even if
1763                  * it has a low weight.
1764                  *
1765                  * That is, for shrinker policy we drop only
1766                  * old locks, but additionally choose them by
1767                  * their weight. Big extent locks will stay in
1768                  * the cache. */
1769                 result = pf(ns, lock, ns->ns_nr_unused, added, count);
1770                 if (result == LDLM_POLICY_KEEP_LOCK) {
1771                         lu_ref_del(&lock->l_reference, __func__, current);
1772                         LDLM_LOCK_RELEASE(lock);
1773                         break;
1774                 }
1775
1776                 if (result == LDLM_POLICY_SKIP_LOCK) {
1777                         lu_ref_del(&lock->l_reference, __func__, current);
1778                         LDLM_LOCK_RELEASE(lock);
1779                         if (no_wait) {
1780                                 spin_lock(&ns->ns_lock);
1781                                 if (!list_empty(&lock->l_lru) &&
1782                                     lock->l_lru.prev == ns->ns_last_pos)
1783                                         ns->ns_last_pos = &lock->l_lru;
1784                                 spin_unlock(&ns->ns_lock);
1785                         }
1786                         continue;
1787                 }
1788
1789                 lock_res_and_lock(lock);
1790                 /* Check flags again under the lock. */
1791                 if (ldlm_is_canceling(lock) ||
1792                     ldlm_lock_remove_from_lru_check(lock, last_use) == 0) {
1793                         /* Another thread is removing lock from LRU, or
1794                          * somebody is already doing CANCEL, or there
1795                          * is a blocking request which will send cancel
1796                          * by itself, or the lock is no longer unused or
1797                          * the lock has been used since the pf() call and
1798                          * pages could be put under it. */
1799                         unlock_res_and_lock(lock);
1800                         lu_ref_del(&lock->l_reference, __FUNCTION__, current);
1801                         LDLM_LOCK_RELEASE(lock);
1802                         continue;
1803                 }
1804                 LASSERT(!lock->l_readers && !lock->l_writers);
1805
1806                 /* If we have chosen to cancel this lock voluntarily, we
1807                  * better send cancel notification to server, so that it
1808                  * frees appropriate state. This might lead to a race
1809                  * where while we are doing cancel here, server is also
1810                  * silently cancelling this lock. */
1811                 ldlm_clear_cancel_on_block(lock);
1812
1813                 /* Setting the CBPENDING flag is a little misleading,
1814                  * but prevents an important race; namely, once
1815                  * CBPENDING is set, the lock can accumulate no more
1816                  * readers/writers. Since readers and writers are
1817                  * already zero here, ldlm_lock_decref() won't see
1818                  * this flag and call l_blocking_ast */
1819                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1820
1821                 if ((lru_flags & LDLM_LRU_FLAG_CLEANUP) &&
1822                     lock->l_resource->lr_type == LDLM_EXTENT &&
1823                     lock->l_granted_mode == LCK_PR)
1824                         ldlm_set_discard_data(lock);
1825
1826                 /* We can't re-add to l_lru as it confuses the
1827                  * refcounting in ldlm_lock_remove_from_lru() if an AST
1828                  * arrives after we drop lr_lock below. We use l_bl_ast
1829                  * and can't use l_pending_chain as it is used both on
1830                  * server and client nevertheless bug 5666 says it is
1831                  * used only on server */
1832                 LASSERT(list_empty(&lock->l_bl_ast));
1833                 list_add(&lock->l_bl_ast, cancels);
1834                 unlock_res_and_lock(lock);
1835                 lu_ref_del(&lock->l_reference, __FUNCTION__, current);
1836                 added++;
1837         }
1838         RETURN(added);
1839 }
1840
1841 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
1842                           int count, int max,
1843                           enum ldlm_cancel_flags cancel_flags,
1844                           enum ldlm_lru_flags lru_flags)
1845 {
1846         int added;
1847
1848         added = ldlm_prepare_lru_list(ns, cancels, count, max, lru_flags);
1849         if (added <= 0)
1850                 return added;
1851
1852         return ldlm_cli_cancel_list_local(cancels, added, cancel_flags);
1853 }
1854
1855 /**
1856  * Cancel at least \a nr locks from given namespace LRU.
1857  *
1858  * When called with LCF_ASYNC the blocking callback will be handled
1859  * in a thread and this function will return after the thread has been
1860  * asked to call the callback.  When called with LCF_ASYNC the blocking
1861  * callback will be performed in this function.
1862  */
1863 int ldlm_cancel_lru(struct ldlm_namespace *ns, int nr,
1864                     enum ldlm_cancel_flags cancel_flags,
1865                     enum ldlm_lru_flags lru_flags)
1866 {
1867         struct list_head cancels = LIST_HEAD_INIT(cancels);
1868         int count, rc;
1869         ENTRY;
1870
1871         /* Just prepare the list of locks, do not actually cancel them yet.
1872          * Locks are cancelled later in a separate thread. */
1873         count = ldlm_prepare_lru_list(ns, &cancels, nr, 0, lru_flags);
1874         rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count, cancel_flags);
1875         if (rc == 0)
1876                 RETURN(count);
1877
1878         RETURN(0);
1879 }
1880
1881 /**
1882  * Find and cancel locally unused locks found on resource, matched to the
1883  * given policy, mode. GET the found locks and add them into the \a cancels
1884  * list.
1885  */
1886 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1887                                struct list_head *cancels,
1888                                union ldlm_policy_data *policy,
1889                                enum ldlm_mode mode, __u64 lock_flags,
1890                                enum ldlm_cancel_flags cancel_flags,
1891                                void *opaque)
1892 {
1893         struct ldlm_lock *lock;
1894         int count = 0;
1895         ENTRY;
1896
1897         lock_res(res);
1898         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1899                 if (opaque != NULL && lock->l_ast_data != opaque) {
1900                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1901                                    lock->l_ast_data, opaque);
1902                         //LBUG();
1903                         continue;
1904                 }
1905
1906                 if (lock->l_readers || lock->l_writers)
1907                         continue;
1908
1909                 /* If somebody is already doing CANCEL, or blocking AST came,
1910                  * skip this lock. */
1911                 if (ldlm_is_bl_ast(lock) || ldlm_is_canceling(lock))
1912                         continue;
1913
1914                 if (lockmode_compat(lock->l_granted_mode, mode))
1915                         continue;
1916
1917                 /* If policy is given and this is IBITS lock, add to list only
1918                  * those locks that match by policy. */
1919                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1920                     !(lock->l_policy_data.l_inodebits.bits &
1921                       policy->l_inodebits.bits))
1922                         continue;
1923
1924                 /* See CBPENDING comment in ldlm_cancel_lru */
1925                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1926                                  lock_flags;
1927
1928                 LASSERT(list_empty(&lock->l_bl_ast));
1929                 list_add(&lock->l_bl_ast, cancels);
1930                 LDLM_LOCK_GET(lock);
1931                 count++;
1932         }
1933         unlock_res(res);
1934
1935         RETURN(ldlm_cli_cancel_list_local(cancels, count, cancel_flags));
1936 }
1937 EXPORT_SYMBOL(ldlm_cancel_resource_local);
1938
1939 /**
1940  * Cancel client-side locks from a list and send/prepare cancel RPCs to the
1941  * server.
1942  * If \a req is NULL, send CANCEL request to server with handles of locks
1943  * in the \a cancels. If EARLY_CANCEL is not supported, send CANCEL requests
1944  * separately per lock.
1945  * If \a req is not NULL, put handles of locks in \a cancels into the request
1946  * buffer at the offset \a off.
1947  * Destroy \a cancels at the end.
1948  */
1949 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1950                          struct ptlrpc_request *req,
1951                          enum ldlm_cancel_flags flags)
1952 {
1953         struct ldlm_lock *lock;
1954         int res = 0;
1955         ENTRY;
1956
1957         if (list_empty(cancels) || count == 0)
1958                 RETURN(0);
1959
1960         /* XXX: requests (both batched and not) could be sent in parallel.
1961          * Usually it is enough to have just 1 RPC, but it is possible that
1962          * there are too many locks to be cancelled in LRU or on a resource.
1963          * It would also speed up the case when the server does not support
1964          * the feature. */
1965         while (count > 0) {
1966                 LASSERT(!list_empty(cancels));
1967                 lock = list_entry(cancels->next, struct ldlm_lock,
1968                                       l_bl_ast);
1969                 LASSERT(lock->l_conn_export);
1970
1971                 if (exp_connect_cancelset(lock->l_conn_export)) {
1972                         res = count;
1973                         if (req)
1974                                 ldlm_cancel_pack(req, cancels, count);
1975                         else
1976                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1977                                                           cancels, count,
1978                                                           flags);
1979                 } else {
1980                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1981                                                   cancels, 1, flags);
1982                 }
1983
1984                 if (res < 0) {
1985                         CDEBUG_LIMIT(res == -ESHUTDOWN ? D_DLMTRACE : D_ERROR,
1986                                      "ldlm_cli_cancel_list: %d\n", res);
1987                         res = count;
1988                 }
1989
1990                 count -= res;
1991                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1992         }
1993         LASSERT(count == 0);
1994         RETURN(0);
1995 }
1996 EXPORT_SYMBOL(ldlm_cli_cancel_list);
1997
1998 /**
1999  * Cancel all locks on a resource that have 0 readers/writers.
2000  *
2001  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
2002  * to notify the server. */
2003 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
2004                                     const struct ldlm_res_id *res_id,
2005                                     union ldlm_policy_data *policy,
2006                                     enum ldlm_mode mode,
2007                                     enum ldlm_cancel_flags flags, void *opaque)
2008 {
2009         struct ldlm_resource *res;
2010         struct list_head cancels = LIST_HEAD_INIT(cancels);
2011         int count;
2012         int rc;
2013         ENTRY;
2014
2015         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
2016         if (IS_ERR(res)) {
2017                 /* This is not a problem. */
2018                 CDEBUG(D_INFO, "No resource %llu\n", res_id->name[0]);
2019                 RETURN(0);
2020         }
2021
2022         LDLM_RESOURCE_ADDREF(res);
2023         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
2024                                            0, flags | LCF_BL_AST, opaque);
2025         rc = ldlm_cli_cancel_list(&cancels, count, NULL, flags);
2026         if (rc != ELDLM_OK)
2027                 CERROR("canceling unused lock "DLDLMRES": rc = %d\n",
2028                        PLDLMRES(res), rc);
2029
2030         LDLM_RESOURCE_DELREF(res);
2031         ldlm_resource_putref(res);
2032         RETURN(0);
2033 }
2034 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2035
2036 struct ldlm_cli_cancel_arg {
2037         int     lc_flags;
2038         void   *lc_opaque;
2039 };
2040
2041 static int
2042 ldlm_cli_hash_cancel_unused(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2043                             struct hlist_node *hnode, void *arg)
2044 {
2045         struct ldlm_resource           *res = cfs_hash_object(hs, hnode);
2046         struct ldlm_cli_cancel_arg     *lc = arg;
2047
2048         ldlm_cli_cancel_unused_resource(ldlm_res_to_ns(res), &res->lr_name,
2049                                         NULL, LCK_MINMODE, lc->lc_flags,
2050                                         lc->lc_opaque);
2051         /* must return 0 for hash iteration */
2052         return 0;
2053 }
2054
2055 /**
2056  * Cancel all locks on a namespace (or a specific resource, if given)
2057  * that have 0 readers/writers.
2058  *
2059  * If flags & LCF_LOCAL, throw the locks away without trying
2060  * to notify the server. */
2061 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
2062                            const struct ldlm_res_id *res_id,
2063                            enum ldlm_cancel_flags flags, void *opaque)
2064 {
2065         struct ldlm_cli_cancel_arg arg = {
2066                 .lc_flags       = flags,
2067                 .lc_opaque      = opaque,
2068         };
2069
2070         ENTRY;
2071
2072         if (ns == NULL)
2073                 RETURN(ELDLM_OK);
2074
2075         if (res_id != NULL) {
2076                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
2077                                                        LCK_MINMODE, flags,
2078                                                        opaque));
2079         } else {
2080                 cfs_hash_for_each_nolock(ns->ns_rs_hash,
2081                                          ldlm_cli_hash_cancel_unused, &arg, 0);
2082                 RETURN(ELDLM_OK);
2083         }
2084 }
2085
2086 /* Lock iterators. */
2087
2088 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
2089                           void *closure)
2090 {
2091         struct list_head *tmp, *next;
2092         struct ldlm_lock *lock;
2093         int rc = LDLM_ITER_CONTINUE;
2094
2095         ENTRY;
2096
2097         if (!res)
2098                 RETURN(LDLM_ITER_CONTINUE);
2099
2100         lock_res(res);
2101         list_for_each_safe(tmp, next, &res->lr_granted) {
2102                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
2103
2104                 if (iter(lock, closure) == LDLM_ITER_STOP)
2105                         GOTO(out, rc = LDLM_ITER_STOP);
2106         }
2107
2108         list_for_each_safe(tmp, next, &res->lr_converting) {
2109                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
2110
2111                 if (iter(lock, closure) == LDLM_ITER_STOP)
2112                         GOTO(out, rc = LDLM_ITER_STOP);
2113         }
2114
2115         list_for_each_safe(tmp, next, &res->lr_waiting) {
2116                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
2117
2118                 if (iter(lock, closure) == LDLM_ITER_STOP)
2119                         GOTO(out, rc = LDLM_ITER_STOP);
2120         }
2121  out:
2122         unlock_res(res);
2123         RETURN(rc);
2124 }
2125
2126 struct iter_helper_data {
2127         ldlm_iterator_t iter;
2128         void *closure;
2129 };
2130
2131 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
2132 {
2133         struct iter_helper_data *helper = closure;
2134         return helper->iter(lock, helper->closure);
2135 }
2136
2137 static int ldlm_res_iter_helper(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2138                                 struct hlist_node *hnode, void *arg)
2139
2140 {
2141         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
2142
2143         return ldlm_resource_foreach(res, ldlm_iter_helper, arg) ==
2144                LDLM_ITER_STOP;
2145 }
2146
2147 void ldlm_namespace_foreach(struct ldlm_namespace *ns,
2148                             ldlm_iterator_t iter, void *closure)
2149
2150 {
2151         struct iter_helper_data helper = { .iter = iter, .closure = closure };
2152
2153         cfs_hash_for_each_nolock(ns->ns_rs_hash,
2154                                  ldlm_res_iter_helper, &helper, 0);
2155
2156 }
2157
2158 /* non-blocking function to manipulate a lock whose cb_data is being put away.
2159  * return  0:  find no resource
2160  *       > 0:  must be LDLM_ITER_STOP/LDLM_ITER_CONTINUE.
2161  *       < 0:  errors
2162  */
2163 int ldlm_resource_iterate(struct ldlm_namespace *ns,
2164                           const struct ldlm_res_id *res_id,
2165                           ldlm_iterator_t iter, void *data)
2166 {
2167         struct ldlm_resource *res;
2168         int rc;
2169         ENTRY;
2170
2171         LASSERTF(ns != NULL, "must pass in namespace\n");
2172
2173         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
2174         if (IS_ERR(res))
2175                 RETURN(0);
2176
2177         LDLM_RESOURCE_ADDREF(res);
2178         rc = ldlm_resource_foreach(res, iter, data);
2179         LDLM_RESOURCE_DELREF(res);
2180         ldlm_resource_putref(res);
2181         RETURN(rc);
2182 }
2183 EXPORT_SYMBOL(ldlm_resource_iterate);
2184
2185 /* Lock replay */
2186
2187 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
2188 {
2189         struct list_head *list = closure;
2190
2191         /* we use l_pending_chain here, because it's unused on clients. */
2192         LASSERTF(list_empty(&lock->l_pending_chain),
2193                  "lock %p next %p prev %p\n",
2194                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
2195         /* bug 9573: don't replay locks left after eviction, or
2196          * bug 17614: locks being actively cancelled. Get a reference
2197          * on a lock so that it does not disapear under us (e.g. due to cancel)
2198          */
2199         if (!(lock->l_flags & (LDLM_FL_FAILED|LDLM_FL_BL_DONE))) {
2200                 list_add(&lock->l_pending_chain, list);
2201                 LDLM_LOCK_GET(lock);
2202         }
2203
2204         return LDLM_ITER_CONTINUE;
2205 }
2206
2207 static int replay_lock_interpret(const struct lu_env *env,
2208                                  struct ptlrpc_request *req,
2209                                  struct ldlm_async_args *aa, int rc)
2210 {
2211         struct ldlm_lock     *lock;
2212         struct ldlm_reply    *reply;
2213         struct obd_export    *exp;
2214
2215         ENTRY;
2216         atomic_dec(&req->rq_import->imp_replay_inflight);
2217         if (rc != ELDLM_OK)
2218                 GOTO(out, rc);
2219
2220         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2221         if (reply == NULL)
2222                 GOTO(out, rc = -EPROTO);
2223
2224         lock = ldlm_handle2lock(&aa->lock_handle);
2225         if (!lock) {
2226                 CERROR("received replay ack for unknown local cookie %#llx"
2227                        " remote cookie %#llx from server %s id %s\n",
2228                        aa->lock_handle.cookie, reply->lock_handle.cookie,
2229                        req->rq_export->exp_client_uuid.uuid,
2230                        libcfs_id2str(req->rq_peer));
2231                 GOTO(out, rc = -ESTALE);
2232         }
2233
2234         /* Key change rehash lock in per-export hash with new key */
2235         exp = req->rq_export;
2236         if (exp && exp->exp_lock_hash) {
2237                 /* In the function below, .hs_keycmp resolves to
2238                  * ldlm_export_lock_keycmp() */
2239                 /* coverity[overrun-buffer-val] */
2240                 cfs_hash_rehash_key(exp->exp_lock_hash,
2241                                     &lock->l_remote_handle,
2242                                     &reply->lock_handle,
2243                                     &lock->l_exp_hash);
2244         } else {
2245                 lock->l_remote_handle = reply->lock_handle;
2246         }
2247
2248         LDLM_DEBUG(lock, "replayed lock:");
2249         ptlrpc_import_recovery_state_machine(req->rq_import);
2250         LDLM_LOCK_PUT(lock);
2251 out:
2252         if (rc != ELDLM_OK)
2253                 ptlrpc_connect_import(req->rq_import);
2254
2255         RETURN(rc);
2256 }
2257
2258 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
2259 {
2260         struct ptlrpc_request *req;
2261         struct ldlm_async_args *aa;
2262         struct ldlm_request   *body;
2263         int flags;
2264         ENTRY;
2265
2266
2267         /* Bug 11974: Do not replay a lock which is actively being canceled */
2268         if (ldlm_is_bl_done(lock)) {
2269                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
2270                 RETURN(0);
2271         }
2272
2273         /* If this is reply-less callback lock, we cannot replay it, since
2274          * server might have long dropped it, but notification of that event was
2275          * lost by network. (and server granted conflicting lock already) */
2276         if (ldlm_is_cancel_on_block(lock)) {
2277                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
2278                 ldlm_lock_cancel(lock);
2279                 RETURN(0);
2280         }
2281
2282         /*
2283          * If granted mode matches the requested mode, this lock is granted.
2284          *
2285          * If they differ, but we have a granted mode, then we were granted
2286          * one mode and now want another: ergo, converting.
2287          *
2288          * If we haven't been granted anything and are on a resource list,
2289          * then we're blocked/waiting.
2290          *
2291          * If we haven't been granted anything and we're NOT on a resource list,
2292          * then we haven't got a reply yet and don't have a known disposition.
2293          * This happens whenever a lock enqueue is the request that triggers
2294          * recovery.
2295          */
2296         if (lock->l_granted_mode == lock->l_req_mode)
2297                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
2298         else if (lock->l_granted_mode)
2299                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
2300         else if (!list_empty(&lock->l_res_link))
2301                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
2302         else
2303                 flags = LDLM_FL_REPLAY;
2304
2305         req = ptlrpc_request_alloc_pack(imp, &RQF_LDLM_ENQUEUE,
2306                                         LUSTRE_DLM_VERSION, LDLM_ENQUEUE);
2307         if (req == NULL)
2308                 RETURN(-ENOMEM);
2309
2310         /* We're part of recovery, so don't wait for it. */
2311         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
2312
2313         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2314         ldlm_lock2desc(lock, &body->lock_desc);
2315         body->lock_flags = ldlm_flags_to_wire(flags);
2316
2317         ldlm_lock2handle(lock, &body->lock_handle[0]);
2318         if (lock->l_lvb_len > 0)
2319                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_ENQUEUE_LVB);
2320         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2321                              lock->l_lvb_len);
2322         ptlrpc_request_set_replen(req);
2323         /* notify the server we've replayed all requests.
2324          * also, we mark the request to be put on a dedicated
2325          * queue to be processed after all request replayes.
2326          * bug 6063 */
2327         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
2328
2329         LDLM_DEBUG(lock, "replaying lock:");
2330
2331         atomic_inc(&req->rq_import->imp_replay_inflight);
2332         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2333         aa = ptlrpc_req_async_args(req);
2334         aa->lock_handle = body->lock_handle[0];
2335         req->rq_interpret_reply = (ptlrpc_interpterer_t)replay_lock_interpret;
2336         ptlrpcd_add_req(req);
2337
2338         RETURN(0);
2339 }
2340
2341 /**
2342  * Cancel as many unused locks as possible before replay. since we are
2343  * in recovery, we can't wait for any outstanding RPCs to send any RPC
2344  * to the server.
2345  *
2346  * Called only in recovery before replaying locks. there is no need to
2347  * replay locks that are unused. since the clients may hold thousands of
2348  * cached unused locks, dropping the unused locks can greatly reduce the
2349  * load on the servers at recovery time.
2350  */
2351 static void ldlm_cancel_unused_locks_for_replay(struct ldlm_namespace *ns)
2352 {
2353         int canceled;
2354         struct list_head cancels = LIST_HEAD_INIT(cancels);
2355
2356         CDEBUG(D_DLMTRACE, "Dropping as many unused locks as possible before"
2357                            "replay for namespace %s (%d)\n",
2358                            ldlm_ns_name(ns), ns->ns_nr_unused);
2359
2360         /* We don't need to care whether or not LRU resize is enabled
2361          * because the LDLM_LRU_FLAG_NO_WAIT policy doesn't use the
2362          * count parameter */
2363         canceled = ldlm_cancel_lru_local(ns, &cancels, ns->ns_nr_unused, 0,
2364                                          LCF_LOCAL, LDLM_LRU_FLAG_NO_WAIT);
2365
2366         CDEBUG(D_DLMTRACE, "Canceled %d unused locks from namespace %s\n",
2367                            canceled, ldlm_ns_name(ns));
2368 }
2369
2370 int ldlm_replay_locks(struct obd_import *imp)
2371 {
2372         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
2373         struct list_head list = LIST_HEAD_INIT(list);
2374         struct ldlm_lock *lock, *next;
2375         int rc = 0;
2376
2377         ENTRY;
2378
2379         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
2380
2381         /* don't replay locks if import failed recovery */
2382         if (imp->imp_vbr_failed)
2383                 RETURN(0);
2384
2385         /* ensure this doesn't fall to 0 before all have been queued */
2386         atomic_inc(&imp->imp_replay_inflight);
2387
2388         if (ldlm_cancel_unused_locks_before_replay)
2389                 ldlm_cancel_unused_locks_for_replay(ns);
2390
2391         ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
2392
2393         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
2394                 list_del_init(&lock->l_pending_chain);
2395                 if (rc) {
2396                         LDLM_LOCK_RELEASE(lock);
2397                         continue; /* or try to do the rest? */
2398                 }
2399                 rc = replay_one_lock(imp, lock);
2400                 LDLM_LOCK_RELEASE(lock);
2401         }
2402
2403         atomic_dec(&imp->imp_replay_inflight);
2404
2405         RETURN(rc);
2406 }