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