Whamcloud - gitweb
6bf1efe2a5f344365ecab914907f180e049208f0
[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         if (likely(avail >= 0))
611                 avail /= (int)sizeof(struct lustre_handle);
612         else
613                 avail = 0;
614         avail += LDLM_LOCKREQ_HANDLES - off;
615
616         return avail;
617 }
618
619 static inline int ldlm_capsule_handles_avail(struct req_capsule *pill,
620                                              enum req_location loc,
621                                              int off)
622 {
623         int size = req_capsule_msg_size(pill, loc);
624         return ldlm_req_handles_avail(size, off);
625 }
626
627 static inline int ldlm_format_handles_avail(struct obd_import *imp,
628                                             const struct req_format *fmt,
629                                             enum req_location loc, int off)
630 {
631         int size = req_capsule_fmt_size(imp->imp_msg_magic, fmt, loc);
632         return ldlm_req_handles_avail(size, off);
633 }
634
635 /* Cancel lru locks and pack them into the enqueue request. Pack there the given
636  * @count locks in @cancels. */
637 int ldlm_prep_elc_req(struct obd_export *exp, struct ptlrpc_request *req,
638                       int version, int opc, int canceloff,
639                       struct list_head *cancels, int count)
640 {
641         struct ldlm_namespace   *ns = exp->exp_obd->obd_namespace;
642         struct req_capsule      *pill = &req->rq_pill;
643         struct ldlm_request     *dlm = NULL;
644         int flags, avail, to_free, bufcount, pack = 0;
645         CFS_LIST_HEAD(head);
646         int rc;
647         ENTRY;
648
649         if (cancels == NULL)
650                 cancels = &head;
651         if (exp_connect_cancelset(exp)) {
652                 /* Estimate the amount of available space in the request. */
653                 bufcount = req_capsule_filled_sizes(pill, RCL_CLIENT);
654                 avail = ldlm_capsule_handles_avail(pill, RCL_CLIENT, canceloff);
655
656                 flags = ns_connect_lru_resize(ns) ?
657                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
658                 to_free = !ns_connect_lru_resize(ns) &&
659                           opc == LDLM_ENQUEUE ? 1 : 0;
660
661                 /* Cancel lru locks here _only_ if the server supports
662                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
663                  * rpc, what will make us slower. */
664                 if (avail > count)
665                         count += ldlm_cancel_lru_local(ns, cancels, to_free,
666                                                        avail - count, 0, flags);
667                 if (avail > count)
668                         pack = count;
669                 else
670                         pack = avail;
671                 req_capsule_set_size(pill, &RMF_DLM_REQ, RCL_CLIENT,
672                                      ldlm_request_bufsize(pack, opc));
673         }
674
675         rc = ptlrpc_request_pack(req, version, opc);
676         if (rc) {
677                 ldlm_lock_list_put(cancels, l_bl_ast, count);
678                 RETURN(rc);
679         }
680
681         if (exp_connect_cancelset(exp)) {
682                 if (canceloff) {
683                         dlm = req_capsule_client_get(pill, &RMF_DLM_REQ);
684                         LASSERT(dlm);
685                         /* Skip first lock handler in ldlm_request_pack(),
686                          * this method will incrment @lock_count according
687                          * to the lock handle amount actually written to
688                          * the buffer. */
689                         dlm->lock_count = canceloff;
690                 }
691                 /* Pack into the request @pack lock handles. */
692                 ldlm_cli_cancel_list(cancels, pack, req, 0);
693                 /* Prepare and send separate cancel rpc for others. */
694                 ldlm_cli_cancel_list(cancels, count - pack, NULL, 0);
695         } else {
696                 ldlm_lock_list_put(cancels, l_bl_ast, count);
697         }
698         RETURN(0);
699 }
700
701 int ldlm_prep_enqueue_req(struct obd_export *exp, struct ptlrpc_request *req,
702                           struct list_head *cancels, int count)
703 {
704         return ldlm_prep_elc_req(exp, req, LUSTRE_DLM_VERSION, LDLM_ENQUEUE,
705                                  LDLM_ENQUEUE_CANCEL_OFF, cancels, count);
706 }
707
708 /* If a request has some specific initialisation it is passed in @reqp,
709  * otherwise it is created in ldlm_cli_enqueue.
710  *
711  * Supports sync and async requests, pass @async flag accordingly. If a
712  * request was created in ldlm_cli_enqueue and it is the async request,
713  * pass it to the caller in @reqp. */
714 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
715                      struct ldlm_enqueue_info *einfo,
716                      const struct ldlm_res_id *res_id,
717                      ldlm_policy_data_t *policy, int *flags,
718                      void *lvb, __u32 lvb_len, void *lvb_swabber,
719                      struct lustre_handle *lockh, int async)
720 {
721         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
722         struct ldlm_lock      *lock;
723         struct ldlm_request   *body;
724         int                    is_replay = *flags & LDLM_FL_REPLAY;
725         int                    req_passed_in = 1;
726         int                    rc, err;
727         struct ptlrpc_request *req;
728         ENTRY;
729
730         LASSERT(exp != NULL);
731
732         /* If we're replaying this lock, just check some invariants.
733          * If we're creating a new lock, get everything all setup nice. */
734         if (is_replay) {
735                 lock = ldlm_handle2lock_long(lockh, 0);
736                 LASSERT(lock != NULL);
737                 LDLM_DEBUG(lock, "client-side enqueue START");
738                 LASSERT(exp == lock->l_conn_export);
739         } else {
740                 const struct ldlm_callback_suite cbs = {
741                         .lcs_completion = einfo->ei_cb_cp,
742                         .lcs_blocking   = einfo->ei_cb_bl,
743                         .lcs_glimpse    = einfo->ei_cb_gl,
744                         .lcs_weigh      = einfo->ei_cb_wg
745                 };
746                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
747                                         einfo->ei_mode, &cbs, einfo->ei_cbdata,
748                                         lvb_len);
749                 if (lock == NULL)
750                         RETURN(-ENOMEM);
751                 /* for the local lock, add the reference */
752                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
753                 ldlm_lock2handle(lock, lockh);
754                 lock->l_lvb_swabber = lvb_swabber;
755                 if (policy != NULL) {
756                         /* INODEBITS_INTEROP: If the server does not support
757                          * inodebits, we will request a plain lock in the
758                          * descriptor (ldlm_lock2desc() below) but use an
759                          * inodebits lock internally with both bits set.
760                          */
761                         if (einfo->ei_type == LDLM_IBITS &&
762                             !(exp->exp_connect_flags & OBD_CONNECT_IBITS))
763                                 lock->l_policy_data.l_inodebits.bits =
764                                         MDS_INODELOCK_LOOKUP |
765                                         MDS_INODELOCK_UPDATE;
766                         else
767                                 lock->l_policy_data = *policy;
768                 }
769
770                 if (einfo->ei_type == LDLM_EXTENT)
771                         lock->l_req_extent = policy->l_extent;
772                 LDLM_DEBUG(lock, "client-side enqueue START");
773         }
774
775         /* lock not sent to server yet */
776
777         if (reqp == NULL || *reqp == NULL) {
778                 req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
779                                                 &RQF_LDLM_ENQUEUE,
780                                                 LUSTRE_DLM_VERSION,
781                                                 LDLM_ENQUEUE);
782                 if (req == NULL) {
783                         failed_lock_cleanup(ns, lock, lockh, einfo->ei_mode);
784                         LDLM_LOCK_RELEASE(lock);
785                         RETURN(-ENOMEM);
786                 }
787                 req_passed_in = 0;
788                 if (reqp)
789                         *reqp = req;
790         } else {
791                 int len;
792
793                 req = *reqp;
794                 len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ,
795                                            RCL_CLIENT);
796                 LASSERTF(len >= sizeof(*body), "buflen[%d] = %d, not %d\n",
797                          DLM_LOCKREQ_OFF, len, (int)sizeof(*body));
798         }
799
800         lock->l_conn_export = exp;
801         lock->l_export = NULL;
802         lock->l_blocking_ast = einfo->ei_cb_bl;
803
804         /* Dump lock data into the request buffer */
805         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
806         ldlm_lock2desc(lock, &body->lock_desc);
807         body->lock_flags = *flags;
808         body->lock_handle[0] = *lockh;
809
810         /* Continue as normal. */
811         if (!req_passed_in) {
812                 if (lvb_len > 0) {
813                         req_capsule_extend(&req->rq_pill,
814                                            &RQF_LDLM_ENQUEUE_LVB);
815                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
816                                              RCL_SERVER, lvb_len);
817                 }
818                 ptlrpc_request_set_replen(req);
819         }
820
821         /*
822          * Liblustre client doesn't get extent locks, except for O_APPEND case
823          * where [0, OBD_OBJECT_EOF] lock is taken, or truncate, where
824          * [i_size, OBD_OBJECT_EOF] lock is taken.
825          */
826         LASSERT(ergo(LIBLUSTRE_CLIENT, einfo->ei_type != LDLM_EXTENT ||
827                      policy->l_extent.end == OBD_OBJECT_EOF));
828
829         if (async) {
830                 LASSERT(reqp != NULL);
831                 RETURN(0);
832         }
833
834         LDLM_DEBUG(lock, "sending request");
835         rc = ptlrpc_queue_wait(req);
836         err = ldlm_cli_enqueue_fini(exp, req, einfo->ei_type, policy ? 1 : 0,
837                                     einfo->ei_mode, flags, lvb, lvb_len,
838                                     lvb_swabber, lockh, rc);
839
840         /* If ldlm_cli_enqueue_fini did not find the lock, we need to free
841          * one reference that we took */
842         if (err == -ENOLCK)
843                 LDLM_LOCK_RELEASE(lock);
844         else
845                 rc = err;
846
847         if (!req_passed_in && req != NULL) {
848                 ptlrpc_req_finished(req);
849                 if (reqp)
850                         *reqp = NULL;
851         }
852
853         RETURN(rc);
854 }
855
856 static int ldlm_cli_convert_local(struct ldlm_lock *lock, int new_mode,
857                                   __u32 *flags)
858 {
859         struct ldlm_resource *res;
860         int rc;
861         ENTRY;
862         if (ns_is_client(lock->l_resource->lr_namespace)) {
863                 CERROR("Trying to cancel local lock\n");
864                 LBUG();
865         }
866         LDLM_DEBUG(lock, "client-side local convert");
867
868         res = ldlm_lock_convert(lock, new_mode, flags);
869         if (res) {
870                 ldlm_reprocess_all(res);
871                 rc = 0;
872         } else {
873                 rc = EDEADLOCK;
874         }
875         LDLM_DEBUG(lock, "client-side local convert handler END");
876         LDLM_LOCK_PUT(lock);
877         RETURN(rc);
878 }
879
880 /* FIXME: one of ldlm_cli_convert or the server side should reject attempted
881  * conversion of locks which are on the waiting or converting queue */
882 /* Caller of this code is supposed to take care of lock readers/writers
883    accounting */
884 int ldlm_cli_convert(struct lustre_handle *lockh, int new_mode, __u32 *flags)
885 {
886         struct ldlm_request   *body;
887         struct ldlm_reply     *reply;
888         struct ldlm_lock      *lock;
889         struct ldlm_resource  *res;
890         struct ptlrpc_request *req;
891         int                    rc;
892         ENTRY;
893
894         lock = ldlm_handle2lock(lockh);
895         if (!lock) {
896                 LBUG();
897                 RETURN(-EINVAL);
898         }
899         *flags = 0;
900
901         if (lock->l_conn_export == NULL)
902                 RETURN(ldlm_cli_convert_local(lock, new_mode, flags));
903
904         LDLM_DEBUG(lock, "client-side convert");
905
906         req = ptlrpc_request_alloc_pack(class_exp2cliimp(lock->l_conn_export),
907                                         &RQF_LDLM_CONVERT, LUSTRE_DLM_VERSION,
908                                         LDLM_CONVERT);
909         if (req == NULL) {
910                 LDLM_LOCK_PUT(lock);
911                 RETURN(-ENOMEM);
912         }
913
914         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
915         body->lock_handle[0] = lock->l_remote_handle;
916
917         body->lock_desc.l_req_mode = new_mode;
918         body->lock_flags = *flags;
919
920
921         ptlrpc_request_set_replen(req);
922         rc = ptlrpc_queue_wait(req);
923         if (rc != ELDLM_OK)
924                 GOTO(out, rc);
925
926         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
927         if (reply == NULL)
928                 GOTO(out, rc = -EPROTO);
929
930         if (req->rq_status)
931                 GOTO(out, rc = req->rq_status);
932
933         res = ldlm_lock_convert(lock, new_mode, &reply->lock_flags);
934         if (res != NULL) {
935                 ldlm_reprocess_all(res);
936                 /* Go to sleep until the lock is granted. */
937                 /* FIXME: or cancelled. */
938                 if (lock->l_completion_ast) {
939                         rc = lock->l_completion_ast(lock, LDLM_FL_WAIT_NOREPROC,
940                                                     NULL);
941                         if (rc)
942                                 GOTO(out, rc);
943                 }
944         } else {
945                 rc = EDEADLOCK;
946         }
947         EXIT;
948  out:
949         LDLM_LOCK_PUT(lock);
950         ptlrpc_req_finished(req);
951         return rc;
952 }
953
954 /* Cancel locks locally.
955  * Returns:
956  * LDLM_FL_LOCAL_ONLY if tere is no need in a CANCEL rpc to the server;
957  * LDLM_FL_CANCELING otherwise;
958  * LDLM_FL_BL_AST if there is a need in a separate CANCEL rpc. */
959 static int ldlm_cli_cancel_local(struct ldlm_lock *lock)
960 {
961         int rc = LDLM_FL_LOCAL_ONLY;
962         ENTRY;
963
964         if (lock->l_conn_export) {
965                 int local_only;
966
967                 LDLM_DEBUG(lock, "client-side cancel");
968                 /* Set this flag to prevent others from getting new references*/
969                 lock_res_and_lock(lock);
970                 lock->l_flags |= LDLM_FL_CBPENDING;
971                 local_only = (lock->l_flags &
972                               (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
973                 ldlm_cancel_callback(lock);
974                 rc = (lock->l_flags & LDLM_FL_BL_AST) ?
975                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
976                 unlock_res_and_lock(lock);
977
978                 if (local_only) {
979                         CDEBUG(D_DLMTRACE, "not sending request (at caller's "
980                                "instruction)\n");
981                         rc = LDLM_FL_LOCAL_ONLY;
982                 }
983                 ldlm_lock_cancel(lock);
984         } else {
985                 if (ns_is_client(lock->l_resource->lr_namespace)) {
986                         LDLM_ERROR(lock, "Trying to cancel local lock");
987                         LBUG();
988                 }
989                 LDLM_DEBUG(lock, "server-side local cancel");
990                 ldlm_lock_cancel(lock);
991                 ldlm_reprocess_all(lock->l_resource);
992                 LDLM_DEBUG(lock, "server-side local cancel handler END");
993         }
994
995         RETURN(rc);
996 }
997
998 /* Pack @count locks in @head into ldlm_request buffer at the offset @off,
999    of the request @req. */
1000 static void ldlm_cancel_pack(struct ptlrpc_request *req,
1001                              struct list_head *head, int count)
1002 {
1003         struct ldlm_request *dlm;
1004         struct ldlm_lock *lock;
1005         int max, packed = 0;
1006         ENTRY;
1007
1008         dlm = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1009         LASSERT(dlm != NULL);
1010
1011         /* Check the room in the request buffer. */
1012         max = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT) -
1013                 sizeof(struct ldlm_request);
1014         max /= sizeof(struct lustre_handle);
1015         max += LDLM_LOCKREQ_HANDLES;
1016         LASSERT(max >= dlm->lock_count + count);
1017
1018         /* XXX: it would be better to pack lock handles grouped by resource.
1019          * so that the server cancel would call filter_lvbo_update() less
1020          * frequently. */
1021         list_for_each_entry(lock, head, l_bl_ast) {
1022                 if (!count--)
1023                         break;
1024                 LASSERT(lock->l_conn_export);
1025                 /* Pack the lock handle to the given request buffer. */
1026                 LDLM_DEBUG(lock, "packing");
1027                 dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
1028                 packed++;
1029         }
1030         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
1031         EXIT;
1032 }
1033
1034 /* Prepare and send a batched cancel rpc, it will include count lock handles
1035  * of locks given in @head. */
1036 int ldlm_cli_cancel_req(struct obd_export *exp, struct list_head *cancels,
1037                         int count, int flags)
1038 {
1039         struct ptlrpc_request *req = NULL;
1040         struct obd_import *imp;
1041         int free, sent = 0;
1042         int rc = 0;
1043         ENTRY;
1044
1045         LASSERT(exp != NULL);
1046         LASSERT(count > 0);
1047
1048         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL, obd_fail_val);
1049
1050         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
1051                 RETURN(count);
1052
1053         free = ldlm_format_handles_avail(class_exp2cliimp(exp),
1054                                          &RQF_LDLM_CANCEL, RCL_CLIENT, 0);
1055         if (count > free)
1056                 count = free;
1057
1058         while (1) {
1059                 int bufcount;
1060
1061                 imp = class_exp2cliimp(exp);
1062                 if (imp == NULL || imp->imp_invalid) {
1063                         CDEBUG(D_DLMTRACE,
1064                                "skipping cancel on invalid import %p\n", imp);
1065                         RETURN(count);
1066                 }
1067
1068                 req = ptlrpc_request_alloc(imp, &RQF_LDLM_CANCEL);
1069                 if (req == NULL)
1070                         GOTO(out, rc = -ENOMEM);
1071
1072                 bufcount = req_capsule_filled_sizes(&req->rq_pill, RCL_CLIENT);
1073                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT,
1074                                      ldlm_request_bufsize(count, LDLM_CANCEL));
1075
1076                 rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CANCEL);
1077                 if (rc) {
1078                         ptlrpc_request_free(req);
1079                         GOTO(out, rc);
1080                 }
1081                 req->rq_no_resend = 1;
1082                 req->rq_no_delay = 1;
1083
1084                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1085                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1086                 ptlrpc_at_set_req_timeout(req);
1087
1088                 ldlm_cancel_pack(req, cancels, count);
1089
1090                 ptlrpc_request_set_replen(req);
1091                 if (flags & LDLM_FL_ASYNC) {
1092                         ptlrpcd_add_req(req);
1093                         sent = count;
1094                         GOTO(out, 0);
1095                 } else {
1096                         rc = ptlrpc_queue_wait(req);
1097                 }
1098                 if (rc == ESTALE) {
1099                         CDEBUG(D_DLMTRACE, "client/server (nid %s) "
1100                                "out of sync -- not fatal\n",
1101                                libcfs_nid2str(req->rq_import->
1102                                               imp_connection->c_peer.nid));
1103                         rc = 0;
1104                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1105                            req->rq_import_generation == imp->imp_generation) {
1106                         ptlrpc_req_finished(req);
1107                         continue;
1108                 } else if (rc != ELDLM_OK) {
1109                         CERROR("Got rc %d from cancel RPC: canceling "
1110                                "anyway\n", rc);
1111                         break;
1112                 }
1113                 sent = count;
1114                 break;
1115         }
1116
1117         ptlrpc_req_finished(req);
1118         EXIT;
1119 out:
1120         return sent ? sent : rc;
1121 }
1122
1123 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1124 {
1125         LASSERT(imp != NULL);
1126         return &imp->imp_obd->obd_namespace->ns_pool;
1127 }
1128
1129 /**
1130  * Update client's obd pool related fields with new SLV and Limit from \a req.
1131  */
1132 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1133 {
1134         struct obd_device *obd;
1135         __u64 old_slv, new_slv;
1136         __u32 new_limit;
1137         ENTRY;
1138
1139         if (unlikely(!req->rq_import || !req->rq_import->imp_obd ||
1140                      !imp_connect_lru_resize(req->rq_import)))
1141         {
1142                 /*
1143                  * Do nothing for corner cases.
1144                  */
1145                 RETURN(0);
1146         }
1147
1148         /*
1149          * In some cases RPC may contain slv and limit zeroed out. This is
1150          * the case when server does not support lru resize feature. This is
1151          * also possible in some recovery cases when server side reqs have no
1152          * ref to obd export and thus access to server side namespace is no
1153          * possible.
1154          */
1155         if (lustre_msg_get_slv(req->rq_repmsg) == 0 ||
1156             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1157                 DEBUG_REQ(D_HA, req, "Zero SLV or Limit found "
1158                           "(SLV: "LPU64", Limit: %u)",
1159                           lustre_msg_get_slv(req->rq_repmsg),
1160                           lustre_msg_get_limit(req->rq_repmsg));
1161                 RETURN(0);
1162         }
1163
1164         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1165         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1166         obd = req->rq_import->imp_obd;
1167
1168         /*
1169          * Set new SLV and Limit to obd fields to make accessible for pool
1170          * thread. We do not access obd_namespace and pool directly here
1171          * as there is no reliable way to make sure that they are still
1172          * alive in cleanup time. Evil races are possible which may cause
1173          * oops in that time.
1174          */
1175         write_lock(&obd->obd_pool_lock);
1176         old_slv = obd->obd_pool_slv;
1177         obd->obd_pool_slv = new_slv;
1178         obd->obd_pool_limit = new_limit;
1179         write_unlock(&obd->obd_pool_lock);
1180
1181         RETURN(0);
1182 }
1183 EXPORT_SYMBOL(ldlm_cli_update_pool);
1184
1185 int ldlm_cli_cancel(struct lustre_handle *lockh)
1186 {
1187         struct obd_export *exp;
1188         int avail, flags, count = 1, rc = 0;
1189         struct ldlm_namespace *ns;
1190         struct ldlm_lock *lock;
1191         CFS_LIST_HEAD(cancels);
1192         ENTRY;
1193
1194         /* concurrent cancels on the same handle can happen */
1195         lock = ldlm_handle2lock_long(lockh, LDLM_FL_CANCELING);
1196         if (lock == NULL) {
1197                 LDLM_DEBUG_NOLOCK("lock is already being destroyed\n");
1198                 RETURN(0);
1199         }
1200
1201         rc = ldlm_cli_cancel_local(lock);
1202         if (rc < 0 || rc == LDLM_FL_LOCAL_ONLY) {
1203                 LDLM_LOCK_RELEASE(lock);
1204                 RETURN(rc < 0 ? rc : 0);
1205         }
1206         /* Even if the lock is marked as LDLM_FL_BL_AST, this is a LDLM_CANCEL
1207          * rpc which goes to canceld portal, so we can cancel other lru locks
1208          * here and send them all as one LDLM_CANCEL rpc. */
1209         LASSERT(list_empty(&lock->l_bl_ast));
1210         list_add(&lock->l_bl_ast, &cancels);
1211
1212         exp = lock->l_conn_export;
1213         if (exp_connect_cancelset(exp)) {
1214                 avail = ldlm_format_handles_avail(class_exp2cliimp(exp),
1215                                                   &RQF_LDLM_CANCEL,
1216                                                   RCL_CLIENT, 0);
1217                 LASSERT(avail > 0);
1218
1219                 ns = lock->l_resource->lr_namespace;
1220                 flags = ns_connect_lru_resize(ns) ?
1221                         LDLM_CANCEL_LRUR : LDLM_CANCEL_AGED;
1222                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1223                                                LDLM_FL_BL_AST, flags);
1224         }
1225         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1226         RETURN(0);
1227 }
1228
1229 /* XXX until we will have compound requests and can cut cancels from generic rpc
1230  * we need send cancels with LDLM_FL_BL_AST flag as separate rpc */
1231 static int ldlm_cancel_list(struct list_head *cancels, int count, int flags)
1232 {
1233         CFS_LIST_HEAD(head);
1234         struct ldlm_lock *lock, *next;
1235         int left = 0, bl_ast = 0, rc;
1236
1237         left = count;
1238         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1239                 if (left-- == 0)
1240                         break;
1241
1242                 if (flags & LDLM_FL_LOCAL_ONLY) {
1243                         rc = LDLM_FL_LOCAL_ONLY;
1244                         ldlm_lock_cancel(lock);
1245                 } else {
1246                         rc = ldlm_cli_cancel_local(lock);
1247                 }
1248                 if (!(flags & LDLM_FL_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1249                         LDLM_DEBUG(lock, "Cancel lock separately");
1250                         list_del_init(&lock->l_bl_ast);
1251                         list_add(&lock->l_bl_ast, &head);
1252                         bl_ast ++;
1253                         continue;
1254                 }
1255                 if (rc == LDLM_FL_LOCAL_ONLY) {
1256                         /* CANCEL RPC should not be sent to server. */
1257                         list_del_init(&lock->l_bl_ast);
1258                         LDLM_LOCK_RELEASE(lock);
1259                         count--;
1260                 }
1261
1262         }
1263         if (bl_ast > 0) {
1264                 count -= bl_ast;
1265                 ldlm_cli_cancel_list(&head, bl_ast, NULL, 0);
1266         }
1267
1268         RETURN(count);
1269 }
1270
1271 /**
1272  * Callback function for shrink policy. Makes decision whether to keep
1273  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1274  * \a added and number of locks to be preferably canceled \a count.
1275  *
1276  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1277  *
1278  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1279  */
1280 static ldlm_policy_res_t ldlm_cancel_shrink_policy(struct ldlm_namespace *ns,
1281                                                    struct ldlm_lock *lock,
1282                                                    int unused, int added,
1283                                                    int count)
1284 {
1285         int lock_cost;
1286         __u64 page_nr;
1287
1288         /*
1289          * Stop lru processing when we reached passed @count or checked all
1290          * locks in lru.
1291          */
1292         if (count && added >= count)
1293                 return LDLM_POLICY_KEEP_LOCK;
1294
1295         if (lock->l_resource->lr_type == LDLM_EXTENT) {
1296                 if (lock->l_weigh_ast) {
1297                         /*
1298                          * For liblustre, l_weigh_ast should return 0 since it
1299                          * don't cache pages
1300                          */
1301                         page_nr = lock->l_weigh_ast(lock);
1302                 } else {
1303                 struct ldlm_extent *l_extent;
1304
1305                 /*
1306                  * For all extent locks cost is 1 + number of pages in
1307                  * their extent.
1308                  */
1309                 l_extent = &lock->l_policy_data.l_extent;
1310                         page_nr = l_extent->end - l_extent->start;
1311                 do_div(page_nr, CFS_PAGE_SIZE);
1312                 }
1313                 lock_cost = 1 + page_nr;
1314         } else {
1315                 /*
1316                  * For all locks which are not extent ones cost is 1
1317                  */
1318                 lock_cost = 1;
1319         }
1320
1321         /*
1322          * Keep all expensive locks in lru for the memory pressure time
1323          * cancel policy. They anyways may be canceled by lru resize
1324          * pplicy if they have not small enough CLV.
1325          */
1326         return lock_cost > ns->ns_shrink_thumb ?
1327                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1328 }
1329
1330 /**
1331  * Callback function for lru-resize policy. Makes decision whether to keep
1332  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1333  * \a added and number of locks to be preferably canceled \a count.
1334  *
1335  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1336  *
1337  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1338  */
1339 static ldlm_policy_res_t ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1340                                                  struct ldlm_lock *lock,
1341                                                  int unused, int added,
1342                                                  int count)
1343 {
1344         cfs_time_t cur = cfs_time_current();
1345         struct ldlm_pool *pl = &ns->ns_pool;
1346         __u64 slv, lvf, lv;
1347         cfs_time_t la;
1348
1349         /*
1350          * Stop lru processing when we reached passed @count or checked all
1351          * locks in lru.
1352          */
1353         if (count && added >= count)
1354                 return LDLM_POLICY_KEEP_LOCK;
1355
1356         slv = ldlm_pool_get_slv(pl);
1357         lvf = ldlm_pool_get_lvf(pl);
1358         la = cfs_duration_sec(cfs_time_sub(cur,
1359                               lock->l_last_used));
1360
1361         /*
1362          * Stop when slv is not yet come from server or lv is smaller than
1363          * it is.
1364          */
1365         lv = lvf * la * unused;
1366
1367         /*
1368          * Inform pool about current CLV to see it via proc.
1369          */
1370         ldlm_pool_set_clv(pl, lv);
1371         return (slv == 1 || lv < slv) ?
1372                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1373 }
1374
1375 /**
1376  * Callback function for proc used policy. Makes decision whether to keep
1377  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1378  * \a added and number of locks to be preferably canceled \a count.
1379  *
1380  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1381  *
1382  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1383  */
1384 static ldlm_policy_res_t ldlm_cancel_passed_policy(struct ldlm_namespace *ns,
1385                                                    struct ldlm_lock *lock,
1386                                                    int unused, int added,
1387                                                    int count)
1388 {
1389         /*
1390          * Stop lru processing when we reached passed @count or checked all
1391          * locks in lru.
1392          */
1393         return (added >= count) ?
1394                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1395 }
1396
1397 /**
1398  * Callback function for aged policy. Makes decision whether to keep
1399  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1400  * \a added and number of locks to be preferably canceled \a count.
1401  *
1402  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1403  *
1404  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1405  */
1406 static ldlm_policy_res_t ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1407                                                  struct ldlm_lock *lock,
1408                                                  int unused, int added,
1409                                                  int count)
1410 {
1411         /*
1412          * Stop lru processing if young lock is found and we reached passed
1413          * @count.
1414          */
1415         return ((added >= count) &&
1416                 cfs_time_before(cfs_time_current(),
1417                                 cfs_time_add(lock->l_last_used,
1418                                              ns->ns_max_age))) ?
1419                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1420 }
1421
1422 /**
1423  * Callback function for default policy. Makes decision whether to keep
1424  * \a lock in LRU for current \a LRU size \a unused, added in current scan
1425  * \a added and number of locks to be preferably canceled \a count.
1426  *
1427  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1428  *
1429  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1430  */
1431 static ldlm_policy_res_t ldlm_cancel_default_policy(struct ldlm_namespace *ns,
1432                                                     struct ldlm_lock *lock,
1433                                                     int unused, int added,
1434                                                     int count)
1435 {
1436         /*
1437          * Stop lru processing when we reached passed @count or checked all
1438          * locks in lru.
1439          */
1440         return (added >= count) ?
1441                 LDLM_POLICY_KEEP_LOCK : LDLM_POLICY_CANCEL_LOCK;
1442 }
1443
1444 typedef ldlm_policy_res_t (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *,
1445                                                       struct ldlm_lock *, int,
1446                                                       int, int);
1447
1448 static ldlm_cancel_lru_policy_t
1449 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, int flags)
1450 {
1451         if (ns_connect_lru_resize(ns)) {
1452                 if (flags & LDLM_CANCEL_SHRINK)
1453                         return ldlm_cancel_shrink_policy;
1454                 else if (flags & LDLM_CANCEL_LRUR)
1455                         return ldlm_cancel_lrur_policy;
1456                 else if (flags & LDLM_CANCEL_PASSED)
1457                         return ldlm_cancel_passed_policy;
1458         } else {
1459                 if (flags & LDLM_CANCEL_AGED)
1460                         return ldlm_cancel_aged_policy;
1461         }
1462
1463         return ldlm_cancel_default_policy;
1464 }
1465
1466 /* - Free space in lru for @count new locks,
1467  *   redundant unused locks are canceled locally;
1468  * - also cancel locally unused aged locks;
1469  * - do not cancel more than @max locks;
1470  * - GET the found locks and add them into the @cancels list.
1471  *
1472  * A client lock can be added to the l_bl_ast list only when it is
1473  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing CANCEL.
1474  * There are the following use cases: ldlm_cancel_resource_local(),
1475  * ldlm_cancel_lru_local() and ldlm_cli_cancel(), which check&set this
1476  * flag properly. As any attempt to cancel a lock rely on this flag,
1477  * l_bl_ast list is accessed later without any special locking.
1478  *
1479  * Calling policies for enabled lru resize:
1480  * ----------------------------------------
1481  * flags & LDLM_CANCEL_LRUR - use lru resize policy (SLV from server) to
1482  *                            cancel not more than @count locks;
1483  *
1484  * flags & LDLM_CANCEL_PASSED - cancel @count number of old locks (located at
1485  *                              the beginning of lru list);
1486  *
1487  * flags & LDLM_CANCEL_SHRINK - cancel not more than @count locks according to
1488  *                              memory pressre policy function;
1489  *
1490  * flags & LDLM_CANCEL_AGED -   cancel alocks according to "aged policy".
1491  */
1492 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
1493                           int count, int max, int cancel_flags, int flags)
1494 {
1495         ldlm_cancel_lru_policy_t pf;
1496         struct ldlm_lock *lock, *next;
1497         int added = 0, unused;
1498         ENTRY;
1499
1500         spin_lock(&ns->ns_unused_lock);
1501         unused = ns->ns_nr_unused;
1502
1503         if (!ns_connect_lru_resize(ns))
1504                 count += unused - ns->ns_max_unused;
1505
1506         pf = ldlm_cancel_lru_policy(ns, flags);
1507         LASSERT(pf != NULL);
1508
1509         while (!list_empty(&ns->ns_unused_list)) {
1510                 /* For any flags, stop scanning if @max is reached. */
1511                 if (max && added >= max)
1512                         break;
1513
1514                 list_for_each_entry_safe(lock, next, &ns->ns_unused_list, l_lru){
1515                         /* No locks which got blocking requests. */
1516                         LASSERT(!(lock->l_flags & LDLM_FL_BL_AST));
1517
1518                         /* Somebody is already doing CANCEL. No need in this
1519                          * lock in lru, do not traverse it again. */
1520                         if (!(lock->l_flags & LDLM_FL_CANCELING))
1521                                 break;
1522
1523                         ldlm_lock_remove_from_lru_nolock(lock);
1524                 }
1525                 if (&lock->l_lru == &ns->ns_unused_list)
1526                         break;
1527
1528                 LDLM_LOCK_GET(lock);
1529                 spin_unlock(&ns->ns_unused_lock);
1530                 lu_ref_add(&lock->l_reference, __FUNCTION__, cfs_current());
1531
1532                 /* Pass the lock through the policy filter and see if it
1533                  * should stay in lru.
1534                  *
1535                  * Even for shrinker policy we stop scanning if
1536                  * we find a lock that should stay in the cache.
1537                  * We should take into account lock age anyway
1538                  * as new lock even if it is small of weight is
1539                  * valuable resource.
1540                  *
1541                  * That is, for shrinker policy we drop only
1542                  * old locks, but additionally chose them by
1543                  * their weight. Big extent locks will stay in
1544                  * the cache. */
1545                 if (pf(ns, lock, unused, added, count) ==
1546                     LDLM_POLICY_KEEP_LOCK) {
1547                         lu_ref_del(&lock->l_reference,
1548                                    __FUNCTION__, cfs_current());
1549                         LDLM_LOCK_RELEASE(lock);
1550                         spin_lock(&ns->ns_unused_lock);
1551                         break;
1552                 }
1553
1554                 lock_res_and_lock(lock);
1555                 /* Check flags again under the lock. */
1556                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1557                     (ldlm_lock_remove_from_lru(lock) == 0)) {
1558                         /* other thread is removing lock from lru or
1559                          * somebody is already doing CANCEL or
1560                          * there is a blocking request which will send
1561                          * cancel by itseft or the lock is matched
1562                          * is already not unused. */
1563                         unlock_res_and_lock(lock);
1564                         lu_ref_del(&lock->l_reference,
1565                                    __FUNCTION__, cfs_current());
1566                         LDLM_LOCK_RELEASE(lock);
1567                         spin_lock(&ns->ns_unused_lock);
1568                         continue;
1569                 }
1570                 LASSERT(!lock->l_readers && !lock->l_writers);
1571
1572                 /* If we have chosen to cancel this lock voluntarily, we
1573                  * better send cancel notification to server, so that it
1574                  * frees appropriate state. This might lead to a race
1575                  * where while we are doing cancel here, server is also
1576                  * silently cancelling this lock. */
1577                 lock->l_flags &= ~LDLM_FL_CANCEL_ON_BLOCK;
1578
1579                 /* Setting the CBPENDING flag is a little misleading,
1580                  * but prevents an important race; namely, once
1581                  * CBPENDING is set, the lock can accumulate no more
1582                  * readers/writers. Since readers and writers are
1583                  * already zero here, ldlm_lock_decref() won't see
1584                  * this flag and call l_blocking_ast */
1585                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
1586
1587                 /* We can't re-add to l_lru as it confuses the
1588                  * refcounting in ldlm_lock_remove_from_lru() if an AST
1589                  * arrives after we drop ns_lock below. We use l_bl_ast
1590                  * and can't use l_pending_chain as it is used both on
1591                  * server and client nevertheless bug 5666 says it is
1592                  * used only on server */
1593                 LASSERT(list_empty(&lock->l_bl_ast));
1594                 list_add(&lock->l_bl_ast, cancels);
1595                 unlock_res_and_lock(lock);
1596                 lu_ref_del(&lock->l_reference, __FUNCTION__, cfs_current());
1597                 spin_lock(&ns->ns_unused_lock);
1598                 added++;
1599                 unused--;
1600         }
1601         spin_unlock(&ns->ns_unused_lock);
1602         RETURN(ldlm_cancel_list(cancels, added, cancel_flags));
1603 }
1604
1605 /* Returns number of locks which could be canceled next time when
1606  * ldlm_cancel_lru() is called. Used from locks pool shrinker. */
1607 int ldlm_cancel_lru_estimate(struct ldlm_namespace *ns,
1608                              int count, int max, int flags)
1609 {
1610         struct list_head disp = CFS_LIST_HEAD_INIT(disp);
1611         ldlm_cancel_lru_policy_t pf;
1612         struct ldlm_lock *lock;
1613         int added = 0, unused;
1614         int loop_stop = 0;
1615         ENTRY;
1616
1617         pf = ldlm_cancel_lru_policy(ns, flags);
1618         LASSERT(pf != NULL);
1619         spin_lock(&ns->ns_unused_lock);
1620         unused = ns->ns_nr_unused;
1621         list_splice_init(&ns->ns_unused_list, &disp);
1622         while (!list_empty(&disp)) {
1623                 lock = list_entry(disp.next, struct ldlm_lock, l_lru);
1624                 list_move_tail(&lock->l_lru, &ns->ns_unused_list);
1625
1626                 /* For any flags, stop scanning if @max is reached. */
1627                 if (max && added >= max)
1628                         break;
1629
1630                 /* Somebody is already doing CANCEL or there is a
1631                  * blocking request will send cancel. Let's not count
1632                  * this lock. */
1633                 if ((lock->l_flags & LDLM_FL_CANCELING) ||
1634                     (lock->l_flags & LDLM_FL_BL_AST))
1635                         continue;
1636
1637                 LDLM_LOCK_GET(lock);
1638                 spin_unlock(&ns->ns_unused_lock);
1639                 lu_ref_add(&lock->l_reference, __FUNCTION__, cfs_current());
1640
1641                 /* Pass the lock through the policy filter and see if it
1642                  * should stay in lru. */
1643                 if (pf(ns, lock, unused, added, count) == LDLM_POLICY_KEEP_LOCK)
1644                         loop_stop = 1;
1645
1646                 lu_ref_del(&lock->l_reference, __FUNCTION__, cfs_current());
1647                 LDLM_LOCK_RELEASE(lock);
1648                 spin_lock(&ns->ns_unused_lock);
1649                 if (loop_stop)
1650                         break;
1651
1652                 added++;
1653                 unused--;
1654         }
1655         list_splice(&disp, ns->ns_unused_list.prev);
1656         spin_unlock(&ns->ns_unused_lock);
1657         RETURN(added);
1658 }
1659
1660 /* when called with LDLM_ASYNC the blocking callback will be handled
1661  * in a thread and this function will return after the thread has been
1662  * asked to call the callback.  when called with LDLM_SYNC the blocking
1663  * callback will be performed in this function. */
1664 int ldlm_cancel_lru(struct ldlm_namespace *ns, int nr, ldlm_sync_t sync,
1665                     int flags)
1666 {
1667         CFS_LIST_HEAD(cancels);
1668         int count, rc;
1669         ENTRY;
1670
1671 #ifndef __KERNEL__
1672         sync = LDLM_SYNC; /* force to be sync in user space */
1673 #endif
1674         count = ldlm_cancel_lru_local(ns, &cancels, nr, 0, 0, flags);
1675         if (sync == LDLM_ASYNC) {
1676                 rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count);
1677                 if (rc == 0)
1678                         RETURN(count);
1679         }
1680
1681         /* If an error occured in ASYNC mode, or
1682          * this is SYNC mode, cancel the list. */
1683         ldlm_cli_cancel_list(&cancels, count, NULL, 0);
1684         RETURN(count);
1685 }
1686
1687 /* Find and cancel locally unused locks found on resource, matched to the
1688  * given policy, mode. GET the found locks and add them into the @cancels
1689  * list. */
1690 int ldlm_cancel_resource_local(struct ldlm_resource *res,
1691                                struct list_head *cancels,
1692                                ldlm_policy_data_t *policy,
1693                                ldlm_mode_t mode, int lock_flags,
1694                                int cancel_flags, void *opaque)
1695 {
1696         struct ldlm_lock *lock;
1697         int count = 0;
1698         ENTRY;
1699
1700         lock_res(res);
1701         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
1702                 if (opaque != NULL && lock->l_ast_data != opaque) {
1703                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
1704                                    lock->l_ast_data, opaque);
1705                         //LBUG();
1706                         continue;
1707                 }
1708
1709                 if (lock->l_readers || lock->l_writers) {
1710                         if (cancel_flags & LDLM_FL_WARN) {
1711                                 LDLM_ERROR(lock, "lock in use");
1712                                 //LBUG();
1713                         }
1714                         continue;
1715                 }
1716
1717                 /* If somebody is already doing CANCEL, or blocking ast came,
1718                  * skip this lock. */
1719                 if (lock->l_flags & LDLM_FL_BL_AST ||
1720                     lock->l_flags & LDLM_FL_CANCELING)
1721                         continue;
1722
1723                 if (lockmode_compat(lock->l_granted_mode, mode))
1724                         continue;
1725
1726                 /* If policy is given and this is IBITS lock, add to list only
1727                  * those locks that match by policy. */
1728                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS) &&
1729                     !(lock->l_policy_data.l_inodebits.bits &
1730                       policy->l_inodebits.bits))
1731                         continue;
1732
1733                 /* See CBPENDING comment in ldlm_cancel_lru */
1734                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
1735                                  lock_flags;
1736
1737                 LASSERT(list_empty(&lock->l_bl_ast));
1738                 list_add(&lock->l_bl_ast, cancels);
1739                 LDLM_LOCK_GET(lock);
1740                 count++;
1741         }
1742         unlock_res(res);
1743
1744         RETURN(ldlm_cancel_list(cancels, count, cancel_flags));
1745 }
1746
1747 /* If @req is NULL, send CANCEL request to server with handles of locks
1748  * in the @cancels. If EARLY_CANCEL is not supported, send CANCEL requests
1749  * separately per lock.
1750  * If @req is not NULL, put handles of locks in @cancels into the request
1751  * buffer at the offset @off.
1752  * Destroy @cancels at the end. */
1753 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
1754                          struct ptlrpc_request *req, int flags)
1755 {
1756         struct ldlm_lock *lock;
1757         int res = 0;
1758         ENTRY;
1759
1760         if (list_empty(cancels) || count == 0)
1761                 RETURN(0);
1762
1763         /* XXX: requests (both batched and not) could be sent in parallel.
1764          * Usually it is enough to have just 1 RPC, but it is possible that
1765          * there are to many locks to be cancelled in LRU or on a resource.
1766          * It would also speed up the case when the server does not support
1767          * the feature. */
1768         while (count > 0) {
1769                 LASSERT(!list_empty(cancels));
1770                 lock = list_entry(cancels->next, struct ldlm_lock, l_bl_ast);
1771                 LASSERT(lock->l_conn_export);
1772
1773                 if (exp_connect_cancelset(lock->l_conn_export)) {
1774                         res = count;
1775                         if (req)
1776                                 ldlm_cancel_pack(req, cancels, count);
1777                         else
1778                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
1779                                                           cancels, count,
1780                                                           flags);
1781                 } else {
1782                         res = ldlm_cli_cancel_req(lock->l_conn_export,
1783                                                   cancels, 1, flags);
1784                 }
1785
1786                 if (res < 0) {
1787                         CERROR("ldlm_cli_cancel_list: %d\n", res);
1788                         res = count;
1789                 }
1790
1791                 count -= res;
1792                 ldlm_lock_list_put(cancels, l_bl_ast, res);
1793         }
1794         LASSERT(count == 0);
1795         RETURN(0);
1796 }
1797
1798 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
1799                                     const struct ldlm_res_id *res_id,
1800                                     ldlm_policy_data_t *policy,
1801                                     ldlm_mode_t mode, int flags, void *opaque)
1802 {
1803         struct ldlm_resource *res;
1804         CFS_LIST_HEAD(cancels);
1805         int count;
1806         int rc;
1807         ENTRY;
1808
1809         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
1810         if (res == NULL) {
1811                 /* This is not a problem. */
1812                 CDEBUG(D_INFO, "No resource "LPU64"\n", res_id->name[0]);
1813                 RETURN(0);
1814         }
1815
1816         LDLM_RESOURCE_ADDREF(res);
1817         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
1818                                            0, flags, opaque);
1819         rc = ldlm_cli_cancel_list(&cancels, count, NULL, flags);
1820         if (rc != ELDLM_OK)
1821                 CERROR("ldlm_cli_cancel_unused_resource: %d\n", rc);
1822
1823         LDLM_RESOURCE_DELREF(res);
1824         ldlm_resource_putref(res);
1825         RETURN(0);
1826 }
1827
1828 static inline int have_no_nsresource(struct ldlm_namespace *ns)
1829 {
1830         int no_resource = 0;
1831
1832         spin_lock(&ns->ns_hash_lock);
1833         if (ns->ns_resources == 0)
1834                 no_resource = 1;
1835         spin_unlock(&ns->ns_hash_lock);
1836
1837         RETURN(no_resource);
1838 }
1839
1840 /* Cancel all locks on a namespace (or a specific resource, if given)
1841  * that have 0 readers/writers.
1842  *
1843  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
1844  * to notify the server. */
1845 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
1846                            const struct ldlm_res_id *res_id,
1847                            int flags, void *opaque)
1848 {
1849         int i;
1850         ENTRY;
1851
1852         if (ns == NULL)
1853                 RETURN(ELDLM_OK);
1854
1855         if (res_id)
1856                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
1857                                                        LCK_MINMODE, flags,
1858                                                        opaque));
1859
1860         spin_lock(&ns->ns_hash_lock);
1861         for (i = 0; i < RES_HASH_SIZE; i++) {
1862                 struct list_head *tmp;
1863                 tmp = ns->ns_hash[i].next;
1864                 while (tmp != &(ns->ns_hash[i])) {
1865                         struct ldlm_resource *res;
1866                         int rc;
1867
1868                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1869                         ldlm_resource_getref(res);
1870                         spin_unlock(&ns->ns_hash_lock);
1871
1872                         LDLM_RESOURCE_ADDREF(res);
1873                         rc = ldlm_cli_cancel_unused_resource(ns, &res->lr_name,
1874                                                              NULL, LCK_MINMODE,
1875                                                              flags, opaque);
1876
1877                         if (rc)
1878                                 CERROR("ldlm_cli_cancel_unused ("LPU64"): %d\n",
1879                                        res->lr_name.name[0], rc);
1880
1881                         LDLM_RESOURCE_DELREF(res);
1882                         spin_lock(&ns->ns_hash_lock);
1883                         tmp = tmp->next;
1884                         ldlm_resource_putref_locked(res);
1885                 }
1886         }
1887         spin_unlock(&ns->ns_hash_lock);
1888
1889         RETURN(ELDLM_OK);
1890 }
1891
1892 /* Lock iterators. */
1893
1894 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
1895                           void *closure)
1896 {
1897         struct list_head *tmp, *next;
1898         struct ldlm_lock *lock;
1899         int rc = LDLM_ITER_CONTINUE;
1900
1901         ENTRY;
1902
1903         if (!res)
1904                 RETURN(LDLM_ITER_CONTINUE);
1905
1906         lock_res(res);
1907         list_for_each_safe(tmp, next, &res->lr_granted) {
1908                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1909
1910                 if (iter(lock, closure) == LDLM_ITER_STOP)
1911                         GOTO(out, rc = LDLM_ITER_STOP);
1912         }
1913
1914         list_for_each_safe(tmp, next, &res->lr_converting) {
1915                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1916
1917                 if (iter(lock, closure) == LDLM_ITER_STOP)
1918                         GOTO(out, rc = LDLM_ITER_STOP);
1919         }
1920
1921         list_for_each_safe(tmp, next, &res->lr_waiting) {
1922                 lock = list_entry(tmp, struct ldlm_lock, l_res_link);
1923
1924                 if (iter(lock, closure) == LDLM_ITER_STOP)
1925                         GOTO(out, rc = LDLM_ITER_STOP);
1926         }
1927  out:
1928         unlock_res(res);
1929         RETURN(rc);
1930 }
1931
1932 struct iter_helper_data {
1933         ldlm_iterator_t iter;
1934         void *closure;
1935 };
1936
1937 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
1938 {
1939         struct iter_helper_data *helper = closure;
1940         return helper->iter(lock, helper->closure);
1941 }
1942
1943 static int ldlm_res_iter_helper(struct ldlm_resource *res, void *closure)
1944 {
1945         return ldlm_resource_foreach(res, ldlm_iter_helper, closure);
1946 }
1947
1948 int ldlm_namespace_foreach(struct ldlm_namespace *ns, ldlm_iterator_t iter,
1949                            void *closure)
1950 {
1951         struct iter_helper_data helper = { iter: iter, closure: closure };
1952         return ldlm_namespace_foreach_res(ns, ldlm_res_iter_helper, &helper);
1953 }
1954
1955 int ldlm_namespace_foreach_res(struct ldlm_namespace *ns,
1956                                ldlm_res_iterator_t iter, void *closure)
1957 {
1958         int i, rc = LDLM_ITER_CONTINUE;
1959         struct ldlm_resource *res;
1960         struct list_head *tmp;
1961
1962         ENTRY;
1963         spin_lock(&ns->ns_hash_lock);
1964         for (i = 0; i < RES_HASH_SIZE; i++) {
1965                 tmp = ns->ns_hash[i].next;
1966                 while (tmp != &(ns->ns_hash[i])) {
1967                         res = list_entry(tmp, struct ldlm_resource, lr_hash);
1968                         ldlm_resource_getref(res);
1969                         spin_unlock(&ns->ns_hash_lock);
1970                         LDLM_RESOURCE_ADDREF(res);
1971
1972                         rc = iter(res, closure);
1973
1974                         LDLM_RESOURCE_DELREF(res);
1975                         spin_lock(&ns->ns_hash_lock);
1976                         tmp = tmp->next;
1977                         ldlm_resource_putref_locked(res);
1978                         if (rc == LDLM_ITER_STOP)
1979                                 GOTO(out, rc);
1980                 }
1981         }
1982  out:
1983         spin_unlock(&ns->ns_hash_lock);
1984         RETURN(rc);
1985 }
1986
1987 /* non-blocking function to manipulate a lock whose cb_data is being put away.*/
1988 void ldlm_resource_iterate(struct ldlm_namespace *ns,
1989                            const struct ldlm_res_id *res_id,
1990                            ldlm_iterator_t iter, void *data)
1991 {
1992         struct ldlm_resource *res;
1993         ENTRY;
1994
1995         if (ns == NULL) {
1996                 CERROR("must pass in namespace\n");
1997                 LBUG();
1998         }
1999
2000         res = ldlm_resource_get(ns, NULL, res_id, 0, 0);
2001         if (res == NULL) {
2002                 EXIT;
2003                 return;
2004         }
2005
2006         LDLM_RESOURCE_ADDREF(res);
2007         ldlm_resource_foreach(res, iter, data);
2008         LDLM_RESOURCE_DELREF(res);
2009         ldlm_resource_putref(res);
2010         EXIT;
2011 }
2012
2013 /* Lock replay */
2014
2015 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
2016 {
2017         struct list_head *list = closure;
2018
2019         /* we use l_pending_chain here, because it's unused on clients. */
2020         LASSERTF(list_empty(&lock->l_pending_chain),"lock %p next %p prev %p\n",
2021                  lock, &lock->l_pending_chain.next,&lock->l_pending_chain.prev);
2022         /* bug 9573: don't replay locks left after eviction */
2023         if (!(lock->l_flags & LDLM_FL_FAILED))
2024                 list_add(&lock->l_pending_chain, list);
2025         return LDLM_ITER_CONTINUE;
2026 }
2027
2028 static int replay_lock_interpret(const struct lu_env *env,
2029                                  struct ptlrpc_request *req,
2030                                  struct ldlm_async_args *aa, int rc)
2031 {
2032         struct lustre_handle  old_hash_key;
2033         struct ldlm_lock     *lock;
2034         struct ldlm_reply    *reply;
2035         struct obd_export    *exp;
2036
2037         ENTRY;
2038         atomic_dec(&req->rq_import->imp_replay_inflight);
2039         if (rc != ELDLM_OK)
2040                 GOTO(out, rc);
2041
2042
2043         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2044         if (reply == NULL)
2045                 GOTO(out, rc = -EPROTO);
2046
2047         lock = ldlm_handle2lock(&aa->lock_handle);
2048         if (!lock) {
2049                 CERROR("received replay ack for unknown local cookie "LPX64
2050                        " remote cookie "LPX64 " from server %s id %s\n",
2051                        aa->lock_handle.cookie, reply->lock_handle.cookie,
2052                        req->rq_export->exp_client_uuid.uuid,
2053                        libcfs_id2str(req->rq_peer));
2054                 GOTO(out, rc = -ESTALE);
2055         }
2056
2057         old_hash_key = lock->l_remote_handle;
2058         lock->l_remote_handle = reply->lock_handle;
2059
2060         /* Key change rehash lock in per-export hash with new key */
2061         exp = req->rq_export;
2062         if (exp && exp->exp_lock_hash)
2063                 lustre_hash_rehash_key(exp->exp_lock_hash, &old_hash_key,
2064                                        &lock->l_remote_handle,
2065                                        &lock->l_exp_hash);
2066
2067         LDLM_DEBUG(lock, "replayed lock:");
2068         ptlrpc_import_recovery_state_machine(req->rq_import);
2069         LDLM_LOCK_PUT(lock);
2070 out:
2071         if (rc != ELDLM_OK)
2072                 ptlrpc_connect_import(req->rq_import, NULL);
2073
2074         RETURN(rc);
2075 }
2076
2077 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
2078 {
2079         struct ptlrpc_request *req;
2080         struct ldlm_async_args *aa;
2081         struct ldlm_request   *body;
2082         int flags;
2083         ENTRY;
2084
2085
2086         /* Bug 11974: Do not replay a lock which is actively being canceled */
2087         if (lock->l_flags & LDLM_FL_CANCELING) {
2088                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
2089                 RETURN(0);
2090         }
2091
2092         /* If this is reply-less callback lock, we cannot replay it, since
2093          * server might have long dropped it, but notification of that event was
2094          * lost by network. (and server granted conflicting lock already) */
2095         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
2096                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
2097                 ldlm_lock_cancel(lock);
2098                 RETURN(0);
2099         }
2100         /*
2101          * If granted mode matches the requested mode, this lock is granted.
2102          *
2103          * If they differ, but we have a granted mode, then we were granted
2104          * one mode and now want another: ergo, converting.
2105          *
2106          * If we haven't been granted anything and are on a resource list,
2107          * then we're blocked/waiting.
2108          *
2109          * If we haven't been granted anything and we're NOT on a resource list,
2110          * then we haven't got a reply yet and don't have a known disposition.
2111          * This happens whenever a lock enqueue is the request that triggers
2112          * recovery.
2113          */
2114         if (lock->l_granted_mode == lock->l_req_mode)
2115                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
2116         else if (lock->l_granted_mode)
2117                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_CONV;
2118         else if (!list_empty(&lock->l_res_link))
2119                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
2120         else
2121                 flags = LDLM_FL_REPLAY;
2122
2123         req = ptlrpc_request_alloc_pack(imp, &RQF_LDLM_ENQUEUE,
2124                                         LUSTRE_DLM_VERSION, LDLM_ENQUEUE);
2125         if (req == NULL)
2126                 RETURN(-ENOMEM);
2127
2128         /* We're part of recovery, so don't wait for it. */
2129         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
2130
2131         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2132         ldlm_lock2desc(lock, &body->lock_desc);
2133         body->lock_flags = flags;
2134
2135         ldlm_lock2handle(lock, &body->lock_handle[0]);
2136         if (lock->l_lvb_len != 0) {
2137                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_ENQUEUE_LVB);
2138                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2139                                      lock->l_lvb_len);
2140         }
2141         ptlrpc_request_set_replen(req);
2142         /* notify the server we've replayed all requests.
2143          * also, we mark the request to be put on a dedicated
2144          * queue to be processed after all request replayes.
2145          * bug 6063 */
2146         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
2147
2148         LDLM_DEBUG(lock, "replaying lock:");
2149
2150         atomic_inc(&req->rq_import->imp_replay_inflight);
2151         CLASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
2152         aa = ptlrpc_req_async_args(req);
2153         aa->lock_handle = body->lock_handle[0];
2154         req->rq_interpret_reply = (ptlrpc_interpterer_t)replay_lock_interpret;
2155         ptlrpcd_add_req(req);
2156
2157         RETURN(0);
2158 }
2159
2160 int ldlm_replay_locks(struct obd_import *imp)
2161 {
2162         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
2163         CFS_LIST_HEAD(list);
2164         struct ldlm_lock *lock, *next;
2165         int rc = 0;
2166
2167         ENTRY;
2168
2169         LASSERT(atomic_read(&imp->imp_replay_inflight) == 0);
2170
2171         /* ensure this doesn't fall to 0 before all have been queued */
2172         atomic_inc(&imp->imp_replay_inflight);
2173
2174         (void)ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
2175
2176         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
2177                 list_del_init(&lock->l_pending_chain);
2178                 if (rc)
2179                         continue; /* or try to do the rest? */
2180                 rc = replay_one_lock(imp, lock);
2181         }
2182
2183         atomic_dec(&imp->imp_replay_inflight);
2184
2185         RETURN(rc);
2186 }