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