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