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