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