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