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