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