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