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