GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / staging / lustre / lustre / osc / osc_lock.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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * Implementation of cl_lock for OSC layer.
33  *
34  *   Author: Nikita Danilov <nikita.danilov@sun.com>
35  *   Author: Jinshan Xiong <jinshan.xiong@intel.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_OSC
39
40 #include <linux/libcfs/libcfs.h>
41 /* fid_build_reg_res_name() */
42 #include <lustre_fid.h>
43
44 #include "osc_cl_internal.h"
45
46 /** \addtogroup osc
47  *  @{
48  */
49
50 /*****************************************************************************
51  *
52  * Type conversions.
53  *
54  */
55
56 static const struct cl_lock_operations osc_lock_ops;
57 static const struct cl_lock_operations osc_lock_lockless_ops;
58 static void osc_lock_to_lockless(const struct lu_env *env,
59                                  struct osc_lock *ols, int force);
60
61 int osc_lock_is_lockless(const struct osc_lock *olck)
62 {
63         return (olck->ols_cl.cls_ops == &osc_lock_lockless_ops);
64 }
65
66 /**
67  * Returns a weak pointer to the ldlm lock identified by a handle. Returned
68  * pointer cannot be dereferenced, as lock is not protected from concurrent
69  * reclaim. This function is a helper for osc_lock_invariant().
70  */
71 static struct ldlm_lock *osc_handle_ptr(struct lustre_handle *handle)
72 {
73         struct ldlm_lock *lock;
74
75         lock = ldlm_handle2lock(handle);
76         if (lock)
77                 LDLM_LOCK_PUT(lock);
78         return lock;
79 }
80
81 /**
82  * Invariant that has to be true all of the time.
83  */
84 static int osc_lock_invariant(struct osc_lock *ols)
85 {
86         struct ldlm_lock *lock = osc_handle_ptr(&ols->ols_handle);
87         struct ldlm_lock *olock = ols->ols_dlmlock;
88         int handle_used = lustre_handle_is_used(&ols->ols_handle);
89
90         if (ergo(osc_lock_is_lockless(ols),
91                  ols->ols_locklessable && !ols->ols_dlmlock))
92                 return 1;
93
94         /*
95          * If all the following "ergo"s are true, return 1, otherwise 0
96          */
97         if (!ergo(olock, handle_used))
98                 return 0;
99
100         if (!ergo(olock, olock->l_handle.h_cookie == ols->ols_handle.cookie))
101                 return 0;
102
103         if (!ergo(handle_used,
104                   ergo(lock && olock, lock == olock) &&
105                   ergo(!lock, !olock)))
106                 return 0;
107         /*
108          * Check that ->ols_handle and ->ols_dlmlock are consistent, but
109          * take into account that they are set at the different time.
110          */
111         if (!ergo(ols->ols_state == OLS_CANCELLED,
112                   !olock && !handle_used))
113                 return 0;
114         /*
115          * DLM lock is destroyed only after we have seen cancellation
116          * ast.
117          */
118         if (!ergo(olock && ols->ols_state < OLS_CANCELLED,
119                   !ldlm_is_destroyed(olock)))
120                 return 0;
121
122         if (!ergo(ols->ols_state == OLS_GRANTED,
123                   olock && olock->l_req_mode == olock->l_granted_mode &&
124                   ols->ols_hold))
125                 return 0;
126         return 1;
127 }
128
129 /*****************************************************************************
130  *
131  * Lock operations.
132  *
133  */
134
135 static void osc_lock_fini(const struct lu_env *env,
136                           struct cl_lock_slice *slice)
137 {
138         struct osc_lock *ols = cl2osc_lock(slice);
139
140         LINVRNT(osc_lock_invariant(ols));
141         LASSERT(!ols->ols_dlmlock);
142
143         kmem_cache_free(osc_lock_kmem, ols);
144 }
145
146 static void osc_lock_build_policy(const struct lu_env *env,
147                                   const struct cl_lock *lock,
148                                   union ldlm_policy_data *policy)
149 {
150         const struct cl_lock_descr *d = &lock->cll_descr;
151
152         osc_index2policy(policy, d->cld_obj, d->cld_start, d->cld_end);
153         policy->l_extent.gid = d->cld_gid;
154 }
155
156 static __u64 osc_enq2ldlm_flags(__u32 enqflags)
157 {
158         __u64 result = 0;
159
160         LASSERT((enqflags & ~CEF_MASK) == 0);
161
162         if (enqflags & CEF_NONBLOCK)
163                 result |= LDLM_FL_BLOCK_NOWAIT;
164         if (enqflags & CEF_ASYNC)
165                 result |= LDLM_FL_HAS_INTENT;
166         if (enqflags & CEF_DISCARD_DATA)
167                 result |= LDLM_FL_AST_DISCARD_DATA;
168         if (enqflags & CEF_PEEK)
169                 result |= LDLM_FL_TEST_LOCK;
170         if (enqflags & CEF_LOCK_MATCH)
171                 result |= LDLM_FL_MATCH_LOCK;
172         return result;
173 }
174
175 /**
176  * Updates object attributes from a lock value block (lvb) received together
177  * with the DLM lock reply from the server. Copy of osc_update_enqueue()
178  * logic.
179  *
180  * This can be optimized to not update attributes when lock is a result of a
181  * local match.
182  *
183  * Called under lock and resource spin-locks.
184  */
185 static void osc_lock_lvb_update(const struct lu_env *env,
186                                 struct osc_object *osc,
187                                 struct ldlm_lock *dlmlock,
188                                 struct ost_lvb *lvb)
189 {
190         struct cl_object *obj = osc2cl(osc);
191         struct lov_oinfo *oinfo = osc->oo_oinfo;
192         struct cl_attr *attr = &osc_env_info(env)->oti_attr;
193         unsigned int valid;
194
195         valid = CAT_BLOCKS | CAT_ATIME | CAT_CTIME | CAT_MTIME | CAT_SIZE;
196         if (!lvb)
197                 lvb = dlmlock->l_lvb_data;
198
199         cl_lvb2attr(attr, lvb);
200
201         cl_object_attr_lock(obj);
202         if (dlmlock) {
203                 __u64 size;
204
205                 check_res_locked(dlmlock->l_resource);
206                 LASSERT(lvb == dlmlock->l_lvb_data);
207                 size = lvb->lvb_size;
208
209                 /* Extend KMS up to the end of this lock and no further
210                  * A lock on [x,y] means a KMS of up to y + 1 bytes!
211                  */
212                 if (size > dlmlock->l_policy_data.l_extent.end)
213                         size = dlmlock->l_policy_data.l_extent.end + 1;
214                 if (size >= oinfo->loi_kms) {
215                         LDLM_DEBUG(dlmlock, "lock acquired, setting rss=%llu, kms=%llu",
216                                    lvb->lvb_size, size);
217                         valid |= CAT_KMS;
218                         attr->cat_kms = size;
219                 } else {
220                         LDLM_DEBUG(dlmlock, "lock acquired, setting rss=%llu; leaving kms=%llu, end=%llu",
221                                    lvb->lvb_size, oinfo->loi_kms,
222                                    dlmlock->l_policy_data.l_extent.end);
223                 }
224                 ldlm_lock_allow_match_locked(dlmlock);
225         }
226
227         cl_object_attr_update(env, obj, attr, valid);
228         cl_object_attr_unlock(obj);
229 }
230
231 static void osc_lock_granted(const struct lu_env *env, struct osc_lock *oscl,
232                              struct lustre_handle *lockh, bool lvb_update)
233 {
234         struct ldlm_lock *dlmlock;
235
236         dlmlock = ldlm_handle2lock_long(lockh, 0);
237         LASSERT(dlmlock);
238
239         /* lock reference taken by ldlm_handle2lock_long() is
240          * owned by osc_lock and released in osc_lock_detach()
241          */
242         lu_ref_add(&dlmlock->l_reference, "osc_lock", oscl);
243         oscl->ols_has_ref = 1;
244
245         LASSERT(!oscl->ols_dlmlock);
246         oscl->ols_dlmlock = dlmlock;
247
248         /* This may be a matched lock for glimpse request, do not hold
249          * lock reference in that case.
250          */
251         if (!oscl->ols_glimpse) {
252                 /* hold a refc for non glimpse lock which will
253                  * be released in osc_lock_cancel()
254                  */
255                 lustre_handle_copy(&oscl->ols_handle, lockh);
256                 ldlm_lock_addref(lockh, oscl->ols_einfo.ei_mode);
257                 oscl->ols_hold = 1;
258         }
259
260         /* Lock must have been granted. */
261         lock_res_and_lock(dlmlock);
262         if (dlmlock->l_granted_mode == dlmlock->l_req_mode) {
263                 struct ldlm_extent *ext = &dlmlock->l_policy_data.l_extent;
264                 struct cl_lock_descr *descr = &oscl->ols_cl.cls_lock->cll_descr;
265
266                 /* extend the lock extent, otherwise it will have problem when
267                  * we decide whether to grant a lockless lock.
268                  */
269                 descr->cld_mode = osc_ldlm2cl_lock(dlmlock->l_granted_mode);
270                 descr->cld_start = cl_index(descr->cld_obj, ext->start);
271                 descr->cld_end = cl_index(descr->cld_obj, ext->end);
272                 descr->cld_gid = ext->gid;
273
274                 /* no lvb update for matched lock */
275                 if (lvb_update) {
276                         LASSERT(oscl->ols_flags & LDLM_FL_LVB_READY);
277                         osc_lock_lvb_update(env, cl2osc(oscl->ols_cl.cls_obj),
278                                             dlmlock, NULL);
279                 }
280                 LINVRNT(osc_lock_invariant(oscl));
281         }
282         unlock_res_and_lock(dlmlock);
283
284         LASSERT(oscl->ols_state != OLS_GRANTED);
285         oscl->ols_state = OLS_GRANTED;
286 }
287
288 /**
289  * Lock upcall function that is executed either when a reply to ENQUEUE rpc is
290  * received from a server, or after osc_enqueue_base() matched a local DLM
291  * lock.
292  */
293 static int osc_lock_upcall(void *cookie, struct lustre_handle *lockh,
294                            int errcode)
295 {
296         struct osc_lock *oscl = cookie;
297         struct cl_lock_slice *slice = &oscl->ols_cl;
298         struct lu_env *env;
299         int rc;
300         u16 refcheck;
301
302         env = cl_env_get(&refcheck);
303         /* should never happen, similar to osc_ldlm_blocking_ast(). */
304         LASSERT(!IS_ERR(env));
305
306         rc = ldlm_error2errno(errcode);
307         if (oscl->ols_state == OLS_ENQUEUED) {
308                 oscl->ols_state = OLS_UPCALL_RECEIVED;
309         } else if (oscl->ols_state == OLS_CANCELLED) {
310                 rc = -EIO;
311         } else {
312                 CERROR("Impossible state: %d\n", oscl->ols_state);
313                 LBUG();
314         }
315
316         if (rc == 0)
317                 osc_lock_granted(env, oscl, lockh, errcode == ELDLM_OK);
318
319         /* Error handling, some errors are tolerable. */
320         if (oscl->ols_locklessable && rc == -EUSERS) {
321                 /* This is a tolerable error, turn this lock into
322                  * lockless lock.
323                  */
324                 osc_object_set_contended(cl2osc(slice->cls_obj));
325                 LASSERT(slice->cls_ops == &osc_lock_ops);
326
327                 /* Change this lock to ldlmlock-less lock. */
328                 osc_lock_to_lockless(env, oscl, 1);
329                 oscl->ols_state = OLS_GRANTED;
330                 rc = 0;
331         } else if (oscl->ols_glimpse && rc == -ENAVAIL) {
332                 LASSERT(oscl->ols_flags & LDLM_FL_LVB_READY);
333                 osc_lock_lvb_update(env, cl2osc(slice->cls_obj),
334                                     NULL, &oscl->ols_lvb);
335                 /* Hide the error. */
336                 rc = 0;
337         }
338
339         if (oscl->ols_owner)
340                 cl_sync_io_note(env, oscl->ols_owner, rc);
341         cl_env_put(env, &refcheck);
342
343         return rc;
344 }
345
346 static int osc_lock_upcall_agl(void *cookie, struct lustre_handle *lockh,
347                                int errcode)
348 {
349         struct osc_object *osc = cookie;
350         struct ldlm_lock *dlmlock;
351         struct lu_env *env;
352         u16 refcheck;
353
354         env = cl_env_get(&refcheck);
355         LASSERT(!IS_ERR(env));
356
357         if (errcode == ELDLM_LOCK_MATCHED) {
358                 errcode = ELDLM_OK;
359                 goto out;
360         }
361
362         if (errcode != ELDLM_OK)
363                 goto out;
364
365         dlmlock = ldlm_handle2lock(lockh);
366         LASSERT(dlmlock);
367
368         lock_res_and_lock(dlmlock);
369         LASSERT(dlmlock->l_granted_mode == dlmlock->l_req_mode);
370
371         /* there is no osc_lock associated with AGL lock */
372         osc_lock_lvb_update(env, osc, dlmlock, NULL);
373
374         unlock_res_and_lock(dlmlock);
375         LDLM_LOCK_PUT(dlmlock);
376
377 out:
378         cl_object_put(env, osc2cl(osc));
379         cl_env_put(env, &refcheck);
380         return ldlm_error2errno(errcode);
381 }
382
383 static int osc_lock_flush(struct osc_object *obj, pgoff_t start, pgoff_t end,
384                           enum cl_lock_mode mode, int discard)
385 {
386         struct lu_env *env;
387         u16 refcheck;
388         int rc = 0;
389         int rc2 = 0;
390
391         env = cl_env_get(&refcheck);
392         if (IS_ERR(env))
393                 return PTR_ERR(env);
394
395         if (mode == CLM_WRITE) {
396                 rc = osc_cache_writeback_range(env, obj, start, end, 1,
397                                                discard);
398                 CDEBUG(D_CACHE, "object %p: [%lu -> %lu] %d pages were %s.\n",
399                        obj, start, end, rc,
400                        discard ? "discarded" : "written back");
401                 if (rc > 0)
402                         rc = 0;
403         }
404
405         rc2 = osc_lock_discard_pages(env, obj, start, end, mode);
406         if (rc == 0 && rc2 < 0)
407                 rc = rc2;
408
409         cl_env_put(env, &refcheck);
410         return rc;
411 }
412
413 /**
414  * Helper for osc_dlm_blocking_ast() handling discrepancies between cl_lock
415  * and ldlm_lock caches.
416  */
417 static int osc_dlm_blocking_ast0(const struct lu_env *env,
418                                  struct ldlm_lock *dlmlock,
419                                  void *data, int flag)
420 {
421         struct cl_object *obj = NULL;
422         int result = 0;
423         int discard;
424         enum cl_lock_mode mode = CLM_READ;
425
426         LASSERT(flag == LDLM_CB_CANCELING);
427
428         lock_res_and_lock(dlmlock);
429         if (dlmlock->l_granted_mode != dlmlock->l_req_mode) {
430                 dlmlock->l_ast_data = NULL;
431                 unlock_res_and_lock(dlmlock);
432                 return 0;
433         }
434
435         discard = ldlm_is_discard_data(dlmlock);
436         if (dlmlock->l_granted_mode & (LCK_PW | LCK_GROUP))
437                 mode = CLM_WRITE;
438
439         if (dlmlock->l_ast_data) {
440                 obj = osc2cl(dlmlock->l_ast_data);
441                 dlmlock->l_ast_data = NULL;
442
443                 cl_object_get(obj);
444         }
445
446         unlock_res_and_lock(dlmlock);
447
448         /* if l_ast_data is NULL, the dlmlock was enqueued by AGL or
449          * the object has been destroyed.
450          */
451         if (obj) {
452                 struct ldlm_extent *extent = &dlmlock->l_policy_data.l_extent;
453                 struct cl_attr *attr = &osc_env_info(env)->oti_attr;
454                 __u64 old_kms;
455
456                 /* Destroy pages covered by the extent of the DLM lock */
457                 result = osc_lock_flush(cl2osc(obj),
458                                         cl_index(obj, extent->start),
459                                         cl_index(obj, extent->end),
460                                         mode, discard);
461
462                 /* losing a lock, update kms */
463                 lock_res_and_lock(dlmlock);
464                 cl_object_attr_lock(obj);
465                 /* Must get the value under the lock to avoid race. */
466                 old_kms = cl2osc(obj)->oo_oinfo->loi_kms;
467                 /* Update the kms. Need to loop all granted locks.
468                  * Not a problem for the client
469                  */
470                 attr->cat_kms = ldlm_extent_shift_kms(dlmlock, old_kms);
471
472                 cl_object_attr_update(env, obj, attr, CAT_KMS);
473                 cl_object_attr_unlock(obj);
474                 unlock_res_and_lock(dlmlock);
475
476                 cl_object_put(env, obj);
477         }
478         return result;
479 }
480
481 /**
482  * Blocking ast invoked by ldlm when dlm lock is either blocking progress of
483  * some other lock, or is canceled. This function is installed as a
484  * ldlm_lock::l_blocking_ast() for client extent locks.
485  *
486  * Control flow is tricky, because ldlm uses the same call-back
487  * (ldlm_lock::l_blocking_ast()) for both blocking and cancellation ast's.
488  *
489  * \param dlmlock lock for which ast occurred.
490  *
491  * \param new description of a conflicting lock in case of blocking ast.
492  *
493  * \param data value of dlmlock->l_ast_data
494  *
495  * \param flag LDLM_CB_BLOCKING or LDLM_CB_CANCELING. Used to distinguish
496  *           cancellation and blocking ast's.
497  *
498  * Possible use cases:
499  *
500  *     - ldlm calls dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING) to cancel
501  *       lock due to lock lru pressure, or explicit user request to purge
502  *       locks.
503  *
504  *     - ldlm calls dlmlock->l_blocking_ast(..., LDLM_CB_BLOCKING) to notify
505  *       us that dlmlock conflicts with another lock that some client is
506  *       enqueing. Lock is canceled.
507  *
508  *         - cl_lock_cancel() is called. osc_lock_cancel() calls
509  *           ldlm_cli_cancel() that calls
510  *
511  *                dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING)
512  *
513  *           recursively entering osc_ldlm_blocking_ast().
514  *
515  *     - client cancels lock voluntary (e.g., as a part of early cancellation):
516  *
517  *         cl_lock_cancel()->
518  *           osc_lock_cancel()->
519  *             ldlm_cli_cancel()->
520  *               dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING)
521  *
522  */
523 static int osc_ldlm_blocking_ast(struct ldlm_lock *dlmlock,
524                                  struct ldlm_lock_desc *new, void *data,
525                                  int flag)
526 {
527         int result = 0;
528
529         switch (flag) {
530         case LDLM_CB_BLOCKING: {
531                 struct lustre_handle lockh;
532
533                 ldlm_lock2handle(dlmlock, &lockh);
534                 result = ldlm_cli_cancel(&lockh, LCF_ASYNC);
535                 if (result == -ENODATA)
536                         result = 0;
537                 break;
538         }
539         case LDLM_CB_CANCELING: {
540                 struct lu_env *env;
541                 u16 refcheck;
542
543                 /*
544                  * This can be called in the context of outer IO, e.g.,
545                  *
546                  *     osc_enqueue_base()->...
547                  *       ->ldlm_prep_elc_req()->...
548                  *         ->ldlm_cancel_callback()->...
549                  *           ->osc_ldlm_blocking_ast()
550                  *
551                  * new environment has to be created to not corrupt outer
552                  * context.
553                  */
554                 env = cl_env_get(&refcheck);
555                 if (IS_ERR(env)) {
556                         result = PTR_ERR(env);
557                         break;
558                 }
559
560                 result = osc_dlm_blocking_ast0(env, dlmlock, data, flag);
561                 cl_env_put(env, &refcheck);
562                 break;
563                 }
564         default:
565                 LBUG();
566         }
567         return result;
568 }
569
570 static int osc_ldlm_glimpse_ast(struct ldlm_lock *dlmlock, void *data)
571 {
572         struct ptlrpc_request *req = data;
573         struct lu_env *env;
574         struct ost_lvb *lvb;
575         struct req_capsule *cap;
576         struct cl_object *obj = NULL;
577         int result;
578         u16 refcheck;
579
580         LASSERT(lustre_msg_get_opc(req->rq_reqmsg) == LDLM_GL_CALLBACK);
581
582         env = cl_env_get(&refcheck);
583         if (IS_ERR(env)) {
584                 result = PTR_ERR(env);
585                 goto out;
586         }
587
588         lock_res_and_lock(dlmlock);
589         if (dlmlock->l_ast_data) {
590                 obj = osc2cl(dlmlock->l_ast_data);
591                 cl_object_get(obj);
592         }
593         unlock_res_and_lock(dlmlock);
594
595         if (obj) {
596                 /* Do not grab the mutex of cl_lock for glimpse.
597                  * See LU-1274 for details.
598                  * BTW, it's okay for cl_lock to be cancelled during
599                  * this period because server can handle this race.
600                  * See ldlm_server_glimpse_ast() for details.
601                  * cl_lock_mutex_get(env, lock);
602                  */
603                 cap = &req->rq_pill;
604                 req_capsule_extend(cap, &RQF_LDLM_GL_CALLBACK);
605                 req_capsule_set_size(cap, &RMF_DLM_LVB, RCL_SERVER,
606                                      sizeof(*lvb));
607                 result = req_capsule_server_pack(cap);
608                 if (result == 0) {
609                         lvb = req_capsule_server_get(cap, &RMF_DLM_LVB);
610                         result = cl_object_glimpse(env, obj, lvb);
611                 }
612                 if (!exp_connect_lvb_type(req->rq_export)) {
613                         req_capsule_shrink(&req->rq_pill, &RMF_DLM_LVB,
614                                            sizeof(struct ost_lvb_v1),
615                                            RCL_SERVER);
616                 }
617                 cl_object_put(env, obj);
618         } else {
619                 /*
620                  * These errors are normal races, so we don't want to
621                  * fill the console with messages by calling
622                  * ptlrpc_error()
623                  */
624                 lustre_pack_reply(req, 1, NULL, NULL);
625                 result = -ELDLM_NO_LOCK_DATA;
626         }
627         cl_env_put(env, &refcheck);
628
629 out:
630         req->rq_status = result;
631         return result;
632 }
633
634 static int weigh_cb(const struct lu_env *env, struct cl_io *io,
635                     struct osc_page *ops, void *cbdata)
636 {
637         struct cl_page *page = ops->ops_cl.cpl_page;
638
639         if (cl_page_is_vmlocked(env, page) ||
640             PageDirty(page->cp_vmpage) || PageWriteback(page->cp_vmpage)
641            )
642                 return CLP_GANG_ABORT;
643
644         *(pgoff_t *)cbdata = osc_index(ops) + 1;
645         return CLP_GANG_OKAY;
646 }
647
648 static unsigned long osc_lock_weight(const struct lu_env *env,
649                                      struct osc_object *oscobj,
650                                      struct ldlm_extent *extent)
651 {
652         struct cl_io *io = &osc_env_info(env)->oti_io;
653         struct cl_object *obj = cl_object_top(&oscobj->oo_cl);
654         pgoff_t page_index;
655         int result;
656
657         io->ci_obj = obj;
658         io->ci_ignore_layout = 1;
659         result = cl_io_init(env, io, CIT_MISC, io->ci_obj);
660         if (result != 0)
661                 return result;
662
663         page_index = cl_index(obj, extent->start);
664         do {
665                 result = osc_page_gang_lookup(env, io, oscobj,
666                                               page_index,
667                                               cl_index(obj, extent->end),
668                                               weigh_cb, (void *)&page_index);
669                 if (result == CLP_GANG_ABORT)
670                         break;
671                 if (result == CLP_GANG_RESCHED)
672                         cond_resched();
673         } while (result != CLP_GANG_OKAY);
674         cl_io_fini(env, io);
675
676         return result == CLP_GANG_ABORT ? 1 : 0;
677 }
678
679 /**
680  * Get the weight of dlm lock for early cancellation.
681  */
682 unsigned long osc_ldlm_weigh_ast(struct ldlm_lock *dlmlock)
683 {
684         struct lu_env           *env;
685         struct osc_object       *obj;
686         struct osc_lock         *oscl;
687         unsigned long            weight;
688         bool                     found = false;
689         u16 refcheck;
690
691         might_sleep();
692         /*
693          * osc_ldlm_weigh_ast has a complex context since it might be called
694          * because of lock canceling, or from user's input. We have to make
695          * a new environment for it. Probably it is implementation safe to use
696          * the upper context because cl_lock_put don't modify environment
697          * variables. But just in case ..
698          */
699         env = cl_env_get(&refcheck);
700         if (IS_ERR(env))
701                 /* Mostly because lack of memory, do not eliminate this lock */
702                 return 1;
703
704         LASSERT(dlmlock->l_resource->lr_type == LDLM_EXTENT);
705         obj = dlmlock->l_ast_data;
706         if (!obj) {
707                 weight = 1;
708                 goto out;
709         }
710
711         spin_lock(&obj->oo_ol_spin);
712         list_for_each_entry(oscl, &obj->oo_ol_list, ols_nextlock_oscobj) {
713                 if (oscl->ols_dlmlock && oscl->ols_dlmlock != dlmlock)
714                         continue;
715                 found = true;
716         }
717         spin_unlock(&obj->oo_ol_spin);
718         if (found) {
719                 /*
720                  * If the lock is being used by an IO, definitely not cancel it.
721                  */
722                 weight = 1;
723                 goto out;
724         }
725
726         weight = osc_lock_weight(env, obj, &dlmlock->l_policy_data.l_extent);
727
728 out:
729         cl_env_put(env, &refcheck);
730         return weight;
731 }
732
733 static void osc_lock_build_einfo(const struct lu_env *env,
734                                  const struct cl_lock *lock,
735                                  struct osc_object *osc,
736                                  struct ldlm_enqueue_info *einfo)
737 {
738         einfo->ei_type = LDLM_EXTENT;
739         einfo->ei_mode   = osc_cl_lock2ldlm(lock->cll_descr.cld_mode);
740         einfo->ei_cb_bl = osc_ldlm_blocking_ast;
741         einfo->ei_cb_cp  = ldlm_completion_ast;
742         einfo->ei_cb_gl = osc_ldlm_glimpse_ast;
743         einfo->ei_cbdata = osc; /* value to be put into ->l_ast_data */
744 }
745
746 /**
747  * Determine if the lock should be converted into a lockless lock.
748  *
749  * Steps to check:
750  * - if the lock has an explicit requirement for a non-lockless lock;
751  * - if the io lock request type ci_lockreq;
752  * - send the enqueue rpc to ost to make the further decision;
753  * - special treat to truncate lockless lock
754  *
755  *  Additional policy can be implemented here, e.g., never do lockless-io
756  *  for large extents.
757  */
758 static void osc_lock_to_lockless(const struct lu_env *env,
759                                  struct osc_lock *ols, int force)
760 {
761         struct cl_lock_slice *slice = &ols->ols_cl;
762
763         LASSERT(ols->ols_state == OLS_NEW ||
764                 ols->ols_state == OLS_UPCALL_RECEIVED);
765
766         if (force) {
767                 ols->ols_locklessable = 1;
768                 slice->cls_ops = &osc_lock_lockless_ops;
769         } else {
770                 struct osc_io *oio = osc_env_io(env);
771                 struct cl_io *io = oio->oi_cl.cis_io;
772                 struct cl_object *obj = slice->cls_obj;
773                 struct osc_object *oob = cl2osc(obj);
774                 const struct osc_device *osd = lu2osc_dev(obj->co_lu.lo_dev);
775                 struct obd_connect_data *ocd;
776
777                 LASSERT(io->ci_lockreq == CILR_MANDATORY ||
778                         io->ci_lockreq == CILR_MAYBE ||
779                         io->ci_lockreq == CILR_NEVER);
780
781                 ocd = &class_exp2cliimp(osc_export(oob))->imp_connect_data;
782                 ols->ols_locklessable = (io->ci_type != CIT_SETATTR) &&
783                                 (io->ci_lockreq == CILR_MAYBE) &&
784                                 (ocd->ocd_connect_flags & OBD_CONNECT_SRVLOCK);
785                 if (io->ci_lockreq == CILR_NEVER ||
786                         /* lockless IO */
787                     (ols->ols_locklessable && osc_object_is_contended(oob)) ||
788                         /* lockless truncate */
789                     (cl_io_is_trunc(io) &&
790                      (ocd->ocd_connect_flags & OBD_CONNECT_TRUNCLOCK) &&
791                       osd->od_lockless_truncate)) {
792                         ols->ols_locklessable = 1;
793                         slice->cls_ops = &osc_lock_lockless_ops;
794                 }
795         }
796         LASSERT(ergo(ols->ols_glimpse, !osc_lock_is_lockless(ols)));
797 }
798
799 static bool osc_lock_compatible(const struct osc_lock *qing,
800                                 const struct osc_lock *qed)
801 {
802         struct cl_lock_descr *qed_descr = &qed->ols_cl.cls_lock->cll_descr;
803         struct cl_lock_descr *qing_descr = &qing->ols_cl.cls_lock->cll_descr;
804
805         if (qed->ols_glimpse)
806                 return true;
807
808         if (qing_descr->cld_mode == CLM_READ && qed_descr->cld_mode == CLM_READ)
809                 return true;
810
811         if (qed->ols_state < OLS_GRANTED)
812                 return true;
813
814         if (qed_descr->cld_mode  >= qing_descr->cld_mode &&
815             qed_descr->cld_start <= qing_descr->cld_start &&
816             qed_descr->cld_end   >= qing_descr->cld_end)
817                 return true;
818
819         return false;
820 }
821
822 static void osc_lock_wake_waiters(const struct lu_env *env,
823                                   struct osc_object *osc,
824                                   struct osc_lock *oscl)
825 {
826         spin_lock(&osc->oo_ol_spin);
827         list_del_init(&oscl->ols_nextlock_oscobj);
828         spin_unlock(&osc->oo_ol_spin);
829
830         spin_lock(&oscl->ols_lock);
831         while (!list_empty(&oscl->ols_waiting_list)) {
832                 struct osc_lock *scan;
833
834                 scan = list_entry(oscl->ols_waiting_list.next, struct osc_lock,
835                                   ols_wait_entry);
836                 list_del_init(&scan->ols_wait_entry);
837
838                 cl_sync_io_note(env, scan->ols_owner, 0);
839         }
840         spin_unlock(&oscl->ols_lock);
841 }
842
843 static int osc_lock_enqueue_wait(const struct lu_env *env,
844                                  struct osc_object *obj,
845                                  struct osc_lock *oscl)
846 {
847         struct osc_lock *tmp_oscl;
848         struct cl_lock_descr *need = &oscl->ols_cl.cls_lock->cll_descr;
849         struct cl_sync_io *waiter = &osc_env_info(env)->oti_anchor;
850         int rc = 0;
851
852         spin_lock(&obj->oo_ol_spin);
853         list_add_tail(&oscl->ols_nextlock_oscobj, &obj->oo_ol_list);
854
855 restart:
856         list_for_each_entry(tmp_oscl, &obj->oo_ol_list,
857                             ols_nextlock_oscobj) {
858                 struct cl_lock_descr *descr;
859
860                 if (tmp_oscl == oscl)
861                         break;
862
863                 descr = &tmp_oscl->ols_cl.cls_lock->cll_descr;
864                 if (descr->cld_start > need->cld_end ||
865                     descr->cld_end   < need->cld_start)
866                         continue;
867
868                 /* We're not supposed to give up group lock */
869                 if (descr->cld_mode == CLM_GROUP)
870                         break;
871
872                 if (!osc_lock_is_lockless(oscl) &&
873                     osc_lock_compatible(oscl, tmp_oscl))
874                         continue;
875
876                 /* wait for conflicting lock to be canceled */
877                 cl_sync_io_init(waiter, 1, cl_sync_io_end);
878                 oscl->ols_owner = waiter;
879
880                 spin_lock(&tmp_oscl->ols_lock);
881                 /* add oscl into tmp's ols_waiting list */
882                 list_add_tail(&oscl->ols_wait_entry,
883                               &tmp_oscl->ols_waiting_list);
884                 spin_unlock(&tmp_oscl->ols_lock);
885
886                 spin_unlock(&obj->oo_ol_spin);
887                 rc = cl_sync_io_wait(env, waiter, 0);
888                 spin_lock(&obj->oo_ol_spin);
889                 if (rc < 0)
890                         break;
891
892                 oscl->ols_owner = NULL;
893                 goto restart;
894         }
895         spin_unlock(&obj->oo_ol_spin);
896
897         return rc;
898 }
899
900 /**
901  * Implementation of cl_lock_operations::clo_enqueue() method for osc
902  * layer. This initiates ldlm enqueue:
903  *
904  *     - cancels conflicting locks early (osc_lock_enqueue_wait());
905  *
906  *     - calls osc_enqueue_base() to do actual enqueue.
907  *
908  * osc_enqueue_base() is supplied with an upcall function that is executed
909  * when lock is received either after a local cached ldlm lock is matched, or
910  * when a reply from the server is received.
911  *
912  * This function does not wait for the network communication to complete.
913  */
914 static int osc_lock_enqueue(const struct lu_env *env,
915                             const struct cl_lock_slice *slice,
916                             struct cl_io *unused, struct cl_sync_io *anchor)
917 {
918         struct osc_thread_info *info = osc_env_info(env);
919         struct osc_io *oio = osc_env_io(env);
920         struct osc_object *osc = cl2osc(slice->cls_obj);
921         struct osc_lock *oscl = cl2osc_lock(slice);
922         struct cl_lock *lock = slice->cls_lock;
923         struct ldlm_res_id *resname = &info->oti_resname;
924         union ldlm_policy_data *policy = &info->oti_policy;
925         osc_enqueue_upcall_f upcall = osc_lock_upcall;
926         void *cookie = oscl;
927         bool async = false;
928         int result;
929
930         LASSERTF(ergo(oscl->ols_glimpse, lock->cll_descr.cld_mode <= CLM_READ),
931                  "lock = %p, ols = %p\n", lock, oscl);
932
933         if (oscl->ols_state == OLS_GRANTED)
934                 return 0;
935
936         if (oscl->ols_flags & LDLM_FL_TEST_LOCK)
937                 goto enqueue_base;
938
939         if (oscl->ols_glimpse) {
940                 LASSERT(equi(oscl->ols_agl, !anchor));
941                 async = true;
942                 goto enqueue_base;
943         }
944
945         result = osc_lock_enqueue_wait(env, osc, oscl);
946         if (result < 0)
947                 goto out;
948
949         /* we can grant lockless lock right after all conflicting locks
950          * are canceled.
951          */
952         if (osc_lock_is_lockless(oscl)) {
953                 oscl->ols_state = OLS_GRANTED;
954                 oio->oi_lockless = 1;
955                 return 0;
956         }
957
958 enqueue_base:
959         oscl->ols_state = OLS_ENQUEUED;
960         if (anchor) {
961                 atomic_inc(&anchor->csi_sync_nr);
962                 oscl->ols_owner = anchor;
963         }
964
965         /**
966          * DLM lock's ast data must be osc_object;
967          * if glimpse or AGL lock, async of osc_enqueue_base() must be true,
968          * DLM's enqueue callback set to osc_lock_upcall() with cookie as
969          * osc_lock.
970          */
971         ostid_build_res_name(&osc->oo_oinfo->loi_oi, resname);
972         osc_lock_build_policy(env, lock, policy);
973         if (oscl->ols_agl) {
974                 oscl->ols_einfo.ei_cbdata = NULL;
975                 /* hold a reference for callback */
976                 cl_object_get(osc2cl(osc));
977                 upcall = osc_lock_upcall_agl;
978                 cookie = osc;
979         }
980         result = osc_enqueue_base(osc_export(osc), resname, &oscl->ols_flags,
981                                   policy, &oscl->ols_lvb,
982                                   osc->oo_oinfo->loi_kms_valid,
983                                   upcall, cookie,
984                                   &oscl->ols_einfo, PTLRPCD_SET, async,
985                                   oscl->ols_agl);
986         if (!result) {
987                 if (osc_lock_is_lockless(oscl)) {
988                         oio->oi_lockless = 1;
989                 } else if (!async) {
990                         LASSERT(oscl->ols_state == OLS_GRANTED);
991                         LASSERT(oscl->ols_hold);
992                         LASSERT(oscl->ols_dlmlock);
993                 }
994         } else if (oscl->ols_agl) {
995                 cl_object_put(env, osc2cl(osc));
996                 result = 0;
997         }
998
999 out:
1000         if (result < 0) {
1001                 oscl->ols_state = OLS_CANCELLED;
1002                 osc_lock_wake_waiters(env, osc, oscl);
1003
1004                 if (anchor)
1005                         cl_sync_io_note(env, anchor, result);
1006         }
1007         return result;
1008 }
1009
1010 /**
1011  * Breaks a link between osc_lock and dlm_lock.
1012  */
1013 static void osc_lock_detach(const struct lu_env *env, struct osc_lock *olck)
1014 {
1015         struct ldlm_lock *dlmlock;
1016
1017         dlmlock = olck->ols_dlmlock;
1018         if (!dlmlock)
1019                 return;
1020
1021         if (olck->ols_hold) {
1022                 olck->ols_hold = 0;
1023                 ldlm_lock_decref(&olck->ols_handle, olck->ols_einfo.ei_mode);
1024                 olck->ols_handle.cookie = 0ULL;
1025         }
1026
1027         olck->ols_dlmlock = NULL;
1028
1029         /* release a reference taken in osc_lock_upcall(). */
1030         LASSERT(olck->ols_has_ref);
1031         lu_ref_del(&dlmlock->l_reference, "osc_lock", olck);
1032         LDLM_LOCK_RELEASE(dlmlock);
1033         olck->ols_has_ref = 0;
1034 }
1035
1036 /**
1037  * Implements cl_lock_operations::clo_cancel() method for osc layer. This is
1038  * called (as part of cl_lock_cancel()) when lock is canceled either voluntary
1039  * (LRU pressure, early cancellation, umount, etc.) or due to the conflict
1040  * with some other lock some where in the cluster. This function does the
1041  * following:
1042  *
1043  *     - invalidates all pages protected by this lock (after sending dirty
1044  *       ones to the server, as necessary);
1045  *
1046  *     - decref's underlying ldlm lock;
1047  *
1048  *     - cancels ldlm lock (ldlm_cli_cancel()).
1049  */
1050 static void osc_lock_cancel(const struct lu_env *env,
1051                             const struct cl_lock_slice *slice)
1052 {
1053         struct osc_object *obj  = cl2osc(slice->cls_obj);
1054         struct osc_lock *oscl = cl2osc_lock(slice);
1055
1056         LINVRNT(osc_lock_invariant(oscl));
1057
1058         osc_lock_detach(env, oscl);
1059         oscl->ols_state = OLS_CANCELLED;
1060         oscl->ols_flags &= ~LDLM_FL_LVB_READY;
1061
1062         osc_lock_wake_waiters(env, obj, oscl);
1063 }
1064
1065 static int osc_lock_print(const struct lu_env *env, void *cookie,
1066                           lu_printer_t p, const struct cl_lock_slice *slice)
1067 {
1068         struct osc_lock *lock = cl2osc_lock(slice);
1069
1070         (*p)(env, cookie, "%p %#16llx %#llx %d %p ",
1071              lock->ols_dlmlock, lock->ols_flags, lock->ols_handle.cookie,
1072              lock->ols_state, lock->ols_owner);
1073         osc_lvb_print(env, cookie, p, &lock->ols_lvb);
1074         return 0;
1075 }
1076
1077 static const struct cl_lock_operations osc_lock_ops = {
1078         .clo_fini    = osc_lock_fini,
1079         .clo_enqueue = osc_lock_enqueue,
1080         .clo_cancel  = osc_lock_cancel,
1081         .clo_print   = osc_lock_print,
1082 };
1083
1084 static void osc_lock_lockless_cancel(const struct lu_env *env,
1085                                      const struct cl_lock_slice *slice)
1086 {
1087         struct osc_lock *ols = cl2osc_lock(slice);
1088         struct osc_object *osc = cl2osc(slice->cls_obj);
1089         struct cl_lock_descr *descr = &slice->cls_lock->cll_descr;
1090         int result;
1091
1092         LASSERT(!ols->ols_dlmlock);
1093         result = osc_lock_flush(osc, descr->cld_start, descr->cld_end,
1094                                 descr->cld_mode, 0);
1095         if (result)
1096                 CERROR("Pages for lockless lock %p were not purged(%d)\n",
1097                        ols, result);
1098
1099         osc_lock_wake_waiters(env, osc, ols);
1100 }
1101
1102 static const struct cl_lock_operations osc_lock_lockless_ops = {
1103         .clo_fini       = osc_lock_fini,
1104         .clo_enqueue    = osc_lock_enqueue,
1105         .clo_cancel     = osc_lock_lockless_cancel,
1106         .clo_print      = osc_lock_print
1107 };
1108
1109 static void osc_lock_set_writer(const struct lu_env *env,
1110                                 const struct cl_io *io,
1111                                 struct cl_object *obj, struct osc_lock *oscl)
1112 {
1113         struct cl_lock_descr *descr = &oscl->ols_cl.cls_lock->cll_descr;
1114         pgoff_t io_start;
1115         pgoff_t io_end;
1116
1117         if (!cl_object_same(io->ci_obj, obj))
1118                 return;
1119
1120         if (likely(io->ci_type == CIT_WRITE)) {
1121                 io_start = cl_index(obj, io->u.ci_rw.crw_pos);
1122                 io_end = cl_index(obj, io->u.ci_rw.crw_pos +
1123                                   io->u.ci_rw.crw_count - 1);
1124                 if (cl_io_is_append(io)) {
1125                         io_start = 0;
1126                         io_end = CL_PAGE_EOF;
1127                 }
1128         } else {
1129                 LASSERT(cl_io_is_mkwrite(io));
1130                 io_start = io->u.ci_fault.ft_index;
1131                 io_end = io->u.ci_fault.ft_index;
1132         }
1133
1134         if (descr->cld_mode >= CLM_WRITE &&
1135             descr->cld_start <= io_start && descr->cld_end >= io_end) {
1136                 struct osc_io *oio = osc_env_io(env);
1137
1138                 /* There must be only one lock to match the write region */
1139                 LASSERT(!oio->oi_write_osclock);
1140                 oio->oi_write_osclock = oscl;
1141         }
1142 }
1143
1144 int osc_lock_init(const struct lu_env *env,
1145                   struct cl_object *obj, struct cl_lock *lock,
1146                   const struct cl_io *io)
1147 {
1148         struct osc_lock *oscl;
1149         __u32 enqflags = lock->cll_descr.cld_enq_flags;
1150
1151         oscl = kmem_cache_zalloc(osc_lock_kmem, GFP_NOFS);
1152         if (!oscl)
1153                 return -ENOMEM;
1154
1155         oscl->ols_state = OLS_NEW;
1156         spin_lock_init(&oscl->ols_lock);
1157         INIT_LIST_HEAD(&oscl->ols_waiting_list);
1158         INIT_LIST_HEAD(&oscl->ols_wait_entry);
1159         INIT_LIST_HEAD(&oscl->ols_nextlock_oscobj);
1160
1161         oscl->ols_flags = osc_enq2ldlm_flags(enqflags);
1162         oscl->ols_agl = !!(enqflags & CEF_AGL);
1163         if (oscl->ols_agl)
1164                 oscl->ols_flags |= LDLM_FL_BLOCK_NOWAIT;
1165         if (oscl->ols_flags & LDLM_FL_HAS_INTENT) {
1166                 oscl->ols_flags |= LDLM_FL_BLOCK_GRANTED;
1167                 oscl->ols_glimpse = 1;
1168         }
1169         osc_lock_build_einfo(env, lock, cl2osc(obj), &oscl->ols_einfo);
1170
1171         cl_lock_slice_add(lock, &oscl->ols_cl, obj, &osc_lock_ops);
1172
1173         if (!(enqflags & CEF_MUST))
1174                 /* try to convert this lock to a lockless lock */
1175                 osc_lock_to_lockless(env, oscl, (enqflags & CEF_NEVER));
1176         if (oscl->ols_locklessable && !(enqflags & CEF_DISCARD_DATA))
1177                 oscl->ols_flags |= LDLM_FL_DENY_ON_CONTENTION;
1178
1179         if (io->ci_type == CIT_WRITE || cl_io_is_mkwrite(io))
1180                 osc_lock_set_writer(env, io, obj, oscl);
1181
1182
1183         LDLM_DEBUG_NOLOCK("lock %p, osc lock %p, flags %llx",
1184                           lock, oscl, oscl->ols_flags);
1185
1186         return 0;
1187 }
1188
1189 /**
1190  * Finds an existing lock covering given index and optionally different from a
1191  * given \a except lock.
1192  */
1193 struct ldlm_lock *osc_dlmlock_at_pgoff(const struct lu_env *env,
1194                                        struct osc_object *obj, pgoff_t index,
1195                                        enum osc_dap_flags dap_flags)
1196 {
1197         struct osc_thread_info *info = osc_env_info(env);
1198         struct ldlm_res_id *resname = &info->oti_resname;
1199         union ldlm_policy_data *policy = &info->oti_policy;
1200         struct lustre_handle lockh;
1201         struct ldlm_lock *lock = NULL;
1202         enum ldlm_mode mode;
1203         __u64 flags;
1204
1205         ostid_build_res_name(&obj->oo_oinfo->loi_oi, resname);
1206         osc_index2policy(policy, osc2cl(obj), index, index);
1207         policy->l_extent.gid = LDLM_GID_ANY;
1208
1209         flags = LDLM_FL_BLOCK_GRANTED | LDLM_FL_CBPENDING;
1210         if (dap_flags & OSC_DAP_FL_TEST_LOCK)
1211                 flags |= LDLM_FL_TEST_LOCK;
1212
1213         /*
1214          * It is fine to match any group lock since there could be only one
1215          * with a uniq gid and it conflicts with all other lock modes too
1216          */
1217 again:
1218         mode = osc_match_base(osc_export(obj), resname, LDLM_EXTENT, policy,
1219                               LCK_PR | LCK_PW | LCK_GROUP, &flags, obj, &lockh,
1220                               dap_flags & OSC_DAP_FL_CANCELING);
1221         if (mode != 0) {
1222                 lock = ldlm_handle2lock(&lockh);
1223                 /* RACE: the lock is cancelled so let's try again */
1224                 if (unlikely(!lock))
1225                         goto again;
1226         }
1227         return lock;
1228 }
1229
1230 /** @} osc */