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