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