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