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