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