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