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