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