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