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