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