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