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