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