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