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