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