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