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