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