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