Whamcloud - gitweb
LU-16747 llapi: fix race in get_root_path_slow()
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2010, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31 /**
32  * This file contains Asynchronous System Trap (AST) handlers and related
33  * LDLM request-processing routines.
34  *
35  * An AST is a callback issued on a lock when its state is changed. There are
36  * several different types of ASTs (callbacks) registered for each lock:
37  *
38  * - completion AST: when a lock is enqueued by some process, but cannot be
39  *   granted immediately due to other conflicting locks on the same resource,
40  *   the completion AST is sent to notify the caller when the lock is
41  *   eventually granted
42  *
43  * - blocking AST: when a lock is granted to some process, if another process
44  *   enqueues a conflicting (blocking) lock on a resource, a blocking AST is
45  *   sent to notify the holder(s) of the lock(s) of the conflicting lock
46  *   request. The lock holder(s) must release their lock(s) on that resource in
47  *   a timely manner or be evicted by the server.
48  *
49  * - glimpse AST: this is used when a process wants information about a lock
50  *   (i.e. the lock value block (LVB)) but does not necessarily require holding
51  *   the lock. If the resource is locked, the lock holder(s) are sent glimpse
52  *   ASTs and the LVB is returned to the caller, and lock holder(s) may CANCEL
53  *   their lock(s) if they are idle. If the resource is not locked, the server
54  *   may grant the lock.
55  */
56
57 #define DEBUG_SUBSYSTEM S_LDLM
58
59 #include <linux/fs_struct.h>
60 #include <lustre_errno.h>
61 #include <lustre_dlm.h>
62 #include <obd_class.h>
63 #include <obd.h>
64
65 #include "ldlm_internal.h"
66
67 unsigned int ldlm_enqueue_min = OBD_TIMEOUT_DEFAULT;
68 module_param(ldlm_enqueue_min, uint, 0644);
69 MODULE_PARM_DESC(ldlm_enqueue_min, "lock enqueue timeout minimum");
70 EXPORT_SYMBOL(ldlm_enqueue_min);
71
72 /* in client side, whether the cached locks will be canceled before replay */
73 unsigned int ldlm_cancel_unused_locks_before_replay = 1;
74
75 struct lock_wait_data {
76         struct ldlm_lock *lwd_lock;
77         __u32             lwd_conn_cnt;
78 };
79
80 struct ldlm_async_args {
81         struct lustre_handle lock_handle;
82 };
83
84 /**
85  * ldlm_request_bufsize
86  *
87  * If opcode=LDLM_ENQUEUE, 1 slot is already occupied,
88  * LDLM_LOCKREQ_HANDLE -1 slots are available.
89  * Otherwise, LDLM_LOCKREQ_HANDLE slots are available.
90  *
91  * \param[in] count
92  * \param[in] type
93  *
94  * \retval size of the request buffer
95  */
96 int ldlm_request_bufsize(int count, int type)
97 {
98         int avail = LDLM_LOCKREQ_HANDLES;
99
100         if (type == LDLM_ENQUEUE)
101                 avail -= LDLM_ENQUEUE_CANCEL_OFF;
102
103         if (count > avail)
104                 avail = (count - avail) * sizeof(struct lustre_handle);
105         else
106                 avail = 0;
107
108         return sizeof(struct ldlm_request) + avail;
109 }
110
111 void ldlm_expired_completion_wait(struct lock_wait_data *lwd)
112 {
113         struct ldlm_lock *lock = lwd->lwd_lock;
114         struct obd_import *imp;
115         struct obd_device *obd;
116
117         ENTRY;
118         if (lock->l_conn_export == NULL) {
119                 static time64_t next_dump, last_dump;
120
121                 LDLM_ERROR(lock,
122                            "lock timed out (enqueued at %lld, %llds ago); not entering recovery in server code, just going back to sleep",
123                            lock->l_activity,
124                            ktime_get_real_seconds() - lock->l_activity);
125                 if (ktime_get_seconds() > next_dump) {
126                         last_dump = next_dump;
127                         next_dump = ktime_get_seconds() + 300;
128                         ldlm_namespace_dump(D_DLMTRACE,
129                                             ldlm_lock_to_ns(lock));
130                         if (last_dump == 0)
131                                 libcfs_debug_dumplog();
132                 }
133                 RETURN_EXIT;
134         }
135
136         obd = lock->l_conn_export->exp_obd;
137         imp = obd->u.cli.cl_import;
138         ptlrpc_fail_import(imp, lwd->lwd_conn_cnt);
139         LDLM_ERROR(lock,
140                    "lock timed out (enqueued at %lld, %llds ago), entering recovery for %s@%s",
141                    lock->l_activity,
142                    ktime_get_real_seconds() - lock->l_activity,
143                    obd2cli_tgt(obd), imp->imp_connection->c_remote_uuid.uuid);
144
145         EXIT;
146 }
147
148 int is_granted_or_cancelled_nolock(struct ldlm_lock *lock)
149 {
150         int ret = 0;
151
152         check_res_locked(lock->l_resource);
153         if (ldlm_is_granted(lock) && !ldlm_is_cp_reqd(lock))
154                 ret = 1;
155         else if (ldlm_is_failed(lock) || ldlm_is_cancel(lock))
156                 ret = 1;
157         return ret;
158 }
159 EXPORT_SYMBOL(is_granted_or_cancelled_nolock);
160
161 /**
162  * Calculate the Completion timeout (covering enqueue, BL AST, data flush,
163  * lock cancel, and their replies). Used for lock completion timeout on the
164  * client side.
165  *
166  * \param[in] lock        lock which is waiting the completion callback
167  *
168  * \retval            timeout in seconds to wait for the server reply
169  */
170 /*
171  * We use the same basis for both server side and client side functions
172  * from a single node.
173  */
174 static timeout_t ldlm_cp_timeout(struct ldlm_lock *lock)
175 {
176         timeout_t timeout;
177
178         if (AT_OFF)
179                 return obd_timeout;
180
181         /*
182          * Wait a long time for enqueue - server may have to callback a
183          * lock from another client.  Server will evict the other client if it
184          * doesn't respond reasonably, and then give us the lock.
185          */
186         timeout = at_get(ldlm_lock_to_ns_at(lock));
187         return max(3 * timeout, (timeout_t)ldlm_enqueue_min);
188 }
189
190 /**
191  * Helper function for ldlm_completion_ast(), updating timings when lock is
192  * actually granted.
193  */
194 static int ldlm_completion_tail(struct ldlm_lock *lock, void *data)
195 {
196         int result = 0;
197
198         if (ldlm_is_destroyed(lock) || ldlm_is_failed(lock)) {
199                 LDLM_DEBUG(lock, "client-side enqueue: destroyed");
200                 result = -EIO;
201         } else if (data == NULL) {
202                 LDLM_DEBUG(lock, "client-side enqueue: granted");
203         } else {
204                 /* Take into AT only CP RPC, not immediately granted locks */
205                 timeout_t delay = 0;
206
207                 /* Discard negative timeouts. We should also limit the
208                  * maximum value of the timeout
209                  */
210                 if (ktime_get_real_seconds() > lock->l_activity)
211                         delay = ktime_get_real_seconds() - lock->l_activity;
212
213                 LDLM_DEBUG(lock, "client-side enqueue: granted after %ds",
214                            delay);
215                 /* Update our time estimate */
216                 at_measured(ldlm_lock_to_ns_at(lock), delay);
217         }
218         return result;
219 }
220
221 /**
222  * Implementation of ->l_completion_ast() for a client, that doesn't wait
223  * until lock is granted. Suitable for locks enqueued through ptlrpcd, of
224  * other threads that cannot block for long.
225  */
226 int ldlm_completion_ast_async(struct ldlm_lock *lock, __u64 flags, void *data)
227 {
228         ENTRY;
229
230         if (flags == LDLM_FL_WAIT_NOREPROC) {
231                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
232                 RETURN(0);
233         }
234
235         if (!(flags & LDLM_FL_BLOCKED_MASK)) {
236                 wake_up(&lock->l_waitq);
237                 RETURN(ldlm_completion_tail(lock, data));
238         }
239
240         LDLM_DEBUG(lock, "client-side enqueue returned a blocked lock, going forward");
241         ldlm_reprocess_all(lock->l_resource, 0);
242         RETURN(0);
243 }
244 EXPORT_SYMBOL(ldlm_completion_ast_async);
245
246 /**
247  * Generic LDLM "completion" AST. This is called in several cases:
248  *
249  *     - when a reply to an ENQUEUE RPC is received from the server
250  *       (ldlm_cli_enqueue_fini()). Lock might be granted or not granted at
251  *       this point (determined by flags);
252  *
253  *     - when LDLM_CP_CALLBACK RPC comes to client to notify it that lock has
254  *       been granted;
255  *
256  *     - when ldlm_lock_match(LDLM_FL_LVB_READY) is about to wait until lock
257  *       gets correct lvb;
258  *
259  *     - to force all locks when resource is destroyed (cleanup_resource());
260  *
261  * If lock is not granted in the first case, this function waits until second
262  * or penultimate cases happen in some other thread.
263  *
264  */
265 int ldlm_completion_ast(struct ldlm_lock *lock, __u64 flags, void *data)
266 {
267         /* XXX ALLOCATE - 160 bytes */
268         struct lock_wait_data lwd;
269         struct obd_device *obd;
270         struct obd_import *imp = NULL;
271         timeout_t timeout;
272         int rc = 0;
273
274         ENTRY;
275
276         if (flags == LDLM_FL_WAIT_NOREPROC) {
277                 LDLM_DEBUG(lock, "client-side enqueue waiting on pending lock");
278                 goto noreproc;
279         }
280
281         if (!(flags & LDLM_FL_BLOCKED_MASK)) {
282                 wake_up(&lock->l_waitq);
283                 RETURN(0);
284         }
285
286         LDLM_DEBUG(lock, "client-side enqueue returned a blocked locksleeping");
287
288 noreproc:
289
290         obd = class_exp2obd(lock->l_conn_export);
291
292         /* if this is a local lock, then there is no import */
293         if (obd != NULL)
294                 imp = obd->u.cli.cl_import;
295
296         timeout = ldlm_cp_timeout(lock);
297
298         lwd.lwd_lock = lock;
299         lock->l_activity = ktime_get_real_seconds();
300
301         if (imp != NULL) {
302                 spin_lock(&imp->imp_lock);
303                 lwd.lwd_conn_cnt = imp->imp_conn_cnt;
304                 spin_unlock(&imp->imp_lock);
305         }
306
307         if (ns_is_client(ldlm_lock_to_ns(lock)) &&
308             CFS_FAIL_CHECK_RESET(OBD_FAIL_LDLM_INTR_CP_AST,
309                                  OBD_FAIL_LDLM_CP_BL_RACE | CFS_FAIL_ONCE)) {
310                 ldlm_set_fail_loc(lock);
311                 rc = -EINTR;
312         } else {
313                 /* Go to sleep until the lock is granted or cancelled. */
314                 if (ldlm_is_no_timeout(lock)) {
315                         LDLM_DEBUG(lock, "waiting indefinitely because of NO_TIMEOUT");
316                         rc = l_wait_event_abortable(
317                                 lock->l_waitq,
318                                 is_granted_or_cancelled(lock));
319                 } else {
320                         if (wait_event_idle_timeout(
321                                     lock->l_waitq,
322                                     is_granted_or_cancelled(lock),
323                                     cfs_time_seconds(timeout)) == 0) {
324                                 ldlm_expired_completion_wait(&lwd);
325                                 rc = l_wait_event_abortable(
326                                         lock->l_waitq,
327                                         is_granted_or_cancelled(lock));
328                         }
329                 }
330         }
331
332         if (rc) {
333                 LDLM_DEBUG(lock, "client-side enqueue waking up: failed (%d)",
334                            rc);
335                 RETURN(rc);
336         }
337
338         RETURN(ldlm_completion_tail(lock, data));
339 }
340 EXPORT_SYMBOL(ldlm_completion_ast);
341
342 /**
343  * A helper to build a blocking AST function
344  *
345  * Perform a common operation for blocking ASTs:
346  * defferred lock cancellation.
347  *
348  * \param lock the lock blocking or canceling AST was called on
349  * \retval 0
350  * \see mdt_blocking_ast
351  * \see ldlm_blocking_ast
352  */
353 int ldlm_blocking_ast_nocheck(struct ldlm_lock *lock)
354 {
355         int do_ast;
356
357         ENTRY;
358
359         ldlm_set_cbpending(lock);
360         do_ast = (!lock->l_readers && !lock->l_writers);
361         unlock_res_and_lock(lock);
362
363         if (do_ast) {
364                 struct lustre_handle lockh;
365                 int rc;
366
367                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
368                 ldlm_lock2handle(lock, &lockh);
369                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
370                 if (rc < 0)
371                         CERROR("ldlm_cli_cancel: %d\n", rc);
372         } else {
373                 LDLM_DEBUG(lock,
374                            "Lock still has references, will be cancelled later");
375         }
376         RETURN(0);
377 }
378 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
379
380 /**
381  * Server blocking AST
382  *
383  * ->l_blocking_ast() callback for LDLM locks acquired by server-side
384  * OBDs.
385  *
386  * \param lock the lock which blocks a request or cancelling lock
387  * \param desc unused
388  * \param data unused
389  * \param flag indicates whether this cancelling or blocking callback
390  * \retval 0
391  * \see ldlm_blocking_ast_nocheck
392  */
393 int ldlm_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
394                       void *data, int flag)
395 {
396         ENTRY;
397
398         if (flag == LDLM_CB_CANCELING) {
399                 /* Don't need to do anything here. */
400                 RETURN(0);
401         }
402
403         lock_res_and_lock(lock);
404         /*
405          * Get this: if ldlm_blocking_ast is racing with intent_policy, such
406          * that ldlm_blocking_ast is called just before intent_policy method
407          * takes the lr_lock, then by the time we get the lock, we might not
408          * be the correct blocking function anymore.  So check, and return
409          * early, if so.
410          */
411         if (lock->l_blocking_ast != ldlm_blocking_ast) {
412                 unlock_res_and_lock(lock);
413                 RETURN(0);
414         }
415         RETURN(ldlm_blocking_ast_nocheck(lock));
416 }
417 EXPORT_SYMBOL(ldlm_blocking_ast);
418
419 /**
420  * Implements ldlm_lock::l_glimpse_ast for extent locks acquired on the server.
421  *
422  * Returning -ELDLM_NO_LOCK_DATA actually works, but the reason for that is
423  * rather subtle: with OST-side locking, it may so happen that _all_ extent
424  * locks are held by the OST. If client wants to obtain the current file size
425  * it calls ll_glimpse_size(), and (as all locks are held only on the server),
426  * this dummy glimpse callback fires and does nothing. The client still
427  * receives the correct file size due to the following fragment of code in
428  * ldlm_cb_interpret():
429  *
430  *      if (rc == -ELDLM_NO_LOCK_DATA) {
431  *              LDLM_DEBUG(lock, "lost race - client has a lock but no"
432  *                         "inode");
433  *              ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
434  *      }
435  *
436  * That is, after the glimpse returns this error, ofd_lvbo_update() is called
437  * and returns the updated file attributes from the inode to the client.
438  *
439  * See also comment in ofd_intent_policy() on why servers must set a non-NULL
440  * l_glimpse_ast when grabbing DLM locks.  Otherwise, the server will assume
441  * that the object is in the process of being destroyed.
442  *
443  * \param[in] lock      DLM lock being glimpsed, unused
444  * \param[in] reqp      pointer to ptlrpc_request, unused
445  *
446  * \retval              -ELDLM_NO_LOCK_DATA to get attributes from disk object
447  */
448 int ldlm_glimpse_ast(struct ldlm_lock *lock, void *reqp)
449 {
450         return -ELDLM_NO_LOCK_DATA;
451 }
452
453 /**
454  * Enqueue a local lock (typically on a server).
455  */
456 int ldlm_cli_enqueue_local(const struct lu_env *env,
457                            struct ldlm_namespace *ns,
458                            const struct ldlm_res_id *res_id,
459                            enum ldlm_type type, union ldlm_policy_data *policy,
460                            enum ldlm_mode mode, __u64 *flags,
461                            ldlm_blocking_callback blocking,
462                            ldlm_completion_callback completion,
463                            ldlm_glimpse_callback glimpse,
464                            void *data, __u32 lvb_len, enum lvb_type lvb_type,
465                            const __u64 *client_cookie,
466                            struct lustre_handle *lockh)
467 {
468         struct ldlm_lock *lock;
469         int err;
470         const struct ldlm_callback_suite cbs = { .lcs_completion = completion,
471                                                  .lcs_blocking   = blocking,
472                                                  .lcs_glimpse    = glimpse,
473         };
474
475         ENTRY;
476
477         LASSERT(!(*flags & LDLM_FL_REPLAY));
478         if (unlikely(ns_is_client(ns))) {
479                 CERROR("Trying to enqueue local lock in a shadow namespace\n");
480                 LBUG();
481         }
482
483         lock = ldlm_lock_create(ns, res_id, type, mode, &cbs, data, lvb_len,
484                                 lvb_type);
485         if (IS_ERR(lock))
486                 GOTO(out_nolock, err = PTR_ERR(lock));
487
488         err = ldlm_lvbo_init(lock->l_resource);
489         if (err < 0) {
490                 LDLM_ERROR(lock, "delayed lvb init failed (rc %d)", err);
491                 ldlm_lock_destroy_nolock(lock);
492                 GOTO(out, err);
493         }
494
495         ldlm_lock2handle(lock, lockh);
496
497         /*
498          * NB: we don't have any lock now (lock_res_and_lock)
499          * because it's a new lock
500          */
501         ldlm_lock_addref_internal_nolock(lock, mode);
502         ldlm_set_local(lock);
503         if (*flags & LDLM_FL_ATOMIC_CB)
504                 ldlm_set_atomic_cb(lock);
505
506         if (*flags & LDLM_FL_CANCEL_ON_BLOCK)
507                 ldlm_set_cancel_on_block(lock);
508
509         if (policy != NULL)
510                 lock->l_policy_data = *policy;
511         if (client_cookie != NULL)
512                 lock->l_client_cookie = *client_cookie;
513         if (type == LDLM_EXTENT) {
514                 /* extent lock without policy is a bug */
515                 if (policy == NULL)
516                         LBUG();
517
518                 lock->l_req_extent = policy->l_extent;
519         }
520
521         err = ldlm_lock_enqueue(env, ns, &lock, policy, flags);
522         if (unlikely(err != ELDLM_OK))
523                 GOTO(out, err);
524
525         if (policy != NULL)
526                 *policy = lock->l_policy_data;
527
528         if (lock->l_completion_ast)
529                 lock->l_completion_ast(lock, *flags, NULL);
530
531         LDLM_DEBUG(lock, "client-side local enqueue handler, new lock created");
532         EXIT;
533  out:
534         LDLM_LOCK_RELEASE(lock);
535  out_nolock:
536         return err;
537 }
538 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
539
540 static void failed_lock_cleanup(struct ldlm_namespace *ns,
541                                 struct ldlm_lock *lock, int mode)
542 {
543         int need_cancel = 0;
544
545         /* Set a flag to prevent us from sending a CANCEL (b=407) */
546         lock_res_and_lock(lock);
547         /* Check that lock is not granted or failed, we might race. */
548         if (!ldlm_is_granted(lock) && !ldlm_is_failed(lock)) {
549                 /*
550                  * Make sure that this lock will not be found by raced
551                  * bl_ast and -EINVAL reply is sent to server anyways.
552                  * b=17645
553                  */
554                 lock->l_flags |= LDLM_FL_FAILED |
555                                  LDLM_FL_ATOMIC_CB | LDLM_FL_CBPENDING;
556                 if (!(ldlm_is_bl_ast(lock) &&
557                       lock->l_remote_handle.cookie != 0))
558                         lock->l_flags |= LDLM_FL_LOCAL_ONLY;
559                 need_cancel = 1;
560         }
561         unlock_res_and_lock(lock);
562
563         if (need_cancel)
564                 LDLM_DEBUG(lock,
565                            "setting FL_LOCAL_ONLY | LDLM_FL_FAILED | LDLM_FL_ATOMIC_CB | LDLM_FL_CBPENDING");
566         else
567                 LDLM_DEBUG(lock, "lock was granted or failed in race");
568
569         /*
570          * XXX - HACK because we shouldn't call ldlm_lock_destroy()
571          *       from llite/file.c/ll_file_flock().
572          */
573         /*
574          * This code makes for the fact that we do not have blocking handler on
575          * a client for flock locks. As such this is the place where we must
576          * completely kill failed locks. (interrupted and those that
577          * were waiting to be granted when server evicted us.
578          */
579         if (lock->l_resource->lr_type == LDLM_FLOCK) {
580                 lock_res_and_lock(lock);
581                 if (!ldlm_is_destroyed(lock)) {
582                         ldlm_resource_unlink_lock(lock);
583                         ldlm_lock_decref_internal_nolock(lock, mode);
584                         ldlm_lock_destroy_nolock(lock);
585                 }
586                 unlock_res_and_lock(lock);
587         } else {
588                 ldlm_lock_decref_internal(lock, mode);
589         }
590 }
591
592 static bool ldlm_request_slot_needed(struct ldlm_enqueue_info *einfo)
593 {
594         /* exclude EXTENT locks and DOM-only IBITS locks because they
595          * are asynchronous and don't wait on server being blocked.
596          */
597         return einfo->ei_req_slot &&
598                (einfo->ei_type == LDLM_FLOCK ||
599                 (einfo->ei_type == LDLM_IBITS &&
600                  einfo->ei_inodebits != MDS_INODELOCK_DOM));
601 }
602
603 /**
604  * Finishing portion of client lock enqueue code.
605  *
606  * Called after receiving reply from server.
607  */
608 int ldlm_cli_enqueue_fini(struct obd_export *exp, struct req_capsule *pill,
609                           struct ldlm_enqueue_info *einfo,
610                           __u8 with_policy, __u64 *ldlm_flags, void *lvb,
611                           __u32 lvb_len, const struct lustre_handle *lockh,
612                           int rc, bool request_slot)
613 {
614         struct ldlm_namespace *ns = exp->exp_obd->obd_namespace;
615         const struct lu_env *env = NULL;
616         int is_replay = *ldlm_flags & LDLM_FL_REPLAY;
617         struct ldlm_lock *lock;
618         struct ldlm_reply *reply;
619         int cleanup_phase = 1;
620
621         ENTRY;
622
623         if (req_capsule_ptlreq(pill)) {
624                 struct ptlrpc_request *req = pill->rc_req;
625
626                 if (request_slot)
627                         obd_put_request_slot(&req->rq_import->imp_obd->u.cli);
628
629                 ptlrpc_put_mod_rpc_slot(req);
630
631                 if (req && req->rq_svc_thread)
632                         env = req->rq_svc_thread->t_env;
633         }
634
635         lock = ldlm_handle2lock(lockh);
636         /* ldlm_cli_enqueue is holding a reference on this lock. */
637         if (!lock) {
638                 LASSERT(einfo->ei_type == LDLM_FLOCK);
639                 RETURN(-ENOLCK);
640         }
641
642         LASSERTF(ergo(lvb_len != 0, lvb_len == lock->l_lvb_len),
643                  "lvb_len = %d, l_lvb_len = %d\n", lvb_len, lock->l_lvb_len);
644
645         if (rc != ELDLM_OK) {
646                 LASSERT(!is_replay);
647                 LDLM_DEBUG(lock, "client-side enqueue END (%s)",
648                            rc == ELDLM_LOCK_ABORTED ? "ABORTED" : "FAILED");
649
650                 if (rc != ELDLM_LOCK_ABORTED)
651                         GOTO(cleanup, rc);
652         }
653
654         /* Before we return, swab the reply */
655         reply = req_capsule_server_get(pill, &RMF_DLM_REP);
656         if (reply == NULL)
657                 GOTO(cleanup, rc = -EPROTO);
658
659         if (lvb_len > 0) {
660                 int size = 0;
661
662                 size = req_capsule_get_size(pill, &RMF_DLM_LVB, RCL_SERVER);
663                 if (size < 0) {
664                         LDLM_ERROR(lock, "Fail to get lvb_len, rc = %d", size);
665                         GOTO(cleanup, rc = size);
666                 } else if (unlikely(size > lvb_len)) {
667                         LDLM_ERROR(lock,
668                                    "Replied LVB is larger than expectation, expected = %d, replied = %d",
669                                    lvb_len, size);
670                         GOTO(cleanup, rc = -EINVAL);
671                 }
672                 lvb_len = size;
673         }
674
675         if (rc == ELDLM_LOCK_ABORTED) {
676                 if (lvb_len > 0 && lvb != NULL)
677                         rc = ldlm_fill_lvb(lock, pill, RCL_SERVER,
678                                            lvb, lvb_len);
679                 GOTO(cleanup, rc = rc ? : ELDLM_LOCK_ABORTED);
680         }
681
682         /* lock enqueued on the server */
683         cleanup_phase = 0;
684
685         lock_res_and_lock(lock);
686         /* Key change rehash lock in per-export hash with new key */
687         if (exp->exp_lock_hash) {
688                 /*
689                  * In the function below, .hs_keycmp resolves to
690                  * ldlm_export_lock_keycmp()
691                  */
692                 /* coverity[overrun-buffer-val] */
693                 cfs_hash_rehash_key(exp->exp_lock_hash,
694                                     &lock->l_remote_handle,
695                                     &reply->lock_handle,
696                                     &lock->l_exp_hash);
697         } else {
698                 lock->l_remote_handle = reply->lock_handle;
699         }
700
701         *ldlm_flags = ldlm_flags_from_wire(reply->lock_flags);
702         lock->l_flags |= ldlm_flags_from_wire(reply->lock_flags &
703                                               LDLM_FL_INHERIT_MASK);
704         unlock_res_and_lock(lock);
705
706         CDEBUG(D_INFO, "local: %p, remote cookie: %#llx, flags: %#llx\n",
707                lock, reply->lock_handle.cookie, *ldlm_flags);
708
709         /*
710          * If enqueue returned a blocked lock but the completion handler has
711          * already run, then it fixed up the resource and we don't need to do it
712          * again.
713          */
714         if ((*ldlm_flags) & LDLM_FL_LOCK_CHANGED) {
715                 int newmode = reply->lock_desc.l_req_mode;
716
717                 LASSERT(!is_replay);
718                 if (newmode && newmode != lock->l_req_mode) {
719                         LDLM_DEBUG(lock, "server returned different mode %s",
720                                    ldlm_lockname[newmode]);
721                         lock->l_req_mode = newmode;
722                 }
723
724                 if (!ldlm_res_eq(&reply->lock_desc.l_resource.lr_name,
725                                  &lock->l_resource->lr_name)) {
726                         CDEBUG(D_INFO,
727                                "remote intent success, locking "DLDLMRES", instead of "DLDLMRES"\n",
728                                PLDLMRES(&reply->lock_desc.l_resource),
729                                PLDLMRES(lock->l_resource));
730
731                         rc = ldlm_lock_change_resource(ns, lock,
732                                         &reply->lock_desc.l_resource.lr_name);
733                         if (rc || lock->l_resource == NULL)
734                                 GOTO(cleanup, rc = -ENOMEM);
735                         LDLM_DEBUG(lock, "client-side enqueue, new resource");
736                 }
737
738                 if (with_policy) {
739                         /* We assume lock type cannot change on server*/
740                         ldlm_convert_policy_to_local(exp,
741                                                 lock->l_resource->lr_type,
742                                                 &reply->lock_desc.l_policy_data,
743                                                 &lock->l_policy_data);
744                 }
745
746                 if (einfo->ei_type != LDLM_PLAIN)
747                         LDLM_DEBUG(lock,
748                                    "client-side enqueue, new policy data");
749         }
750
751         if ((*ldlm_flags) & LDLM_FL_AST_SENT) {
752                 lock_res_and_lock(lock);
753                 ldlm_bl_desc2lock(&reply->lock_desc, lock);
754                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
755                 unlock_res_and_lock(lock);
756                 LDLM_DEBUG(lock, "enqueue reply includes blocking AST");
757         }
758
759         /*
760          * If the lock has already been granted by a completion AST, don't
761          * clobber the LVB with an older one.
762          */
763         if (lvb_len > 0) {
764                 /*
765                  * We must lock or a racing completion might update lvb without
766                  * letting us know and we'll clobber the correct value.
767                  * Cannot unlock after the check either, a that still leaves
768                  * a tiny window for completion to get in
769                  */
770                 lock_res_and_lock(lock);
771                 if (!ldlm_is_granted(lock))
772                         rc = ldlm_fill_lvb(lock, pill, RCL_SERVER,
773                                            lock->l_lvb_data, lvb_len);
774                 unlock_res_and_lock(lock);
775                 if (rc < 0) {
776                         cleanup_phase = 1;
777                         GOTO(cleanup, rc);
778                 }
779         }
780
781         if (!is_replay) {
782                 rc = ldlm_lock_enqueue(env, ns, &lock, NULL, ldlm_flags);
783                 if (lock->l_completion_ast != NULL) {
784                         int err = lock->l_completion_ast(lock, *ldlm_flags,
785                                                          NULL);
786
787                         if (!rc)
788                                 rc = err;
789                         if (rc)
790                                 cleanup_phase = 1;
791                 }
792         }
793
794         if (lvb_len > 0 && lvb != NULL) {
795                 /*
796                  * Copy the LVB here, and not earlier, because the completion
797                  * AST (if any) can override what we got in the reply
798                  */
799                 memcpy(lvb, lock->l_lvb_data, lvb_len);
800         }
801
802         LDLM_DEBUG(lock, "client-side enqueue END");
803         EXIT;
804 cleanup:
805         if (cleanup_phase == 1 && rc)
806                 failed_lock_cleanup(ns, lock, einfo->ei_mode);
807         /* Put lock 2 times, the second reference is held by ldlm_cli_enqueue */
808         LDLM_LOCK_PUT(lock);
809         LDLM_LOCK_RELEASE(lock);
810         return rc;
811 }
812 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
813
814 /**
815  * Estimate number of lock handles that would fit into request of given
816  * size.  PAGE_SIZE-512 is to allow TCP/IP and LNET headers to fit into
817  * a single page on the send/receive side. XXX: 512 should be changed to
818  * more adequate value.
819  */
820 static inline int ldlm_req_handles_avail(int req_size, int off)
821 {
822         int avail;
823
824         avail = min_t(int, LDLM_MAXREQSIZE, PAGE_SIZE - 512) - req_size;
825         if (likely(avail >= 0))
826                 avail /= (int)sizeof(struct lustre_handle);
827         else
828                 avail = 0;
829         avail += LDLM_LOCKREQ_HANDLES - off;
830
831         return avail;
832 }
833
834 static inline int ldlm_capsule_handles_avail(struct req_capsule *pill,
835                                              enum req_location loc,
836                                              int off)
837 {
838         __u32 size = req_capsule_msg_size(pill, loc);
839
840         return ldlm_req_handles_avail(size, off);
841 }
842
843 static inline int ldlm_format_handles_avail(struct obd_import *imp,
844                                             const struct req_format *fmt,
845                                             enum req_location loc, int off)
846 {
847         __u32 size = req_capsule_fmt_size(imp->imp_msg_magic, fmt, loc);
848
849         return ldlm_req_handles_avail(size, off);
850 }
851
852 /**
853  * Cancel LRU locks and pack them into the enqueue request. Pack there the given
854  * \a count locks in \a cancels.
855  *
856  * This is to be called by functions preparing their own requests that
857  * might contain lists of locks to cancel in addition to actual operation
858  * that needs to be performed.
859  */
860 int ldlm_prep_elc_req(struct obd_export *exp, struct ptlrpc_request *req,
861                       int version, int opc, int canceloff,
862                       struct list_head *cancels, int count)
863 {
864         struct ldlm_namespace   *ns = exp->exp_obd->obd_namespace;
865         struct req_capsule      *pill = &req->rq_pill;
866         struct ldlm_request     *dlm = NULL;
867         LIST_HEAD(head);
868         int avail, to_free = 0, pack = 0;
869         int rc;
870
871         ENTRY;
872
873         if (cancels == NULL)
874                 cancels = &head;
875         if (ns_connect_cancelset(ns)) {
876                 /* Estimate the amount of available space in the request. */
877                 req_capsule_filled_sizes(pill, RCL_CLIENT);
878                 avail = ldlm_capsule_handles_avail(pill, RCL_CLIENT, canceloff);
879
880                 /* If we have reached the limit, free +1 slot for the new one */
881                 if (!ns_connect_lru_resize(ns) && opc == LDLM_ENQUEUE &&
882                     ns->ns_nr_unused >= ns->ns_max_unused)
883                         to_free = 1;
884
885                 /*
886                  * Cancel LRU locks here _only_ if the server supports
887                  * EARLY_CANCEL. Otherwise we have to send extra CANCEL
888                  * RPC, which will make us slower.
889                  */
890                 if (avail > count)
891                         count += ldlm_cancel_lru_local(ns, cancels, to_free,
892                                                        avail - count, 0,
893                                                        LDLM_LRU_FLAG_NO_WAIT);
894                 if (avail > count)
895                         pack = count;
896                 else
897                         pack = avail;
898                 req_capsule_set_size(pill, &RMF_DLM_REQ, RCL_CLIENT,
899                                      ldlm_request_bufsize(pack, opc));
900         }
901
902         rc = ptlrpc_request_pack(req, version, opc);
903         if (rc) {
904                 ldlm_lock_list_put(cancels, l_bl_ast, count);
905                 RETURN(rc);
906         }
907
908         if (ns_connect_cancelset(ns)) {
909                 if (canceloff) {
910                         dlm = req_capsule_client_get(pill, &RMF_DLM_REQ);
911                         LASSERT(dlm);
912                         /*
913                          * Skip first lock handler in ldlm_request_pack(),
914                          * this method will increment @lock_count according
915                          * to the lock handle amount actually written to
916                          * the buffer.
917                          */
918                         dlm->lock_count = canceloff;
919                 }
920                 /* Pack into the request @pack lock handles. */
921                 ldlm_cli_cancel_list(cancels, pack, req, 0);
922                 /* Prepare and send separate cancel RPC for others. */
923                 ldlm_cli_cancel_list(cancels, count - pack, NULL, 0);
924         } else {
925                 ldlm_lock_list_put(cancels, l_bl_ast, count);
926         }
927         RETURN(0);
928 }
929 EXPORT_SYMBOL(ldlm_prep_elc_req);
930
931 int ldlm_prep_enqueue_req(struct obd_export *exp, struct ptlrpc_request *req,
932                           struct list_head *cancels, int count)
933 {
934         return ldlm_prep_elc_req(exp, req, LUSTRE_DLM_VERSION, LDLM_ENQUEUE,
935                                  LDLM_ENQUEUE_CANCEL_OFF, cancels, count);
936 }
937 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
938
939 struct ptlrpc_request *ldlm_enqueue_pack(struct obd_export *exp, int lvb_len)
940 {
941         struct ptlrpc_request *req;
942         int rc;
943
944         ENTRY;
945
946         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LDLM_ENQUEUE);
947         if (req == NULL)
948                 RETURN(ERR_PTR(-ENOMEM));
949
950         rc = ldlm_prep_enqueue_req(exp, req, NULL, 0);
951         if (rc) {
952                 ptlrpc_request_free(req);
953                 RETURN(ERR_PTR(rc));
954         }
955
956         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, lvb_len);
957         ptlrpc_request_set_replen(req);
958         RETURN(req);
959 }
960 EXPORT_SYMBOL(ldlm_enqueue_pack);
961
962 /**
963  * Client-side lock enqueue.
964  *
965  * If a request has some specific initialisation it is passed in \a reqp,
966  * otherwise it is created in ldlm_cli_enqueue.
967  *
968  * Supports sync and async requests, pass \a async flag accordingly. If a
969  * request was created in ldlm_cli_enqueue and it is the async request,
970  * pass it to the caller in \a reqp.
971  */
972 int ldlm_cli_enqueue(struct obd_export *exp, struct ptlrpc_request **reqp,
973                      struct ldlm_enqueue_info *einfo,
974                      const struct ldlm_res_id *res_id,
975                      union ldlm_policy_data const *policy, __u64 *flags,
976                      void *lvb, __u32 lvb_len, enum lvb_type lvb_type,
977                      struct lustre_handle *lockh, int async)
978 {
979         struct ldlm_namespace *ns;
980         struct ldlm_lock      *lock;
981         struct ldlm_request   *body;
982         int                    is_replay = *flags & LDLM_FL_REPLAY;
983         int                    req_passed_in = 1;
984         int                    rc, err;
985         bool                   need_req_slot;
986         struct ptlrpc_request *req;
987
988         ENTRY;
989
990         LASSERT(exp != NULL);
991
992         ns = exp->exp_obd->obd_namespace;
993
994         /*
995          * If we're replaying this lock, just check some invariants.
996          * If we're creating a new lock, get everything all setup nice.
997          */
998         if (is_replay) {
999                 lock = ldlm_handle2lock_long(lockh, 0);
1000                 LASSERT(lock != NULL);
1001                 LDLM_DEBUG(lock, "client-side enqueue START");
1002                 LASSERT(exp == lock->l_conn_export);
1003         } else {
1004                 const struct ldlm_callback_suite cbs = {
1005                         .lcs_completion = einfo->ei_cb_cp,
1006                         .lcs_blocking   = einfo->ei_cb_bl,
1007                         .lcs_glimpse    = einfo->ei_cb_gl
1008                 };
1009                 lock = ldlm_lock_create(ns, res_id, einfo->ei_type,
1010                                         einfo->ei_mode, &cbs, einfo->ei_cbdata,
1011                                         lvb_len, lvb_type);
1012                 if (IS_ERR(lock))
1013                         RETURN(PTR_ERR(lock));
1014
1015                 if (einfo->ei_cb_created)
1016                         einfo->ei_cb_created(lock);
1017
1018                 /* for the local lock, add the reference */
1019                 ldlm_lock_addref_internal(lock, einfo->ei_mode);
1020                 ldlm_lock2handle(lock, lockh);
1021                 if (policy != NULL)
1022                         lock->l_policy_data = *policy;
1023
1024                 if (einfo->ei_type == LDLM_EXTENT) {
1025                         /* extent lock without policy is a bug */
1026                         if (policy == NULL)
1027                                 LBUG();
1028
1029                         lock->l_req_extent = policy->l_extent;
1030                 }
1031                 LDLM_DEBUG(lock, "client-side enqueue START, flags %#llx",
1032                            *flags);
1033         }
1034
1035         lock->l_conn_export = exp;
1036         lock->l_export = NULL;
1037         lock->l_blocking_ast = einfo->ei_cb_bl;
1038         lock->l_flags |= (*flags & (LDLM_FL_NO_LRU | LDLM_FL_EXCL));
1039         lock->l_activity = ktime_get_real_seconds();
1040
1041         /* lock not sent to server yet */
1042         if (reqp == NULL || *reqp == NULL) {
1043                 req = ldlm_enqueue_pack(exp, lvb_len);
1044                 if (IS_ERR(req)) {
1045                         failed_lock_cleanup(ns, lock, einfo->ei_mode);
1046                         LDLM_LOCK_RELEASE(lock);
1047                         RETURN(PTR_ERR(req));
1048                 }
1049
1050                 req_passed_in = 0;
1051                 if (reqp)
1052                         *reqp = req;
1053         } else {
1054                 int len;
1055
1056                 req = *reqp;
1057                 len = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ,
1058                                            RCL_CLIENT);
1059                 LASSERTF(len >= sizeof(*body), "buflen[%d] = %d, not %d\n",
1060                          DLM_LOCKREQ_OFF, len, (int)sizeof(*body));
1061         }
1062
1063         if (*flags & LDLM_FL_NDELAY) {
1064                 DEBUG_REQ(D_DLMTRACE, req, "enqueue lock with no delay");
1065                 req->rq_no_resend = req->rq_no_delay = 1;
1066                 /*
1067                  * probably set a shorter timeout value and handle ETIMEDOUT
1068                  * in osc_lock_upcall() correctly
1069                  */
1070                 /* lustre_msg_set_timeout(req, req->rq_timeout / 2); */
1071         }
1072
1073         /* Dump lock data into the request buffer */
1074         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1075         ldlm_lock2desc(lock, &body->lock_desc);
1076         body->lock_flags = ldlm_flags_to_wire(*flags);
1077         body->lock_handle[0] = *lockh;
1078
1079         /* extended LDLM opcodes in client stats */
1080         if (exp->exp_obd->obd_svc_stats != NULL) {
1081                 /* glimpse is intent with no intent buffer */
1082                 if (*flags & LDLM_FL_HAS_INTENT &&
1083                     !req_capsule_has_field(&req->rq_pill, &RMF_LDLM_INTENT,
1084                                            RCL_CLIENT))
1085                         lprocfs_counter_incr(exp->exp_obd->obd_svc_stats,
1086                                              PTLRPC_LAST_CNTR +
1087                                              LDLM_GLIMPSE_ENQUEUE);
1088                 else
1089                         ldlm_svc_get_eopc(body, exp->exp_obd->obd_svc_stats);
1090         }
1091
1092         /* It is important to obtain modify RPC slot first (if applicable), so
1093          * that threads that are waiting for a modify RPC slot are not polluting
1094          * our rpcs in flight counter. */
1095
1096         if (einfo->ei_mod_slot)
1097                 ptlrpc_get_mod_rpc_slot(req);
1098
1099         need_req_slot = ldlm_request_slot_needed(einfo);
1100
1101         if (need_req_slot) {
1102                 rc = obd_get_request_slot(&req->rq_import->imp_obd->u.cli);
1103                 if (rc) {
1104                         if (einfo->ei_mod_slot)
1105                                 ptlrpc_put_mod_rpc_slot(req);
1106                         failed_lock_cleanup(ns, lock, einfo->ei_mode);
1107                         LDLM_LOCK_RELEASE(lock);
1108                         if (!req_passed_in)
1109                                 ptlrpc_req_finished(req);
1110                         GOTO(out, rc);
1111                 }
1112         }
1113
1114         if (async) {
1115                 LASSERT(reqp != NULL);
1116                 RETURN(0);
1117         }
1118
1119         LDLM_DEBUG(lock, "sending request");
1120
1121         rc = ptlrpc_queue_wait(req);
1122
1123         err = ldlm_cli_enqueue_fini(exp, &req->rq_pill, einfo, policy ? 1 : 0,
1124                                     flags, lvb, lvb_len, lockh, rc,
1125                                     need_req_slot);
1126
1127         /*
1128          * If ldlm_cli_enqueue_fini did not find the lock, we need to free
1129          * one reference that we took
1130          */
1131         if (err == -ENOLCK)
1132                 LDLM_LOCK_RELEASE(lock);
1133         else
1134                 rc = err;
1135
1136 out:
1137         if (!req_passed_in && req != NULL) {
1138                 ptlrpc_req_finished(req);
1139                 if (reqp)
1140                         *reqp = NULL;
1141         }
1142
1143         RETURN(rc);
1144 }
1145 EXPORT_SYMBOL(ldlm_cli_enqueue);
1146
1147 /**
1148  * Client-side IBITS lock create and pack for WBC EX lock request.
1149  */
1150 int ldlm_cli_lock_create_pack(struct obd_export *exp,
1151                               struct ldlm_request *dlmreq,
1152                               struct ldlm_enqueue_info *einfo,
1153                               const struct ldlm_res_id *res_id,
1154                               union ldlm_policy_data const *policy,
1155                               __u64 *flags, void *lvb, __u32 lvb_len,
1156                               enum lvb_type lvb_type,
1157                               struct lustre_handle *lockh)
1158 {
1159         const struct ldlm_callback_suite cbs = {
1160                 .lcs_completion = einfo->ei_cb_cp,
1161                 .lcs_blocking   = einfo->ei_cb_bl,
1162                 .lcs_glimpse    = einfo->ei_cb_gl
1163         };
1164         struct ldlm_namespace *ns;
1165         struct ldlm_lock *lock;
1166
1167         ENTRY;
1168
1169         LASSERT(exp != NULL);
1170         LASSERT(!(*flags & LDLM_FL_REPLAY));
1171
1172         ns = exp->exp_obd->obd_namespace;
1173         lock = ldlm_lock_create(ns, res_id, einfo->ei_type, einfo->ei_mode,
1174                                 &cbs, einfo->ei_cbdata, lvb_len, lvb_type);
1175         if (IS_ERR(lock))
1176                 RETURN(PTR_ERR(lock));
1177
1178         if (einfo->ei_cb_created)
1179                 einfo->ei_cb_created(lock);
1180
1181         /* For the local lock, add the reference */
1182         ldlm_lock_addref_internal(lock, einfo->ei_mode);
1183         ldlm_lock2handle(lock, lockh);
1184         if (policy != NULL)
1185                 lock->l_policy_data = *policy;
1186
1187         LDLM_DEBUG(lock, "client-side enqueue START, flags %#llx", *flags);
1188         lock->l_conn_export = exp;
1189         lock->l_export = NULL;
1190         lock->l_blocking_ast = einfo->ei_cb_bl;
1191         lock->l_flags |= (*flags & (LDLM_FL_NO_LRU | LDLM_FL_EXCL |
1192                                     LDLM_FL_ATOMIC_CB));
1193         lock->l_activity = ktime_get_real_seconds();
1194
1195         ldlm_lock2desc(lock, &dlmreq->lock_desc);
1196         dlmreq->lock_flags = ldlm_flags_to_wire(*flags);
1197         dlmreq->lock_handle[0] = *lockh;
1198
1199         RETURN(0);
1200 }
1201 EXPORT_SYMBOL(ldlm_cli_lock_create_pack);
1202
1203 /**
1204  * Client-side IBITS lock convert.
1205  *
1206  * Inform server that lock has been converted instead of canceling.
1207  * Server finishes convert on own side and does reprocess to grant
1208  * all related waiting locks.
1209  *
1210  * Since convert means only ibits downgrading, client doesn't need to
1211  * wait for server reply to finish local converting process so this request
1212  * is made asynchronous.
1213  *
1214  */
1215 int ldlm_cli_convert_req(struct ldlm_lock *lock, __u32 *flags, __u64 new_bits)
1216 {
1217         struct ldlm_request *body;
1218         struct ptlrpc_request *req;
1219         struct obd_export *exp = lock->l_conn_export;
1220
1221         ENTRY;
1222
1223         LASSERT(exp != NULL);
1224
1225         /*
1226          * this is better to check earlier and it is done so already,
1227          * but this check is kept too as final one to issue an error
1228          * if any new code will miss such check.
1229          */
1230         if (!exp_connect_lock_convert(exp)) {
1231                 LDLM_ERROR(lock, "server doesn't support lock convert\n");
1232                 RETURN(-EPROTO);
1233         }
1234
1235         if (lock->l_resource->lr_type != LDLM_IBITS) {
1236                 LDLM_ERROR(lock, "convert works with IBITS locks only.");
1237                 RETURN(-EINVAL);
1238         }
1239
1240         LDLM_DEBUG(lock, "client-side convert");
1241
1242         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1243                                         &RQF_LDLM_CONVERT, LUSTRE_DLM_VERSION,
1244                                         LDLM_CONVERT);
1245         if (req == NULL)
1246                 RETURN(-ENOMEM);
1247
1248         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1249         body->lock_handle[0] = lock->l_remote_handle;
1250
1251         body->lock_desc.l_req_mode = lock->l_req_mode;
1252         body->lock_desc.l_granted_mode = lock->l_granted_mode;
1253
1254         body->lock_desc.l_policy_data.l_inodebits.bits = new_bits;
1255         body->lock_desc.l_policy_data.l_inodebits.cancel_bits = 0;
1256
1257         body->lock_flags = ldlm_flags_to_wire(*flags);
1258         body->lock_count = 1;
1259
1260         ptlrpc_request_set_replen(req);
1261
1262         /*
1263          * Use cancel portals for convert as well as high-priority handling.
1264          */
1265         req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1266         req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1267
1268         ptlrpc_at_set_req_timeout(req);
1269
1270         if (exp->exp_obd->obd_svc_stats != NULL)
1271                 lprocfs_counter_incr(exp->exp_obd->obd_svc_stats,
1272                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1273
1274         ptlrpcd_add_req(req);
1275         RETURN(0);
1276 }
1277
1278 /**
1279  * Cancel locks locally.
1280  * Returns:
1281  * \retval LDLM_FL_LOCAL_ONLY if there is no need for a CANCEL RPC to the server
1282  * \retval LDLM_FL_CANCELING otherwise;
1283  * \retval LDLM_FL_BL_AST if there is a need for a separate CANCEL RPC.
1284  */
1285 static __u64 ldlm_cli_cancel_local(struct ldlm_lock *lock)
1286 {
1287         __u64 rc = LDLM_FL_LOCAL_ONLY;
1288
1289         ENTRY;
1290
1291         if (lock->l_conn_export) {
1292                 bool local_only;
1293
1294                 LDLM_DEBUG(lock, "client-side cancel");
1295                 CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL_LOCAL,
1296                                  cfs_fail_val);
1297
1298                 /* Set this flag to prevent others from getting new references*/
1299                 lock_res_and_lock(lock);
1300                 ldlm_set_cbpending(lock);
1301                 local_only = !!(lock->l_flags &
1302                                 (LDLM_FL_LOCAL_ONLY|LDLM_FL_CANCEL_ON_BLOCK));
1303                 ldlm_cancel_callback(lock);
1304                 rc = (ldlm_is_bl_ast(lock)) ?
1305                         LDLM_FL_BL_AST : LDLM_FL_CANCELING;
1306                 unlock_res_and_lock(lock);
1307
1308                 if (local_only) {
1309                         CDEBUG(D_DLMTRACE,
1310                                "not sending request (at caller's instruction)\n");
1311                         rc = LDLM_FL_LOCAL_ONLY;
1312                 }
1313                 ldlm_lock_cancel(lock);
1314         } else {
1315                 if (ns_is_client(ldlm_lock_to_ns(lock))) {
1316                         LDLM_ERROR(lock, "Trying to cancel local lock");
1317                         LBUG();
1318                 }
1319                 LDLM_DEBUG(lock, "server-side local cancel");
1320                 ldlm_lock_cancel(lock);
1321                 ldlm_reprocess_all(lock->l_resource,
1322                                    lock->l_policy_data.l_inodebits.bits);
1323         }
1324
1325         RETURN(rc);
1326 }
1327
1328 static inline int __ldlm_pack_lock(struct ldlm_lock *lock,
1329                                    struct ldlm_request *dlm)
1330 {
1331         LASSERT(lock->l_conn_export);
1332         lock_res_and_lock(lock);
1333         if (ldlm_is_ast_sent(lock)) {
1334                 unlock_res_and_lock(lock);
1335                 return 0;
1336         }
1337         ldlm_set_ast_sent(lock);
1338         unlock_res_and_lock(lock);
1339
1340         /* Pack the lock handle to the given request buffer. */
1341         LDLM_DEBUG(lock, "packing");
1342         dlm->lock_handle[dlm->lock_count++] = lock->l_remote_handle;
1343
1344         return 1;
1345 }
1346 #define ldlm_cancel_pack(req, head, count) \
1347                 _ldlm_cancel_pack(req, NULL, head, count)
1348 /**
1349  * Pack \a count locks in \a head into ldlm_request buffer of request \a req.
1350  */
1351 static int _ldlm_cancel_pack(struct ptlrpc_request *req, struct ldlm_lock *lock,
1352                              struct list_head *head, int count)
1353 {
1354         struct ldlm_request *dlm;
1355         int max, packed = 0;
1356
1357         ENTRY;
1358
1359         dlm = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1360         LASSERT(dlm != NULL);
1361
1362         /* Check the room in the request buffer. */
1363         max = req_capsule_get_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT) -
1364                 sizeof(struct ldlm_request);
1365         max /= sizeof(struct lustre_handle);
1366         max += LDLM_LOCKREQ_HANDLES;
1367         LASSERT(max >= dlm->lock_count + count);
1368
1369         /*
1370          * XXX: it would be better to pack lock handles grouped by resource.
1371          * so that the server cancel would call filter_lvbo_update() less
1372          * frequently.
1373          */
1374         if (lock) { /* only pack one lock */
1375                 packed = __ldlm_pack_lock(lock, dlm);
1376         } else {
1377                 list_for_each_entry(lock, head, l_bl_ast) {
1378                         if (!count--)
1379                                 break;
1380                         packed += __ldlm_pack_lock(lock, dlm);
1381                 }
1382         }
1383         CDEBUG(D_DLMTRACE, "%d locks packed\n", packed);
1384         RETURN(packed);
1385 }
1386
1387 /**
1388  * Prepare and send a batched cancel RPC. It will include \a count lock
1389  * handles of locks given in \a cancels list.
1390  */
1391 int ldlm_cli_cancel_req(struct obd_export *exp, struct ldlm_lock *lock,
1392                         struct list_head *head, int count,
1393                         enum ldlm_cancel_flags flags)
1394 {
1395         struct ptlrpc_request *req = NULL;
1396         struct obd_import *imp;
1397         int free, sent = 0;
1398         int rc = 0;
1399
1400         ENTRY;
1401
1402         LASSERT(exp != NULL);
1403         LASSERT(count > 0);
1404         LASSERT(head == NULL || lock == NULL);
1405
1406         CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_PAUSE_CANCEL, cfs_fail_val);
1407
1408         if (CFS_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_RACE))
1409                 RETURN(count);
1410
1411         free = ldlm_format_handles_avail(class_exp2cliimp(exp),
1412                                          &RQF_LDLM_CANCEL, RCL_CLIENT, 0);
1413         if (count > free)
1414                 count = free;
1415
1416         while (1) {
1417                 imp = class_exp2cliimp(exp);
1418                 if (imp == NULL || imp->imp_invalid) {
1419                         CDEBUG(D_DLMTRACE,
1420                                "skipping cancel on invalid import %p\n", imp);
1421                         RETURN(count);
1422                 }
1423
1424                 req = ptlrpc_request_alloc(imp, &RQF_LDLM_CANCEL);
1425                 if (req == NULL)
1426                         GOTO(out, rc = -ENOMEM);
1427
1428                 req_capsule_filled_sizes(&req->rq_pill, RCL_CLIENT);
1429                 req_capsule_set_size(&req->rq_pill, &RMF_DLM_REQ, RCL_CLIENT,
1430                                      ldlm_request_bufsize(count, LDLM_CANCEL));
1431
1432                 rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CANCEL);
1433                 if (rc) {
1434                         ptlrpc_request_free(req);
1435                         GOTO(out, rc);
1436                 }
1437
1438                 /*
1439                  * If OSP want cancel cross-MDT lock, let's not block it in
1440                  * in recovery, otherwise the lock will not released, if
1441                  * the remote target is also in recovery, and it also need
1442                  * this lock, it might cause deadlock.
1443                  */
1444                 if (exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS &&
1445                     exp->exp_obd->obd_lu_dev != NULL &&
1446                     exp->exp_obd->obd_lu_dev->ld_site != NULL) {
1447                         struct lu_device *top_dev;
1448
1449                         top_dev = exp->exp_obd->obd_lu_dev->ld_site->ls_top_dev;
1450                         if (top_dev != NULL &&
1451                             top_dev->ld_obd->obd_recovering)
1452                                 req->rq_allow_replay = 1;
1453                 }
1454
1455                 req->rq_request_portal = LDLM_CANCEL_REQUEST_PORTAL;
1456                 req->rq_reply_portal = LDLM_CANCEL_REPLY_PORTAL;
1457                 ptlrpc_at_set_req_timeout(req);
1458
1459                 rc = _ldlm_cancel_pack(req, lock, head, count);
1460                 if (rc == 0) {
1461                         ptlrpc_req_finished(req);
1462                         sent = count;
1463                         GOTO(out, rc);
1464                 }
1465
1466                 ptlrpc_request_set_replen(req);
1467                 if (flags & LCF_ASYNC) {
1468                         ptlrpcd_add_req(req);
1469                         sent = count;
1470                         GOTO(out, 0);
1471                 }
1472
1473                 rc = ptlrpc_queue_wait(req);
1474                 if (rc == LUSTRE_ESTALE) {
1475                         CDEBUG(D_DLMTRACE,
1476                                "client/server (nid %s) out of sync -- not fatal\n",
1477                                libcfs_nidstr(&req->rq_import->imp_connection->c_peer.nid));
1478                         rc = 0;
1479                 } else if (rc == -ETIMEDOUT && /* check there was no reconnect*/
1480                            req->rq_import_generation == imp->imp_generation) {
1481                         ptlrpc_req_finished(req);
1482                         continue;
1483                 } else if (rc != ELDLM_OK) {
1484                         /* -ESHUTDOWN is common on umount */
1485                         CDEBUG_LIMIT(rc == -ESHUTDOWN ? D_DLMTRACE : D_ERROR,
1486                                      "Got rc %d from cancel RPC: canceling anyway\n",
1487                                      rc);
1488                         break;
1489                 }
1490                 sent = count;
1491                 break;
1492         }
1493
1494         ptlrpc_req_finished(req);
1495         EXIT;
1496 out:
1497         return sent ? sent : rc;
1498 }
1499
1500 static inline struct ldlm_pool *ldlm_imp2pl(struct obd_import *imp)
1501 {
1502         LASSERT(imp != NULL);
1503         return &imp->imp_obd->obd_namespace->ns_pool;
1504 }
1505
1506 /**
1507  * Update client's OBD pool related fields with new SLV and Limit from \a req.
1508  */
1509 int ldlm_cli_update_pool(struct ptlrpc_request *req)
1510 {
1511         struct ldlm_namespace *ns;
1512         struct obd_device *obd;
1513         __u64 new_slv, ratio;
1514         __u32 new_limit;
1515
1516         ENTRY;
1517         if (unlikely(!req->rq_import || !req->rq_import->imp_obd ||
1518                      !imp_connect_lru_resize(req->rq_import)))
1519                 /* Do nothing for corner cases. */
1520                 RETURN(0);
1521
1522         /*
1523          * In some cases RPC may contain SLV and limit zeroed out. This
1524          * is the case when server does not support LRU resize feature.
1525          * This is also possible in some recovery cases when server-side
1526          * reqs have no reference to the OBD export and thus access to
1527          * server-side namespace is not possible.
1528          */
1529         if (lustre_msg_get_slv(req->rq_repmsg) == 0 ||
1530             lustre_msg_get_limit(req->rq_repmsg) == 0) {
1531                 DEBUG_REQ(D_HA, req,
1532                           "Zero SLV or limit found (SLV=%llu, limit=%u)",
1533                           lustre_msg_get_slv(req->rq_repmsg),
1534                           lustre_msg_get_limit(req->rq_repmsg));
1535                 RETURN(0);
1536         }
1537
1538         new_limit = lustre_msg_get_limit(req->rq_repmsg);
1539         new_slv = lustre_msg_get_slv(req->rq_repmsg);
1540         obd = req->rq_import->imp_obd;
1541
1542         read_lock(&obd->obd_pool_lock);
1543         if (obd->obd_pool_slv == new_slv &&
1544             obd->obd_pool_limit == new_limit) {
1545                 read_unlock(&obd->obd_pool_lock);
1546                 RETURN(0);
1547         }
1548         read_unlock(&obd->obd_pool_lock);
1549
1550         /*
1551          * OBD device keeps the new pool attributes before they are handled by
1552          * the pool.
1553          */
1554         write_lock(&obd->obd_pool_lock);
1555         obd->obd_pool_slv = new_slv;
1556         obd->obd_pool_limit = new_limit;
1557         write_unlock(&obd->obd_pool_lock);
1558
1559         /*
1560          * Check if an urgent pool recalc is needed, let it to be a change of
1561          * SLV on 10%. It is applicable to LRU resize enabled case only.
1562          */
1563         ns = obd->obd_namespace;
1564         if (!ns_connect_lru_resize(ns) ||
1565             ldlm_pool_get_slv(&ns->ns_pool) < new_slv)
1566                 RETURN(0);
1567
1568         ratio = 100 * new_slv / ldlm_pool_get_slv(&ns->ns_pool);
1569         if (100 - ratio >= ns->ns_recalc_pct &&
1570             !ns->ns_stopping && !ns->ns_rpc_recalc) {
1571                 bool recalc = false;
1572
1573                 spin_lock(&ns->ns_lock);
1574                 if (!ns->ns_stopping && !ns->ns_rpc_recalc) {
1575                         ldlm_namespace_get(ns);
1576                         recalc = true;
1577                         ns->ns_rpc_recalc = 1;
1578                 }
1579                 spin_unlock(&ns->ns_lock);
1580                 if (recalc)
1581                         ldlm_bl_to_thread_ns(ns);
1582         }
1583
1584         RETURN(0);
1585 }
1586
1587 int ldlm_cli_convert(struct ldlm_lock *lock,
1588                      enum ldlm_cancel_flags cancel_flags)
1589 {
1590         int rc = -EINVAL;
1591
1592         LASSERT(!lock->l_readers && !lock->l_writers);
1593         LDLM_DEBUG(lock, "client lock convert START");
1594
1595         if (lock->l_resource->lr_type == LDLM_IBITS) {
1596                 lock_res_and_lock(lock);
1597                 do {
1598                         rc = ldlm_cli_inodebits_convert(lock, cancel_flags);
1599                 } while (rc == -EAGAIN);
1600                 unlock_res_and_lock(lock);
1601         }
1602
1603         LDLM_DEBUG(lock, "client lock convert END");
1604         RETURN(rc);
1605 }
1606 EXPORT_SYMBOL(ldlm_cli_convert);
1607
1608 /**
1609  * Client side lock cancel.
1610  *
1611  * Lock must not have any readers or writers by this time.
1612  */
1613 int ldlm_cli_cancel(const struct lustre_handle *lockh,
1614                     enum ldlm_cancel_flags flags)
1615 {
1616         struct obd_export *exp;
1617         int avail, count = 1, separate = 0;
1618         enum ldlm_lru_flags lru_flags = 0;
1619         __u64 rc = 0;
1620         struct ldlm_namespace *ns;
1621         struct ldlm_lock *lock;
1622         LIST_HEAD(cancels);
1623
1624         ENTRY;
1625
1626         lock = ldlm_handle2lock_long(lockh, 0);
1627         if (lock == NULL) {
1628                 LDLM_DEBUG_NOLOCK("lock is already being destroyed");
1629                 RETURN(0);
1630         }
1631
1632         lock_res_and_lock(lock);
1633         LASSERT(!ldlm_is_converting(lock));
1634
1635         if (ldlm_is_bl_ast(lock)) {
1636                 if (ldlm_is_ast_sent(lock)) {
1637                         unlock_res_and_lock(lock);
1638                         LDLM_LOCK_RELEASE(lock);
1639                         RETURN(0);
1640                 }
1641                 if (ldlm_is_canceling(lock))
1642                         separate = 1;
1643         } else if (ldlm_is_canceling(lock)) {
1644                 /* Lock is being canceled and the caller doesn't want to wait */
1645                 if (flags & LCF_ASYNC) {
1646                         unlock_res_and_lock(lock);
1647                 } else {
1648                         unlock_res_and_lock(lock);
1649                         wait_event_idle(lock->l_waitq, is_bl_done(lock));
1650                 }
1651                 LDLM_LOCK_RELEASE(lock);
1652                 RETURN(0);
1653         }
1654
1655         ldlm_set_canceling(lock);
1656         unlock_res_and_lock(lock);
1657
1658         if (flags & LCF_LOCAL)
1659                 CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_LOCAL_CANCEL_PAUSE,
1660                                  cfs_fail_val);
1661
1662         rc = ldlm_cli_cancel_local(lock);
1663         if (rc == LDLM_FL_LOCAL_ONLY || flags & LCF_LOCAL) {
1664                 LDLM_LOCK_RELEASE(lock);
1665                 RETURN(0);
1666         } else if (rc == LDLM_FL_BL_AST) {
1667                 /* BL_AST lock must not wait. */
1668                 lru_flags |= LDLM_LRU_FLAG_NO_WAIT;
1669         }
1670
1671         exp = lock->l_conn_export;
1672         /* If a lock has been taken from lru for a batched cancel and a later
1673          * BL_AST came, send a CANCEL RPC individually for it right away, not
1674          * waiting for the batch to be handled. */
1675         if (separate) {
1676                 ldlm_cli_cancel_req(exp, lock, NULL, 1, flags);
1677                 LDLM_LOCK_RELEASE(lock);
1678                 RETURN(0);
1679         }
1680
1681         LASSERT(list_empty(&lock->l_bl_ast));
1682         list_add(&lock->l_bl_ast, &cancels);
1683         /*
1684          * This is a LDLM_CANCEL RPC which goes to canceld portal,
1685          * so we can cancel other LRU locks here and send them all
1686          * as one LDLM_CANCEL RPC.
1687          */
1688         if (exp_connect_cancelset(exp)) {
1689                 avail = ldlm_format_handles_avail(class_exp2cliimp(exp),
1690                                                   &RQF_LDLM_CANCEL,
1691                                                   RCL_CLIENT, 0);
1692                 LASSERT(avail > 0);
1693
1694                 ns = ldlm_lock_to_ns(lock);
1695                 count += ldlm_cancel_lru_local(ns, &cancels, 0, avail - 1,
1696                                                LCF_BL_AST, lru_flags);
1697         }
1698         ldlm_cli_cancel_list(&cancels, count, NULL, flags);
1699
1700         RETURN(0);
1701 }
1702 EXPORT_SYMBOL(ldlm_cli_cancel);
1703
1704 /**
1705  * Locally cancel up to \a count locks in list \a cancels.
1706  * Return the number of cancelled locks.
1707  */
1708 int ldlm_cli_cancel_list_local(struct list_head *cancels, int count,
1709                                enum ldlm_cancel_flags cancel_flags)
1710 {
1711         LIST_HEAD(head);
1712         struct ldlm_lock *lock, *next;
1713         int left = 0, bl_ast = 0;
1714         __u64 rc;
1715
1716         left = count;
1717         list_for_each_entry_safe(lock, next, cancels, l_bl_ast) {
1718                 if (left-- == 0)
1719                         break;
1720
1721                 if (cancel_flags & LCF_LOCAL) {
1722                         rc = LDLM_FL_LOCAL_ONLY;
1723                         ldlm_lock_cancel(lock);
1724                 } else {
1725                         rc = ldlm_cli_cancel_local(lock);
1726                 }
1727                 /*
1728                  * Until we have compound requests and can send LDLM_CANCEL
1729                  * requests batched with generic RPCs, we need to send cancels
1730                  * with the LDLM_FL_BL_AST flag in a separate RPC from
1731                  * the one being generated now.
1732                  */
1733                 if (!(cancel_flags & LCF_BL_AST) && (rc == LDLM_FL_BL_AST)) {
1734                         LDLM_DEBUG(lock, "Cancel lock separately");
1735                         list_move(&lock->l_bl_ast, &head);
1736                         bl_ast++;
1737                         continue;
1738                 }
1739                 if (rc == LDLM_FL_LOCAL_ONLY) {
1740                         /* CANCEL RPC should not be sent to server. */
1741                         list_del_init(&lock->l_bl_ast);
1742                         LDLM_LOCK_RELEASE(lock);
1743                         count--;
1744                 }
1745         }
1746         if (bl_ast > 0) {
1747                 count -= bl_ast;
1748                 ldlm_cli_cancel_list(&head, bl_ast, NULL, cancel_flags);
1749         }
1750
1751         RETURN(count);
1752 }
1753
1754 /**
1755  * Cancel as many locks as possible w/o sending any RPCs (e.g. to write back
1756  * dirty data, to close a file, ...) or waiting for any RPCs in-flight (e.g.
1757  * readahead requests, ...)
1758  */
1759 static enum ldlm_policy_res
1760 ldlm_cancel_no_wait_policy(struct ldlm_namespace *ns, struct ldlm_lock *lock,
1761                            int added, int min)
1762 {
1763         enum ldlm_policy_res result = LDLM_POLICY_CANCEL_LOCK;
1764
1765         /*
1766          * don't check @added & @min since we want to process all locks
1767          * from unused list.
1768          * It's fine to not take lock to access lock->l_resource since
1769          * the lock has already been granted so it won't change.
1770          */
1771         switch (lock->l_resource->lr_type) {
1772                 case LDLM_EXTENT:
1773                 case LDLM_IBITS:
1774                         if (ns->ns_cancel != NULL && ns->ns_cancel(lock) != 0)
1775                                 break;
1776                         fallthrough;
1777                 default:
1778                         result = LDLM_POLICY_SKIP_LOCK;
1779                         break;
1780         }
1781
1782         RETURN(result);
1783 }
1784
1785 /**
1786  * Callback function for LRU-resize policy. Decides whether to keep
1787  * \a lock in LRU for \a added in current scan and \a min number of locks
1788  * to be preferably canceled.
1789  *
1790  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1791  *
1792  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1793  */
1794 static enum ldlm_policy_res ldlm_cancel_lrur_policy(struct ldlm_namespace *ns,
1795                                                     struct ldlm_lock *lock,
1796                                                     int added, int min)
1797 {
1798         ktime_t cur = ktime_get();
1799         struct ldlm_pool *pl = &ns->ns_pool;
1800         u64 slv, lvf, lv;
1801         s64 la;
1802
1803         if (added < min)
1804                 return LDLM_POLICY_CANCEL_LOCK;
1805
1806         /*
1807          * Despite of the LV, It doesn't make sense to keep the lock which
1808          * is unused for ns_max_age time.
1809          */
1810         if (ktime_after(cur, ktime_add(lock->l_last_used, ns->ns_max_age)))
1811                 return LDLM_POLICY_CANCEL_LOCK;
1812
1813         slv = ldlm_pool_get_slv(pl);
1814         lvf = ldlm_pool_get_lvf(pl);
1815         la = div_u64(ktime_to_ns(ktime_sub(cur, lock->l_last_used)),
1816                      NSEC_PER_SEC);
1817         lv = lvf * la * ns->ns_nr_unused >> 8;
1818
1819         /* Inform pool about current CLV to see it via debugfs. */
1820         ldlm_pool_set_clv(pl, lv);
1821
1822         /*
1823          * Stop when SLV is not yet come from server or lv is smaller than
1824          * it is.
1825          */
1826         if (slv == 0 || lv < slv)
1827                 return LDLM_POLICY_KEEP_LOCK;
1828
1829         return LDLM_POLICY_CANCEL_LOCK;
1830 }
1831
1832 static enum ldlm_policy_res
1833 ldlm_cancel_lrur_no_wait_policy(struct ldlm_namespace *ns,
1834                                 struct ldlm_lock *lock,
1835                                 int added, int min)
1836 {
1837         enum ldlm_policy_res result;
1838
1839         result = ldlm_cancel_lrur_policy(ns, lock, added, min);
1840         if (result == LDLM_POLICY_KEEP_LOCK)
1841                 return result;
1842
1843         return ldlm_cancel_no_wait_policy(ns, lock, added, min);
1844 }
1845
1846 /**
1847  * Callback function for aged policy. Decides whether to keep
1848  * \a lock in LRU for \a added in current scan and \a min number of locks
1849  * to be preferably canceled.
1850  *
1851  * \retval LDLM_POLICY_KEEP_LOCK keep lock in LRU in stop scanning
1852  *
1853  * \retval LDLM_POLICY_CANCEL_LOCK cancel lock from LRU
1854  */
1855 static enum ldlm_policy_res ldlm_cancel_aged_policy(struct ldlm_namespace *ns,
1856                                                     struct ldlm_lock *lock,
1857                                                     int added, int min)
1858 {
1859         if ((added >= min) &&
1860             ktime_before(ktime_get(),
1861                          ktime_add(lock->l_last_used, ns->ns_max_age)))
1862                 return LDLM_POLICY_KEEP_LOCK;
1863
1864         return LDLM_POLICY_CANCEL_LOCK;
1865 }
1866
1867 static enum ldlm_policy_res
1868 ldlm_cancel_aged_no_wait_policy(struct ldlm_namespace *ns,
1869                                 struct ldlm_lock *lock,
1870                                 int added, int min)
1871 {
1872         enum ldlm_policy_res result;
1873
1874         result = ldlm_cancel_aged_policy(ns, lock, added, min);
1875         if (result == LDLM_POLICY_KEEP_LOCK)
1876                 return result;
1877
1878         return ldlm_cancel_no_wait_policy(ns, lock, added, min);
1879 }
1880
1881 typedef enum ldlm_policy_res
1882 (*ldlm_cancel_lru_policy_t)(struct ldlm_namespace *ns, struct ldlm_lock *lock,
1883                             int added, int min);
1884
1885 static ldlm_cancel_lru_policy_t
1886 ldlm_cancel_lru_policy(struct ldlm_namespace *ns, enum ldlm_lru_flags lru_flags)
1887 {
1888         if (ns_connect_lru_resize(ns)) {
1889                 if (lru_flags & LDLM_LRU_FLAG_NO_WAIT)
1890                         return ldlm_cancel_lrur_no_wait_policy;
1891                 else
1892                         return ldlm_cancel_lrur_policy;
1893         } else {
1894                 if (lru_flags & LDLM_LRU_FLAG_NO_WAIT)
1895                         return ldlm_cancel_aged_no_wait_policy;
1896                 else
1897                         return ldlm_cancel_aged_policy;
1898         }
1899 }
1900
1901 /**
1902  * - Free space in LRU for \a min new locks,
1903  *   redundant unused locks are canceled locally;
1904  * - also cancel locally unused aged locks;
1905  * - do not cancel more than \a max locks;
1906  * - if some locks are cancelled, try to cancel at least \a batch locks
1907  * - GET the found locks and add them into the \a cancels list.
1908  *
1909  * A client lock can be added to the l_bl_ast list only when it is
1910  * marked LDLM_FL_CANCELING. Otherwise, somebody is already doing
1911  * CANCEL.  There are the following use cases:
1912  * ldlm_cancel_resource_local(), ldlm_cancel_lru_local() and
1913  * ldlm_cli_cancel(), which check and set this flag properly. As any
1914  * attempt to cancel a lock rely on this flag, l_bl_ast list is accessed
1915  * later without any special locking.
1916  *
1917  * Locks are cancelled according to the LRU resize policy (SLV from server)
1918  * if LRU resize is enabled; otherwise, the "aged policy" is used;
1919  *
1920  * LRU flags:
1921  * ----------------------------------------
1922  *
1923  * flags & LDLM_LRU_FLAG_NO_WAIT - cancel locks w/o sending any RPCs or waiting
1924  *                                 for any outstanding RPC to complete.
1925  *
1926  * flags & LDLM_CANCEL_CLEANUP - when cancelling read locks, do not check for
1927  *                               other read locks covering the same pages, just
1928  *                               discard those pages.
1929  */
1930 static int ldlm_prepare_lru_list(struct ldlm_namespace *ns,
1931                                  struct list_head *cancels,
1932                                  int min, int max, int batch,
1933                                  enum ldlm_lru_flags lru_flags)
1934 {
1935         ldlm_cancel_lru_policy_t pf;
1936         int added = 0;
1937         int no_wait = lru_flags & LDLM_LRU_FLAG_NO_WAIT;
1938         ENTRY;
1939
1940         /*
1941          * Let only 1 thread to proceed. However, not for those which have the
1942          * @max limit given (ELC), as LRU may be left not cleaned up in full.
1943          */
1944         if (max == 0) {
1945                 if (test_and_set_bit(LDLM_LRU_CANCEL, &ns->ns_flags))
1946                         RETURN(0);
1947         } else if (test_bit(LDLM_LRU_CANCEL, &ns->ns_flags))
1948                 RETURN(0);
1949
1950         LASSERT(ergo(max, min <= max));
1951         /* No sense to give @batch for ELC */
1952         LASSERT(ergo(max, batch == 0));
1953
1954         if (!ns_connect_lru_resize(ns))
1955                 min = max_t(int, min, ns->ns_nr_unused - ns->ns_max_unused);
1956
1957         /* If at least 1 lock is to be cancelled, cancel at least @batch locks */
1958         if (min && min < batch)
1959                 min = batch;
1960
1961         pf = ldlm_cancel_lru_policy(ns, lru_flags);
1962         LASSERT(pf != NULL);
1963
1964         /* For any flags, stop scanning if @max is reached. */
1965         while (!list_empty(&ns->ns_unused_list) && (max == 0 || added < max)) {
1966                 struct ldlm_lock *lock;
1967                 struct list_head *item, *next;
1968                 enum ldlm_policy_res result;
1969                 ktime_t last_use = ktime_set(0, 0);
1970
1971                 spin_lock(&ns->ns_lock);
1972                 item = no_wait ? ns->ns_last_pos : &ns->ns_unused_list;
1973                 for (item = item->next, next = item->next;
1974                      item != &ns->ns_unused_list;
1975                      item = next, next = item->next) {
1976                         lock = list_entry(item, struct ldlm_lock, l_lru);
1977
1978                         /* No locks which got blocking requests. */
1979                         LASSERT(!ldlm_is_bl_ast(lock));
1980
1981                         if (!ldlm_is_canceling(lock))
1982                                 break;
1983
1984                         /*
1985                          * Somebody is already doing CANCEL. No need for this
1986                          * lock in LRU, do not traverse it again.
1987                          */
1988                         ldlm_lock_remove_from_lru_nolock(lock);
1989                 }
1990                 if (item == &ns->ns_unused_list) {
1991                         spin_unlock(&ns->ns_lock);
1992                         break;
1993                 }
1994
1995                 last_use = lock->l_last_used;
1996
1997                 LDLM_LOCK_GET(lock);
1998                 spin_unlock(&ns->ns_lock);
1999                 lu_ref_add(&lock->l_reference, __FUNCTION__, current);
2000
2001                 /*
2002                  * Pass the lock through the policy filter and see if it
2003                  * should stay in LRU.
2004                  *
2005                  * Even for shrinker policy we stop scanning if
2006                  * we find a lock that should stay in the cache.
2007                  * We should take into account lock age anyway
2008                  * as a new lock is a valuable resource even if
2009                  * it has a low weight.
2010                  *
2011                  * That is, for shrinker policy we drop only
2012                  * old locks, but additionally choose them by
2013                  * their weight. Big extent locks will stay in
2014                  * the cache.
2015                  */
2016                 result = pf(ns, lock, added, min);
2017                 if (result == LDLM_POLICY_KEEP_LOCK) {
2018                         lu_ref_del(&lock->l_reference, __func__, current);
2019                         LDLM_LOCK_RELEASE(lock);
2020                         break;
2021                 }
2022
2023                 if (result == LDLM_POLICY_SKIP_LOCK) {
2024                         lu_ref_del(&lock->l_reference, __func__, current);
2025                         if (no_wait) {
2026                                 spin_lock(&ns->ns_lock);
2027                                 if (!list_empty(&lock->l_lru) &&
2028                                     lock->l_lru.prev == ns->ns_last_pos)
2029                                         ns->ns_last_pos = &lock->l_lru;
2030                                 spin_unlock(&ns->ns_lock);
2031                         }
2032
2033                         LDLM_LOCK_RELEASE(lock);
2034                         continue;
2035                 }
2036
2037                 lock_res_and_lock(lock);
2038                 /* Check flags again under the lock. */
2039                 if (ldlm_is_canceling(lock) ||
2040                     ldlm_lock_remove_from_lru_check(lock, last_use) == 0) {
2041                         /*
2042                          * Another thread is removing lock from LRU, or
2043                          * somebody is already doing CANCEL, or there
2044                          * is a blocking request which will send cancel
2045                          * by itself, or the lock is no longer unused or
2046                          * the lock has been used since the pf() call and
2047                          * pages could be put under it.
2048                          */
2049                         unlock_res_and_lock(lock);
2050                         lu_ref_del(&lock->l_reference, __FUNCTION__, current);
2051                         LDLM_LOCK_RELEASE(lock);
2052                         continue;
2053                 }
2054                 LASSERT(!lock->l_readers && !lock->l_writers);
2055
2056                 /*
2057                  * If we have chosen to cancel this lock voluntarily, we
2058                  * better send cancel notification to server, so that it
2059                  * frees appropriate state. This might lead to a race
2060                  * where while we are doing cancel here, server is also
2061                  * silently cancelling this lock.
2062                  */
2063                 ldlm_clear_cancel_on_block(lock);
2064
2065                 /*
2066                  * Setting the CBPENDING flag is a little misleading,
2067                  * but prevents an important race; namely, once
2068                  * CBPENDING is set, the lock can accumulate no more
2069                  * readers/writers. Since readers and writers are
2070                  * already zero here, ldlm_lock_decref() won't see
2071                  * this flag and call l_blocking_ast
2072                  */
2073                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING;
2074
2075                 if ((lru_flags & LDLM_LRU_FLAG_CLEANUP) &&
2076                     (lock->l_resource->lr_type == LDLM_EXTENT ||
2077                      ldlm_has_dom(lock)) && lock->l_granted_mode == LCK_PR)
2078                         ldlm_set_discard_data(lock);
2079
2080                 /*
2081                  * We can't re-add to l_lru as it confuses the
2082                  * refcounting in ldlm_lock_remove_from_lru() if an AST
2083                  * arrives after we drop lr_lock below. We use l_bl_ast
2084                  * and can't use l_pending_chain as it is used both on
2085                  * server and client nevertheless b=5666 says it is
2086                  * used only on server
2087                  */
2088                 LASSERT(list_empty(&lock->l_bl_ast));
2089                 list_add(&lock->l_bl_ast, cancels);
2090                 unlock_res_and_lock(lock);
2091                 lu_ref_del(&lock->l_reference, __FUNCTION__, current);
2092                 added++;
2093                 /* Once a lock added, batch the requested amount */
2094                 if (min == 0)
2095                         min = batch;
2096         }
2097
2098         if (max == 0)
2099                 clear_bit(LDLM_LRU_CANCEL, &ns->ns_flags);
2100
2101         RETURN(added);
2102 }
2103
2104 int ldlm_cancel_lru_local(struct ldlm_namespace *ns, struct list_head *cancels,
2105                           int min, int max,
2106                           enum ldlm_cancel_flags cancel_flags,
2107                           enum ldlm_lru_flags lru_flags)
2108 {
2109         int added;
2110
2111         added = ldlm_prepare_lru_list(ns, cancels, min, max, 0, lru_flags);
2112         if (added <= 0)
2113                 return added;
2114
2115         return ldlm_cli_cancel_list_local(cancels, added, cancel_flags);
2116 }
2117
2118 /**
2119  * Cancel at least \a min locks from given namespace LRU.
2120  *
2121  * When called with LCF_ASYNC the blocking callback will be handled
2122  * in a thread and this function will return after the thread has been
2123  * asked to call the callback.  When called with LCF_ASYNC the blocking
2124  * callback will be performed in this function.
2125  */
2126 int ldlm_cancel_lru(struct ldlm_namespace *ns, int min,
2127                     enum ldlm_cancel_flags cancel_flags,
2128                     enum ldlm_lru_flags lru_flags)
2129 {
2130         LIST_HEAD(cancels);
2131         int count, rc;
2132
2133         ENTRY;
2134
2135         /*
2136          * Just prepare the list of locks, do not actually cancel them yet.
2137          * Locks are cancelled later in a separate thread.
2138          */
2139         count = ldlm_prepare_lru_list(ns, &cancels, min, 0,
2140                                       ns->ns_cancel_batch, lru_flags);
2141         rc = ldlm_bl_to_thread_list(ns, NULL, &cancels, count, cancel_flags);
2142         if (rc == 0)
2143                 RETURN(count);
2144
2145         RETURN(0);
2146 }
2147
2148 /**
2149  * Find and cancel locally unused locks found on resource, matched to the
2150  * given policy, mode. GET the found locks and add them into the \a cancels
2151  * list.
2152  */
2153 int ldlm_cancel_resource_local(struct ldlm_resource *res,
2154                                struct list_head *cancels,
2155                                union ldlm_policy_data *policy,
2156                                enum ldlm_mode mode, __u64 lock_flags,
2157                                enum ldlm_cancel_flags cancel_flags,
2158                                void *opaque)
2159 {
2160         struct ldlm_lock *lock;
2161         int count = 0;
2162
2163         ENTRY;
2164
2165         lock_res(res);
2166         list_for_each_entry(lock, &res->lr_granted, l_res_link) {
2167                 if (opaque != NULL && lock->l_ast_data != opaque) {
2168                         LDLM_ERROR(lock, "data %p doesn't match opaque %p",
2169                                    lock->l_ast_data, opaque);
2170                         continue;
2171                 }
2172
2173                 if (lock->l_readers || lock->l_writers)
2174                         continue;
2175
2176                 /*
2177                  * If somebody is already doing CANCEL, or blocking AST came
2178                  * then skip this lock.
2179                  */
2180                 if (ldlm_is_bl_ast(lock) || ldlm_is_canceling(lock))
2181                         continue;
2182
2183                 if (lockmode_compat(lock->l_granted_mode, mode))
2184                         continue;
2185
2186                 /*
2187                  * If policy is given and this is IBITS lock, add to list only
2188                  * those locks that match by policy.
2189                  */
2190                 if (policy && (lock->l_resource->lr_type == LDLM_IBITS)) {
2191                         if (!(lock->l_policy_data.l_inodebits.bits &
2192                               policy->l_inodebits.bits))
2193                                 continue;
2194                         /* Skip locks with DoM bit if it is not set in policy
2195                          * to don't flush data by side-bits. Lock convert will
2196                          * drop those bits separately.
2197                          */
2198                         if (ldlm_has_dom(lock) &&
2199                             !(policy->l_inodebits.bits & MDS_INODELOCK_DOM))
2200                                 continue;
2201                 }
2202
2203                 /* See CBPENDING comment in ldlm_cancel_lru */
2204                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_CANCELING |
2205                                  lock_flags;
2206                 LASSERT(list_empty(&lock->l_bl_ast));
2207                 list_add(&lock->l_bl_ast, cancels);
2208                 LDLM_LOCK_GET(lock);
2209                 count++;
2210         }
2211         unlock_res(res);
2212
2213         RETURN(ldlm_cli_cancel_list_local(cancels, count, cancel_flags));
2214 }
2215 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2216
2217 /**
2218  * Cancel client-side locks from a list and send/prepare cancel RPCs to the
2219  * server.
2220  * If \a req is NULL, send CANCEL request to server with handles of locks
2221  * in the \a cancels. If EARLY_CANCEL is not supported, send CANCEL requests
2222  * separately per lock.
2223  * If \a req is not NULL, put handles of locks in \a cancels into the request
2224  * buffer at the offset \a off.
2225  * Destroy \a cancels at the end.
2226  */
2227 int ldlm_cli_cancel_list(struct list_head *cancels, int count,
2228                          struct ptlrpc_request *req,
2229                          enum ldlm_cancel_flags flags)
2230 {
2231         struct ldlm_lock *lock;
2232         int res = 0;
2233
2234         ENTRY;
2235
2236         if (list_empty(cancels) || count == 0)
2237                 RETURN(0);
2238
2239         /*
2240          * XXX: requests (both batched and not) could be sent in parallel.
2241          * Usually it is enough to have just 1 RPC, but it is possible that
2242          * there are too many locks to be cancelled in LRU or on a resource.
2243          * It would also speed up the case when the server does not support
2244          * the feature.
2245          */
2246         while (count > 0) {
2247                 LASSERT(!list_empty(cancels));
2248                 lock = list_first_entry(cancels, struct ldlm_lock, l_bl_ast);
2249                 LASSERT(lock->l_conn_export);
2250
2251                 if (exp_connect_cancelset(lock->l_conn_export)) {
2252                         res = count;
2253                         if (req)
2254                                 ldlm_cancel_pack(req, cancels, count);
2255                         else
2256                                 res = ldlm_cli_cancel_req(lock->l_conn_export,
2257                                                           NULL, cancels, count,
2258                                                           flags);
2259                 } else {
2260                         res = ldlm_cli_cancel_req(lock->l_conn_export,
2261                                                   NULL, cancels, 1, flags);
2262                 }
2263
2264                 if (res < 0) {
2265                         CDEBUG_LIMIT(res == -ESHUTDOWN ? D_DLMTRACE : D_ERROR,
2266                                      "ldlm_cli_cancel_list: %d\n", res);
2267                         res = count;
2268                 }
2269
2270                 count -= res;
2271                 ldlm_lock_list_put(cancels, l_bl_ast, res);
2272         }
2273         LASSERT(count == 0);
2274         RETURN(0);
2275 }
2276 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2277
2278 /**
2279  * Cancel all locks on a resource that have 0 readers/writers.
2280  *
2281  * If flags & LDLM_FL_LOCAL_ONLY, throw the locks away without trying
2282  * to notify the server.
2283  */
2284 int ldlm_cli_cancel_unused_resource(struct ldlm_namespace *ns,
2285                                     const struct ldlm_res_id *res_id,
2286                                     union ldlm_policy_data *policy,
2287                                     enum ldlm_mode mode,
2288                                     enum ldlm_cancel_flags flags, void *opaque)
2289 {
2290         struct ldlm_resource *res;
2291         LIST_HEAD(cancels);
2292         int count;
2293         int rc;
2294
2295         ENTRY;
2296
2297         res = ldlm_resource_get(ns, res_id, 0, 0);
2298         if (IS_ERR(res)) {
2299                 /* This is not a problem. */
2300                 CDEBUG(D_INFO, "No resource %llu\n", res_id->name[0]);
2301                 RETURN(0);
2302         }
2303
2304         LDLM_RESOURCE_ADDREF(res);
2305         count = ldlm_cancel_resource_local(res, &cancels, policy, mode,
2306                                            0, flags | LCF_BL_AST, opaque);
2307         rc = ldlm_cli_cancel_list(&cancels, count, NULL, flags);
2308         if (rc != ELDLM_OK)
2309                 CERROR("canceling unused lock "DLDLMRES": rc = %d\n",
2310                        PLDLMRES(res), rc);
2311
2312         LDLM_RESOURCE_DELREF(res);
2313         ldlm_resource_putref(res);
2314         RETURN(0);
2315 }
2316 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2317
2318 struct ldlm_cli_cancel_arg {
2319         int     lc_flags;
2320         void   *lc_opaque;
2321 };
2322
2323 static int
2324 ldlm_cli_hash_cancel_unused(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2325                             struct hlist_node *hnode, void *arg)
2326 {
2327         struct ldlm_resource           *res = cfs_hash_object(hs, hnode);
2328         struct ldlm_cli_cancel_arg     *lc = arg;
2329
2330         ldlm_cli_cancel_unused_resource(ldlm_res_to_ns(res), &res->lr_name,
2331                                         NULL, LCK_MINMODE, lc->lc_flags,
2332                                         lc->lc_opaque);
2333         /* must return 0 for hash iteration */
2334         return 0;
2335 }
2336
2337 /**
2338  * Cancel all locks on a namespace (or a specific resource, if given)
2339  * that have 0 readers/writers.
2340  *
2341  * If flags & LCF_LOCAL, throw the locks away without trying
2342  * to notify the server.
2343  */
2344 int ldlm_cli_cancel_unused(struct ldlm_namespace *ns,
2345                            const struct ldlm_res_id *res_id,
2346                            enum ldlm_cancel_flags flags, void *opaque)
2347 {
2348         struct ldlm_cli_cancel_arg arg = {
2349                 .lc_flags       = flags,
2350                 .lc_opaque      = opaque,
2351         };
2352
2353         ENTRY;
2354
2355         if (ns == NULL)
2356                 RETURN(ELDLM_OK);
2357
2358         if (res_id != NULL) {
2359                 RETURN(ldlm_cli_cancel_unused_resource(ns, res_id, NULL,
2360                                                        LCK_MINMODE, flags,
2361                                                        opaque));
2362         } else {
2363                 cfs_hash_for_each_nolock(ns->ns_rs_hash,
2364                                          ldlm_cli_hash_cancel_unused, &arg, 0);
2365                 RETURN(ELDLM_OK);
2366         }
2367 }
2368
2369 /* Lock iterators. */
2370
2371 int ldlm_resource_foreach(struct ldlm_resource *res, ldlm_iterator_t iter,
2372                           void *closure)
2373 {
2374         struct ldlm_lock *tmp;
2375         struct ldlm_lock *lock;
2376         int rc = LDLM_ITER_CONTINUE;
2377
2378         ENTRY;
2379         if (!res)
2380                 RETURN(LDLM_ITER_CONTINUE);
2381
2382         lock_res(res);
2383         list_for_each_entry_safe(lock, tmp, &res->lr_granted, l_res_link) {
2384                 if (iter(lock, closure) == LDLM_ITER_STOP)
2385                         GOTO(out, rc = LDLM_ITER_STOP);
2386         }
2387
2388         list_for_each_entry_safe(lock, tmp, &res->lr_waiting, l_res_link) {
2389                 if (iter(lock, closure) == LDLM_ITER_STOP)
2390                         GOTO(out, rc = LDLM_ITER_STOP);
2391         }
2392 out:
2393         unlock_res(res);
2394         RETURN(rc);
2395 }
2396
2397 struct iter_helper_data {
2398         ldlm_iterator_t iter;
2399         void *closure;
2400 };
2401
2402 static int ldlm_iter_helper(struct ldlm_lock *lock, void *closure)
2403 {
2404         struct iter_helper_data *helper = closure;
2405
2406         return helper->iter(lock, helper->closure);
2407 }
2408
2409 static int ldlm_res_iter_helper(struct cfs_hash *hs, struct cfs_hash_bd *bd,
2410                                 struct hlist_node *hnode, void *arg)
2411
2412 {
2413         struct ldlm_resource *res = cfs_hash_object(hs, hnode);
2414
2415         return ldlm_resource_foreach(res, ldlm_iter_helper, arg) ==
2416                                      LDLM_ITER_STOP;
2417 }
2418
2419 void ldlm_namespace_foreach(struct ldlm_namespace *ns,
2420                             ldlm_iterator_t iter, void *closure)
2421
2422 {
2423         struct iter_helper_data helper = { .iter = iter, .closure = closure };
2424
2425         cfs_hash_for_each_nolock(ns->ns_rs_hash,
2426                                  ldlm_res_iter_helper, &helper, 0);
2427
2428 }
2429
2430 /*
2431  * non-blocking function to manipulate a lock whose cb_data is being put away.
2432  * return  0:  find no resource
2433  *       > 0:  must be LDLM_ITER_STOP/LDLM_ITER_CONTINUE.
2434  *       < 0:  errors
2435  */
2436 int ldlm_resource_iterate(struct ldlm_namespace *ns,
2437                           const struct ldlm_res_id *res_id,
2438                           ldlm_iterator_t iter, void *data)
2439 {
2440         struct ldlm_resource *res;
2441         int rc;
2442
2443         ENTRY;
2444
2445         LASSERTF(ns != NULL, "must pass in namespace\n");
2446
2447         res = ldlm_resource_get(ns, res_id, 0, 0);
2448         if (IS_ERR(res))
2449                 RETURN(0);
2450
2451         LDLM_RESOURCE_ADDREF(res);
2452         rc = ldlm_resource_foreach(res, iter, data);
2453         LDLM_RESOURCE_DELREF(res);
2454         ldlm_resource_putref(res);
2455         RETURN(rc);
2456 }
2457 EXPORT_SYMBOL(ldlm_resource_iterate);
2458
2459 /* Lock replay */
2460 static int ldlm_chain_lock_for_replay(struct ldlm_lock *lock, void *closure)
2461 {
2462         struct list_head *list = closure;
2463
2464         /* we use l_pending_chain here, because it's unused on clients. */
2465         LASSERTF(list_empty(&lock->l_pending_chain),
2466                  "lock %p next %p prev %p\n",
2467                  lock, &lock->l_pending_chain.next,
2468                  &lock->l_pending_chain.prev);
2469         /*
2470          * b=9573: don't replay locks left after eviction, or
2471          * b=17614: locks being actively cancelled. Get a reference
2472          * on a lock so that it does not disapear under us (e.g. due to cancel)
2473          */
2474         if (!(lock->l_flags & (LDLM_FL_FAILED|LDLM_FL_BL_DONE))) {
2475                 list_add(&lock->l_pending_chain, list);
2476                 LDLM_LOCK_GET(lock);
2477         }
2478
2479         return LDLM_ITER_CONTINUE;
2480 }
2481
2482 static int replay_lock_interpret(const struct lu_env *env,
2483                                  struct ptlrpc_request *req, void *args, int rc)
2484 {
2485         struct ldlm_async_args *aa = args;
2486         struct ldlm_lock     *lock;
2487         struct ldlm_reply    *reply;
2488         struct obd_export    *exp;
2489
2490         ENTRY;
2491         atomic_dec(&req->rq_import->imp_replay_inflight);
2492         wake_up(&req->rq_import->imp_replay_waitq);
2493
2494         if (rc != ELDLM_OK)
2495                 GOTO(out, rc);
2496
2497         reply = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
2498         if (reply == NULL)
2499                 GOTO(out, rc = -EPROTO);
2500
2501         lock = ldlm_handle2lock(&aa->lock_handle);
2502         if (!lock) {
2503                 CERROR("received replay ack for unknown local cookie %#llx remote cookie %#llx from server %s id %s\n",
2504                        aa->lock_handle.cookie, reply->lock_handle.cookie,
2505                        req->rq_export->exp_client_uuid.uuid,
2506                        libcfs_idstr(&req->rq_peer));
2507                 GOTO(out, rc = -ESTALE);
2508         }
2509
2510         /* Key change rehash lock in per-export hash with new key */
2511         exp = req->rq_export;
2512         if (exp && exp->exp_lock_hash) {
2513                 /*
2514                  * In the function below, .hs_keycmp resolves to
2515                  * ldlm_export_lock_keycmp()
2516                  */
2517                 /* coverity[overrun-buffer-val] */
2518                 cfs_hash_rehash_key(exp->exp_lock_hash,
2519                                     &lock->l_remote_handle,
2520                                     &reply->lock_handle,
2521                                     &lock->l_exp_hash);
2522         } else {
2523                 lock->l_remote_handle = reply->lock_handle;
2524         }
2525
2526         LDLM_DEBUG(lock, "replayed lock:");
2527         ptlrpc_import_recovery_state_machine(req->rq_import);
2528         LDLM_LOCK_PUT(lock);
2529 out:
2530         if (rc != ELDLM_OK)
2531                 ptlrpc_connect_import(req->rq_import);
2532
2533         RETURN(rc);
2534 }
2535
2536 static int replay_one_lock(struct obd_import *imp, struct ldlm_lock *lock)
2537 {
2538         struct ptlrpc_request *req;
2539         struct ldlm_async_args *aa;
2540         struct ldlm_request   *body;
2541         int flags;
2542
2543         ENTRY;
2544
2545
2546         /* b=11974: Do not replay a lock which is actively being canceled */
2547         if (ldlm_is_bl_done(lock)) {
2548                 LDLM_DEBUG(lock, "Not replaying canceled lock:");
2549                 RETURN(0);
2550         }
2551
2552         /*
2553          * If this is reply-less callback lock, we cannot replay it, since
2554          * server might have long dropped it, but notification of that event was
2555          * lost by network. (and server granted conflicting lock already)
2556          */
2557         if (ldlm_is_cancel_on_block(lock)) {
2558                 LDLM_DEBUG(lock, "Not replaying reply-less lock:");
2559                 ldlm_lock_cancel(lock);
2560                 RETURN(0);
2561         }
2562
2563         /*
2564          * If granted mode matches the requested mode, this lock is granted.
2565          *
2566          * If we haven't been granted anything and are on a resource list,
2567          * then we're blocked/waiting.
2568          *
2569          * If we haven't been granted anything and we're NOT on a resource list,
2570          * then we haven't got a reply yet and don't have a known disposition.
2571          * This happens whenever a lock enqueue is the request that triggers
2572          * recovery.
2573          */
2574         if (ldlm_is_granted(lock))
2575                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_GRANTED;
2576         else if (!list_empty(&lock->l_res_link))
2577                 flags = LDLM_FL_REPLAY | LDLM_FL_BLOCK_WAIT;
2578         else
2579                 flags = LDLM_FL_REPLAY;
2580
2581         req = ptlrpc_request_alloc_pack(imp, &RQF_LDLM_ENQUEUE,
2582                                         LUSTRE_DLM_VERSION, LDLM_ENQUEUE);
2583         if (req == NULL)
2584                 RETURN(-ENOMEM);
2585
2586         /* We're part of recovery, so don't wait for it. */
2587         req->rq_send_state = LUSTRE_IMP_REPLAY_LOCKS;
2588         /* If the state changed while we were prepared, don't wait */
2589         req->rq_no_delay = 1;
2590
2591         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
2592         ldlm_lock2desc(lock, &body->lock_desc);
2593         body->lock_flags = ldlm_flags_to_wire(flags);
2594
2595         ldlm_lock2handle(lock, &body->lock_handle[0]);
2596         if (lock->l_lvb_len > 0)
2597                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_ENQUEUE_LVB);
2598         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
2599                              lock->l_lvb_len);
2600         ptlrpc_request_set_replen(req);
2601         /*
2602          * notify the server we've replayed all requests.
2603          * also, we mark the request to be put on a dedicated
2604          * queue to be processed after all request replayes.
2605          * b=6063
2606          */
2607         lustre_msg_set_flags(req->rq_reqmsg, MSG_REQ_REPLAY_DONE);
2608
2609         LDLM_DEBUG(lock, "replaying lock:");
2610
2611         atomic_inc(&imp->imp_replay_inflight);
2612         aa = ptlrpc_req_async_args(aa, req);
2613         aa->lock_handle = body->lock_handle[0];
2614         req->rq_interpret_reply = replay_lock_interpret;
2615         ptlrpcd_add_req(req);
2616
2617         RETURN(0);
2618 }
2619
2620 /**
2621  * Cancel as many unused locks as possible before replay. since we are
2622  * in recovery, we can't wait for any outstanding RPCs to send any RPC
2623  * to the server.
2624  *
2625  * Called only in recovery before replaying locks. there is no need to
2626  * replay locks that are unused. since the clients may hold thousands of
2627  * cached unused locks, dropping the unused locks can greatly reduce the
2628  * load on the servers at recovery time.
2629  */
2630 static void ldlm_cancel_unused_locks_for_replay(struct ldlm_namespace *ns)
2631 {
2632         int canceled;
2633         LIST_HEAD(cancels);
2634
2635         CDEBUG(D_DLMTRACE,
2636                "Dropping as many unused locks as possible before replay for namespace %s (%d)\n",
2637                ldlm_ns_name(ns), ns->ns_nr_unused);
2638
2639         CFS_FAIL_TIMEOUT(OBD_FAIL_LDLM_REPLAY_PAUSE, cfs_fail_val);
2640
2641         /*
2642          * We don't need to care whether or not LRU resize is enabled
2643          * because the LDLM_LRU_FLAG_NO_WAIT policy doesn't use the
2644          * count parameter
2645          */
2646         canceled = ldlm_cancel_lru_local(ns, &cancels, ns->ns_nr_unused, 0,
2647                                          LCF_LOCAL, LDLM_LRU_FLAG_NO_WAIT);
2648
2649         CDEBUG(D_DLMTRACE, "Canceled %d unused locks from namespace %s\n",
2650                            canceled, ldlm_ns_name(ns));
2651 }
2652
2653 static int lock_can_replay(struct obd_import *imp)
2654 {
2655         struct client_obd *cli = &imp->imp_obd->u.cli;
2656
2657         CDEBUG(D_HA, "check lock replay limit, inflights = %u(%u)\n",
2658                atomic_read(&imp->imp_replay_inflight) - 1,
2659                cli->cl_max_rpcs_in_flight);
2660
2661         /* +1 due to ldlm_lock_replay() increment */
2662         return atomic_read(&imp->imp_replay_inflight) <
2663                1 + min_t(u32, cli->cl_max_rpcs_in_flight, 8);
2664 }
2665
2666 int __ldlm_replay_locks(struct obd_import *imp, bool rate_limit)
2667 {
2668         struct ldlm_namespace *ns = imp->imp_obd->obd_namespace;
2669         LIST_HEAD(list);
2670         struct ldlm_lock *lock, *next;
2671         int rc = 0;
2672
2673         ENTRY;
2674
2675         while (atomic_read(&imp->imp_replay_inflight) != 1)
2676                 cond_resched();
2677
2678         /* don't replay locks if import failed recovery */
2679         if (imp->imp_vbr_failed)
2680                 RETURN(0);
2681
2682         if (ldlm_cancel_unused_locks_before_replay)
2683                 ldlm_cancel_unused_locks_for_replay(ns);
2684
2685         ldlm_namespace_foreach(ns, ldlm_chain_lock_for_replay, &list);
2686
2687         list_for_each_entry_safe(lock, next, &list, l_pending_chain) {
2688                 list_del_init(&lock->l_pending_chain);
2689                 /* If we disconnected in the middle - cleanup and let
2690                  * reconnection to happen again. LU-14027 */
2691                 if (rc || (imp->imp_state != LUSTRE_IMP_REPLAY_LOCKS)) {
2692                         LDLM_LOCK_RELEASE(lock);
2693                         continue;
2694                 }
2695                 rc = replay_one_lock(imp, lock);
2696                 LDLM_LOCK_RELEASE(lock);
2697
2698                 if (rate_limit)
2699                         wait_event_idle_exclusive(imp->imp_replay_waitq,
2700                                                   lock_can_replay(imp));
2701         }
2702
2703         RETURN(rc);
2704 }
2705
2706 /**
2707  * Lock replay uses rate control and can sleep waiting so
2708  * must be in separate thread from ptlrpcd itself
2709  */
2710 static int ldlm_lock_replay_thread(void *data)
2711 {
2712         struct obd_import *imp = data;
2713
2714         unshare_fs_struct();
2715         CDEBUG(D_HA, "lock replay thread %s to %s@%s\n",
2716                imp->imp_obd->obd_name, obd2cli_tgt(imp->imp_obd),
2717                imp->imp_connection->c_remote_uuid.uuid);
2718
2719         __ldlm_replay_locks(imp, true);
2720         atomic_dec(&imp->imp_replay_inflight);
2721         ptlrpc_import_recovery_state_machine(imp);
2722         class_import_put(imp);
2723
2724         return 0;
2725 }
2726
2727 int ldlm_replay_locks(struct obd_import *imp)
2728 {
2729         struct task_struct *task;
2730         int rc = 0;
2731
2732         /* ensure this doesn't fall to 0 before all have been queued */
2733         if (atomic_inc_return(&imp->imp_replay_inflight) > 1) {
2734                 atomic_dec(&imp->imp_replay_inflight);
2735                 return 0;
2736         }
2737         class_import_get(imp);
2738
2739         task = kthread_run(ldlm_lock_replay_thread, imp, "ldlm_lock_replay");
2740         if (IS_ERR(task)) {
2741                 rc = PTR_ERR(task);
2742                 CDEBUG(D_HA, "can't start lock replay thread: rc = %d\n", rc);
2743
2744                 /* run lock replay without rate control */
2745                 rc = __ldlm_replay_locks(imp, false);
2746                 atomic_dec(&imp->imp_replay_inflight);
2747                 class_import_put(imp);
2748         }
2749
2750         return rc;
2751 }