Whamcloud - gitweb
9aa7f59c596028a6a0615ce4b23eb4db5d918130
[fs/lustre-release.git] / lustre / osc / osc_lock.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011 Whamcloud, Inc.
33  *
34  */
35 /*
36  * This file is part of Lustre, http://www.lustre.org/
37  * Lustre is a trademark of Sun Microsystems, Inc.
38  *
39  * Implementation of cl_lock for OSC layer.
40  *
41  *   Author: Nikita Danilov <nikita.danilov@sun.com>
42  */
43
44 #define DEBUG_SUBSYSTEM S_OSC
45
46 #ifdef __KERNEL__
47 # include <libcfs/libcfs.h>
48 #else
49 # include <liblustre.h>
50 #endif
51 /* fid_build_reg_res_name() */
52 #include <lustre_fid.h>
53
54 #include "osc_cl_internal.h"
55
56 /** \addtogroup osc 
57  *  @{ 
58  */
59
60 #define _PAGEREF_MAGIC  (-10000000)
61
62 /*****************************************************************************
63  *
64  * Type conversions.
65  *
66  */
67
68 static const struct cl_lock_operations osc_lock_ops;
69 static const struct cl_lock_operations osc_lock_lockless_ops;
70 static void osc_lock_to_lockless(const struct lu_env *env,
71                                  struct osc_lock *ols, int force);
72 static int osc_lock_has_pages(struct osc_lock *olck);
73
74 int osc_lock_is_lockless(const struct osc_lock *olck)
75 {
76         return (olck->ols_cl.cls_ops == &osc_lock_lockless_ops);
77 }
78
79 /**
80  * Returns a weak pointer to the ldlm lock identified by a handle. Returned
81  * pointer cannot be dereferenced, as lock is not protected from concurrent
82  * reclaim. This function is a helper for osc_lock_invariant().
83  */
84 static struct ldlm_lock *osc_handle_ptr(struct lustre_handle *handle)
85 {
86         struct ldlm_lock *lock;
87
88         lock = ldlm_handle2lock(handle);
89         if (lock != NULL)
90                 LDLM_LOCK_PUT(lock);
91         return lock;
92 }
93
94 /**
95  * Invariant that has to be true all of the time.
96  */
97 static int osc_lock_invariant(struct osc_lock *ols)
98 {
99         struct ldlm_lock *lock        = osc_handle_ptr(&ols->ols_handle);
100         struct ldlm_lock *olock       = ols->ols_lock;
101         int               handle_used = lustre_handle_is_used(&ols->ols_handle);
102
103         return
104                 ergo(osc_lock_is_lockless(ols),
105                      ols->ols_locklessable && ols->ols_lock == NULL)  ||
106                 (ergo(olock != NULL, handle_used) &&
107                  ergo(olock != NULL,
108                       olock->l_handle.h_cookie == ols->ols_handle.cookie) &&
109                  /*
110                   * Check that ->ols_handle and ->ols_lock are consistent, but
111                   * take into account that they are set at the different time.
112                   */
113                  ergo(handle_used,
114                       ergo(lock != NULL && olock != NULL, lock == olock) &&
115                       ergo(lock == NULL, olock == NULL)) &&
116                  ergo(ols->ols_state == OLS_CANCELLED,
117                       olock == NULL && !handle_used) &&
118                  /*
119                   * DLM lock is destroyed only after we have seen cancellation
120                   * ast.
121                   */
122                  ergo(olock != NULL && ols->ols_state < OLS_CANCELLED,
123                       !olock->l_destroyed) &&
124                  ergo(ols->ols_state == OLS_GRANTED,
125                       olock != NULL &&
126                       olock->l_req_mode == olock->l_granted_mode &&
127                       ols->ols_hold));
128 }
129
130 /*****************************************************************************
131  *
132  * Lock operations.
133  *
134  */
135
136 /**
137  * Breaks a link between osc_lock and dlm_lock.
138  */
139 static void osc_lock_detach(const struct lu_env *env, struct osc_lock *olck)
140 {
141         struct ldlm_lock *dlmlock;
142
143         cfs_spin_lock(&osc_ast_guard);
144         dlmlock = olck->ols_lock;
145         if (dlmlock == NULL) {
146                 cfs_spin_unlock(&osc_ast_guard);
147                 return;
148         }
149
150         olck->ols_lock = NULL;
151         /* wb(); --- for all who checks (ols->ols_lock != NULL) before
152          * call to osc_lock_detach() */
153         dlmlock->l_ast_data = NULL;
154         olck->ols_handle.cookie = 0ULL;
155         cfs_spin_unlock(&osc_ast_guard);
156
157         lock_res_and_lock(dlmlock);
158         if (dlmlock->l_granted_mode == dlmlock->l_req_mode) {
159                 struct cl_object *obj = olck->ols_cl.cls_obj;
160                 struct cl_attr *attr  = &osc_env_info(env)->oti_attr;
161                 __u64 old_kms;
162
163                 cl_object_attr_lock(obj);
164                 /* Must get the value under the lock to avoid possible races. */
165                 old_kms = cl2osc(obj)->oo_oinfo->loi_kms;
166                 /* Update the kms. Need to loop all granted locks.
167                  * Not a problem for the client */
168                 attr->cat_kms = ldlm_extent_shift_kms(dlmlock, old_kms);
169
170                 cl_object_attr_set(env, obj, attr, CAT_KMS);
171                 cl_object_attr_unlock(obj);
172         }
173         unlock_res_and_lock(dlmlock);
174
175         /* release a reference taken in osc_lock_upcall0(). */
176         LASSERT(olck->ols_has_ref);
177         lu_ref_del(&dlmlock->l_reference, "osc_lock", olck);
178         LDLM_LOCK_RELEASE(dlmlock);
179         olck->ols_has_ref = 0;
180 }
181
182 static int osc_lock_unhold(struct osc_lock *ols)
183 {
184         int result = 0;
185
186         if (ols->ols_hold) {
187                 ols->ols_hold = 0;
188                 result = osc_cancel_base(&ols->ols_handle,
189                                          ols->ols_einfo.ei_mode);
190         }
191         return result;
192 }
193
194 static int osc_lock_unuse(const struct lu_env *env,
195                           const struct cl_lock_slice *slice)
196 {
197         struct osc_lock *ols = cl2osc_lock(slice);
198
199         LINVRNT(osc_lock_invariant(ols));
200
201         switch (ols->ols_state) {
202         case OLS_NEW:
203                 LASSERT(!ols->ols_hold);
204                 LASSERT(ols->ols_agl);
205                 return 0;
206         case OLS_UPCALL_RECEIVED:
207                 LASSERT(!ols->ols_hold);
208                 ols->ols_state = OLS_NEW;
209                 return 0;
210         case OLS_GRANTED:
211                 LASSERT(!ols->ols_glimpse);
212                 LASSERT(ols->ols_hold);
213                 /*
214                  * Move lock into OLS_RELEASED state before calling
215                  * osc_cancel_base() so that possible synchronous cancellation
216                  * (that always happens e.g., for liblustre) sees that lock is
217                  * released.
218                  */
219                 ols->ols_state = OLS_RELEASED;
220                 return osc_lock_unhold(ols);
221         default:
222                 CERROR("Impossible state: %d\n", ols->ols_state);
223                 LBUG();
224         }
225 }
226
227 static void osc_lock_fini(const struct lu_env *env,
228                           struct cl_lock_slice *slice)
229 {
230         struct osc_lock  *ols = cl2osc_lock(slice);
231
232         LINVRNT(osc_lock_invariant(ols));
233         /*
234          * ->ols_hold can still be true at this point if, for example, a
235          * thread that requested a lock was killed (and released a reference
236          * to the lock), before reply from a server was received. In this case
237          * lock is destroyed immediately after upcall.
238          */
239         osc_lock_unhold(ols);
240         LASSERT(ols->ols_lock == NULL);
241         LASSERT(cfs_atomic_read(&ols->ols_pageref) == 0 ||
242                 cfs_atomic_read(&ols->ols_pageref) == _PAGEREF_MAGIC);
243
244         OBD_SLAB_FREE_PTR(ols, osc_lock_kmem);
245 }
246
247 void osc_lock_build_res(const struct lu_env *env, const struct osc_object *obj,
248                         struct ldlm_res_id *resname)
249 {
250         const struct lu_fid *fid = lu_object_fid(&obj->oo_cl.co_lu);
251         if (0) {
252                 /*
253                  * In the perfect world of the future, where ost servers talk
254                  * idif-fids...
255                  */
256                 fid_build_reg_res_name(fid, resname);
257         } else {
258                 /*
259                  * In reality, where ost server expects ->lsm_object_id and
260                  * ->lsm_object_seq in rename.
261                  */
262                 osc_build_res_name(obj->oo_oinfo->loi_id, obj->oo_oinfo->loi_seq,
263                                    resname);
264         }
265 }
266
267 static void osc_lock_build_policy(const struct lu_env *env,
268                                   const struct cl_lock *lock,
269                                   ldlm_policy_data_t *policy)
270 {
271         const struct cl_lock_descr *d = &lock->cll_descr;
272
273         osc_index2policy(policy, d->cld_obj, d->cld_start, d->cld_end);
274         policy->l_extent.gid = d->cld_gid;
275 }
276
277 static int osc_enq2ldlm_flags(__u32 enqflags)
278 {
279         int result = 0;
280
281         LASSERT((enqflags & ~CEF_MASK) == 0);
282
283         if (enqflags & CEF_NONBLOCK)
284                 result |= LDLM_FL_BLOCK_NOWAIT;
285         if (enqflags & CEF_ASYNC)
286                 result |= LDLM_FL_HAS_INTENT;
287         if (enqflags & CEF_DISCARD_DATA)
288                 result |= LDLM_AST_DISCARD_DATA;
289         return result;
290 }
291
292 /**
293  * Global spin-lock protecting consistency of ldlm_lock::l_ast_data
294  * pointers. Initialized in osc_init().
295  */
296 cfs_spinlock_t osc_ast_guard;
297
298 static struct osc_lock *osc_ast_data_get(struct ldlm_lock *dlm_lock)
299 {
300         struct osc_lock *olck;
301
302         lock_res_and_lock(dlm_lock);
303         cfs_spin_lock(&osc_ast_guard);
304         olck = dlm_lock->l_ast_data;
305         if (olck != NULL) {
306                 struct cl_lock *lock = olck->ols_cl.cls_lock;
307                 /*
308                  * If osc_lock holds a reference on ldlm lock, return it even
309                  * when cl_lock is in CLS_FREEING state. This way
310                  *
311                  *         osc_ast_data_get(dlmlock) == NULL
312                  *
313                  * guarantees that all osc references on dlmlock were
314                  * released. osc_dlm_blocking_ast0() relies on that.
315                  */
316                 if (lock->cll_state < CLS_FREEING || olck->ols_has_ref) {
317                         cl_lock_get_trust(lock);
318                         lu_ref_add_atomic(&lock->cll_reference,
319                                           "ast", cfs_current());
320                 } else
321                         olck = NULL;
322         }
323         cfs_spin_unlock(&osc_ast_guard);
324         unlock_res_and_lock(dlm_lock);
325         return olck;
326 }
327
328 static void osc_ast_data_put(const struct lu_env *env, struct osc_lock *olck)
329 {
330         struct cl_lock *lock;
331
332         lock = olck->ols_cl.cls_lock;
333         lu_ref_del(&lock->cll_reference, "ast", cfs_current());
334         cl_lock_put(env, lock);
335 }
336
337 /**
338  * Updates object attributes from a lock value block (lvb) received together
339  * with the DLM lock reply from the server. Copy of osc_update_enqueue()
340  * logic.
341  *
342  * This can be optimized to not update attributes when lock is a result of a
343  * local match.
344  *
345  * Called under lock and resource spin-locks.
346  */
347 static void osc_lock_lvb_update(const struct lu_env *env, struct osc_lock *olck,
348                                 int rc)
349 {
350         struct ost_lvb    *lvb;
351         struct cl_object  *obj;
352         struct lov_oinfo  *oinfo;
353         struct cl_attr    *attr;
354         unsigned           valid;
355
356         ENTRY;
357
358         if (!(olck->ols_flags & LDLM_FL_LVB_READY))
359                 RETURN_EXIT;
360
361         lvb   = &olck->ols_lvb;
362         obj   = olck->ols_cl.cls_obj;
363         oinfo = cl2osc(obj)->oo_oinfo;
364         attr  = &osc_env_info(env)->oti_attr;
365         valid = CAT_BLOCKS | CAT_ATIME | CAT_CTIME | CAT_MTIME | CAT_SIZE;
366         cl_lvb2attr(attr, lvb);
367
368         cl_object_attr_lock(obj);
369         if (rc == 0) {
370                 struct ldlm_lock  *dlmlock;
371                 __u64 size;
372
373                 dlmlock = olck->ols_lock;
374                 LASSERT(dlmlock != NULL);
375
376                 /* re-grab LVB from a dlm lock under DLM spin-locks. */
377                 *lvb = *(struct ost_lvb *)dlmlock->l_lvb_data;
378                 size = lvb->lvb_size;
379                 /* Extend KMS up to the end of this lock and no further
380                  * A lock on [x,y] means a KMS of up to y + 1 bytes! */
381                 if (size > dlmlock->l_policy_data.l_extent.end)
382                         size = dlmlock->l_policy_data.l_extent.end + 1;
383                 if (size >= oinfo->loi_kms) {
384                         LDLM_DEBUG(dlmlock, "lock acquired, setting rss="LPU64
385                                    ", kms="LPU64, lvb->lvb_size, size);
386                         valid |= CAT_KMS;
387                         attr->cat_kms = size;
388                 } else {
389                         LDLM_DEBUG(dlmlock, "lock acquired, setting rss="
390                                    LPU64"; leaving kms="LPU64", end="LPU64,
391                                    lvb->lvb_size, oinfo->loi_kms,
392                                    dlmlock->l_policy_data.l_extent.end);
393                 }
394                 ldlm_lock_allow_match_locked(dlmlock);
395         } else if (rc == -ENAVAIL && olck->ols_glimpse) {
396                 CDEBUG(D_INODE, "glimpsed, setting rss="LPU64"; leaving"
397                        " kms="LPU64"\n", lvb->lvb_size, oinfo->loi_kms);
398         } else
399                 valid = 0;
400
401         if (valid != 0)
402                 cl_object_attr_set(env, obj, attr, valid);
403
404         cl_object_attr_unlock(obj);
405
406         EXIT;
407 }
408
409 /**
410  * Called when a lock is granted, from an upcall (when server returned a
411  * granted lock), or from completion AST, when server returned a blocked lock.
412  *
413  * Called under lock and resource spin-locks, that are released temporarily
414  * here.
415  */
416 static void osc_lock_granted(const struct lu_env *env, struct osc_lock *olck,
417                              struct ldlm_lock *dlmlock, int rc)
418 {
419         struct ldlm_extent   *ext;
420         struct cl_lock       *lock;
421         struct cl_lock_descr *descr;
422
423         LASSERT(dlmlock->l_granted_mode == dlmlock->l_req_mode);
424
425         ENTRY;
426         if (olck->ols_state < OLS_GRANTED) {
427                 lock  = olck->ols_cl.cls_lock;
428                 ext   = &dlmlock->l_policy_data.l_extent;
429                 descr = &osc_env_info(env)->oti_descr;
430                 descr->cld_obj = lock->cll_descr.cld_obj;
431
432                 /* XXX check that ->l_granted_mode is valid. */
433                 descr->cld_mode  = osc_ldlm2cl_lock(dlmlock->l_granted_mode);
434                 descr->cld_start = cl_index(descr->cld_obj, ext->start);
435                 descr->cld_end   = cl_index(descr->cld_obj, ext->end);
436                 descr->cld_gid   = ext->gid;
437                 /*
438                  * tell upper layers the extent of the lock that was actually
439                  * granted
440                  */
441                 olck->ols_state = OLS_GRANTED;
442                 osc_lock_lvb_update(env, olck, rc);
443
444                 /* release DLM spin-locks to allow cl_lock_{modify,signal}()
445                  * to take a semaphore on a parent lock. This is safe, because
446                  * spin-locks are needed to protect consistency of
447                  * dlmlock->l_*_mode and LVB, and we have finished processing
448                  * them. */
449                 unlock_res_and_lock(dlmlock);
450                 cl_lock_modify(env, lock, descr);
451                 cl_lock_signal(env, lock);
452                 LINVRNT(osc_lock_invariant(olck));
453                 lock_res_and_lock(dlmlock);
454         }
455         EXIT;
456 }
457
458 static void osc_lock_upcall0(const struct lu_env *env, struct osc_lock *olck)
459
460 {
461         struct ldlm_lock *dlmlock;
462
463         ENTRY;
464
465         dlmlock = ldlm_handle2lock_long(&olck->ols_handle, 0);
466         LASSERT(dlmlock != NULL);
467
468         lock_res_and_lock(dlmlock);
469         cfs_spin_lock(&osc_ast_guard);
470         LASSERT(dlmlock->l_ast_data == olck);
471         LASSERT(olck->ols_lock == NULL);
472         olck->ols_lock = dlmlock;
473         cfs_spin_unlock(&osc_ast_guard);
474
475         /*
476          * Lock might be not yet granted. In this case, completion ast
477          * (osc_ldlm_completion_ast()) comes later and finishes lock
478          * granting.
479          */
480         if (dlmlock->l_granted_mode == dlmlock->l_req_mode)
481                 osc_lock_granted(env, olck, dlmlock, 0);
482         unlock_res_and_lock(dlmlock);
483
484         /*
485          * osc_enqueue_interpret() decrefs asynchronous locks, counter
486          * this.
487          */
488         ldlm_lock_addref(&olck->ols_handle, olck->ols_einfo.ei_mode);
489         olck->ols_hold = 1;
490
491         /* lock reference taken by ldlm_handle2lock_long() is owned by
492          * osc_lock and released in osc_lock_detach() */
493         lu_ref_add(&dlmlock->l_reference, "osc_lock", olck);
494         olck->ols_has_ref = 1;
495 }
496
497 /**
498  * Lock upcall function that is executed either when a reply to ENQUEUE rpc is
499  * received from a server, or after osc_enqueue_base() matched a local DLM
500  * lock.
501  */
502 static int osc_lock_upcall(void *cookie, int errcode)
503 {
504         struct osc_lock         *olck  = cookie;
505         struct cl_lock_slice    *slice = &olck->ols_cl;
506         struct cl_lock          *lock  = slice->cls_lock;
507         struct lu_env           *env;
508         struct cl_env_nest       nest;
509
510         ENTRY;
511         env = cl_env_nested_get(&nest);
512         if (!IS_ERR(env)) {
513                 int rc;
514
515                 cl_lock_mutex_get(env, lock);
516
517                 LASSERT(lock->cll_state >= CLS_QUEUING);
518                 if (olck->ols_state == OLS_ENQUEUED) {
519                         olck->ols_state = OLS_UPCALL_RECEIVED;
520                         rc = ldlm_error2errno(errcode);
521                 } else if (olck->ols_state == OLS_CANCELLED) {
522                         rc = -EIO;
523                 } else {
524                         CERROR("Impossible state: %d\n", olck->ols_state);
525                         LBUG();
526                 }
527                 if (rc) {
528                         struct ldlm_lock *dlmlock;
529
530                         dlmlock = ldlm_handle2lock(&olck->ols_handle);
531                         if (dlmlock != NULL) {
532                                 lock_res_and_lock(dlmlock);
533                                 cfs_spin_lock(&osc_ast_guard);
534                                 LASSERT(olck->ols_lock == NULL);
535                                 dlmlock->l_ast_data = NULL;
536                                 olck->ols_handle.cookie = 0ULL;
537                                 cfs_spin_unlock(&osc_ast_guard);
538                                 ldlm_lock_fail_match_locked(dlmlock, rc);
539                                 unlock_res_and_lock(dlmlock);
540                                 LDLM_LOCK_PUT(dlmlock);
541                         }
542                 } else {
543                         if (olck->ols_glimpse)
544                                 olck->ols_glimpse = 0;
545                         osc_lock_upcall0(env, olck);
546                 }
547
548                 /* Error handling, some errors are tolerable. */
549                 if (olck->ols_locklessable && rc == -EUSERS) {
550                         /* This is a tolerable error, turn this lock into
551                          * lockless lock.
552                          */
553                         osc_object_set_contended(cl2osc(slice->cls_obj));
554                         LASSERT(slice->cls_ops == &osc_lock_ops);
555
556                         /* Change this lock to ldlmlock-less lock. */
557                         osc_lock_to_lockless(env, olck, 1);
558                         olck->ols_state = OLS_GRANTED;
559                         rc = 0;
560                 } else if (olck->ols_glimpse && rc == -ENAVAIL) {
561                         osc_lock_lvb_update(env, olck, rc);
562                         cl_lock_delete(env, lock);
563                         /* Hide the error. */
564                         rc = 0;
565                 }
566
567                 if (rc == 0) {
568                         cl_lock_signal(env, lock);
569                         /* del user for lock upcall cookie */
570                         cl_unuse_try(env, lock);
571                 } else {
572                         /* del user for lock upcall cookie */
573                         cl_lock_user_del(env, lock);
574                         cl_lock_error(env, lock, rc);
575                 }
576
577                 cl_lock_mutex_put(env, lock);
578
579                 /* release cookie reference, acquired by osc_lock_enqueue() */
580                 lu_ref_del(&lock->cll_reference, "upcall", lock);
581                 cl_lock_put(env, lock);
582
583                 cl_env_nested_put(&nest, env);
584         } else
585                 /* should never happen, similar to osc_ldlm_blocking_ast(). */
586                 LBUG();
587         RETURN(errcode);
588 }
589
590 /**
591  * Core of osc_dlm_blocking_ast() logic.
592  */
593 static void osc_lock_blocking(const struct lu_env *env,
594                               struct ldlm_lock *dlmlock,
595                               struct osc_lock *olck, int blocking)
596 {
597         struct cl_lock *lock = olck->ols_cl.cls_lock;
598
599         LASSERT(olck->ols_lock == dlmlock);
600         CLASSERT(OLS_BLOCKED < OLS_CANCELLED);
601         LASSERT(!osc_lock_is_lockless(olck));
602
603         /*
604          * Lock might be still addref-ed here, if e.g., blocking ast
605          * is sent for a failed lock.
606          */
607         osc_lock_unhold(olck);
608
609         if (blocking && olck->ols_state < OLS_BLOCKED)
610                 /*
611                  * Move osc_lock into OLS_BLOCKED before canceling the lock,
612                  * because it recursively re-enters osc_lock_blocking(), with
613                  * the state set to OLS_CANCELLED.
614                  */
615                 olck->ols_state = OLS_BLOCKED;
616         /*
617          * cancel and destroy lock at least once no matter how blocking ast is
618          * entered (see comment above osc_ldlm_blocking_ast() for use
619          * cases). cl_lock_cancel() and cl_lock_delete() are idempotent.
620          */
621         cl_lock_cancel(env, lock);
622         cl_lock_delete(env, lock);
623 }
624
625 /**
626  * Helper for osc_dlm_blocking_ast() handling discrepancies between cl_lock
627  * and ldlm_lock caches.
628  */
629 static int osc_dlm_blocking_ast0(const struct lu_env *env,
630                                  struct ldlm_lock *dlmlock,
631                                  void *data, int flag)
632 {
633         struct osc_lock *olck;
634         struct cl_lock  *lock;
635         int result;
636         int cancel;
637
638         LASSERT(flag == LDLM_CB_BLOCKING || flag == LDLM_CB_CANCELING);
639
640         cancel = 0;
641         olck = osc_ast_data_get(dlmlock);
642         if (olck != NULL) {
643                 lock = olck->ols_cl.cls_lock;
644                 cl_lock_mutex_get(env, lock);
645                 LINVRNT(osc_lock_invariant(olck));
646                 if (olck->ols_ast_wait) {
647                         /* wake up osc_lock_use() */
648                         cl_lock_signal(env, lock);
649                         olck->ols_ast_wait = 0;
650                 }
651                 /*
652                  * Lock might have been canceled while this thread was
653                  * sleeping for lock mutex, but olck is pinned in memory.
654                  */
655                 if (olck == dlmlock->l_ast_data) {
656                         /*
657                          * NOTE: DLM sends blocking AST's for failed locks
658                          *       (that are still in pre-OLS_GRANTED state)
659                          *       too, and they have to be canceled otherwise
660                          *       DLM lock is never destroyed and stuck in
661                          *       the memory.
662                          *
663                          *       Alternatively, ldlm_cli_cancel() can be
664                          *       called here directly for osc_locks with
665                          *       ols_state < OLS_GRANTED to maintain an
666                          *       invariant that ->clo_cancel() is only called
667                          *       for locks that were granted.
668                          */
669                         LASSERT(data == olck);
670                         osc_lock_blocking(env, dlmlock,
671                                           olck, flag == LDLM_CB_BLOCKING);
672                 } else
673                         cancel = 1;
674                 cl_lock_mutex_put(env, lock);
675                 osc_ast_data_put(env, olck);
676         } else
677                 /*
678                  * DLM lock exists, but there is no cl_lock attached to it.
679                  * This is a `normal' race. cl_object and its cl_lock's can be
680                  * removed by memory pressure, together with all pages.
681                  */
682                 cancel = (flag == LDLM_CB_BLOCKING);
683
684         if (cancel) {
685                 struct lustre_handle *lockh;
686
687                 lockh = &osc_env_info(env)->oti_handle;
688                 ldlm_lock2handle(dlmlock, lockh);
689                 result = ldlm_cli_cancel(lockh);
690         } else
691                 result = 0;
692         return result;
693 }
694
695 /**
696  * Blocking ast invoked by ldlm when dlm lock is either blocking progress of
697  * some other lock, or is canceled. This function is installed as a
698  * ldlm_lock::l_blocking_ast() for client extent locks.
699  *
700  * Control flow is tricky, because ldlm uses the same call-back
701  * (ldlm_lock::l_blocking_ast()) for both blocking and cancellation ast's.
702  *
703  * \param dlmlock lock for which ast occurred.
704  *
705  * \param new description of a conflicting lock in case of blocking ast.
706  *
707  * \param data value of dlmlock->l_ast_data
708  *
709  * \param flag LDLM_CB_BLOCKING or LDLM_CB_CANCELING. Used to distinguish
710  *             cancellation and blocking ast's.
711  *
712  * Possible use cases:
713  *
714  *     - ldlm calls dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING) to cancel
715  *       lock due to lock lru pressure, or explicit user request to purge
716  *       locks.
717  *
718  *     - ldlm calls dlmlock->l_blocking_ast(..., LDLM_CB_BLOCKING) to notify
719  *       us that dlmlock conflicts with another lock that some client is
720  *       enqueing. Lock is canceled.
721  *
722  *           - cl_lock_cancel() is called. osc_lock_cancel() calls
723  *             ldlm_cli_cancel() that calls
724  *
725  *                  dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING)
726  *
727  *             recursively entering osc_ldlm_blocking_ast().
728  *
729  *     - client cancels lock voluntary (e.g., as a part of early cancellation):
730  *
731  *           cl_lock_cancel()->
732  *             osc_lock_cancel()->
733  *               ldlm_cli_cancel()->
734  *                 dlmlock->l_blocking_ast(..., LDLM_CB_CANCELING)
735  *
736  */
737 static int osc_ldlm_blocking_ast(struct ldlm_lock *dlmlock,
738                                  struct ldlm_lock_desc *new, void *data,
739                                  int flag)
740 {
741         struct lu_env     *env;
742         struct cl_env_nest nest;
743         int                result;
744
745         /*
746          * This can be called in the context of outer IO, e.g.,
747          *
748          *     cl_enqueue()->...
749          *       ->osc_enqueue_base()->...
750          *         ->ldlm_prep_elc_req()->...
751          *           ->ldlm_cancel_callback()->...
752          *             ->osc_ldlm_blocking_ast()
753          *
754          * new environment has to be created to not corrupt outer context.
755          */
756         env = cl_env_nested_get(&nest);
757         if (!IS_ERR(env)) {
758                 result = osc_dlm_blocking_ast0(env, dlmlock, data, flag);
759                 cl_env_nested_put(&nest, env);
760         } else {
761                 result = PTR_ERR(env);
762                 /*
763                  * XXX This should never happen, as cl_lock is
764                  * stuck. Pre-allocated environment a la vvp_inode_fini_env
765                  * should be used.
766                  */
767                 LBUG();
768         }
769         if (result != 0) {
770                 if (result == -ENODATA)
771                         result = 0;
772                 else
773                         CERROR("BAST failed: %d\n", result);
774         }
775         return result;
776 }
777
778 static int osc_ldlm_completion_ast(struct ldlm_lock *dlmlock,
779                                    int flags, void *data)
780 {
781         struct cl_env_nest nest;
782         struct lu_env     *env;
783         struct osc_lock   *olck;
784         struct cl_lock    *lock;
785         int result;
786         int dlmrc;
787
788         /* first, do dlm part of the work */
789         dlmrc = ldlm_completion_ast_async(dlmlock, flags, data);
790         /* then, notify cl_lock */
791         env = cl_env_nested_get(&nest);
792         if (!IS_ERR(env)) {
793                 olck = osc_ast_data_get(dlmlock);
794                 if (olck != NULL) {
795                         lock = olck->ols_cl.cls_lock;
796                         cl_lock_mutex_get(env, lock);
797                         /*
798                          * ldlm_handle_cp_callback() copied LVB from request
799                          * to lock->l_lvb_data, store it in osc_lock.
800                          */
801                         LASSERT(dlmlock->l_lvb_data != NULL);
802                         lock_res_and_lock(dlmlock);
803                         olck->ols_lvb = *(struct ost_lvb *)dlmlock->l_lvb_data;
804                         if (olck->ols_lock == NULL) {
805                                 /*
806                                  * upcall (osc_lock_upcall()) hasn't yet been
807                                  * called. Do nothing now, upcall will bind
808                                  * olck to dlmlock and signal the waiters.
809                                  *
810                                  * This maintains an invariant that osc_lock
811                                  * and ldlm_lock are always bound when
812                                  * osc_lock is in OLS_GRANTED state.
813                                  */
814                         } else if (dlmlock->l_granted_mode ==
815                                    dlmlock->l_req_mode) {
816                                 osc_lock_granted(env, olck, dlmlock, dlmrc);
817                         }
818                         unlock_res_and_lock(dlmlock);
819
820                         if (dlmrc != 0) {
821                                 CL_LOCK_DEBUG(D_ERROR, env, lock,
822                                               "dlmlock returned %d\n", dlmrc);
823                                 cl_lock_error(env, lock, dlmrc);
824                         }
825                         cl_lock_mutex_put(env, lock);
826                         osc_ast_data_put(env, olck);
827                         result = 0;
828                 } else
829                         result = -ELDLM_NO_LOCK_DATA;
830                 cl_env_nested_put(&nest, env);
831         } else
832                 result = PTR_ERR(env);
833         return dlmrc ?: result;
834 }
835
836 static int osc_ldlm_glimpse_ast(struct ldlm_lock *dlmlock, void *data)
837 {
838         struct ptlrpc_request  *req  = data;
839         struct osc_lock        *olck;
840         struct cl_lock         *lock;
841         struct cl_object       *obj;
842         struct cl_env_nest      nest;
843         struct lu_env          *env;
844         struct ost_lvb         *lvb;
845         struct req_capsule     *cap;
846         int                     result;
847
848         LASSERT(lustre_msg_get_opc(req->rq_reqmsg) == LDLM_GL_CALLBACK);
849
850         env = cl_env_nested_get(&nest);
851         if (!IS_ERR(env)) {
852                 /*
853                  * osc_ast_data_get() has to go after environment is
854                  * allocated, because osc_ast_data() acquires a
855                  * reference to a lock, and it can only be released in
856                  * environment.
857                  */
858                 olck = osc_ast_data_get(dlmlock);
859                 if (olck != NULL) {
860                         lock = olck->ols_cl.cls_lock;
861                         cl_lock_mutex_get(env, lock);
862                         cap = &req->rq_pill;
863                         req_capsule_extend(cap, &RQF_LDLM_GL_CALLBACK);
864                         req_capsule_set_size(cap, &RMF_DLM_LVB, RCL_SERVER,
865                                              sizeof *lvb);
866                         result = req_capsule_server_pack(cap);
867                         if (result == 0) {
868                                 lvb = req_capsule_server_get(cap, &RMF_DLM_LVB);
869                                 obj = lock->cll_descr.cld_obj;
870                                 result = cl_object_glimpse(env, obj, lvb);
871                         }
872                         cl_lock_mutex_put(env, lock);
873                         osc_ast_data_put(env, olck);
874                 } else {
875                         /*
876                          * These errors are normal races, so we don't want to
877                          * fill the console with messages by calling
878                          * ptlrpc_error()
879                          */
880                         lustre_pack_reply(req, 1, NULL, NULL);
881                         result = -ELDLM_NO_LOCK_DATA;
882                 }
883                 cl_env_nested_put(&nest, env);
884         } else
885                 result = PTR_ERR(env);
886         req->rq_status = result;
887         return result;
888 }
889
890 static unsigned long osc_lock_weigh(const struct lu_env *env,
891                                     const struct cl_lock_slice *slice)
892 {
893         /*
894          * don't need to grab coh_page_guard since we don't care the exact #
895          * of pages..
896          */
897         return cl_object_header(slice->cls_obj)->coh_pages;
898 }
899
900 /**
901  * Get the weight of dlm lock for early cancellation.
902  *
903  * XXX: it should return the pages covered by this \a dlmlock.
904  */
905 static unsigned long osc_ldlm_weigh_ast(struct ldlm_lock *dlmlock)
906 {
907         struct cl_env_nest       nest;
908         struct lu_env           *env;
909         struct osc_lock         *lock;
910         struct cl_lock          *cll;
911         unsigned long            weight;
912         ENTRY;
913
914         cfs_might_sleep();
915         /*
916          * osc_ldlm_weigh_ast has a complex context since it might be called
917          * because of lock canceling, or from user's input. We have to make
918          * a new environment for it. Probably it is implementation safe to use
919          * the upper context because cl_lock_put don't modify environment
920          * variables. But in case of ..
921          */
922         env = cl_env_nested_get(&nest);
923         if (IS_ERR(env))
924                 /* Mostly because lack of memory, tend to eliminate this lock*/
925                 RETURN(0);
926
927         LASSERT(dlmlock->l_resource->lr_type == LDLM_EXTENT);
928         lock = osc_ast_data_get(dlmlock);
929         if (lock == NULL) {
930                 /* cl_lock was destroyed because of memory pressure.
931                  * It is much reasonable to assign this type of lock
932                  * a lower cost.
933                  */
934                 GOTO(out, weight = 0);
935         }
936
937         cll = lock->ols_cl.cls_lock;
938         cl_lock_mutex_get(env, cll);
939         weight = cl_lock_weigh(env, cll);
940         cl_lock_mutex_put(env, cll);
941         osc_ast_data_put(env, lock);
942         EXIT;
943
944 out:
945         cl_env_nested_put(&nest, env);
946         return weight;
947 }
948
949 static void osc_lock_build_einfo(const struct lu_env *env,
950                                  const struct cl_lock *clock,
951                                  struct osc_lock *lock,
952                                  struct ldlm_enqueue_info *einfo)
953 {
954         enum cl_lock_mode mode;
955
956         mode = clock->cll_descr.cld_mode;
957         if (mode == CLM_PHANTOM)
958                 /*
959                  * For now, enqueue all glimpse locks in read mode. In the
960                  * future, client might choose to enqueue LCK_PW lock for
961                  * glimpse on a file opened for write.
962                  */
963                 mode = CLM_READ;
964
965         einfo->ei_type   = LDLM_EXTENT;
966         einfo->ei_mode   = osc_cl_lock2ldlm(mode);
967         einfo->ei_cb_bl  = osc_ldlm_blocking_ast;
968         einfo->ei_cb_cp  = osc_ldlm_completion_ast;
969         einfo->ei_cb_gl  = osc_ldlm_glimpse_ast;
970         einfo->ei_cb_wg  = osc_ldlm_weigh_ast;
971         einfo->ei_cbdata = lock; /* value to be put into ->l_ast_data */
972 }
973
974 /**
975  * Determine if the lock should be converted into a lockless lock.
976  *
977  * Steps to check:
978  * - if the lock has an explicite requirment for a non-lockless lock;
979  * - if the io lock request type ci_lockreq;
980  * - send the enqueue rpc to ost to make the further decision;
981  * - special treat to truncate lockless lock
982  *
983  *  Additional policy can be implemented here, e.g., never do lockless-io
984  *  for large extents.
985  */
986 static void osc_lock_to_lockless(const struct lu_env *env,
987                                  struct osc_lock *ols, int force)
988 {
989         struct cl_lock_slice *slice = &ols->ols_cl;
990         struct cl_lock *lock        = slice->cls_lock;
991
992         LASSERT(ols->ols_state == OLS_NEW ||
993                 ols->ols_state == OLS_UPCALL_RECEIVED);
994
995         if (force) {
996                 ols->ols_locklessable = 1;
997                 LASSERT(cl_lock_is_mutexed(lock));
998                 slice->cls_ops = &osc_lock_lockless_ops;
999         } else {
1000                 struct osc_io *oio     = osc_env_io(env);
1001                 struct cl_io  *io      = oio->oi_cl.cis_io;
1002                 struct cl_object *obj  = slice->cls_obj;
1003                 struct osc_object *oob = cl2osc(obj);
1004                 const struct osc_device *osd = lu2osc_dev(obj->co_lu.lo_dev);
1005                 struct obd_connect_data *ocd;
1006
1007                 LASSERT(io->ci_lockreq == CILR_MANDATORY ||
1008                         io->ci_lockreq == CILR_MAYBE ||
1009                         io->ci_lockreq == CILR_NEVER);
1010
1011                 ocd = &class_exp2cliimp(osc_export(oob))->imp_connect_data;
1012                 ols->ols_locklessable = (io->ci_type != CIT_SETATTR) &&
1013                                 (io->ci_lockreq == CILR_MAYBE) &&
1014                                 (ocd->ocd_connect_flags & OBD_CONNECT_SRVLOCK);
1015                 if (io->ci_lockreq == CILR_NEVER ||
1016                         /* lockless IO */
1017                     (ols->ols_locklessable && osc_object_is_contended(oob)) ||
1018                         /* lockless truncate */
1019                     (cl_io_is_trunc(io) &&
1020                      (ocd->ocd_connect_flags & OBD_CONNECT_TRUNCLOCK) &&
1021                       osd->od_lockless_truncate)) {
1022                         ols->ols_locklessable = 1;
1023                         slice->cls_ops = &osc_lock_lockless_ops;
1024                 }
1025         }
1026         LASSERT(ergo(ols->ols_glimpse, !osc_lock_is_lockless(ols)));
1027 }
1028
1029 static int osc_lock_compatible(const struct osc_lock *qing,
1030                                const struct osc_lock *qed)
1031 {
1032         enum cl_lock_mode qing_mode;
1033         enum cl_lock_mode qed_mode;
1034
1035         qing_mode = qing->ols_cl.cls_lock->cll_descr.cld_mode;
1036         if (qed->ols_glimpse &&
1037             (qed->ols_state >= OLS_UPCALL_RECEIVED || qing_mode == CLM_READ))
1038                 return 1;
1039
1040         qed_mode = qed->ols_cl.cls_lock->cll_descr.cld_mode;
1041         return ((qing_mode == CLM_READ) && (qed_mode == CLM_READ));
1042 }
1043
1044 /**
1045  * Cancel all conflicting locks and wait for them to be destroyed.
1046  *
1047  * This function is used for two purposes:
1048  *
1049  *     - early cancel all conflicting locks before starting IO, and
1050  *
1051  *     - guarantee that pages added to the page cache by lockless IO are never
1052  *       covered by locks other than lockless IO lock, and, hence, are not
1053  *       visible to other threads.
1054  */
1055 static int osc_lock_enqueue_wait(const struct lu_env *env,
1056                                  const struct osc_lock *olck)
1057 {
1058         struct cl_lock          *lock    = olck->ols_cl.cls_lock;
1059         struct cl_lock_descr    *descr   = &lock->cll_descr;
1060         struct cl_object_header *hdr     = cl_object_header(descr->cld_obj);
1061         struct cl_lock          *scan;
1062         struct cl_lock          *conflict= NULL;
1063         int lockless                     = osc_lock_is_lockless(olck);
1064         int rc                           = 0;
1065         ENTRY;
1066
1067         LASSERT(cl_lock_is_mutexed(lock));
1068
1069         /* make it enqueue anyway for glimpse lock, because we actually
1070          * don't need to cancel any conflicting locks. */
1071         if (olck->ols_glimpse)
1072                 return 0;
1073
1074         cfs_spin_lock(&hdr->coh_lock_guard);
1075         cfs_list_for_each_entry(scan, &hdr->coh_locks, cll_linkage) {
1076                 struct cl_lock_descr *cld = &scan->cll_descr;
1077                 const struct osc_lock *scan_ols;
1078
1079                 if (scan == lock)
1080                         break;
1081
1082                 if (scan->cll_state < CLS_QUEUING ||
1083                     scan->cll_state == CLS_FREEING ||
1084                     cld->cld_start > descr->cld_end ||
1085                     cld->cld_end < descr->cld_start)
1086                         continue;
1087
1088                 /* overlapped and living locks. */
1089
1090                 /* We're not supposed to give up group lock. */
1091                 if (scan->cll_descr.cld_mode == CLM_GROUP) {
1092                         LASSERT(descr->cld_mode != CLM_GROUP ||
1093                                 descr->cld_gid != scan->cll_descr.cld_gid);
1094                         continue;
1095                 }
1096
1097                 scan_ols = osc_lock_at(scan);
1098
1099                 /* We need to cancel the compatible locks if we're enqueuing
1100                  * a lockless lock, for example:
1101                  * imagine that client has PR lock on [0, 1000], and thread T0
1102                  * is doing lockless IO in [500, 1500] region. Concurrent
1103                  * thread T1 can see lockless data in [500, 1000], which is
1104                  * wrong, because these data are possibly stale. */
1105                 if (!lockless && osc_lock_compatible(olck, scan_ols))
1106                         continue;
1107
1108                 /* Now @scan is conflicting with @lock, this means current
1109                  * thread have to sleep for @scan being destroyed. */
1110                 if (scan_ols->ols_owner == osc_env_io(env)) {
1111                         CERROR("DEADLOCK POSSIBLE!\n");
1112                         CL_LOCK_DEBUG(D_ERROR, env, scan, "queued.\n");
1113                         CL_LOCK_DEBUG(D_ERROR, env, lock, "queuing.\n");
1114                         libcfs_debug_dumpstack(NULL);
1115                 }
1116                 cl_lock_get_trust(scan);
1117                 conflict = scan;
1118                 break;
1119         }
1120         cfs_spin_unlock(&hdr->coh_lock_guard);
1121
1122         if (conflict) {
1123                 if (lock->cll_descr.cld_mode == CLM_GROUP) {
1124                         /* we want a group lock but a previous lock request
1125                          * conflicts, we do not wait but return 0 so the
1126                          * request is send to the server
1127                          */
1128                         CDEBUG(D_DLMTRACE, "group lock %p is conflicted "
1129                                            "with %p, no wait, send to server\n",
1130                                lock, conflict);
1131                         cl_lock_put(env, conflict);
1132                         rc = 0;
1133                 } else {
1134                         CDEBUG(D_DLMTRACE, "lock %p is conflicted with %p, "
1135                                            "will wait\n",
1136                                lock, conflict);
1137                         LASSERT(lock->cll_conflict == NULL);
1138                         lu_ref_add(&conflict->cll_reference, "cancel-wait",
1139                                    lock);
1140                         lock->cll_conflict = conflict;
1141                         rc = CLO_WAIT;
1142                 }
1143         }
1144         RETURN(rc);
1145 }
1146
1147 /**
1148  * Implementation of cl_lock_operations::clo_enqueue() method for osc
1149  * layer. This initiates ldlm enqueue:
1150  *
1151  *     - cancels conflicting locks early (osc_lock_enqueue_wait());
1152  *
1153  *     - calls osc_enqueue_base() to do actual enqueue.
1154  *
1155  * osc_enqueue_base() is supplied with an upcall function that is executed
1156  * when lock is received either after a local cached ldlm lock is matched, or
1157  * when a reply from the server is received.
1158  *
1159  * This function does not wait for the network communication to complete.
1160  */
1161 static int osc_lock_enqueue(const struct lu_env *env,
1162                             const struct cl_lock_slice *slice,
1163                             struct cl_io *unused, __u32 enqflags)
1164 {
1165         struct osc_lock          *ols     = cl2osc_lock(slice);
1166         struct cl_lock           *lock    = ols->ols_cl.cls_lock;
1167         int result;
1168         ENTRY;
1169
1170         LASSERT(cl_lock_is_mutexed(lock));
1171         LASSERTF(ols->ols_state == OLS_NEW,
1172                  "Impossible state: %d\n", ols->ols_state);
1173
1174         ols->ols_flags = osc_enq2ldlm_flags(enqflags);
1175         if (enqflags & CEF_AGL) {
1176                 ols->ols_flags |= LDLM_FL_BLOCK_NOWAIT;
1177                 ols->ols_agl = 1;
1178         }
1179         if (ols->ols_flags & LDLM_FL_HAS_INTENT)
1180                 ols->ols_glimpse = 1;
1181         if (!osc_lock_is_lockless(ols) && !(enqflags & CEF_MUST))
1182                 /* try to convert this lock to a lockless lock */
1183                 osc_lock_to_lockless(env, ols, (enqflags & CEF_NEVER));
1184
1185         result = osc_lock_enqueue_wait(env, ols);
1186         if (result == 0) {
1187                 if (!osc_lock_is_lockless(ols)) {
1188                         struct osc_object        *obj = cl2osc(slice->cls_obj);
1189                         struct osc_thread_info   *info = osc_env_info(env);
1190                         struct ldlm_res_id       *resname = &info->oti_resname;
1191                         ldlm_policy_data_t       *policy = &info->oti_policy;
1192                         struct ldlm_enqueue_info *einfo = &ols->ols_einfo;
1193
1194                         if (ols->ols_locklessable)
1195                                 ols->ols_flags |= LDLM_FL_DENY_ON_CONTENTION;
1196
1197                         /* a reference for lock, passed as an upcall cookie */
1198                         cl_lock_get(lock);
1199                         lu_ref_add(&lock->cll_reference, "upcall", lock);
1200                         /* a user for lock also */
1201                         cl_lock_user_add(env, lock);
1202                         ols->ols_state = OLS_ENQUEUED;
1203
1204                         /*
1205                          * XXX: this is possible blocking point as
1206                          * ldlm_lock_match(LDLM_FL_LVB_READY) waits for
1207                          * LDLM_CP_CALLBACK.
1208                          */
1209                         osc_lock_build_res(env, obj, resname);
1210                         osc_lock_build_policy(env, lock, policy);
1211                         result = osc_enqueue_base(osc_export(obj), resname,
1212                                           &ols->ols_flags, policy,
1213                                           &ols->ols_lvb,
1214                                           obj->oo_oinfo->loi_kms_valid,
1215                                           osc_lock_upcall,
1216                                           ols, einfo, &ols->ols_handle,
1217                                           PTLRPCD_SET, 1, ols->ols_agl);
1218                         if (result != 0) {
1219                                 cl_lock_user_del(env, lock);
1220                                 lu_ref_del(&lock->cll_reference,
1221                                            "upcall", lock);
1222                                 cl_lock_put(env, lock);
1223                                 if (unlikely(result == -ECANCELED)) {
1224                                         ols->ols_state = OLS_NEW;
1225                                         result = 0;
1226                                 }
1227                         }
1228                 } else {
1229                         ols->ols_state = OLS_GRANTED;
1230                         ols->ols_owner = osc_env_io(env);
1231                 }
1232         }
1233         LASSERT(ergo(ols->ols_glimpse, !osc_lock_is_lockless(ols)));
1234         RETURN(result);
1235 }
1236
1237 static int osc_lock_wait(const struct lu_env *env,
1238                          const struct cl_lock_slice *slice)
1239 {
1240         struct osc_lock *olck = cl2osc_lock(slice);
1241         struct cl_lock  *lock = olck->ols_cl.cls_lock;
1242
1243         LINVRNT(osc_lock_invariant(olck));
1244
1245         if (olck->ols_glimpse && olck->ols_state >= OLS_UPCALL_RECEIVED) {
1246                 if (olck->ols_flags & LDLM_FL_LVB_READY) {
1247                         return 0;
1248                 } else if (olck->ols_agl) {
1249                         olck->ols_state = OLS_NEW;
1250                 } else {
1251                         LASSERT(lock->cll_error);
1252                         return lock->cll_error;
1253                 }
1254         }
1255
1256         if (olck->ols_state == OLS_NEW) {
1257                 if (lock->cll_descr.cld_enq_flags & CEF_NO_REENQUEUE) {
1258                         return -ENAVAIL;
1259                 } else {
1260                         int rc;
1261
1262                         LASSERT(olck->ols_agl);
1263
1264                         rc = osc_lock_enqueue(env, slice, NULL, CEF_ASYNC |
1265                                                                 CEF_MUST);
1266                         if (rc != 0)
1267                                 return rc;
1268                         else
1269                                 return CLO_REENQUEUED;
1270                 }
1271         }
1272
1273         LASSERT(equi(olck->ols_state >= OLS_UPCALL_RECEIVED &&
1274                      lock->cll_error == 0, olck->ols_lock != NULL));
1275
1276         return lock->cll_error ?: olck->ols_state >= OLS_GRANTED ? 0 : CLO_WAIT;
1277 }
1278
1279 /**
1280  * An implementation of cl_lock_operations::clo_use() method that pins cached
1281  * lock.
1282  */
1283 static int osc_lock_use(const struct lu_env *env,
1284                         const struct cl_lock_slice *slice)
1285 {
1286         struct osc_lock *olck = cl2osc_lock(slice);
1287         int rc;
1288
1289         LASSERT(!olck->ols_hold);
1290
1291         /*
1292          * Atomically check for LDLM_FL_CBPENDING and addref a lock if this
1293          * flag is not set. This protects us from a concurrent blocking ast.
1294          */
1295         rc = ldlm_lock_addref_try(&olck->ols_handle, olck->ols_einfo.ei_mode);
1296         if (rc == 0) {
1297                 olck->ols_hold = 1;
1298                 olck->ols_state = OLS_GRANTED;
1299         } else {
1300                 struct cl_lock *lock;
1301
1302                 /*
1303                  * Lock is being cancelled somewhere within
1304                  * ldlm_handle_bl_callback(): LDLM_FL_CBPENDING is already
1305                  * set, but osc_ldlm_blocking_ast() hasn't yet acquired
1306                  * cl_lock mutex.
1307                  */
1308                 lock = slice->cls_lock;
1309                 LASSERT(lock->cll_state == CLS_INTRANSIT);
1310                 LASSERT(lock->cll_users > 0);
1311                 /* set a flag for osc_dlm_blocking_ast0() to signal the
1312                  * lock.*/
1313                 olck->ols_ast_wait = 1;
1314                 rc = CLO_WAIT;
1315         }
1316         return rc;
1317 }
1318
1319 static int osc_lock_flush(struct osc_lock *ols, int discard)
1320 {
1321         struct cl_lock       *lock  = ols->ols_cl.cls_lock;
1322         struct cl_env_nest    nest;
1323         struct lu_env        *env;
1324         int result = 0;
1325
1326         env = cl_env_nested_get(&nest);
1327         if (!IS_ERR(env)) {
1328                 result = cl_lock_page_out(env, lock, discard);
1329                 cl_env_nested_put(&nest, env);
1330         } else
1331                 result = PTR_ERR(env);
1332         if (result == 0) {
1333                 ols->ols_flush = 1;
1334                 LINVRNT(!osc_lock_has_pages(ols));
1335         }
1336         return result;
1337 }
1338
1339 /**
1340  * Implements cl_lock_operations::clo_cancel() method for osc layer. This is
1341  * called (as part of cl_lock_cancel()) when lock is canceled either voluntary
1342  * (LRU pressure, early cancellation, umount, etc.) or due to the conflict
1343  * with some other lock some where in the cluster. This function does the
1344  * following:
1345  *
1346  *     - invalidates all pages protected by this lock (after sending dirty
1347  *       ones to the server, as necessary);
1348  *
1349  *     - decref's underlying ldlm lock;
1350  *
1351  *     - cancels ldlm lock (ldlm_cli_cancel()).
1352  */
1353 static void osc_lock_cancel(const struct lu_env *env,
1354                             const struct cl_lock_slice *slice)
1355 {
1356         struct cl_lock   *lock    = slice->cls_lock;
1357         struct osc_lock  *olck    = cl2osc_lock(slice);
1358         struct ldlm_lock *dlmlock = olck->ols_lock;
1359         int               result  = 0;
1360         int               discard;
1361
1362         LASSERT(cl_lock_is_mutexed(lock));
1363         LINVRNT(osc_lock_invariant(olck));
1364
1365         if (dlmlock != NULL) {
1366                 int do_cancel;
1367
1368                 discard = !!(dlmlock->l_flags & LDLM_FL_DISCARD_DATA);
1369                 result = osc_lock_flush(olck, discard);
1370                 osc_lock_unhold(olck);
1371
1372                 lock_res_and_lock(dlmlock);
1373                 /* Now that we're the only user of dlm read/write reference,
1374                  * mostly the ->l_readers + ->l_writers should be zero.
1375                  * However, there is a corner case.
1376                  * See bug 18829 for details.*/
1377                 do_cancel = (dlmlock->l_readers == 0 &&
1378                              dlmlock->l_writers == 0);
1379                 dlmlock->l_flags |= LDLM_FL_CBPENDING;
1380                 unlock_res_and_lock(dlmlock);
1381                 if (do_cancel)
1382                         result = ldlm_cli_cancel(&olck->ols_handle);
1383                 if (result < 0)
1384                         CL_LOCK_DEBUG(D_ERROR, env, lock,
1385                                       "lock %p cancel failure with error(%d)\n",
1386                                       lock, result);
1387         }
1388         olck->ols_state = OLS_CANCELLED;
1389         olck->ols_flags &= ~LDLM_FL_LVB_READY;
1390         osc_lock_detach(env, olck);
1391 }
1392
1393 void cl_lock_page_list_fixup(const struct lu_env *env,
1394                              struct cl_io *io, struct cl_lock *lock,
1395                              struct cl_page_list *queue);
1396
1397 #ifdef INVARIANT_CHECK
1398 /**
1399  * Returns true iff there are pages under \a olck not protected by other
1400  * locks.
1401  */
1402 static int osc_lock_has_pages(struct osc_lock *olck)
1403 {
1404         struct cl_lock       *lock;
1405         struct cl_lock_descr *descr;
1406         struct cl_object     *obj;
1407         struct osc_object    *oob;
1408         struct cl_page_list  *plist;
1409         struct cl_page       *page;
1410         struct cl_env_nest    nest;
1411         struct cl_io         *io;
1412         struct lu_env        *env;
1413         int                   result;
1414
1415         env = cl_env_nested_get(&nest);
1416         if (!IS_ERR(env)) {
1417                 obj   = olck->ols_cl.cls_obj;
1418                 oob   = cl2osc(obj);
1419                 io    = &oob->oo_debug_io;
1420                 lock  = olck->ols_cl.cls_lock;
1421                 descr = &lock->cll_descr;
1422                 plist = &osc_env_info(env)->oti_plist;
1423                 cl_page_list_init(plist);
1424
1425                 cfs_mutex_lock(&oob->oo_debug_mutex);
1426
1427                 io->ci_obj = cl_object_top(obj);
1428                 cl_io_init(env, io, CIT_MISC, io->ci_obj);
1429                 cl_page_gang_lookup(env, obj, io,
1430                                     descr->cld_start, descr->cld_end, plist);
1431                 cl_lock_page_list_fixup(env, io, lock, plist);
1432                 if (plist->pl_nr > 0) {
1433                         CL_LOCK_DEBUG(D_ERROR, env, lock, "still has pages\n");
1434                         cl_page_list_for_each(page, plist)
1435                                 CL_PAGE_DEBUG(D_ERROR, env, page, "\n");
1436                 }
1437                 result = plist->pl_nr > 0;
1438                 cl_page_list_disown(env, io, plist);
1439                 cl_page_list_fini(env, plist);
1440                 cl_io_fini(env, io);
1441                 cfs_mutex_unlock(&oob->oo_debug_mutex);
1442                 cl_env_nested_put(&nest, env);
1443         } else
1444                 result = 0;
1445         return result;
1446 }
1447 #else
1448 static int osc_lock_has_pages(struct osc_lock *olck)
1449 {
1450         return 0;
1451 }
1452 #endif /* INVARIANT_CHECK */
1453
1454 static void osc_lock_delete(const struct lu_env *env,
1455                             const struct cl_lock_slice *slice)
1456 {
1457         struct osc_lock *olck;
1458
1459         olck = cl2osc_lock(slice);
1460         if (olck->ols_glimpse) {
1461                 LASSERT(!olck->ols_hold);
1462                 LASSERT(!olck->ols_lock);
1463                 return;
1464         }
1465
1466         LINVRNT(osc_lock_invariant(olck));
1467         LINVRNT(!osc_lock_has_pages(olck));
1468
1469         osc_lock_unhold(olck);
1470         osc_lock_detach(env, olck);
1471 }
1472
1473 /**
1474  * Implements cl_lock_operations::clo_state() method for osc layer.
1475  *
1476  * Maintains osc_lock::ols_owner field.
1477  *
1478  * This assumes that lock always enters CLS_HELD (from some other state) in
1479  * the same IO context as one that requested the lock. This should not be a
1480  * problem, because context is by definition shared by all activity pertaining
1481  * to the same high-level IO.
1482  */
1483 static void osc_lock_state(const struct lu_env *env,
1484                            const struct cl_lock_slice *slice,
1485                            enum cl_lock_state state)
1486 {
1487         struct osc_lock *lock = cl2osc_lock(slice);
1488
1489         /*
1490          * XXX multiple io contexts can use the lock at the same time.
1491          */
1492         LINVRNT(osc_lock_invariant(lock));
1493         if (state == CLS_HELD && slice->cls_lock->cll_state != CLS_HELD) {
1494                 struct osc_io *oio = osc_env_io(env);
1495
1496                 LASSERT(lock->ols_owner == NULL);
1497                 lock->ols_owner = oio;
1498         } else if (state != CLS_HELD)
1499                 lock->ols_owner = NULL;
1500 }
1501
1502 static int osc_lock_print(const struct lu_env *env, void *cookie,
1503                           lu_printer_t p, const struct cl_lock_slice *slice)
1504 {
1505         struct osc_lock *lock = cl2osc_lock(slice);
1506
1507         /*
1508          * XXX print ldlm lock and einfo properly.
1509          */
1510         (*p)(env, cookie, "%p %08x "LPX64" %d %p ",
1511              lock->ols_lock, lock->ols_flags, lock->ols_handle.cookie,
1512              lock->ols_state, lock->ols_owner);
1513         osc_lvb_print(env, cookie, p, &lock->ols_lvb);
1514         return 0;
1515 }
1516
1517 static int osc_lock_fits_into(const struct lu_env *env,
1518                               const struct cl_lock_slice *slice,
1519                               const struct cl_lock_descr *need,
1520                               const struct cl_io *io)
1521 {
1522         struct osc_lock *ols = cl2osc_lock(slice);
1523
1524         if (need->cld_enq_flags & CEF_NEVER)
1525                 return 0;
1526
1527         if (need->cld_mode == CLM_PHANTOM) {
1528                 if (ols->ols_agl)
1529                         return !(ols->ols_state > OLS_RELEASED);
1530
1531                 /*
1532                  * Note: the QUEUED lock can't be matched here, otherwise
1533                  * it might cause the deadlocks.
1534                  * In read_process,
1535                  * P1: enqueued read lock, create sublock1
1536                  * P2: enqueued write lock, create sublock2(conflicted
1537                  *     with sublock1).
1538                  * P1: Grant read lock.
1539                  * P1: enqueued glimpse lock(with holding sublock1_read),
1540                  *     matched with sublock2, waiting sublock2 to be granted.
1541                  *     But sublock2 can not be granted, because P1
1542                  *     will not release sublock1. Bang!
1543                  */
1544                 if (ols->ols_state < OLS_GRANTED ||
1545                     ols->ols_state > OLS_RELEASED)
1546                         return 0;
1547         } else if (need->cld_enq_flags & CEF_MUST) {
1548                 /*
1549                  * If the lock hasn't ever enqueued, it can't be matched
1550                  * because enqueue process brings in many information
1551                  * which can be used to determine things such as lockless,
1552                  * CEF_MUST, etc.
1553                  */
1554                 if (ols->ols_state < OLS_UPCALL_RECEIVED &&
1555                     ols->ols_locklessable)
1556                         return 0;
1557         }
1558         return 1;
1559 }
1560
1561 static const struct cl_lock_operations osc_lock_ops = {
1562         .clo_fini    = osc_lock_fini,
1563         .clo_enqueue = osc_lock_enqueue,
1564         .clo_wait    = osc_lock_wait,
1565         .clo_unuse   = osc_lock_unuse,
1566         .clo_use     = osc_lock_use,
1567         .clo_delete  = osc_lock_delete,
1568         .clo_state   = osc_lock_state,
1569         .clo_cancel  = osc_lock_cancel,
1570         .clo_weigh   = osc_lock_weigh,
1571         .clo_print   = osc_lock_print,
1572         .clo_fits_into = osc_lock_fits_into,
1573 };
1574
1575 static int osc_lock_lockless_unuse(const struct lu_env *env,
1576                                    const struct cl_lock_slice *slice)
1577 {
1578         struct osc_lock *ols = cl2osc_lock(slice);
1579         struct cl_lock *lock = slice->cls_lock;
1580
1581         LASSERT(ols->ols_state == OLS_GRANTED);
1582         LINVRNT(osc_lock_invariant(ols));
1583
1584         cl_lock_cancel(env, lock);
1585         cl_lock_delete(env, lock);
1586         return 0;
1587 }
1588
1589 static void osc_lock_lockless_cancel(const struct lu_env *env,
1590                                      const struct cl_lock_slice *slice)
1591 {
1592         struct osc_lock   *ols  = cl2osc_lock(slice);
1593         int result;
1594
1595         result = osc_lock_flush(ols, 0);
1596         if (result)
1597                 CERROR("Pages for lockless lock %p were not purged(%d)\n",
1598                        ols, result);
1599         ols->ols_state = OLS_CANCELLED;
1600 }
1601
1602 static int osc_lock_lockless_wait(const struct lu_env *env,
1603                                   const struct cl_lock_slice *slice)
1604 {
1605         struct osc_lock *olck = cl2osc_lock(slice);
1606         struct cl_lock  *lock = olck->ols_cl.cls_lock;
1607
1608         LINVRNT(osc_lock_invariant(olck));
1609         LASSERT(olck->ols_state >= OLS_UPCALL_RECEIVED);
1610
1611         return lock->cll_error;
1612 }
1613
1614 static void osc_lock_lockless_state(const struct lu_env *env,
1615                                     const struct cl_lock_slice *slice,
1616                                     enum cl_lock_state state)
1617 {
1618         struct osc_lock *lock = cl2osc_lock(slice);
1619
1620         LINVRNT(osc_lock_invariant(lock));
1621         if (state == CLS_HELD) {
1622                 struct osc_io *oio  = osc_env_io(env);
1623
1624                 LASSERT(ergo(lock->ols_owner, lock->ols_owner == oio));
1625                 lock->ols_owner = oio;
1626
1627                 /* set the io to be lockless if this lock is for io's
1628                  * host object */
1629                 if (cl_object_same(oio->oi_cl.cis_obj, slice->cls_obj))
1630                         oio->oi_lockless = 1;
1631         }
1632 }
1633
1634 static int osc_lock_lockless_fits_into(const struct lu_env *env,
1635                                        const struct cl_lock_slice *slice,
1636                                        const struct cl_lock_descr *need,
1637                                        const struct cl_io *io)
1638 {
1639         struct osc_lock *lock = cl2osc_lock(slice);
1640
1641         if (!(need->cld_enq_flags & CEF_NEVER))
1642                 return 0;
1643
1644         /* lockless lock should only be used by its owning io. b22147 */
1645         return (lock->ols_owner == osc_env_io(env));
1646 }
1647
1648 static const struct cl_lock_operations osc_lock_lockless_ops = {
1649         .clo_fini      = osc_lock_fini,
1650         .clo_enqueue   = osc_lock_enqueue,
1651         .clo_wait      = osc_lock_lockless_wait,
1652         .clo_unuse     = osc_lock_lockless_unuse,
1653         .clo_state     = osc_lock_lockless_state,
1654         .clo_fits_into = osc_lock_lockless_fits_into,
1655         .clo_cancel    = osc_lock_lockless_cancel,
1656         .clo_print     = osc_lock_print
1657 };
1658
1659 int osc_lock_init(const struct lu_env *env,
1660                   struct cl_object *obj, struct cl_lock *lock,
1661                   const struct cl_io *unused)
1662 {
1663         struct osc_lock *clk;
1664         int result;
1665
1666         OBD_SLAB_ALLOC_PTR_GFP(clk, osc_lock_kmem, CFS_ALLOC_IO);
1667         if (clk != NULL) {
1668                 osc_lock_build_einfo(env, lock, clk, &clk->ols_einfo);
1669                 cfs_atomic_set(&clk->ols_pageref, 0);
1670                 clk->ols_state = OLS_NEW;
1671                 cl_lock_slice_add(lock, &clk->ols_cl, obj, &osc_lock_ops);
1672                 result = 0;
1673         } else
1674                 result = -ENOMEM;
1675         return result;
1676 }
1677
1678 int osc_dlm_lock_pageref(struct ldlm_lock *dlm)
1679 {
1680         struct osc_lock *olock;
1681         int              rc = 0;
1682
1683         cfs_spin_lock(&osc_ast_guard);
1684         olock = dlm->l_ast_data;
1685         /*
1686          * there's a very rare race with osc_page_addref_lock(), but that
1687          * doesn't matter because in the worst case we don't cancel a lock
1688          * which we actually can, that's no harm.
1689          */
1690         if (olock != NULL &&
1691             cfs_atomic_add_return(_PAGEREF_MAGIC,
1692                                   &olock->ols_pageref) != _PAGEREF_MAGIC) {
1693                 cfs_atomic_sub(_PAGEREF_MAGIC, &olock->ols_pageref);
1694                 rc = 1;
1695         }
1696         cfs_spin_unlock(&osc_ast_guard);
1697         return rc;
1698 }
1699
1700 /** @} osc */