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