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