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