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