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