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