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