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