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