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