Whamcloud - gitweb
d95e6dfb2553362e376da69634e34b70eee44961
[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, 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                 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                 imp = class_exp2cliimp(exp);
1123                 if (imp == NULL || imp->imp_invalid) {
1124                         CDEBUG(D_DLMTRACE,
1125                                "skipping cancel on invalid import %p\n", imp);
1126                         RETURN(count);
1127                 }
1128
1129                 req = ptlrpc_request_alloc(imp, &RQF_LDLM_CANCEL);
1130                 if (req == NULL)
1131                         GOTO(out, rc = -ENOMEM);
1132
1133                 req_capsule_filled_sizes(&req->rq_pill, RCL_CLIENT);
1134                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT,
1135                                      ldlm_request_bufsize(count, LDLM_CANCEL));
1136
1137                 rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CANCEL);
1138                 if (rc) {
1139                         ptlrpc_request_free(req);
1140                         GOTO(out, rc);
1141                 }
1142                 req->rq_no_resend = 1;
1143                 req->rq_no_delay = 1;
1144
1145                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1146                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1147                 ptlrpc_at_set_req_timeout(req);
1148
1149                 ldlm_cancel_pack(req, cancels, count);
1150
1151                 ptlrpc_request_set_replen(req);
1152                 if (flags & LCF_ASYNC) {
1153                         ptlrpcd_add_req(req, PDL_POLICY_LOCAL, -1);
1154                         sent = count;
1155                         GOTO(out, 0);
1156                 } else {
1157                         rc = ptlrpc_queue_wait(req);
1158                 }
1159                 if (rc == ESTALE) {
1160                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
1161                                "out of sync -- not fatal\n",
1162                                libcfs_nid2str(req->rq_import->
1163                                               imp_connection->c_peer.nid));
1164                         rc = 0;
1165                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1166                            req->rq_import_generation == imp->imp_generation) {
1167                         ptlrpc_req_finished(req);
1168                         continue;
1169                 } else if (rc != ELDLM_OK) {
1170                         CERROR("Got rc %d from cancel RPC: canceling "
1171                                "anyway\n", rc);
1172                         break;
1173                 }
1174                 sent = count;
1175                 break;
1176         }
1177
1178         ptlrpc_req_finished(req);
1179         EXIT;
1180 out:
1181         return sent ? sent : rc;
1182 }
1183
1184 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1185 {
1186         LASSERT(imp != NULL);
1187         return &imp->imp_obd->obd_namespace->ns_pool;
1188 }
1189
1190 /**
1191  * Update client's obd pool related fields with new SLV and Limit from \a req.
1192  */
1193 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1194 {
1195         struct obd_device *obd;
1196         __u64 new_slv;
1197         __u32 new_limit;
1198         ENTRY;
1199         if (unlikely(!req->rq_import || !req->rq_import->imp_obd ||
1200                      !imp_connect_lru_resize(req->rq_import)))
1201         {
1202                 /*
1203                  * Do nothing for corner cases.
1204                  */
1205                 RETURN(0);
1206         }
1207
1208         /*
1209          * In some cases RPC may contain slv and limit zeroed out. This is
1210          * the case when server does not support lru resize feature. This is
1211          * also possible in some recovery cases when server side reqs have no
1212          * ref to obd export and thus access to server side namespace is no
1213          * possible.
1214          */
1215         if (lustre_msg_get_slv(req->rq_repmsg) == 0 ||
1216             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1217                 DEBUG_REQ(D_HA, req, "Zero SLV or Limit found "
1218                           "(SLV: "LPU64", Limit: %u)",
1219                           lustre_msg_get_slv(req->rq_repmsg),
1220                           lustre_msg_get_limit(req->rq_repmsg));
1221                 RETURN(0);
1222         }
1223
1224         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1225         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1226         obd = req->rq_import->imp_obd;
1227
1228         /*
1229          * Set new SLV and Limit to obd fields to make accessible for pool
1230          * thread. We do not access obd_namespace and pool directly here
1231          * as there is no reliable way to make sure that they are still
1232          * alive in cleanup time. Evil races are possible which may cause
1233          * oops in that time.
1234          */
1235         cfs_write_lock(&obd->obd_pool_lock);
1236         obd->obd_pool_slv = new_slv;
1237         obd->obd_pool_limit = new_limit;
1238         cfs_write_unlock(&obd->obd_pool_lock);
1239
1240         RETURN(0);
1241 }
1242 EXPORT_SYMBOL(ldlm_cli_update_pool);
1243
1244 int ldlm_cli_cancel(struct lustre_handle *lockh)
1245 {
1246         struct obd_export *exp;
1247         int avail, flags, count = 1, rc = 0;
1248         struct ldlm_namespace *ns;
1249         struct ldlm_lock *lock;
1250         CFS_LIST_HEAD(cancels);
1251         ENTRY;
1252
1253         /* concurrent cancels on the same handle can happen */
1254         lock = ldlm_handle2lock_long(lockh, LDLM_FL_CANCELING);
1255         if (lock == NULL) {
1256                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
1257                 RETURN(0);
1258         }
1259
1260         rc = ldlm_cli_cancel_local(lock);
1261         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY) {
1262                 LDLM_LOCK_RELEASE(lock);
1263                 RETURN(rc < 0 ? rc : 0);
1264         }
1265         /* Even if the lock is marked as LDLM_FL_BL_AST, this is a LDLM_CANCEL
1266          * rpc which goes to canceld portal, so we can cancel other lru locks
1267          * here and send them all as one LDLM_CANCEL rpc. */
1268         LASSERT(cfs_list_empty(&lock->l_bl_ast));
1269         cfs_list_add(&lock->l_bl_ast, &cancels);
1270
1271         exp = lock->l_conn_export;
1272         if (exp_connect_cancelset(exp)) {
1273                 avail = ldlm_format_handles_avail(class_exp2cliimp(exp),
1274                                                   &RQF_LDLM_CANCEL,
1275                                                   RCL_CLIENT, 0);
1276                 LASSERT(avail > 0);
1277
1278                 ns = ldlm_lock_to_ns(lock);
1279                 flags = ns_connect_lru_resize(ns) ?
1280                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
1281                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1282                                                LCF_BL_AST, flags);
1283         }
1284         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1285         RETURN(0);
1286 }
1287
1288 /* XXX until we will have compound requests and can cut cancels from generic rpc
1289  * we need send cancels with LDLM_FL_BL_AST flag as separate rpc */
1290 int ldlm_cli_cancel_list_local(cfs_list_t *cancels, int count,
1291                                ldlm_cancel_flags_t flags)
1292 {
1293         CFS_LIST_HEAD(head);
1294         struct ldlm_lock *lock, *next;
1295         int left = 0, bl_ast = 0, rc;
1296
1297         left = count;
1298         cfs_list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1299                 if (left-- == 0)
1300                         break;
1301
1302                 if (flags & LCF_LOCAL) {
1303                         rc = LDLM_FL_LOCAL_ONLY;
1304                         ldlm_lock_cancel(lock);
1305                 } else {
1306                         rc = ldlm_cli_cancel_local(lock);
1307                 }
1308                 if (!(flags & LCF_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1309                         LDLM_DEBUG(lock, "Cancel lock separately");
1310                         cfs_list_del_init(&lock->l_bl_ast);
1311                         cfs_list_add(&lock->l_bl_ast, &head);
1312                         bl_ast ++;
1313                         continue;
1314                 }
1315                 if (rc == LDLM_FL_LOCAL_ONLY) {
1316                         /* CANCEL RPC should not be sent to server. */
1317                         cfs_list_del_init(&lock->l_bl_ast);
1318                         LDLM_LOCK_RELEASE(lock);
1319                         count--;
1320                 }
1321
1322         }
1323         if (bl_ast > 0) {
1324                 count -= bl_ast;
1325                 ldlm_cli_cancel_list(&head, bl_ast, NULL, 0);
1326         }
1327
1328         RETURN(count);
1329 }
1330
1331 /**
1332  * Cancel as many locks as possible w/o sending any rpcs (e.g. to write back
1333  * dirty data, to close a file, ...) or waiting for any rpcs in-flight (e.g.
1334  * readahead requests, ...)
1335  */
1336 static ldlm_policy_res_t ldlm_cancel_no_wait_policy(struct ldlm_namespace *ns,
1337                                                     struct ldlm_lock *lock,
1338                                                     int unused, int added,
1339                                                     int count)
1340 {
1341         ldlm_policy_res_t result = LDLM_POLICY_CANCEL_LOCK;
1342         ldlm_cancel_for_recovery cb = ns->ns_cancel_for_recovery;
1343         lock_res_and_lock(lock);
1344
1345         /* don't check added & count since we want to process all locks
1346          * from unused list */
1347         switch (lock->l_resource->lr_type) {
1348                 case LDLM_EXTENT:
1349                 case LDLM_IBITS:
1350                         if (cb && cb(lock))
1351                                 break;
1352                 default:
1353                         result = LDLM_POLICY_SKIP_LOCK;
1354                         lock->l_flags |= LDLM_FL_SKIPPED;
1355                         break;
1356         }
1357
1358         unlock_res_and_lock(lock);
1359         RETURN(result);
1360 }
1361
1362 /**
1363  * Callback function for lru-resize policy. Makes decision whether to keep
1364  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1365  * \a added and number of locks to be preferably canceled \a count.
1366  *
1367  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1368  *
1369  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1370  */
1371 static ldlm_policy_res_t ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1372                                                  struct ldlm_lock *lock,
1373                                                  int unused, int added,
1374                                                  int count)
1375 {
1376         cfs_time_t cur = cfs_time_current();
1377         struct ldlm_pool *pl = &ns->ns_pool;
1378         __u64 slv, lvf, lv;
1379         cfs_time_t la;
1380
1381         /*
1382          * Stop lru processing when we reached passed @count or checked all
1383          * locks in lru.
1384          */
1385         if (count && added >= count)
1386                 return LDLM_POLICY_KEEP_LOCK;
1387
1388         slv = ldlm_pool_get_slv(pl);
1389         lvf = ldlm_pool_get_lvf(pl);
1390         la = cfs_duration_sec(cfs_time_sub(cur,
1391                               lock->l_last_used));
1392
1393         /*
1394          * Stop when slv is not yet come from server or lv is smaller than
1395          * it is.
1396          */
1397         lv = lvf * la * unused;
1398
1399         /*
1400          * Inform pool about current CLV to see it via proc.
1401          */
1402         ldlm_pool_set_clv(pl, lv);
1403         return (slv == 0 || lv < slv) ?
1404                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1405 }
1406
1407 /**
1408  * Callback function for proc used policy. Makes decision whether to keep
1409  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1410  * \a added and number of locks to be preferably canceled \a count.
1411  *
1412  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1413  *
1414  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1415  */
1416 static ldlm_policy_res_t ldlm_cancel_passed_policy(struct ldlm_namespace *ns,
1417                                                    struct ldlm_lock *lock,
1418                                                    int unused, int added,
1419                                                    int count)
1420 {
1421         /*
1422          * Stop lru processing when we reached passed @count or checked all
1423          * locks in lru.
1424          */
1425         return (added >= count) ?
1426                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1427 }
1428
1429 /**
1430  * Callback function for aged policy. Makes decision whether to keep
1431  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1432  * \a added and number of locks to be preferably canceled \a count.
1433  *
1434  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1435  *
1436  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1437  */
1438 static ldlm_policy_res_t ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1439                                                  struct ldlm_lock *lock,
1440                                                  int unused, int added,
1441                                                  int count)
1442 {
1443         /*
1444          * Stop lru processing if young lock is found and we reached passed
1445          * @count.
1446          */
1447         return ((added >= count) &&
1448                 cfs_time_before(cfs_time_current(),
1449                                 cfs_time_add(lock->l_last_used,
1450                                              ns->ns_max_age))) ?
1451                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1452 }
1453
1454 /**
1455  * Callback function for default policy. Makes decision whether to keep
1456  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1457  * \a added and number of locks to be preferably canceled \a count.
1458  *
1459  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1460  *
1461  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1462  */
1463 static ldlm_policy_res_t ldlm_cancel_default_policy(struct ldlm_namespace *ns,
1464                                                     struct ldlm_lock *lock,
1465                                                     int unused, int added,
1466                                                     int count)
1467 {
1468         /*
1469          * Stop lru processing when we reached passed @count or checked all
1470          * locks in lru.
1471          */
1472         return (added >= count) ?
1473                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1474 }
1475
1476 typedef ldlm_policy_res_t (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *,
1477                                                       struct ldlm_lock *, int,
1478                                                       int, int);
1479
1480 static ldlm_cancel_lru_policy_t
1481 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, int flags)
1482 {
1483         if (flags & LDLM_CANCEL_NO_WAIT)
1484                 return ldlm_cancel_no_wait_policy;
1485
1486         if (ns_connect_lru_resize(ns)) {
1487                 if (flags & LDLM_CANCEL_SHRINK)
1488                         /* We kill passed number of old locks. */
1489                         return ldlm_cancel_passed_policy;
1490                 else if (flags & LDLM_CANCEL_LRUR)
1491                         return ldlm_cancel_lrur_policy;
1492                 else if (flags & LDLM_CANCEL_PASSED)
1493                         return ldlm_cancel_passed_policy;
1494         } else {
1495                 if (flags & LDLM_CANCEL_AGED)
1496                         return ldlm_cancel_aged_policy;
1497         }
1498
1499         return ldlm_cancel_default_policy;
1500 }
1501
1502 /* - Free space in lru for @count new locks,
1503  *   redundant unused locks are canceled locally;
1504  * - also cancel locally unused aged locks;
1505  * - do not cancel more than @max locks;
1506  * - GET the found locks and add them into the @cancels list.
1507  *
1508  * A client lock can be added to the l_bl_ast list only when it is
1509  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
1510  * There are the following use cases: ldlm_cancel_resource_local(),
1511  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
1512  * flag properly. As any attempt to cancel a lock rely on this flag,
1513  * l_bl_ast list is accessed later without any special locking.
1514  *
1515  * Calling policies for enabled lru resize:
1516  * ----------------------------------------
1517  * flags & LDLM_CANCEL_LRUR - use lru resize policy (SLV from server) to
1518  *                            cancel not more than @count locks;
1519  *
1520  * flags & LDLM_CANCEL_PASSED - cancel @count number of old locks (located at
1521  *                              the beginning of lru list);
1522  *
1523  * flags & LDLM_CANCEL_SHRINK - cancel not more than @count locks according to
1524  *                              memory pressre policy function;
1525  *
1526  * flags & LDLM_CANCEL_AGED -   cancel alocks according to "aged policy".
1527  *
1528  * flags & LDLM_CANCEL_NO_WAIT - cancel as many unused locks as possible
1529  *                               (typically before replaying locks) w/o
1530  *                               sending any rpcs or waiting for any
1531  *                               outstanding rpc to complete.
1532  */
1533 static int ldlm_prepare_lru_list(struct ldlm_namespace *ns, cfs_list_t *cancels,
1534                                  int count, int max, int flags)
1535 {
1536         ldlm_cancel_lru_policy_t pf;
1537         struct ldlm_lock *lock, *next;
1538         int added = 0, unused, remained;
1539         ENTRY;
1540
1541         cfs_spin_lock(&ns->ns_lock);
1542         unused = ns->ns_nr_unused;
1543         remained = unused;
1544
1545         if (!ns_connect_lru_resize(ns))
1546                 count += unused - ns->ns_max_unused;
1547
1548         pf = ldlm_cancel_lru_policy(ns, flags);
1549         LASSERT(pf != NULL);
1550
1551         while (!cfs_list_empty(&ns->ns_unused_list)) {
1552                 ldlm_policy_res_t result;
1553
1554                 /* all unused locks */
1555                 if (remained-- <= 0)
1556                         break;
1557
1558                 /* For any flags, stop scanning if @max is reached. */
1559                 if (max && added >= max)
1560                         break;
1561
1562                 cfs_list_for_each_entry_safe(lock, next, &ns->ns_unused_list,
1563                                              l_lru){
1564                         /* No locks which got blocking requests. */
1565                         LASSERT(!(lock->l_flags & LDLM_FL_BL_AST));
1566
1567                         if (flags & LDLM_CANCEL_NO_WAIT &&
1568                             lock->l_flags & LDLM_FL_SKIPPED)
1569                                 /* already processed */
1570                                 continue;
1571
1572                         /* Somebody is already doing CANCEL. No need in this
1573                          * lock in lru, do not traverse it again. */
1574                         if (!(lock->l_flags & LDLM_FL_CANCELING))
1575                                 break;
1576
1577                         ldlm_lock_remove_from_lru_nolock(lock);
1578                 }
1579                 if (&lock->l_lru == &ns->ns_unused_list)
1580                         break;
1581
1582                 LDLM_LOCK_GET(lock);
1583                 cfs_spin_unlock(&ns->ns_lock);
1584                 lu_ref_add(&lock->l_reference, __FUNCTION__, cfs_current());
1585
1586                 /* Pass the lock through the policy filter and see if it
1587                  * should stay in lru.
1588                  *
1589                  * Even for shrinker policy we stop scanning if
1590                  * we find a lock that should stay in the cache.
1591                  * We should take into account lock age anyway
1592                  * as new lock even if it is small of weight is
1593                  * valuable resource.
1594                  *
1595                  * That is, for shrinker policy we drop only
1596                  * old locks, but additionally chose them by
1597                  * their weight. Big extent locks will stay in
1598                  * the cache. */
1599                 result = pf(ns, lock, unused, added, count);
1600                 if (result == LDLM_POLICY_KEEP_LOCK) {
1601                         lu_ref_del(&lock->l_reference,
1602                                    __FUNCTION__, cfs_current());
1603                         LDLM_LOCK_RELEASE(lock);
1604                         cfs_spin_lock(&ns->ns_lock);
1605                         break;
1606                 }
1607                 if (result == LDLM_POLICY_SKIP_LOCK) {
1608                         lu_ref_del(&lock->l_reference,
1609                                    __FUNCTION__, cfs_current());
1610                         LDLM_LOCK_RELEASE(lock);
1611                         cfs_spin_lock(&ns->ns_lock);
1612                         continue;
1613                 }
1614
1615                 lock_res_and_lock(lock);
1616                 /* Check flags again under the lock. */
1617                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1618                     (ldlm_lock_remove_from_lru(lock) == 0)) {
1619                         /* other thread is removing lock from lru or
1620                          * somebody is already doing CANCEL or
1621                          * there is a blocking request which will send
1622                          * cancel by itseft or the lock is matched
1623                          * is already not unused. */
1624                         unlock_res_and_lock(lock);
1625                         lu_ref_del(&lock->l_reference,
1626                                    __FUNCTION__, cfs_current());
1627                         LDLM_LOCK_RELEASE(lock);
1628                         cfs_spin_lock(&ns->ns_lock);
1629                         continue;
1630                 }
1631                 LASSERT(!lock->l_readers && !lock->l_writers);
1632
1633                 /* If we have chosen to cancel this lock voluntarily, we
1634                  * better send cancel notification to server, so that it
1635                  * frees appropriate state. This might lead to a race
1636                  * where while we are doing cancel here, server is also
1637                  * silently cancelling this lock. */
1638                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1639
1640                 /* Setting the CBPENDING flag is a little misleading,
1641                  * but prevents an important race; namely, once
1642                  * CBPENDING is set, the lock can accumulate no more
1643                  * readers/writers. Since readers and writers are
1644                  * already zero here, ldlm_lock_decref() won't see
1645                  * this flag and call l_blocking_ast */
1646                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1647
1648                 /* We can't re-add to l_lru as it confuses the
1649                  * refcounting in ldlm_lock_remove_from_lru() if an AST
1650                  * arrives after we drop lr_lock below. We use l_bl_ast
1651                  * and can't use l_pending_chain as it is used both on
1652                  * server and client nevertheless bug 5666 says it is
1653                  * used only on server */
1654                 LASSERT(cfs_list_empty(&lock->l_bl_ast));
1655                 cfs_list_add(&lock->l_bl_ast, cancels);
1656                 unlock_res_and_lock(lock);
1657                 lu_ref_del(&lock->l_reference, __FUNCTION__, cfs_current());
1658                 cfs_spin_lock(&ns->ns_lock);
1659                 added++;
1660                 unused--;
1661         }
1662         cfs_spin_unlock(&ns->ns_lock);
1663         RETURN(added);
1664 }
1665
1666 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, cfs_list_t *cancels,
1667                           int count, int max, ldlm_cancel_flags_t cancel_flags,
1668                           int flags)
1669 {
1670         int added;
1671         added = ldlm_prepare_lru_list(ns, cancels, count, max, flags);
1672         if (added <= 0)
1673                 return added;
1674         return ldlm_cli_cancel_list_local(cancels, added, cancel_flags);
1675 }
1676
1677 /* when called with LDLM_ASYNC the blocking callback will be handled
1678  * in a thread and this function will return after the thread has been
1679  * asked to call the callback.  when called with LDLM_SYNC the blocking
1680  * callback will be performed in this function. */
1681 int ldlm_cancel_lru(struct ldlm_namespace *ns, int nr, ldlm_sync_t mode,
1682                     int flags)
1683 {
1684         CFS_LIST_HEAD(cancels);
1685         int count, rc;
1686         ENTRY;
1687
1688 #ifndef __KERNEL__
1689         mode = LDLM_SYNC; /* force to be sync in user space */
1690 #endif
1691         /* Just prepare the list of locks, do not actually cancel them yet.
1692          * Locks are cancelled later in a separate thread. */
1693         count = ldlm_prepare_lru_list(ns, &cancels, nr, 0, flags);
1694         rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count, mode);
1695         if (rc == 0)
1696                 RETURN(count);
1697
1698         RETURN(0);
1699 }
1700
1701 /* Find and cancel locally unused locks found on resource, matched to the
1702  * given policy, mode. GET the found locks and add them into the @cancels
1703  * list. */
1704 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1705                                cfs_list_t *cancels,
1706                                ldlm_policy_data_t *policy,
1707                                ldlm_mode_t mode, int lock_flags,
1708                                ldlm_cancel_flags_t cancel_flags, void *opaque)
1709 {
1710         struct ldlm_lock *lock;
1711         int count = 0;
1712         ENTRY;
1713
1714         lock_res(res);
1715         cfs_list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1716                 if (opaque != NULL && lock->l_ast_data != opaque) {
1717                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1718                                    lock->l_ast_data, opaque);
1719                         //LBUG();
1720                         continue;
1721                 }
1722
1723                 if (lock->l_readers || lock->l_writers)
1724                         continue;
1725
1726                 /* If somebody is already doing CANCEL, or blocking ast came,
1727                  * skip this lock. */
1728                 if (lock->l_flags & LDLM_FL_BL_AST ||
1729                     lock->l_flags & LDLM_FL_CANCELING)
1730                         continue;
1731
1732                 if (lockmode_compat(lock->l_granted_mode, mode))
1733                         continue;
1734
1735                 /* If policy is given and this is IBITS lock, add to list only
1736                  * those locks that match by policy. */
1737                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1738                     !(lock->l_policy_data.l_inodebits.bits &
1739                       policy->l_inodebits.bits))
1740                         continue;
1741
1742                 /* See CBPENDING comment in ldlm_cancel_lru */
1743                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1744                                  lock_flags;
1745
1746                 LASSERT(cfs_list_empty(&lock->l_bl_ast));
1747                 cfs_list_add(&lock->l_bl_ast, cancels);
1748                 LDLM_LOCK_GET(lock);
1749                 count++;
1750         }
1751         unlock_res(res);
1752
1753         RETURN(ldlm_cli_cancel_list_local(cancels, count, cancel_flags));
1754 }
1755
1756 /* If @req is NULL, send CANCEL request to server with handles of locks
1757  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests
1758  * separately per lock.
1759  * If @req is not NULL, put handles of locks in @cancels into the request
1760  * buffer at the offset @off.
1761  * Destroy @cancels at the end. */
1762 int ldlm_cli_cancel_list(cfs_list_t *cancels, int count,
1763                          struct ptlrpc_request *req, ldlm_cancel_flags_t flags)
1764 {
1765         struct ldlm_lock *lock;
1766         int res = 0;
1767         ENTRY;
1768
1769         if (cfs_list_empty(cancels) || count == 0)
1770                 RETURN(0);
1771
1772         /* XXX: requests (both batched and not) could be sent in parallel.
1773          * Usually it is enough to have just 1 RPC, but it is possible that
1774          * there are to many locks to be cancelled in LRU or on a resource.
1775          * It would also speed up the case when the server does not support
1776          * the feature. */
1777         while (count > 0) {
1778                 LASSERT(!cfs_list_empty(cancels));
1779                 lock = cfs_list_entry(cancels->next, struct ldlm_lock,
1780                                       l_bl_ast);
1781                 LASSERT(lock->l_conn_export);
1782
1783                 if (exp_connect_cancelset(lock->l_conn_export)) {
1784                         res = count;
1785                         if (req)
1786                                 ldlm_cancel_pack(req, cancels, count);
1787                         else
1788                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1789                                                           cancels, count,
1790                                                           flags);
1791                 } else {
1792                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1793                                                   cancels, 1, flags);
1794                 }
1795
1796                 if (res < 0) {
1797                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1798                         res = count;
1799                 }
1800
1801                 count -= res;
1802                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1803         }
1804         LASSERT(count == 0);
1805         RETURN(0);
1806 }
1807
1808 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1809                                     const struct ldlm_res_id *res_id,
1810                                     ldlm_policy_data_t *policy,
1811                                     ldlm_mode_t mode,
1812                                     ldlm_cancel_flags_t flags,
1813                                     void *opaque)
1814 {
1815         struct ldlm_resource *res;
1816         CFS_LIST_HEAD(cancels);
1817         int count;
1818         int rc;
1819         ENTRY;
1820
1821         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1822         if (res == NULL) {
1823                 /* This is not a problem. */
1824                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id->name[0]);
1825                 RETURN(0);
1826         }
1827
1828         LDLM_RESOURCE_ADDREF(res);
1829         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
1830                                            0, flags | LCF_BL_AST, opaque);
1831         rc = ldlm_cli_cancel_list(&cancels, count, NULL, flags);
1832         if (rc != ELDLM_OK)
1833                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1834
1835         LDLM_RESOURCE_DELREF(res);
1836         ldlm_resource_putref(res);
1837         RETURN(0);
1838 }
1839
1840 struct ldlm_cli_cancel_arg {
1841         int     lc_flags;
1842         void   *lc_opaque;
1843 };
1844
1845 static int ldlm_cli_hash_cancel_unused(cfs_hash_t *hs, cfs_hash_bd_t *bd,
1846                                        cfs_hlist_node_t *hnode, void *arg)
1847 {
1848         struct ldlm_resource           *res = cfs_hash_object(hs, hnode);
1849         struct ldlm_cli_cancel_arg     *lc = arg;
1850         int                             rc;
1851
1852         rc = ldlm_cli_cancel_unused_resource(ldlm_res_to_ns(res), &res->lr_name,
1853                                              NULL, LCK_MINMODE,
1854                                              lc->lc_flags, lc->lc_opaque);
1855         if (rc != 0) {
1856                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1857                        res->lr_name.name[0], rc);
1858         }
1859         /* must return 0 for hash iteration */
1860         return 0;
1861 }
1862
1863 /* Cancel all locks on a namespace (or a specific resource, if given)
1864  * that have 0 readers/writers.
1865  *
1866  * If flags & LCF_LOCAL, throw the locks away without trying
1867  * to notify the server. */
1868 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1869                            const struct ldlm_res_id *res_id,
1870                            ldlm_cancel_flags_t flags, void *opaque)
1871 {
1872         struct ldlm_cli_cancel_arg arg = {
1873                 .lc_flags       = flags,
1874                 .lc_opaque      = opaque,
1875         };
1876
1877         ENTRY;
1878
1879         if (ns == NULL)
1880                 RETURN(ELDLM_OK);
1881
1882         if (res_id != NULL) {
1883                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
1884                                                        LCK_MINMODE, flags,
1885                                                        opaque));
1886         } else {
1887                 cfs_hash_for_each_nolock(ns->ns_rs_hash,
1888                                          ldlm_cli_hash_cancel_unused, &arg);
1889                 RETURN(ELDLM_OK);
1890         }
1891 }
1892
1893 /* Lock iterators. */
1894
1895 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1896                           void *closure)
1897 {
1898         cfs_list_t *tmp, *next;
1899         struct ldlm_lock *lock;
1900         int rc = LDLM_ITER_CONTINUE;
1901
1902         ENTRY;
1903
1904         if (!res)
1905                 RETURN(LDLM_ITER_CONTINUE);
1906
1907         lock_res(res);
1908         cfs_list_for_each_safe(tmp, next, &res->lr_granted) {
1909                 lock = cfs_list_entry(tmp, struct ldlm_lock, l_res_link);
1910
1911                 if (iter(lock, closure) == LDLM_ITER_STOP)
1912                         GOTO(out, rc = LDLM_ITER_STOP);
1913         }
1914
1915         cfs_list_for_each_safe(tmp, next, &res->lr_converting) {
1916                 lock = cfs_list_entry(tmp, struct ldlm_lock, l_res_link);
1917
1918                 if (iter(lock, closure) == LDLM_ITER_STOP)
1919                         GOTO(out, rc = LDLM_ITER_STOP);
1920         }
1921
1922         cfs_list_for_each_safe(tmp, next, &res->lr_waiting) {
1923                 lock = cfs_list_entry(tmp, struct ldlm_lock, l_res_link);
1924
1925                 if (iter(lock, closure) == LDLM_ITER_STOP)
1926                         GOTO(out, rc = LDLM_ITER_STOP);
1927         }
1928  out:
1929         unlock_res(res);
1930         RETURN(rc);
1931 }
1932
1933 struct iter_helper_data {
1934         ldlm_iterator_t iter;
1935         void *closure;
1936 };
1937
1938 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1939 {
1940         struct iter_helper_data *helper = closure;
1941         return helper->iter(lock, helper->closure);
1942 }
1943
1944 static int ldlm_res_iter_helper(cfs_hash_t *hs, cfs_hash_bd_t *bd,
1945                                 cfs_hlist_node_t *hnode, void *arg)
1946
1947 {
1948         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
1949
1950         return ldlm_resource_foreach(res, ldlm_iter_helper, arg) ==
1951                LDLM_ITER_STOP;
1952 }
1953
1954 void ldlm_namespace_foreach(struct ldlm_namespace *ns,
1955                             ldlm_iterator_t iter, void *closure)
1956
1957 {
1958         struct iter_helper_data helper = { iter: iter, closure: closure };
1959
1960         cfs_hash_for_each_nolock(ns->ns_rs_hash,
1961                                  ldlm_res_iter_helper, &helper);
1962
1963 }
1964
1965 /* non-blocking function to manipulate a lock whose cb_data is being put away.
1966  * return  0:  find no resource
1967  *       > 0:  must be LDLM_ITER_STOP/LDLM_ITER_CONTINUE.
1968  *       < 0:  errors
1969  */
1970 int ldlm_resource_iterate(struct ldlm_namespace *ns,
1971                           const struct ldlm_res_id *res_id,
1972                           ldlm_iterator_t iter, void *data)
1973 {
1974         struct ldlm_resource *res;
1975         int rc;
1976         ENTRY;
1977
1978         if (ns == NULL) {
1979                 CERROR("must pass in namespace\n");
1980                 LBUG();
1981         }
1982
1983         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1984         if (res == NULL)
1985                 RETURN(0);
1986
1987         LDLM_RESOURCE_ADDREF(res);
1988         rc = ldlm_resource_foreach(res, iter, data);
1989         LDLM_RESOURCE_DELREF(res);
1990         ldlm_resource_putref(res);
1991         RETURN(rc);
1992 }
1993
1994 /* Lock replay */
1995
1996 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
1997 {
1998         cfs_list_t *list = closure;
1999
2000         /* we use l_pending_chain here, because it's unused on clients. */
2001         LASSERTF(cfs_list_empty(&lock->l_pending_chain),
2002                  "lock %p next %p prev %p\n",
2003                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
2004         /* bug 9573: don't replay locks left after eviction, or
2005          * bug 17614: locks being actively cancelled. Get a reference
2006          * on a lock so that it does not disapear under us (e.g. due to cancel)
2007          */
2008         if (!(lock->l_flags & (LDLM_FL_FAILED|LDLM_FL_CANCELING))) {
2009                 cfs_list_add(&lock->l_pending_chain, list);
2010                 LDLM_LOCK_GET(lock);
2011         }
2012
2013         return LDLM_ITER_CONTINUE;
2014 }
2015
2016 static int replay_lock_interpret(const struct lu_env *env,
2017                                  struct ptlrpc_request *req,
2018                                  struct ldlm_async_args *aa, int rc)
2019 {
2020         struct ldlm_lock     *lock;
2021         struct ldlm_reply    *reply;
2022         struct obd_export    *exp;
2023
2024         ENTRY;
2025         cfs_atomic_dec(&req->rq_import->imp_replay_inflight);
2026         if (rc != ELDLM_OK)
2027                 GOTO(out, rc);
2028
2029
2030         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2031         if (reply == NULL)
2032                 GOTO(out, rc = -EPROTO);
2033
2034         lock = ldlm_handle2lock(&aa->lock_handle);
2035         if (!lock) {
2036                 CERROR("received replay ack for unknown local cookie "LPX64
2037                        " remote cookie "LPX64 " from server %s id %s\n",
2038                        aa->lock_handle.cookie, reply->lock_handle.cookie,
2039                        req->rq_export->exp_client_uuid.uuid,
2040                        libcfs_id2str(req->rq_peer));
2041                 GOTO(out, rc = -ESTALE);
2042         }
2043
2044         /* Key change rehash lock in per-export hash with new key */
2045         exp = req->rq_export;
2046         if (exp && exp->exp_lock_hash) {
2047                 cfs_hash_rehash_key(exp->exp_lock_hash,
2048                                     &lock->l_remote_handle,
2049                                     &reply->lock_handle,
2050                                     &lock->l_exp_hash);
2051         } else {
2052                 lock->l_remote_handle = reply->lock_handle;
2053         }
2054
2055         LDLM_DEBUG(lock, "replayed lock:");
2056         ptlrpc_import_recovery_state_machine(req->rq_import);
2057         LDLM_LOCK_PUT(lock);
2058 out:
2059         if (rc != ELDLM_OK)
2060                 ptlrpc_connect_import(req->rq_import);
2061
2062         RETURN(rc);
2063 }
2064
2065 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
2066 {
2067         struct ptlrpc_request *req;
2068         struct ldlm_async_args *aa;
2069         struct ldlm_request   *body;
2070         int flags;
2071         ENTRY;
2072
2073
2074         /* Bug 11974: Do not replay a lock which is actively being canceled */
2075         if (lock->l_flags & LDLM_FL_CANCELING) {
2076                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
2077                 RETURN(0);
2078         }
2079
2080         /* If this is reply-less callback lock, we cannot replay it, since
2081          * server might have long dropped it, but notification of that event was
2082          * lost by network. (and server granted conflicting lock already) */
2083         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
2084                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
2085                 ldlm_lock_cancel(lock);
2086                 RETURN(0);
2087         }
2088         /*
2089          * If granted mode matches the requested mode, this lock is granted.
2090          *
2091          * If they differ, but we have a granted mode, then we were granted
2092          * one mode and now want another: ergo, converting.
2093          *
2094          * If we haven't been granted anything and are on a resource list,
2095          * then we're blocked/waiting.
2096          *
2097          * If we haven't been granted anything and we're NOT on a resource list,
2098          * then we haven't got a reply yet and don't have a known disposition.
2099          * This happens whenever a lock enqueue is the request that triggers
2100          * recovery.
2101          */
2102         if (lock->l_granted_mode == lock->l_req_mode)
2103                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
2104         else if (lock->l_granted_mode)
2105                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
2106         else if (!cfs_list_empty(&lock->l_res_link))
2107                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
2108         else
2109                 flags = LDLM_FL_REPLAY;
2110
2111         req = ptlrpc_request_alloc_pack(imp, &RQF_LDLM_ENQUEUE,
2112                                         LUSTRE_DLM_VERSION, LDLM_ENQUEUE);
2113         if (req == NULL)
2114                 RETURN(-ENOMEM);
2115
2116         /* We're part of recovery, so don't wait for it. */
2117         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
2118
2119         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2120         ldlm_lock2desc(lock, &body->lock_desc);
2121         body->lock_flags = flags;
2122
2123         ldlm_lock2handle(lock, &body->lock_handle[0]);
2124         if (lock->l_lvb_len != 0) {
2125                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_ENQUEUE_LVB);
2126                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2127                                      lock->l_lvb_len);
2128         }
2129         ptlrpc_request_set_replen(req);
2130         /* notify the server we've replayed all requests.
2131          * also, we mark the request to be put on a dedicated
2132          * queue to be processed after all request replayes.
2133          * bug 6063 */
2134         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
2135
2136         LDLM_DEBUG(lock, "replaying lock:");
2137
2138         cfs_atomic_inc(&req->rq_import->imp_replay_inflight);
2139         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2140         aa = ptlrpc_req_async_args(req);
2141         aa->lock_handle = body->lock_handle[0];
2142         req->rq_interpret_reply = (ptlrpc_interpterer_t)replay_lock_interpret;
2143         ptlrpcd_add_req(req, PDL_POLICY_LOCAL, -1);
2144
2145         RETURN(0);
2146 }
2147
2148 /**
2149  * Cancel as many unused locks as possible before replay. since we are
2150  * in recovery, we can't wait for any outstanding RPCs to send any RPC
2151  * to the server.
2152  *
2153  * Called only in recovery before replaying locks. there is no need to
2154  * replay locks that are unused. since the clients may hold thousands of
2155  * cached unused locks, dropping the unused locks can greatly reduce the
2156  * load on the servers at recovery time.
2157  */
2158 static void ldlm_cancel_unused_locks_for_replay(struct ldlm_namespace *ns)
2159 {
2160         int canceled;
2161         CFS_LIST_HEAD(cancels);
2162
2163         CDEBUG(D_DLMTRACE, "Dropping as many unused locks as possible before"
2164                            "replay for namespace %s (%d)\n",
2165                            ldlm_ns_name(ns), ns->ns_nr_unused);
2166
2167         /* We don't need to care whether or not LRU resize is enabled
2168          * because the LDLM_CANCEL_NO_WAIT policy doesn't use the
2169          * count parameter */
2170         canceled = ldlm_cancel_lru_local(ns, &cancels, ns->ns_nr_unused, 0,
2171                                          LCF_LOCAL, LDLM_CANCEL_NO_WAIT);
2172
2173         CDEBUG(D_DLMTRACE, "Canceled %d unused locks from namespace %s\n",
2174                            canceled, ldlm_ns_name(ns));
2175 }
2176
2177 int ldlm_replay_locks(struct obd_import *imp)
2178 {
2179         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
2180         CFS_LIST_HEAD(list);
2181         struct ldlm_lock *lock, *next;
2182         int rc = 0;
2183
2184         ENTRY;
2185
2186         LASSERT(cfs_atomic_read(&imp->imp_replay_inflight) == 0);
2187
2188         /* don't replay locks if import failed recovery */
2189         if (imp->imp_vbr_failed)
2190                 RETURN(0);
2191
2192         /* ensure this doesn't fall to 0 before all have been queued */
2193         cfs_atomic_inc(&imp->imp_replay_inflight);
2194
2195         if (ldlm_cancel_unused_locks_before_replay)
2196                 ldlm_cancel_unused_locks_for_replay(ns);
2197
2198         ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
2199
2200         cfs_list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
2201                 cfs_list_del_init(&lock->l_pending_chain);
2202                 if (rc) {
2203                         LDLM_LOCK_RELEASE(lock);
2204                         continue; /* or try to do the rest? */
2205                 }
2206                 rc = replay_one_lock(imp, lock);
2207                 LDLM_LOCK_RELEASE(lock);
2208         }
2209
2210         cfs_atomic_dec(&imp->imp_replay_inflight);
2211
2212         RETURN(rc);
2213 }