OSDN Git Service

ARM: tegra: Enable PLLP bypass during Tegra124 LP1
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / fs / ocfs2 / dlmglue.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * dlmglue.c
5  *
6  * Code which implements an OCFS2 specific interface to our DLM.
7  *
8  * Copyright (C) 2003, 2004 Oracle.  All rights reserved.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public
21  * License along with this program; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 021110-1307, USA.
24  */
25
26 #include <linux/types.h>
27 #include <linux/slab.h>
28 #include <linux/highmem.h>
29 #include <linux/mm.h>
30 #include <linux/kthread.h>
31 #include <linux/pagemap.h>
32 #include <linux/debugfs.h>
33 #include <linux/seq_file.h>
34 #include <linux/time.h>
35 #include <linux/quotaops.h>
36
37 #define MLOG_MASK_PREFIX ML_DLM_GLUE
38 #include <cluster/masklog.h>
39
40 #include "ocfs2.h"
41 #include "ocfs2_lockingver.h"
42
43 #include "alloc.h"
44 #include "dcache.h"
45 #include "dlmglue.h"
46 #include "extent_map.h"
47 #include "file.h"
48 #include "heartbeat.h"
49 #include "inode.h"
50 #include "journal.h"
51 #include "stackglue.h"
52 #include "slot_map.h"
53 #include "super.h"
54 #include "uptodate.h"
55 #include "quota.h"
56 #include "refcounttree.h"
57
58 #include "buffer_head_io.h"
59
60 struct ocfs2_mask_waiter {
61         struct list_head        mw_item;
62         int                     mw_status;
63         struct completion       mw_complete;
64         unsigned long           mw_mask;
65         unsigned long           mw_goal;
66 #ifdef CONFIG_OCFS2_FS_STATS
67         ktime_t                 mw_lock_start;
68 #endif
69 };
70
71 static struct ocfs2_super *ocfs2_get_dentry_osb(struct ocfs2_lock_res *lockres);
72 static struct ocfs2_super *ocfs2_get_inode_osb(struct ocfs2_lock_res *lockres);
73 static struct ocfs2_super *ocfs2_get_file_osb(struct ocfs2_lock_res *lockres);
74 static struct ocfs2_super *ocfs2_get_qinfo_osb(struct ocfs2_lock_res *lockres);
75
76 /*
77  * Return value from ->downconvert_worker functions.
78  *
79  * These control the precise actions of ocfs2_unblock_lock()
80  * and ocfs2_process_blocked_lock()
81  *
82  */
83 enum ocfs2_unblock_action {
84         UNBLOCK_CONTINUE        = 0, /* Continue downconvert */
85         UNBLOCK_CONTINUE_POST   = 1, /* Continue downconvert, fire
86                                       * ->post_unlock callback */
87         UNBLOCK_STOP_POST       = 2, /* Do not downconvert, fire
88                                       * ->post_unlock() callback. */
89 };
90
91 struct ocfs2_unblock_ctl {
92         int requeue;
93         enum ocfs2_unblock_action unblock_action;
94 };
95
96 /* Lockdep class keys */
97 struct lock_class_key lockdep_keys[OCFS2_NUM_LOCK_TYPES];
98
99 static int ocfs2_check_meta_downconvert(struct ocfs2_lock_res *lockres,
100                                         int new_level);
101 static void ocfs2_set_meta_lvb(struct ocfs2_lock_res *lockres);
102
103 static int ocfs2_data_convert_worker(struct ocfs2_lock_res *lockres,
104                                      int blocking);
105
106 static int ocfs2_dentry_convert_worker(struct ocfs2_lock_res *lockres,
107                                        int blocking);
108
109 static void ocfs2_dentry_post_unlock(struct ocfs2_super *osb,
110                                      struct ocfs2_lock_res *lockres);
111
112 static void ocfs2_set_qinfo_lvb(struct ocfs2_lock_res *lockres);
113
114 static int ocfs2_check_refcount_downconvert(struct ocfs2_lock_res *lockres,
115                                             int new_level);
116 static int ocfs2_refcount_convert_worker(struct ocfs2_lock_res *lockres,
117                                          int blocking);
118
119 #define mlog_meta_lvb(__level, __lockres) ocfs2_dump_meta_lvb_info(__level, __PRETTY_FUNCTION__, __LINE__, __lockres)
120
121 /* This aids in debugging situations where a bad LVB might be involved. */
122 static void ocfs2_dump_meta_lvb_info(u64 level,
123                                      const char *function,
124                                      unsigned int line,
125                                      struct ocfs2_lock_res *lockres)
126 {
127         struct ocfs2_meta_lvb *lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
128
129         mlog(level, "LVB information for %s (called from %s:%u):\n",
130              lockres->l_name, function, line);
131         mlog(level, "version: %u, clusters: %u, generation: 0x%x\n",
132              lvb->lvb_version, be32_to_cpu(lvb->lvb_iclusters),
133              be32_to_cpu(lvb->lvb_igeneration));
134         mlog(level, "size: %llu, uid %u, gid %u, mode 0x%x\n",
135              (unsigned long long)be64_to_cpu(lvb->lvb_isize),
136              be32_to_cpu(lvb->lvb_iuid), be32_to_cpu(lvb->lvb_igid),
137              be16_to_cpu(lvb->lvb_imode));
138         mlog(level, "nlink %u, atime_packed 0x%llx, ctime_packed 0x%llx, "
139              "mtime_packed 0x%llx iattr 0x%x\n", be16_to_cpu(lvb->lvb_inlink),
140              (long long)be64_to_cpu(lvb->lvb_iatime_packed),
141              (long long)be64_to_cpu(lvb->lvb_ictime_packed),
142              (long long)be64_to_cpu(lvb->lvb_imtime_packed),
143              be32_to_cpu(lvb->lvb_iattr));
144 }
145
146
147 /*
148  * OCFS2 Lock Resource Operations
149  *
150  * These fine tune the behavior of the generic dlmglue locking infrastructure.
151  *
152  * The most basic of lock types can point ->l_priv to their respective
153  * struct ocfs2_super and allow the default actions to manage things.
154  *
155  * Right now, each lock type also needs to implement an init function,
156  * and trivial lock/unlock wrappers. ocfs2_simple_drop_lockres()
157  * should be called when the lock is no longer needed (i.e., object
158  * destruction time).
159  */
160 struct ocfs2_lock_res_ops {
161         /*
162          * Translate an ocfs2_lock_res * into an ocfs2_super *. Define
163          * this callback if ->l_priv is not an ocfs2_super pointer
164          */
165         struct ocfs2_super * (*get_osb)(struct ocfs2_lock_res *);
166
167         /*
168          * Optionally called in the downconvert thread after a
169          * successful downconvert. The lockres will not be referenced
170          * after this callback is called, so it is safe to free
171          * memory, etc.
172          *
173          * The exact semantics of when this is called are controlled
174          * by ->downconvert_worker()
175          */
176         void (*post_unlock)(struct ocfs2_super *, struct ocfs2_lock_res *);
177
178         /*
179          * Allow a lock type to add checks to determine whether it is
180          * safe to downconvert a lock. Return 0 to re-queue the
181          * downconvert at a later time, nonzero to continue.
182          *
183          * For most locks, the default checks that there are no
184          * incompatible holders are sufficient.
185          *
186          * Called with the lockres spinlock held.
187          */
188         int (*check_downconvert)(struct ocfs2_lock_res *, int);
189
190         /*
191          * Allows a lock type to populate the lock value block. This
192          * is called on downconvert, and when we drop a lock.
193          *
194          * Locks that want to use this should set LOCK_TYPE_USES_LVB
195          * in the flags field.
196          *
197          * Called with the lockres spinlock held.
198          */
199         void (*set_lvb)(struct ocfs2_lock_res *);
200
201         /*
202          * Called from the downconvert thread when it is determined
203          * that a lock will be downconverted. This is called without
204          * any locks held so the function can do work that might
205          * schedule (syncing out data, etc).
206          *
207          * This should return any one of the ocfs2_unblock_action
208          * values, depending on what it wants the thread to do.
209          */
210         int (*downconvert_worker)(struct ocfs2_lock_res *, int);
211
212         /*
213          * LOCK_TYPE_* flags which describe the specific requirements
214          * of a lock type. Descriptions of each individual flag follow.
215          */
216         int flags;
217 };
218
219 /*
220  * Some locks want to "refresh" potentially stale data when a
221  * meaningful (PRMODE or EXMODE) lock level is first obtained. If this
222  * flag is set, the OCFS2_LOCK_NEEDS_REFRESH flag will be set on the
223  * individual lockres l_flags member from the ast function. It is
224  * expected that the locking wrapper will clear the
225  * OCFS2_LOCK_NEEDS_REFRESH flag when done.
226  */
227 #define LOCK_TYPE_REQUIRES_REFRESH 0x1
228
229 /*
230  * Indicate that a lock type makes use of the lock value block. The
231  * ->set_lvb lock type callback must be defined.
232  */
233 #define LOCK_TYPE_USES_LVB              0x2
234
235 static struct ocfs2_lock_res_ops ocfs2_inode_rw_lops = {
236         .get_osb        = ocfs2_get_inode_osb,
237         .flags          = 0,
238 };
239
240 static struct ocfs2_lock_res_ops ocfs2_inode_inode_lops = {
241         .get_osb        = ocfs2_get_inode_osb,
242         .check_downconvert = ocfs2_check_meta_downconvert,
243         .set_lvb        = ocfs2_set_meta_lvb,
244         .downconvert_worker = ocfs2_data_convert_worker,
245         .flags          = LOCK_TYPE_REQUIRES_REFRESH|LOCK_TYPE_USES_LVB,
246 };
247
248 static struct ocfs2_lock_res_ops ocfs2_super_lops = {
249         .flags          = LOCK_TYPE_REQUIRES_REFRESH,
250 };
251
252 static struct ocfs2_lock_res_ops ocfs2_rename_lops = {
253         .flags          = 0,
254 };
255
256 static struct ocfs2_lock_res_ops ocfs2_nfs_sync_lops = {
257         .flags          = 0,
258 };
259
260 static struct ocfs2_lock_res_ops ocfs2_orphan_scan_lops = {
261         .flags          = LOCK_TYPE_REQUIRES_REFRESH|LOCK_TYPE_USES_LVB,
262 };
263
264 static struct ocfs2_lock_res_ops ocfs2_dentry_lops = {
265         .get_osb        = ocfs2_get_dentry_osb,
266         .post_unlock    = ocfs2_dentry_post_unlock,
267         .downconvert_worker = ocfs2_dentry_convert_worker,
268         .flags          = 0,
269 };
270
271 static struct ocfs2_lock_res_ops ocfs2_inode_open_lops = {
272         .get_osb        = ocfs2_get_inode_osb,
273         .flags          = 0,
274 };
275
276 static struct ocfs2_lock_res_ops ocfs2_flock_lops = {
277         .get_osb        = ocfs2_get_file_osb,
278         .flags          = 0,
279 };
280
281 static struct ocfs2_lock_res_ops ocfs2_qinfo_lops = {
282         .set_lvb        = ocfs2_set_qinfo_lvb,
283         .get_osb        = ocfs2_get_qinfo_osb,
284         .flags          = LOCK_TYPE_REQUIRES_REFRESH | LOCK_TYPE_USES_LVB,
285 };
286
287 static struct ocfs2_lock_res_ops ocfs2_refcount_block_lops = {
288         .check_downconvert = ocfs2_check_refcount_downconvert,
289         .downconvert_worker = ocfs2_refcount_convert_worker,
290         .flags          = 0,
291 };
292
293 static inline int ocfs2_is_inode_lock(struct ocfs2_lock_res *lockres)
294 {
295         return lockres->l_type == OCFS2_LOCK_TYPE_META ||
296                 lockres->l_type == OCFS2_LOCK_TYPE_RW ||
297                 lockres->l_type == OCFS2_LOCK_TYPE_OPEN;
298 }
299
300 static inline struct ocfs2_lock_res *ocfs2_lksb_to_lock_res(struct ocfs2_dlm_lksb *lksb)
301 {
302         return container_of(lksb, struct ocfs2_lock_res, l_lksb);
303 }
304
305 static inline struct inode *ocfs2_lock_res_inode(struct ocfs2_lock_res *lockres)
306 {
307         BUG_ON(!ocfs2_is_inode_lock(lockres));
308
309         return (struct inode *) lockres->l_priv;
310 }
311
312 static inline struct ocfs2_dentry_lock *ocfs2_lock_res_dl(struct ocfs2_lock_res *lockres)
313 {
314         BUG_ON(lockres->l_type != OCFS2_LOCK_TYPE_DENTRY);
315
316         return (struct ocfs2_dentry_lock *)lockres->l_priv;
317 }
318
319 static inline struct ocfs2_mem_dqinfo *ocfs2_lock_res_qinfo(struct ocfs2_lock_res *lockres)
320 {
321         BUG_ON(lockres->l_type != OCFS2_LOCK_TYPE_QINFO);
322
323         return (struct ocfs2_mem_dqinfo *)lockres->l_priv;
324 }
325
326 static inline struct ocfs2_refcount_tree *
327 ocfs2_lock_res_refcount_tree(struct ocfs2_lock_res *res)
328 {
329         return container_of(res, struct ocfs2_refcount_tree, rf_lockres);
330 }
331
332 static inline struct ocfs2_super *ocfs2_get_lockres_osb(struct ocfs2_lock_res *lockres)
333 {
334         if (lockres->l_ops->get_osb)
335                 return lockres->l_ops->get_osb(lockres);
336
337         return (struct ocfs2_super *)lockres->l_priv;
338 }
339
340 static int ocfs2_lock_create(struct ocfs2_super *osb,
341                              struct ocfs2_lock_res *lockres,
342                              int level,
343                              u32 dlm_flags);
344 static inline int ocfs2_may_continue_on_blocked_lock(struct ocfs2_lock_res *lockres,
345                                                      int wanted);
346 static void __ocfs2_cluster_unlock(struct ocfs2_super *osb,
347                                    struct ocfs2_lock_res *lockres,
348                                    int level, unsigned long caller_ip);
349 static inline void ocfs2_cluster_unlock(struct ocfs2_super *osb,
350                                         struct ocfs2_lock_res *lockres,
351                                         int level)
352 {
353         __ocfs2_cluster_unlock(osb, lockres, level, _RET_IP_);
354 }
355
356 static inline void ocfs2_generic_handle_downconvert_action(struct ocfs2_lock_res *lockres);
357 static inline void ocfs2_generic_handle_convert_action(struct ocfs2_lock_res *lockres);
358 static inline void ocfs2_generic_handle_attach_action(struct ocfs2_lock_res *lockres);
359 static int ocfs2_generic_handle_bast(struct ocfs2_lock_res *lockres, int level);
360 static void ocfs2_schedule_blocked_lock(struct ocfs2_super *osb,
361                                         struct ocfs2_lock_res *lockres);
362 static inline void ocfs2_recover_from_dlm_error(struct ocfs2_lock_res *lockres,
363                                                 int convert);
364 #define ocfs2_log_dlm_error(_func, _err, _lockres) do {                                 \
365         if ((_lockres)->l_type != OCFS2_LOCK_TYPE_DENTRY)                               \
366                 mlog(ML_ERROR, "DLM error %d while calling %s on resource %s\n",        \
367                      _err, _func, _lockres->l_name);                                    \
368         else                                                                            \
369                 mlog(ML_ERROR, "DLM error %d while calling %s on resource %.*s%08x\n",  \
370                      _err, _func, OCFS2_DENTRY_LOCK_INO_START - 1, (_lockres)->l_name,  \
371                      (unsigned int)ocfs2_get_dentry_lock_ino(_lockres));                \
372 } while (0)
373 static int ocfs2_downconvert_thread(void *arg);
374 static void ocfs2_downconvert_on_unlock(struct ocfs2_super *osb,
375                                         struct ocfs2_lock_res *lockres);
376 static int ocfs2_inode_lock_update(struct inode *inode,
377                                   struct buffer_head **bh);
378 static void ocfs2_drop_osb_locks(struct ocfs2_super *osb);
379 static inline int ocfs2_highest_compat_lock_level(int level);
380 static unsigned int ocfs2_prepare_downconvert(struct ocfs2_lock_res *lockres,
381                                               int new_level);
382 static int ocfs2_downconvert_lock(struct ocfs2_super *osb,
383                                   struct ocfs2_lock_res *lockres,
384                                   int new_level,
385                                   int lvb,
386                                   unsigned int generation);
387 static int ocfs2_prepare_cancel_convert(struct ocfs2_super *osb,
388                                         struct ocfs2_lock_res *lockres);
389 static int ocfs2_cancel_convert(struct ocfs2_super *osb,
390                                 struct ocfs2_lock_res *lockres);
391
392
393 static void ocfs2_build_lock_name(enum ocfs2_lock_type type,
394                                   u64 blkno,
395                                   u32 generation,
396                                   char *name)
397 {
398         int len;
399
400         BUG_ON(type >= OCFS2_NUM_LOCK_TYPES);
401
402         len = snprintf(name, OCFS2_LOCK_ID_MAX_LEN, "%c%s%016llx%08x",
403                        ocfs2_lock_type_char(type), OCFS2_LOCK_ID_PAD,
404                        (long long)blkno, generation);
405
406         BUG_ON(len != (OCFS2_LOCK_ID_MAX_LEN - 1));
407
408         mlog(0, "built lock resource with name: %s\n", name);
409 }
410
411 static DEFINE_SPINLOCK(ocfs2_dlm_tracking_lock);
412
413 static void ocfs2_add_lockres_tracking(struct ocfs2_lock_res *res,
414                                        struct ocfs2_dlm_debug *dlm_debug)
415 {
416         mlog(0, "Add tracking for lockres %s\n", res->l_name);
417
418         spin_lock(&ocfs2_dlm_tracking_lock);
419         list_add(&res->l_debug_list, &dlm_debug->d_lockres_tracking);
420         spin_unlock(&ocfs2_dlm_tracking_lock);
421 }
422
423 static void ocfs2_remove_lockres_tracking(struct ocfs2_lock_res *res)
424 {
425         spin_lock(&ocfs2_dlm_tracking_lock);
426         if (!list_empty(&res->l_debug_list))
427                 list_del_init(&res->l_debug_list);
428         spin_unlock(&ocfs2_dlm_tracking_lock);
429 }
430
431 #ifdef CONFIG_OCFS2_FS_STATS
432 static void ocfs2_init_lock_stats(struct ocfs2_lock_res *res)
433 {
434         res->l_lock_refresh = 0;
435         memset(&res->l_lock_prmode, 0, sizeof(struct ocfs2_lock_stats));
436         memset(&res->l_lock_exmode, 0, sizeof(struct ocfs2_lock_stats));
437 }
438
439 static void ocfs2_update_lock_stats(struct ocfs2_lock_res *res, int level,
440                                     struct ocfs2_mask_waiter *mw, int ret)
441 {
442         u32 usec;
443         ktime_t kt;
444         struct ocfs2_lock_stats *stats;
445
446         if (level == LKM_PRMODE)
447                 stats = &res->l_lock_prmode;
448         else if (level == LKM_EXMODE)
449                 stats = &res->l_lock_exmode;
450         else
451                 return;
452
453         kt = ktime_sub(ktime_get(), mw->mw_lock_start);
454         usec = ktime_to_us(kt);
455
456         stats->ls_gets++;
457         stats->ls_total += ktime_to_ns(kt);
458         /* overflow */
459         if (unlikely(stats->ls_gets == 0)) {
460                 stats->ls_gets++;
461                 stats->ls_total = ktime_to_ns(kt);
462         }
463
464         if (stats->ls_max < usec)
465                 stats->ls_max = usec;
466
467         if (ret)
468                 stats->ls_fail++;
469 }
470
471 static inline void ocfs2_track_lock_refresh(struct ocfs2_lock_res *lockres)
472 {
473         lockres->l_lock_refresh++;
474 }
475
476 static inline void ocfs2_init_start_time(struct ocfs2_mask_waiter *mw)
477 {
478         mw->mw_lock_start = ktime_get();
479 }
480 #else
481 static inline void ocfs2_init_lock_stats(struct ocfs2_lock_res *res)
482 {
483 }
484 static inline void ocfs2_update_lock_stats(struct ocfs2_lock_res *res,
485                            int level, struct ocfs2_mask_waiter *mw, int ret)
486 {
487 }
488 static inline void ocfs2_track_lock_refresh(struct ocfs2_lock_res *lockres)
489 {
490 }
491 static inline void ocfs2_init_start_time(struct ocfs2_mask_waiter *mw)
492 {
493 }
494 #endif
495
496 static void ocfs2_lock_res_init_common(struct ocfs2_super *osb,
497                                        struct ocfs2_lock_res *res,
498                                        enum ocfs2_lock_type type,
499                                        struct ocfs2_lock_res_ops *ops,
500                                        void *priv)
501 {
502         res->l_type          = type;
503         res->l_ops           = ops;
504         res->l_priv          = priv;
505
506         res->l_level         = DLM_LOCK_IV;
507         res->l_requested     = DLM_LOCK_IV;
508         res->l_blocking      = DLM_LOCK_IV;
509         res->l_action        = OCFS2_AST_INVALID;
510         res->l_unlock_action = OCFS2_UNLOCK_INVALID;
511
512         res->l_flags         = OCFS2_LOCK_INITIALIZED;
513
514         ocfs2_add_lockres_tracking(res, osb->osb_dlm_debug);
515
516         ocfs2_init_lock_stats(res);
517 #ifdef CONFIG_DEBUG_LOCK_ALLOC
518         if (type != OCFS2_LOCK_TYPE_OPEN)
519                 lockdep_init_map(&res->l_lockdep_map, ocfs2_lock_type_strings[type],
520                                  &lockdep_keys[type], 0);
521         else
522                 res->l_lockdep_map.key = NULL;
523 #endif
524 }
525
526 void ocfs2_lock_res_init_once(struct ocfs2_lock_res *res)
527 {
528         /* This also clears out the lock status block */
529         memset(res, 0, sizeof(struct ocfs2_lock_res));
530         spin_lock_init(&res->l_lock);
531         init_waitqueue_head(&res->l_event);
532         INIT_LIST_HEAD(&res->l_blocked_list);
533         INIT_LIST_HEAD(&res->l_mask_waiters);
534         INIT_LIST_HEAD(&res->l_holders);
535 }
536
537 void ocfs2_inode_lock_res_init(struct ocfs2_lock_res *res,
538                                enum ocfs2_lock_type type,
539                                unsigned int generation,
540                                struct inode *inode)
541 {
542         struct ocfs2_lock_res_ops *ops;
543
544         switch(type) {
545                 case OCFS2_LOCK_TYPE_RW:
546                         ops = &ocfs2_inode_rw_lops;
547                         break;
548                 case OCFS2_LOCK_TYPE_META:
549                         ops = &ocfs2_inode_inode_lops;
550                         break;
551                 case OCFS2_LOCK_TYPE_OPEN:
552                         ops = &ocfs2_inode_open_lops;
553                         break;
554                 default:
555                         mlog_bug_on_msg(1, "type: %d\n", type);
556                         ops = NULL; /* thanks, gcc */
557                         break;
558         };
559
560         ocfs2_build_lock_name(type, OCFS2_I(inode)->ip_blkno,
561                               generation, res->l_name);
562         ocfs2_lock_res_init_common(OCFS2_SB(inode->i_sb), res, type, ops, inode);
563 }
564
565 static struct ocfs2_super *ocfs2_get_inode_osb(struct ocfs2_lock_res *lockres)
566 {
567         struct inode *inode = ocfs2_lock_res_inode(lockres);
568
569         return OCFS2_SB(inode->i_sb);
570 }
571
572 static struct ocfs2_super *ocfs2_get_qinfo_osb(struct ocfs2_lock_res *lockres)
573 {
574         struct ocfs2_mem_dqinfo *info = lockres->l_priv;
575
576         return OCFS2_SB(info->dqi_gi.dqi_sb);
577 }
578
579 static struct ocfs2_super *ocfs2_get_file_osb(struct ocfs2_lock_res *lockres)
580 {
581         struct ocfs2_file_private *fp = lockres->l_priv;
582
583         return OCFS2_SB(fp->fp_file->f_mapping->host->i_sb);
584 }
585
586 static __u64 ocfs2_get_dentry_lock_ino(struct ocfs2_lock_res *lockres)
587 {
588         __be64 inode_blkno_be;
589
590         memcpy(&inode_blkno_be, &lockres->l_name[OCFS2_DENTRY_LOCK_INO_START],
591                sizeof(__be64));
592
593         return be64_to_cpu(inode_blkno_be);
594 }
595
596 static struct ocfs2_super *ocfs2_get_dentry_osb(struct ocfs2_lock_res *lockres)
597 {
598         struct ocfs2_dentry_lock *dl = lockres->l_priv;
599
600         return OCFS2_SB(dl->dl_inode->i_sb);
601 }
602
603 void ocfs2_dentry_lock_res_init(struct ocfs2_dentry_lock *dl,
604                                 u64 parent, struct inode *inode)
605 {
606         int len;
607         u64 inode_blkno = OCFS2_I(inode)->ip_blkno;
608         __be64 inode_blkno_be = cpu_to_be64(inode_blkno);
609         struct ocfs2_lock_res *lockres = &dl->dl_lockres;
610
611         ocfs2_lock_res_init_once(lockres);
612
613         /*
614          * Unfortunately, the standard lock naming scheme won't work
615          * here because we have two 16 byte values to use. Instead,
616          * we'll stuff the inode number as a binary value. We still
617          * want error prints to show something without garbling the
618          * display, so drop a null byte in there before the inode
619          * number. A future version of OCFS2 will likely use all
620          * binary lock names. The stringified names have been a
621          * tremendous aid in debugging, but now that the debugfs
622          * interface exists, we can mangle things there if need be.
623          *
624          * NOTE: We also drop the standard "pad" value (the total lock
625          * name size stays the same though - the last part is all
626          * zeros due to the memset in ocfs2_lock_res_init_once()
627          */
628         len = snprintf(lockres->l_name, OCFS2_DENTRY_LOCK_INO_START,
629                        "%c%016llx",
630                        ocfs2_lock_type_char(OCFS2_LOCK_TYPE_DENTRY),
631                        (long long)parent);
632
633         BUG_ON(len != (OCFS2_DENTRY_LOCK_INO_START - 1));
634
635         memcpy(&lockres->l_name[OCFS2_DENTRY_LOCK_INO_START], &inode_blkno_be,
636                sizeof(__be64));
637
638         ocfs2_lock_res_init_common(OCFS2_SB(inode->i_sb), lockres,
639                                    OCFS2_LOCK_TYPE_DENTRY, &ocfs2_dentry_lops,
640                                    dl);
641 }
642
643 static void ocfs2_super_lock_res_init(struct ocfs2_lock_res *res,
644                                       struct ocfs2_super *osb)
645 {
646         /* Superblock lockres doesn't come from a slab so we call init
647          * once on it manually.  */
648         ocfs2_lock_res_init_once(res);
649         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_SUPER, OCFS2_SUPER_BLOCK_BLKNO,
650                               0, res->l_name);
651         ocfs2_lock_res_init_common(osb, res, OCFS2_LOCK_TYPE_SUPER,
652                                    &ocfs2_super_lops, osb);
653 }
654
655 static void ocfs2_rename_lock_res_init(struct ocfs2_lock_res *res,
656                                        struct ocfs2_super *osb)
657 {
658         /* Rename lockres doesn't come from a slab so we call init
659          * once on it manually.  */
660         ocfs2_lock_res_init_once(res);
661         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_RENAME, 0, 0, res->l_name);
662         ocfs2_lock_res_init_common(osb, res, OCFS2_LOCK_TYPE_RENAME,
663                                    &ocfs2_rename_lops, osb);
664 }
665
666 static void ocfs2_nfs_sync_lock_res_init(struct ocfs2_lock_res *res,
667                                          struct ocfs2_super *osb)
668 {
669         /* nfs_sync lockres doesn't come from a slab so we call init
670          * once on it manually.  */
671         ocfs2_lock_res_init_once(res);
672         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_NFS_SYNC, 0, 0, res->l_name);
673         ocfs2_lock_res_init_common(osb, res, OCFS2_LOCK_TYPE_NFS_SYNC,
674                                    &ocfs2_nfs_sync_lops, osb);
675 }
676
677 static void ocfs2_orphan_scan_lock_res_init(struct ocfs2_lock_res *res,
678                                             struct ocfs2_super *osb)
679 {
680         ocfs2_lock_res_init_once(res);
681         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_ORPHAN_SCAN, 0, 0, res->l_name);
682         ocfs2_lock_res_init_common(osb, res, OCFS2_LOCK_TYPE_ORPHAN_SCAN,
683                                    &ocfs2_orphan_scan_lops, osb);
684 }
685
686 void ocfs2_file_lock_res_init(struct ocfs2_lock_res *lockres,
687                               struct ocfs2_file_private *fp)
688 {
689         struct inode *inode = fp->fp_file->f_mapping->host;
690         struct ocfs2_inode_info *oi = OCFS2_I(inode);
691
692         ocfs2_lock_res_init_once(lockres);
693         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_FLOCK, oi->ip_blkno,
694                               inode->i_generation, lockres->l_name);
695         ocfs2_lock_res_init_common(OCFS2_SB(inode->i_sb), lockres,
696                                    OCFS2_LOCK_TYPE_FLOCK, &ocfs2_flock_lops,
697                                    fp);
698         lockres->l_flags |= OCFS2_LOCK_NOCACHE;
699 }
700
701 void ocfs2_qinfo_lock_res_init(struct ocfs2_lock_res *lockres,
702                                struct ocfs2_mem_dqinfo *info)
703 {
704         ocfs2_lock_res_init_once(lockres);
705         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_QINFO, info->dqi_gi.dqi_type,
706                               0, lockres->l_name);
707         ocfs2_lock_res_init_common(OCFS2_SB(info->dqi_gi.dqi_sb), lockres,
708                                    OCFS2_LOCK_TYPE_QINFO, &ocfs2_qinfo_lops,
709                                    info);
710 }
711
712 void ocfs2_refcount_lock_res_init(struct ocfs2_lock_res *lockres,
713                                   struct ocfs2_super *osb, u64 ref_blkno,
714                                   unsigned int generation)
715 {
716         ocfs2_lock_res_init_once(lockres);
717         ocfs2_build_lock_name(OCFS2_LOCK_TYPE_REFCOUNT, ref_blkno,
718                               generation, lockres->l_name);
719         ocfs2_lock_res_init_common(osb, lockres, OCFS2_LOCK_TYPE_REFCOUNT,
720                                    &ocfs2_refcount_block_lops, osb);
721 }
722
723 void ocfs2_lock_res_free(struct ocfs2_lock_res *res)
724 {
725         if (!(res->l_flags & OCFS2_LOCK_INITIALIZED))
726                 return;
727
728         ocfs2_remove_lockres_tracking(res);
729
730         mlog_bug_on_msg(!list_empty(&res->l_blocked_list),
731                         "Lockres %s is on the blocked list\n",
732                         res->l_name);
733         mlog_bug_on_msg(!list_empty(&res->l_mask_waiters),
734                         "Lockres %s has mask waiters pending\n",
735                         res->l_name);
736         mlog_bug_on_msg(spin_is_locked(&res->l_lock),
737                         "Lockres %s is locked\n",
738                         res->l_name);
739         mlog_bug_on_msg(res->l_ro_holders,
740                         "Lockres %s has %u ro holders\n",
741                         res->l_name, res->l_ro_holders);
742         mlog_bug_on_msg(res->l_ex_holders,
743                         "Lockres %s has %u ex holders\n",
744                         res->l_name, res->l_ex_holders);
745
746         /* Need to clear out the lock status block for the dlm */
747         memset(&res->l_lksb, 0, sizeof(res->l_lksb));
748
749         res->l_flags = 0UL;
750 }
751
752 /*
753  * Keep a list of processes who have interest in a lockres.
754  * Note: this is now only uesed for check recursive cluster locking.
755  */
756 static inline void ocfs2_add_holder(struct ocfs2_lock_res *lockres,
757                                    struct ocfs2_lock_holder *oh)
758 {
759         INIT_LIST_HEAD(&oh->oh_list);
760         oh->oh_owner_pid = get_pid(task_pid(current));
761
762         spin_lock(&lockres->l_lock);
763         list_add_tail(&oh->oh_list, &lockres->l_holders);
764         spin_unlock(&lockres->l_lock);
765 }
766
767 static inline void ocfs2_remove_holder(struct ocfs2_lock_res *lockres,
768                                        struct ocfs2_lock_holder *oh)
769 {
770         spin_lock(&lockres->l_lock);
771         list_del(&oh->oh_list);
772         spin_unlock(&lockres->l_lock);
773
774         put_pid(oh->oh_owner_pid);
775 }
776
777 static inline int ocfs2_is_locked_by_me(struct ocfs2_lock_res *lockres)
778 {
779         struct ocfs2_lock_holder *oh;
780         struct pid *pid;
781
782         /* look in the list of holders for one with the current task as owner */
783         spin_lock(&lockres->l_lock);
784         pid = task_pid(current);
785         list_for_each_entry(oh, &lockres->l_holders, oh_list) {
786                 if (oh->oh_owner_pid == pid) {
787                         spin_unlock(&lockres->l_lock);
788                         return 1;
789                 }
790         }
791         spin_unlock(&lockres->l_lock);
792
793         return 0;
794 }
795
796 static inline void ocfs2_inc_holders(struct ocfs2_lock_res *lockres,
797                                      int level)
798 {
799         BUG_ON(!lockres);
800
801         switch(level) {
802         case DLM_LOCK_EX:
803                 lockres->l_ex_holders++;
804                 break;
805         case DLM_LOCK_PR:
806                 lockres->l_ro_holders++;
807                 break;
808         default:
809                 BUG();
810         }
811 }
812
813 static inline void ocfs2_dec_holders(struct ocfs2_lock_res *lockres,
814                                      int level)
815 {
816         BUG_ON(!lockres);
817
818         switch(level) {
819         case DLM_LOCK_EX:
820                 BUG_ON(!lockres->l_ex_holders);
821                 lockres->l_ex_holders--;
822                 break;
823         case DLM_LOCK_PR:
824                 BUG_ON(!lockres->l_ro_holders);
825                 lockres->l_ro_holders--;
826                 break;
827         default:
828                 BUG();
829         }
830 }
831
832 /* WARNING: This function lives in a world where the only three lock
833  * levels are EX, PR, and NL. It *will* have to be adjusted when more
834  * lock types are added. */
835 static inline int ocfs2_highest_compat_lock_level(int level)
836 {
837         int new_level = DLM_LOCK_EX;
838
839         if (level == DLM_LOCK_EX)
840                 new_level = DLM_LOCK_NL;
841         else if (level == DLM_LOCK_PR)
842                 new_level = DLM_LOCK_PR;
843         return new_level;
844 }
845
846 static void lockres_set_flags(struct ocfs2_lock_res *lockres,
847                               unsigned long newflags)
848 {
849         struct ocfs2_mask_waiter *mw, *tmp;
850
851         assert_spin_locked(&lockres->l_lock);
852
853         lockres->l_flags = newflags;
854
855         list_for_each_entry_safe(mw, tmp, &lockres->l_mask_waiters, mw_item) {
856                 if ((lockres->l_flags & mw->mw_mask) != mw->mw_goal)
857                         continue;
858
859                 list_del_init(&mw->mw_item);
860                 mw->mw_status = 0;
861                 complete(&mw->mw_complete);
862         }
863 }
864 static void lockres_or_flags(struct ocfs2_lock_res *lockres, unsigned long or)
865 {
866         lockres_set_flags(lockres, lockres->l_flags | or);
867 }
868 static void lockres_clear_flags(struct ocfs2_lock_res *lockres,
869                                 unsigned long clear)
870 {
871         lockres_set_flags(lockres, lockres->l_flags & ~clear);
872 }
873
874 static inline void ocfs2_generic_handle_downconvert_action(struct ocfs2_lock_res *lockres)
875 {
876         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_BUSY));
877         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_ATTACHED));
878         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_BLOCKED));
879         BUG_ON(lockres->l_blocking <= DLM_LOCK_NL);
880
881         lockres->l_level = lockres->l_requested;
882         if (lockres->l_level <=
883             ocfs2_highest_compat_lock_level(lockres->l_blocking)) {
884                 lockres->l_blocking = DLM_LOCK_NL;
885                 lockres_clear_flags(lockres, OCFS2_LOCK_BLOCKED);
886         }
887         lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
888 }
889
890 static inline void ocfs2_generic_handle_convert_action(struct ocfs2_lock_res *lockres)
891 {
892         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_BUSY));
893         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_ATTACHED));
894
895         /* Convert from RO to EX doesn't really need anything as our
896          * information is already up to data. Convert from NL to
897          * *anything* however should mark ourselves as needing an
898          * update */
899         if (lockres->l_level == DLM_LOCK_NL &&
900             lockres->l_ops->flags & LOCK_TYPE_REQUIRES_REFRESH)
901                 lockres_or_flags(lockres, OCFS2_LOCK_NEEDS_REFRESH);
902
903         lockres->l_level = lockres->l_requested;
904
905         /*
906          * We set the OCFS2_LOCK_UPCONVERT_FINISHING flag before clearing
907          * the OCFS2_LOCK_BUSY flag to prevent the dc thread from
908          * downconverting the lock before the upconvert has fully completed.
909          * Do not prevent the dc thread from downconverting if NONBLOCK lock
910          * had already returned.
911          */
912         if (!(lockres->l_flags & OCFS2_LOCK_NONBLOCK_FINISHED))
913                 lockres_or_flags(lockres, OCFS2_LOCK_UPCONVERT_FINISHING);
914         else
915                 lockres_clear_flags(lockres, OCFS2_LOCK_NONBLOCK_FINISHED);
916
917         lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
918 }
919
920 static inline void ocfs2_generic_handle_attach_action(struct ocfs2_lock_res *lockres)
921 {
922         BUG_ON((!(lockres->l_flags & OCFS2_LOCK_BUSY)));
923         BUG_ON(lockres->l_flags & OCFS2_LOCK_ATTACHED);
924
925         if (lockres->l_requested > DLM_LOCK_NL &&
926             !(lockres->l_flags & OCFS2_LOCK_LOCAL) &&
927             lockres->l_ops->flags & LOCK_TYPE_REQUIRES_REFRESH)
928                 lockres_or_flags(lockres, OCFS2_LOCK_NEEDS_REFRESH);
929
930         lockres->l_level = lockres->l_requested;
931         lockres_or_flags(lockres, OCFS2_LOCK_ATTACHED);
932         lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
933 }
934
935 static int ocfs2_generic_handle_bast(struct ocfs2_lock_res *lockres,
936                                      int level)
937 {
938         int needs_downconvert = 0;
939
940         assert_spin_locked(&lockres->l_lock);
941
942         if (level > lockres->l_blocking) {
943                 /* only schedule a downconvert if we haven't already scheduled
944                  * one that goes low enough to satisfy the level we're
945                  * blocking.  this also catches the case where we get
946                  * duplicate BASTs */
947                 if (ocfs2_highest_compat_lock_level(level) <
948                     ocfs2_highest_compat_lock_level(lockres->l_blocking))
949                         needs_downconvert = 1;
950
951                 lockres->l_blocking = level;
952         }
953
954         mlog(ML_BASTS, "lockres %s, block %d, level %d, l_block %d, dwn %d\n",
955              lockres->l_name, level, lockres->l_level, lockres->l_blocking,
956              needs_downconvert);
957
958         if (needs_downconvert)
959                 lockres_or_flags(lockres, OCFS2_LOCK_BLOCKED);
960         mlog(0, "needs_downconvert = %d\n", needs_downconvert);
961         return needs_downconvert;
962 }
963
964 /*
965  * OCFS2_LOCK_PENDING and l_pending_gen.
966  *
967  * Why does OCFS2_LOCK_PENDING exist?  To close a race between setting
968  * OCFS2_LOCK_BUSY and calling ocfs2_dlm_lock().  See ocfs2_unblock_lock()
969  * for more details on the race.
970  *
971  * OCFS2_LOCK_PENDING closes the race quite nicely.  However, it introduces
972  * a race on itself.  In o2dlm, we can get the ast before ocfs2_dlm_lock()
973  * returns.  The ast clears OCFS2_LOCK_BUSY, and must therefore clear
974  * OCFS2_LOCK_PENDING at the same time.  When ocfs2_dlm_lock() returns,
975  * the caller is going to try to clear PENDING again.  If nothing else is
976  * happening, __lockres_clear_pending() sees PENDING is unset and does
977  * nothing.
978  *
979  * But what if another path (eg downconvert thread) has just started a
980  * new locking action?  The other path has re-set PENDING.  Our path
981  * cannot clear PENDING, because that will re-open the original race
982  * window.
983  *
984  * [Example]
985  *
986  * ocfs2_meta_lock()
987  *  ocfs2_cluster_lock()
988  *   set BUSY
989  *   set PENDING
990  *   drop l_lock
991  *   ocfs2_dlm_lock()
992  *    ocfs2_locking_ast()               ocfs2_downconvert_thread()
993  *     clear PENDING                     ocfs2_unblock_lock()
994  *                                        take_l_lock
995  *                                        !BUSY
996  *                                        ocfs2_prepare_downconvert()
997  *                                         set BUSY
998  *                                         set PENDING
999  *                                        drop l_lock
1000  *   take l_lock
1001  *   clear PENDING
1002  *   drop l_lock
1003  *                      <window>
1004  *                                        ocfs2_dlm_lock()
1005  *
1006  * So as you can see, we now have a window where l_lock is not held,
1007  * PENDING is not set, and ocfs2_dlm_lock() has not been called.
1008  *
1009  * The core problem is that ocfs2_cluster_lock() has cleared the PENDING
1010  * set by ocfs2_prepare_downconvert().  That wasn't nice.
1011  *
1012  * To solve this we introduce l_pending_gen.  A call to
1013  * lockres_clear_pending() will only do so when it is passed a generation
1014  * number that matches the lockres.  lockres_set_pending() will return the
1015  * current generation number.  When ocfs2_cluster_lock() goes to clear
1016  * PENDING, it passes the generation it got from set_pending().  In our
1017  * example above, the generation numbers will *not* match.  Thus,
1018  * ocfs2_cluster_lock() will not clear the PENDING set by
1019  * ocfs2_prepare_downconvert().
1020  */
1021
1022 /* Unlocked version for ocfs2_locking_ast() */
1023 static void __lockres_clear_pending(struct ocfs2_lock_res *lockres,
1024                                     unsigned int generation,
1025                                     struct ocfs2_super *osb)
1026 {
1027         assert_spin_locked(&lockres->l_lock);
1028
1029         /*
1030          * The ast and locking functions can race us here.  The winner
1031          * will clear pending, the loser will not.
1032          */
1033         if (!(lockres->l_flags & OCFS2_LOCK_PENDING) ||
1034             (lockres->l_pending_gen != generation))
1035                 return;
1036
1037         lockres_clear_flags(lockres, OCFS2_LOCK_PENDING);
1038         lockres->l_pending_gen++;
1039
1040         /*
1041          * The downconvert thread may have skipped us because we
1042          * were PENDING.  Wake it up.
1043          */
1044         if (lockres->l_flags & OCFS2_LOCK_BLOCKED)
1045                 ocfs2_wake_downconvert_thread(osb);
1046 }
1047
1048 /* Locked version for callers of ocfs2_dlm_lock() */
1049 static void lockres_clear_pending(struct ocfs2_lock_res *lockres,
1050                                   unsigned int generation,
1051                                   struct ocfs2_super *osb)
1052 {
1053         unsigned long flags;
1054
1055         spin_lock_irqsave(&lockres->l_lock, flags);
1056         __lockres_clear_pending(lockres, generation, osb);
1057         spin_unlock_irqrestore(&lockres->l_lock, flags);
1058 }
1059
1060 static unsigned int lockres_set_pending(struct ocfs2_lock_res *lockres)
1061 {
1062         assert_spin_locked(&lockres->l_lock);
1063         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_BUSY));
1064
1065         lockres_or_flags(lockres, OCFS2_LOCK_PENDING);
1066
1067         return lockres->l_pending_gen;
1068 }
1069
1070 static void ocfs2_blocking_ast(struct ocfs2_dlm_lksb *lksb, int level)
1071 {
1072         struct ocfs2_lock_res *lockres = ocfs2_lksb_to_lock_res(lksb);
1073         struct ocfs2_super *osb = ocfs2_get_lockres_osb(lockres);
1074         int needs_downconvert;
1075         unsigned long flags;
1076
1077         BUG_ON(level <= DLM_LOCK_NL);
1078
1079         mlog(ML_BASTS, "BAST fired for lockres %s, blocking %d, level %d, "
1080              "type %s\n", lockres->l_name, level, lockres->l_level,
1081              ocfs2_lock_type_string(lockres->l_type));
1082
1083         /*
1084          * We can skip the bast for locks which don't enable caching -
1085          * they'll be dropped at the earliest possible time anyway.
1086          */
1087         if (lockres->l_flags & OCFS2_LOCK_NOCACHE)
1088                 return;
1089
1090         spin_lock_irqsave(&lockres->l_lock, flags);
1091         needs_downconvert = ocfs2_generic_handle_bast(lockres, level);
1092         if (needs_downconvert)
1093                 ocfs2_schedule_blocked_lock(osb, lockres);
1094         spin_unlock_irqrestore(&lockres->l_lock, flags);
1095
1096         wake_up(&lockres->l_event);
1097
1098         ocfs2_wake_downconvert_thread(osb);
1099 }
1100
1101 static void ocfs2_locking_ast(struct ocfs2_dlm_lksb *lksb)
1102 {
1103         struct ocfs2_lock_res *lockres = ocfs2_lksb_to_lock_res(lksb);
1104         struct ocfs2_super *osb = ocfs2_get_lockres_osb(lockres);
1105         unsigned long flags;
1106         int status;
1107
1108         spin_lock_irqsave(&lockres->l_lock, flags);
1109
1110         status = ocfs2_dlm_lock_status(&lockres->l_lksb);
1111
1112         if (status == -EAGAIN) {
1113                 lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
1114                 goto out;
1115         }
1116
1117         if (status) {
1118                 mlog(ML_ERROR, "lockres %s: lksb status value of %d!\n",
1119                      lockres->l_name, status);
1120                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1121                 return;
1122         }
1123
1124         mlog(ML_BASTS, "AST fired for lockres %s, action %d, unlock %d, "
1125              "level %d => %d\n", lockres->l_name, lockres->l_action,
1126              lockres->l_unlock_action, lockres->l_level, lockres->l_requested);
1127
1128         switch(lockres->l_action) {
1129         case OCFS2_AST_ATTACH:
1130                 ocfs2_generic_handle_attach_action(lockres);
1131                 lockres_clear_flags(lockres, OCFS2_LOCK_LOCAL);
1132                 break;
1133         case OCFS2_AST_CONVERT:
1134                 ocfs2_generic_handle_convert_action(lockres);
1135                 break;
1136         case OCFS2_AST_DOWNCONVERT:
1137                 ocfs2_generic_handle_downconvert_action(lockres);
1138                 break;
1139         default:
1140                 mlog(ML_ERROR, "lockres %s: AST fired with invalid action: %u, "
1141                      "flags 0x%lx, unlock: %u\n",
1142                      lockres->l_name, lockres->l_action, lockres->l_flags,
1143                      lockres->l_unlock_action);
1144                 BUG();
1145         }
1146 out:
1147         /* set it to something invalid so if we get called again we
1148          * can catch it. */
1149         lockres->l_action = OCFS2_AST_INVALID;
1150
1151         /* Did we try to cancel this lock?  Clear that state */
1152         if (lockres->l_unlock_action == OCFS2_UNLOCK_CANCEL_CONVERT)
1153                 lockres->l_unlock_action = OCFS2_UNLOCK_INVALID;
1154
1155         /*
1156          * We may have beaten the locking functions here.  We certainly
1157          * know that dlm_lock() has been called :-)
1158          * Because we can't have two lock calls in flight at once, we
1159          * can use lockres->l_pending_gen.
1160          */
1161         __lockres_clear_pending(lockres, lockres->l_pending_gen,  osb);
1162
1163         wake_up(&lockres->l_event);
1164         spin_unlock_irqrestore(&lockres->l_lock, flags);
1165 }
1166
1167 static void ocfs2_unlock_ast(struct ocfs2_dlm_lksb *lksb, int error)
1168 {
1169         struct ocfs2_lock_res *lockres = ocfs2_lksb_to_lock_res(lksb);
1170         unsigned long flags;
1171
1172         mlog(ML_BASTS, "UNLOCK AST fired for lockres %s, action = %d\n",
1173              lockres->l_name, lockres->l_unlock_action);
1174
1175         spin_lock_irqsave(&lockres->l_lock, flags);
1176         if (error) {
1177                 mlog(ML_ERROR, "Dlm passes error %d for lock %s, "
1178                      "unlock_action %d\n", error, lockres->l_name,
1179                      lockres->l_unlock_action);
1180                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1181                 return;
1182         }
1183
1184         switch(lockres->l_unlock_action) {
1185         case OCFS2_UNLOCK_CANCEL_CONVERT:
1186                 mlog(0, "Cancel convert success for %s\n", lockres->l_name);
1187                 lockres->l_action = OCFS2_AST_INVALID;
1188                 /* Downconvert thread may have requeued this lock, we
1189                  * need to wake it. */
1190                 if (lockres->l_flags & OCFS2_LOCK_BLOCKED)
1191                         ocfs2_wake_downconvert_thread(ocfs2_get_lockres_osb(lockres));
1192                 break;
1193         case OCFS2_UNLOCK_DROP_LOCK:
1194                 lockres->l_level = DLM_LOCK_IV;
1195                 break;
1196         default:
1197                 BUG();
1198         }
1199
1200         lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
1201         lockres->l_unlock_action = OCFS2_UNLOCK_INVALID;
1202         wake_up(&lockres->l_event);
1203         spin_unlock_irqrestore(&lockres->l_lock, flags);
1204 }
1205
1206 /*
1207  * This is the filesystem locking protocol.  It provides the lock handling
1208  * hooks for the underlying DLM.  It has a maximum version number.
1209  * The version number allows interoperability with systems running at
1210  * the same major number and an equal or smaller minor number.
1211  *
1212  * Whenever the filesystem does new things with locks (adds or removes a
1213  * lock, orders them differently, does different things underneath a lock),
1214  * the version must be changed.  The protocol is negotiated when joining
1215  * the dlm domain.  A node may join the domain if its major version is
1216  * identical to all other nodes and its minor version is greater than
1217  * or equal to all other nodes.  When its minor version is greater than
1218  * the other nodes, it will run at the minor version specified by the
1219  * other nodes.
1220  *
1221  * If a locking change is made that will not be compatible with older
1222  * versions, the major number must be increased and the minor version set
1223  * to zero.  If a change merely adds a behavior that can be disabled when
1224  * speaking to older versions, the minor version must be increased.  If a
1225  * change adds a fully backwards compatible change (eg, LVB changes that
1226  * are just ignored by older versions), the version does not need to be
1227  * updated.
1228  */
1229 static struct ocfs2_locking_protocol lproto = {
1230         .lp_max_version = {
1231                 .pv_major = OCFS2_LOCKING_PROTOCOL_MAJOR,
1232                 .pv_minor = OCFS2_LOCKING_PROTOCOL_MINOR,
1233         },
1234         .lp_lock_ast            = ocfs2_locking_ast,
1235         .lp_blocking_ast        = ocfs2_blocking_ast,
1236         .lp_unlock_ast          = ocfs2_unlock_ast,
1237 };
1238
1239 void ocfs2_set_locking_protocol(void)
1240 {
1241         ocfs2_stack_glue_set_max_proto_version(&lproto.lp_max_version);
1242 }
1243
1244 static inline void ocfs2_recover_from_dlm_error(struct ocfs2_lock_res *lockres,
1245                                                 int convert)
1246 {
1247         unsigned long flags;
1248
1249         spin_lock_irqsave(&lockres->l_lock, flags);
1250         lockres_clear_flags(lockres, OCFS2_LOCK_BUSY);
1251         lockres_clear_flags(lockres, OCFS2_LOCK_UPCONVERT_FINISHING);
1252         if (convert)
1253                 lockres->l_action = OCFS2_AST_INVALID;
1254         else
1255                 lockres->l_unlock_action = OCFS2_UNLOCK_INVALID;
1256         spin_unlock_irqrestore(&lockres->l_lock, flags);
1257
1258         wake_up(&lockres->l_event);
1259 }
1260
1261 /* Note: If we detect another process working on the lock (i.e.,
1262  * OCFS2_LOCK_BUSY), we'll bail out returning 0. It's up to the caller
1263  * to do the right thing in that case.
1264  */
1265 static int ocfs2_lock_create(struct ocfs2_super *osb,
1266                              struct ocfs2_lock_res *lockres,
1267                              int level,
1268                              u32 dlm_flags)
1269 {
1270         int ret = 0;
1271         unsigned long flags;
1272         unsigned int gen;
1273
1274         mlog(0, "lock %s, level = %d, flags = %u\n", lockres->l_name, level,
1275              dlm_flags);
1276
1277         spin_lock_irqsave(&lockres->l_lock, flags);
1278         if ((lockres->l_flags & OCFS2_LOCK_ATTACHED) ||
1279             (lockres->l_flags & OCFS2_LOCK_BUSY)) {
1280                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1281                 goto bail;
1282         }
1283
1284         lockres->l_action = OCFS2_AST_ATTACH;
1285         lockres->l_requested = level;
1286         lockres_or_flags(lockres, OCFS2_LOCK_BUSY);
1287         gen = lockres_set_pending(lockres);
1288         spin_unlock_irqrestore(&lockres->l_lock, flags);
1289
1290         ret = ocfs2_dlm_lock(osb->cconn,
1291                              level,
1292                              &lockres->l_lksb,
1293                              dlm_flags,
1294                              lockres->l_name,
1295                              OCFS2_LOCK_ID_MAX_LEN - 1);
1296         lockres_clear_pending(lockres, gen, osb);
1297         if (ret) {
1298                 ocfs2_log_dlm_error("ocfs2_dlm_lock", ret, lockres);
1299                 ocfs2_recover_from_dlm_error(lockres, 1);
1300         }
1301
1302         mlog(0, "lock %s, return from ocfs2_dlm_lock\n", lockres->l_name);
1303
1304 bail:
1305         return ret;
1306 }
1307
1308 static inline int ocfs2_check_wait_flag(struct ocfs2_lock_res *lockres,
1309                                         int flag)
1310 {
1311         unsigned long flags;
1312         int ret;
1313
1314         spin_lock_irqsave(&lockres->l_lock, flags);
1315         ret = lockres->l_flags & flag;
1316         spin_unlock_irqrestore(&lockres->l_lock, flags);
1317
1318         return ret;
1319 }
1320
1321 static inline void ocfs2_wait_on_busy_lock(struct ocfs2_lock_res *lockres)
1322
1323 {
1324         wait_event(lockres->l_event,
1325                    !ocfs2_check_wait_flag(lockres, OCFS2_LOCK_BUSY));
1326 }
1327
1328 static inline void ocfs2_wait_on_refreshing_lock(struct ocfs2_lock_res *lockres)
1329
1330 {
1331         wait_event(lockres->l_event,
1332                    !ocfs2_check_wait_flag(lockres, OCFS2_LOCK_REFRESHING));
1333 }
1334
1335 /* predict what lock level we'll be dropping down to on behalf
1336  * of another node, and return true if the currently wanted
1337  * level will be compatible with it. */
1338 static inline int ocfs2_may_continue_on_blocked_lock(struct ocfs2_lock_res *lockres,
1339                                                      int wanted)
1340 {
1341         BUG_ON(!(lockres->l_flags & OCFS2_LOCK_BLOCKED));
1342
1343         return wanted <= ocfs2_highest_compat_lock_level(lockres->l_blocking);
1344 }
1345
1346 static void ocfs2_init_mask_waiter(struct ocfs2_mask_waiter *mw)
1347 {
1348         INIT_LIST_HEAD(&mw->mw_item);
1349         init_completion(&mw->mw_complete);
1350         ocfs2_init_start_time(mw);
1351 }
1352
1353 static int ocfs2_wait_for_mask(struct ocfs2_mask_waiter *mw)
1354 {
1355         wait_for_completion(&mw->mw_complete);
1356         /* Re-arm the completion in case we want to wait on it again */
1357         reinit_completion(&mw->mw_complete);
1358         return mw->mw_status;
1359 }
1360
1361 static void lockres_add_mask_waiter(struct ocfs2_lock_res *lockres,
1362                                     struct ocfs2_mask_waiter *mw,
1363                                     unsigned long mask,
1364                                     unsigned long goal)
1365 {
1366         BUG_ON(!list_empty(&mw->mw_item));
1367
1368         assert_spin_locked(&lockres->l_lock);
1369
1370         list_add_tail(&mw->mw_item, &lockres->l_mask_waiters);
1371         mw->mw_mask = mask;
1372         mw->mw_goal = goal;
1373 }
1374
1375 /* returns 0 if the mw that was removed was already satisfied, -EBUSY
1376  * if the mask still hadn't reached its goal */
1377 static int __lockres_remove_mask_waiter(struct ocfs2_lock_res *lockres,
1378                                       struct ocfs2_mask_waiter *mw)
1379 {
1380         int ret = 0;
1381
1382         assert_spin_locked(&lockres->l_lock);
1383         if (!list_empty(&mw->mw_item)) {
1384                 if ((lockres->l_flags & mw->mw_mask) != mw->mw_goal)
1385                         ret = -EBUSY;
1386
1387                 list_del_init(&mw->mw_item);
1388                 init_completion(&mw->mw_complete);
1389         }
1390
1391         return ret;
1392 }
1393
1394 static int lockres_remove_mask_waiter(struct ocfs2_lock_res *lockres,
1395                                       struct ocfs2_mask_waiter *mw)
1396 {
1397         unsigned long flags;
1398         int ret = 0;
1399
1400         spin_lock_irqsave(&lockres->l_lock, flags);
1401         ret = __lockres_remove_mask_waiter(lockres, mw);
1402         spin_unlock_irqrestore(&lockres->l_lock, flags);
1403
1404         return ret;
1405
1406 }
1407
1408 static int ocfs2_wait_for_mask_interruptible(struct ocfs2_mask_waiter *mw,
1409                                              struct ocfs2_lock_res *lockres)
1410 {
1411         int ret;
1412
1413         ret = wait_for_completion_interruptible(&mw->mw_complete);
1414         if (ret)
1415                 lockres_remove_mask_waiter(lockres, mw);
1416         else
1417                 ret = mw->mw_status;
1418         /* Re-arm the completion in case we want to wait on it again */
1419         reinit_completion(&mw->mw_complete);
1420         return ret;
1421 }
1422
1423 static int __ocfs2_cluster_lock(struct ocfs2_super *osb,
1424                                 struct ocfs2_lock_res *lockres,
1425                                 int level,
1426                                 u32 lkm_flags,
1427                                 int arg_flags,
1428                                 int l_subclass,
1429                                 unsigned long caller_ip)
1430 {
1431         struct ocfs2_mask_waiter mw;
1432         int wait, catch_signals = !(osb->s_mount_opt & OCFS2_MOUNT_NOINTR);
1433         int ret = 0; /* gcc doesn't realize wait = 1 guarantees ret is set */
1434         unsigned long flags;
1435         unsigned int gen;
1436         int noqueue_attempted = 0;
1437         int dlm_locked = 0;
1438         int kick_dc = 0;
1439
1440         if (!(lockres->l_flags & OCFS2_LOCK_INITIALIZED)) {
1441                 mlog_errno(-EINVAL);
1442                 return -EINVAL;
1443         }
1444
1445         ocfs2_init_mask_waiter(&mw);
1446
1447         if (lockres->l_ops->flags & LOCK_TYPE_USES_LVB)
1448                 lkm_flags |= DLM_LKF_VALBLK;
1449
1450 again:
1451         wait = 0;
1452
1453         spin_lock_irqsave(&lockres->l_lock, flags);
1454
1455         if (catch_signals && signal_pending(current)) {
1456                 ret = -ERESTARTSYS;
1457                 goto unlock;
1458         }
1459
1460         mlog_bug_on_msg(lockres->l_flags & OCFS2_LOCK_FREEING,
1461                         "Cluster lock called on freeing lockres %s! flags "
1462                         "0x%lx\n", lockres->l_name, lockres->l_flags);
1463
1464         /* We only compare against the currently granted level
1465          * here. If the lock is blocked waiting on a downconvert,
1466          * we'll get caught below. */
1467         if (lockres->l_flags & OCFS2_LOCK_BUSY &&
1468             level > lockres->l_level) {
1469                 /* is someone sitting in dlm_lock? If so, wait on
1470                  * them. */
1471                 lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BUSY, 0);
1472                 wait = 1;
1473                 goto unlock;
1474         }
1475
1476         if (lockres->l_flags & OCFS2_LOCK_UPCONVERT_FINISHING) {
1477                 /*
1478                  * We've upconverted. If the lock now has a level we can
1479                  * work with, we take it. If, however, the lock is not at the
1480                  * required level, we go thru the full cycle. One way this could
1481                  * happen is if a process requesting an upconvert to PR is
1482                  * closely followed by another requesting upconvert to an EX.
1483                  * If the process requesting EX lands here, we want it to
1484                  * continue attempting to upconvert and let the process
1485                  * requesting PR take the lock.
1486                  * If multiple processes request upconvert to PR, the first one
1487                  * here will take the lock. The others will have to go thru the
1488                  * OCFS2_LOCK_BLOCKED check to ensure that there is no pending
1489                  * downconvert request.
1490                  */
1491                 if (level <= lockres->l_level)
1492                         goto update_holders;
1493         }
1494
1495         if (lockres->l_flags & OCFS2_LOCK_BLOCKED &&
1496             !ocfs2_may_continue_on_blocked_lock(lockres, level)) {
1497                 /* is the lock is currently blocked on behalf of
1498                  * another node */
1499                 lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BLOCKED, 0);
1500                 wait = 1;
1501                 goto unlock;
1502         }
1503
1504         if (level > lockres->l_level) {
1505                 if (noqueue_attempted > 0) {
1506                         ret = -EAGAIN;
1507                         goto unlock;
1508                 }
1509                 if (lkm_flags & DLM_LKF_NOQUEUE)
1510                         noqueue_attempted = 1;
1511
1512                 if (lockres->l_action != OCFS2_AST_INVALID)
1513                         mlog(ML_ERROR, "lockres %s has action %u pending\n",
1514                              lockres->l_name, lockres->l_action);
1515
1516                 if (!(lockres->l_flags & OCFS2_LOCK_ATTACHED)) {
1517                         lockres->l_action = OCFS2_AST_ATTACH;
1518                         lkm_flags &= ~DLM_LKF_CONVERT;
1519                 } else {
1520                         lockres->l_action = OCFS2_AST_CONVERT;
1521                         lkm_flags |= DLM_LKF_CONVERT;
1522                 }
1523
1524                 lockres->l_requested = level;
1525                 lockres_or_flags(lockres, OCFS2_LOCK_BUSY);
1526                 gen = lockres_set_pending(lockres);
1527                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1528
1529                 BUG_ON(level == DLM_LOCK_IV);
1530                 BUG_ON(level == DLM_LOCK_NL);
1531
1532                 mlog(ML_BASTS, "lockres %s, convert from %d to %d\n",
1533                      lockres->l_name, lockres->l_level, level);
1534
1535                 /* call dlm_lock to upgrade lock now */
1536                 ret = ocfs2_dlm_lock(osb->cconn,
1537                                      level,
1538                                      &lockres->l_lksb,
1539                                      lkm_flags,
1540                                      lockres->l_name,
1541                                      OCFS2_LOCK_ID_MAX_LEN - 1);
1542                 lockres_clear_pending(lockres, gen, osb);
1543                 if (ret) {
1544                         if (!(lkm_flags & DLM_LKF_NOQUEUE) ||
1545                             (ret != -EAGAIN)) {
1546                                 ocfs2_log_dlm_error("ocfs2_dlm_lock",
1547                                                     ret, lockres);
1548                         }
1549                         ocfs2_recover_from_dlm_error(lockres, 1);
1550                         goto out;
1551                 }
1552                 dlm_locked = 1;
1553
1554                 mlog(0, "lock %s, successful return from ocfs2_dlm_lock\n",
1555                      lockres->l_name);
1556
1557                 /* At this point we've gone inside the dlm and need to
1558                  * complete our work regardless. */
1559                 catch_signals = 0;
1560
1561                 /* wait for busy to clear and carry on */
1562                 goto again;
1563         }
1564
1565 update_holders:
1566         /* Ok, if we get here then we're good to go. */
1567         ocfs2_inc_holders(lockres, level);
1568
1569         ret = 0;
1570 unlock:
1571         lockres_clear_flags(lockres, OCFS2_LOCK_UPCONVERT_FINISHING);
1572
1573         /* ocfs2_unblock_lock reques on seeing OCFS2_LOCK_UPCONVERT_FINISHING */
1574         kick_dc = (lockres->l_flags & OCFS2_LOCK_BLOCKED);
1575
1576         spin_unlock_irqrestore(&lockres->l_lock, flags);
1577         if (kick_dc)
1578                 ocfs2_wake_downconvert_thread(osb);
1579 out:
1580         /*
1581          * This is helping work around a lock inversion between the page lock
1582          * and dlm locks.  One path holds the page lock while calling aops
1583          * which block acquiring dlm locks.  The voting thread holds dlm
1584          * locks while acquiring page locks while down converting data locks.
1585          * This block is helping an aop path notice the inversion and back
1586          * off to unlock its page lock before trying the dlm lock again.
1587          */
1588         if (wait && arg_flags & OCFS2_LOCK_NONBLOCK &&
1589             mw.mw_mask & (OCFS2_LOCK_BUSY|OCFS2_LOCK_BLOCKED)) {
1590                 wait = 0;
1591                 spin_lock_irqsave(&lockres->l_lock, flags);
1592                 if (__lockres_remove_mask_waiter(lockres, &mw)) {
1593                         if (dlm_locked)
1594                                 lockres_or_flags(lockres,
1595                                         OCFS2_LOCK_NONBLOCK_FINISHED);
1596                         spin_unlock_irqrestore(&lockres->l_lock, flags);
1597                         ret = -EAGAIN;
1598                 } else {
1599                         spin_unlock_irqrestore(&lockres->l_lock, flags);
1600                         goto again;
1601                 }
1602         }
1603         if (wait) {
1604                 ret = ocfs2_wait_for_mask(&mw);
1605                 if (ret == 0)
1606                         goto again;
1607                 mlog_errno(ret);
1608         }
1609         ocfs2_update_lock_stats(lockres, level, &mw, ret);
1610
1611 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1612         if (!ret && lockres->l_lockdep_map.key != NULL) {
1613                 if (level == DLM_LOCK_PR)
1614                         rwsem_acquire_read(&lockres->l_lockdep_map, l_subclass,
1615                                 !!(arg_flags & OCFS2_META_LOCK_NOQUEUE),
1616                                 caller_ip);
1617                 else
1618                         rwsem_acquire(&lockres->l_lockdep_map, l_subclass,
1619                                 !!(arg_flags & OCFS2_META_LOCK_NOQUEUE),
1620                                 caller_ip);
1621         }
1622 #endif
1623         return ret;
1624 }
1625
1626 static inline int ocfs2_cluster_lock(struct ocfs2_super *osb,
1627                                      struct ocfs2_lock_res *lockres,
1628                                      int level,
1629                                      u32 lkm_flags,
1630                                      int arg_flags)
1631 {
1632         return __ocfs2_cluster_lock(osb, lockres, level, lkm_flags, arg_flags,
1633                                     0, _RET_IP_);
1634 }
1635
1636
1637 static void __ocfs2_cluster_unlock(struct ocfs2_super *osb,
1638                                    struct ocfs2_lock_res *lockres,
1639                                    int level,
1640                                    unsigned long caller_ip)
1641 {
1642         unsigned long flags;
1643
1644         spin_lock_irqsave(&lockres->l_lock, flags);
1645         ocfs2_dec_holders(lockres, level);
1646         ocfs2_downconvert_on_unlock(osb, lockres);
1647         spin_unlock_irqrestore(&lockres->l_lock, flags);
1648 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1649         if (lockres->l_lockdep_map.key != NULL)
1650                 rwsem_release(&lockres->l_lockdep_map, 1, caller_ip);
1651 #endif
1652 }
1653
1654 static int ocfs2_create_new_lock(struct ocfs2_super *osb,
1655                                  struct ocfs2_lock_res *lockres,
1656                                  int ex,
1657                                  int local)
1658 {
1659         int level =  ex ? DLM_LOCK_EX : DLM_LOCK_PR;
1660         unsigned long flags;
1661         u32 lkm_flags = local ? DLM_LKF_LOCAL : 0;
1662
1663         spin_lock_irqsave(&lockres->l_lock, flags);
1664         BUG_ON(lockres->l_flags & OCFS2_LOCK_ATTACHED);
1665         lockres_or_flags(lockres, OCFS2_LOCK_LOCAL);
1666         spin_unlock_irqrestore(&lockres->l_lock, flags);
1667
1668         return ocfs2_lock_create(osb, lockres, level, lkm_flags);
1669 }
1670
1671 /* Grants us an EX lock on the data and metadata resources, skipping
1672  * the normal cluster directory lookup. Use this ONLY on newly created
1673  * inodes which other nodes can't possibly see, and which haven't been
1674  * hashed in the inode hash yet. This can give us a good performance
1675  * increase as it'll skip the network broadcast normally associated
1676  * with creating a new lock resource. */
1677 int ocfs2_create_new_inode_locks(struct inode *inode)
1678 {
1679         int ret;
1680         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1681
1682         BUG_ON(!inode);
1683         BUG_ON(!ocfs2_inode_is_new(inode));
1684
1685         mlog(0, "Inode %llu\n", (unsigned long long)OCFS2_I(inode)->ip_blkno);
1686
1687         /* NOTE: That we don't increment any of the holder counts, nor
1688          * do we add anything to a journal handle. Since this is
1689          * supposed to be a new inode which the cluster doesn't know
1690          * about yet, there is no need to.  As far as the LVB handling
1691          * is concerned, this is basically like acquiring an EX lock
1692          * on a resource which has an invalid one -- we'll set it
1693          * valid when we release the EX. */
1694
1695         ret = ocfs2_create_new_lock(osb, &OCFS2_I(inode)->ip_rw_lockres, 1, 1);
1696         if (ret) {
1697                 mlog_errno(ret);
1698                 goto bail;
1699         }
1700
1701         /*
1702          * We don't want to use DLM_LKF_LOCAL on a meta data lock as they
1703          * don't use a generation in their lock names.
1704          */
1705         ret = ocfs2_create_new_lock(osb, &OCFS2_I(inode)->ip_inode_lockres, 1, 0);
1706         if (ret) {
1707                 mlog_errno(ret);
1708                 goto bail;
1709         }
1710
1711         ret = ocfs2_create_new_lock(osb, &OCFS2_I(inode)->ip_open_lockres, 0, 0);
1712         if (ret) {
1713                 mlog_errno(ret);
1714                 goto bail;
1715         }
1716
1717 bail:
1718         return ret;
1719 }
1720
1721 int ocfs2_rw_lock(struct inode *inode, int write)
1722 {
1723         int status, level;
1724         struct ocfs2_lock_res *lockres;
1725         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1726
1727         BUG_ON(!inode);
1728
1729         mlog(0, "inode %llu take %s RW lock\n",
1730              (unsigned long long)OCFS2_I(inode)->ip_blkno,
1731              write ? "EXMODE" : "PRMODE");
1732
1733         if (ocfs2_mount_local(osb))
1734                 return 0;
1735
1736         lockres = &OCFS2_I(inode)->ip_rw_lockres;
1737
1738         level = write ? DLM_LOCK_EX : DLM_LOCK_PR;
1739
1740         status = ocfs2_cluster_lock(OCFS2_SB(inode->i_sb), lockres, level, 0,
1741                                     0);
1742         if (status < 0)
1743                 mlog_errno(status);
1744
1745         return status;
1746 }
1747
1748 void ocfs2_rw_unlock(struct inode *inode, int write)
1749 {
1750         int level = write ? DLM_LOCK_EX : DLM_LOCK_PR;
1751         struct ocfs2_lock_res *lockres = &OCFS2_I(inode)->ip_rw_lockres;
1752         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1753
1754         mlog(0, "inode %llu drop %s RW lock\n",
1755              (unsigned long long)OCFS2_I(inode)->ip_blkno,
1756              write ? "EXMODE" : "PRMODE");
1757
1758         if (!ocfs2_mount_local(osb))
1759                 ocfs2_cluster_unlock(OCFS2_SB(inode->i_sb), lockres, level);
1760 }
1761
1762 /*
1763  * ocfs2_open_lock always get PR mode lock.
1764  */
1765 int ocfs2_open_lock(struct inode *inode)
1766 {
1767         int status = 0;
1768         struct ocfs2_lock_res *lockres;
1769         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1770
1771         BUG_ON(!inode);
1772
1773         mlog(0, "inode %llu take PRMODE open lock\n",
1774              (unsigned long long)OCFS2_I(inode)->ip_blkno);
1775
1776         if (ocfs2_is_hard_readonly(osb) || ocfs2_mount_local(osb))
1777                 goto out;
1778
1779         lockres = &OCFS2_I(inode)->ip_open_lockres;
1780
1781         status = ocfs2_cluster_lock(OCFS2_SB(inode->i_sb), lockres,
1782                                     DLM_LOCK_PR, 0, 0);
1783         if (status < 0)
1784                 mlog_errno(status);
1785
1786 out:
1787         return status;
1788 }
1789
1790 int ocfs2_try_open_lock(struct inode *inode, int write)
1791 {
1792         int status = 0, level;
1793         struct ocfs2_lock_res *lockres;
1794         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1795
1796         BUG_ON(!inode);
1797
1798         mlog(0, "inode %llu try to take %s open lock\n",
1799              (unsigned long long)OCFS2_I(inode)->ip_blkno,
1800              write ? "EXMODE" : "PRMODE");
1801
1802         if (ocfs2_is_hard_readonly(osb)) {
1803                 if (write)
1804                         status = -EROFS;
1805                 goto out;
1806         }
1807
1808         if (ocfs2_mount_local(osb))
1809                 goto out;
1810
1811         lockres = &OCFS2_I(inode)->ip_open_lockres;
1812
1813         level = write ? DLM_LOCK_EX : DLM_LOCK_PR;
1814
1815         /*
1816          * The file system may already holding a PRMODE/EXMODE open lock.
1817          * Since we pass DLM_LKF_NOQUEUE, the request won't block waiting on
1818          * other nodes and the -EAGAIN will indicate to the caller that
1819          * this inode is still in use.
1820          */
1821         status = ocfs2_cluster_lock(OCFS2_SB(inode->i_sb), lockres,
1822                                     level, DLM_LKF_NOQUEUE, 0);
1823
1824 out:
1825         return status;
1826 }
1827
1828 /*
1829  * ocfs2_open_unlock unlock PR and EX mode open locks.
1830  */
1831 void ocfs2_open_unlock(struct inode *inode)
1832 {
1833         struct ocfs2_lock_res *lockres = &OCFS2_I(inode)->ip_open_lockres;
1834         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1835
1836         mlog(0, "inode %llu drop open lock\n",
1837              (unsigned long long)OCFS2_I(inode)->ip_blkno);
1838
1839         if (ocfs2_mount_local(osb))
1840                 goto out;
1841
1842         if(lockres->l_ro_holders)
1843                 ocfs2_cluster_unlock(OCFS2_SB(inode->i_sb), lockres,
1844                                      DLM_LOCK_PR);
1845         if(lockres->l_ex_holders)
1846                 ocfs2_cluster_unlock(OCFS2_SB(inode->i_sb), lockres,
1847                                      DLM_LOCK_EX);
1848
1849 out:
1850         return;
1851 }
1852
1853 static int ocfs2_flock_handle_signal(struct ocfs2_lock_res *lockres,
1854                                      int level)
1855 {
1856         int ret;
1857         struct ocfs2_super *osb = ocfs2_get_lockres_osb(lockres);
1858         unsigned long flags;
1859         struct ocfs2_mask_waiter mw;
1860
1861         ocfs2_init_mask_waiter(&mw);
1862
1863 retry_cancel:
1864         spin_lock_irqsave(&lockres->l_lock, flags);
1865         if (lockres->l_flags & OCFS2_LOCK_BUSY) {
1866                 ret = ocfs2_prepare_cancel_convert(osb, lockres);
1867                 if (ret) {
1868                         spin_unlock_irqrestore(&lockres->l_lock, flags);
1869                         ret = ocfs2_cancel_convert(osb, lockres);
1870                         if (ret < 0) {
1871                                 mlog_errno(ret);
1872                                 goto out;
1873                         }
1874                         goto retry_cancel;
1875                 }
1876                 lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BUSY, 0);
1877                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1878
1879                 ocfs2_wait_for_mask(&mw);
1880                 goto retry_cancel;
1881         }
1882
1883         ret = -ERESTARTSYS;
1884         /*
1885          * We may still have gotten the lock, in which case there's no
1886          * point to restarting the syscall.
1887          */
1888         if (lockres->l_level == level)
1889                 ret = 0;
1890
1891         mlog(0, "Cancel returning %d. flags: 0x%lx, level: %d, act: %d\n", ret,
1892              lockres->l_flags, lockres->l_level, lockres->l_action);
1893
1894         spin_unlock_irqrestore(&lockres->l_lock, flags);
1895
1896 out:
1897         return ret;
1898 }
1899
1900 /*
1901  * ocfs2_file_lock() and ocfs2_file_unlock() map to a single pair of
1902  * flock() calls. The locking approach this requires is sufficiently
1903  * different from all other cluster lock types that we implement a
1904  * separate path to the "low-level" dlm calls. In particular:
1905  *
1906  * - No optimization of lock levels is done - we take at exactly
1907  *   what's been requested.
1908  *
1909  * - No lock caching is employed. We immediately downconvert to
1910  *   no-lock at unlock time. This also means flock locks never go on
1911  *   the blocking list).
1912  *
1913  * - Since userspace can trivially deadlock itself with flock, we make
1914  *   sure to allow cancellation of a misbehaving applications flock()
1915  *   request.
1916  *
1917  * - Access to any flock lockres doesn't require concurrency, so we
1918  *   can simplify the code by requiring the caller to guarantee
1919  *   serialization of dlmglue flock calls.
1920  */
1921 int ocfs2_file_lock(struct file *file, int ex, int trylock)
1922 {
1923         int ret, level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
1924         unsigned int lkm_flags = trylock ? DLM_LKF_NOQUEUE : 0;
1925         unsigned long flags;
1926         struct ocfs2_file_private *fp = file->private_data;
1927         struct ocfs2_lock_res *lockres = &fp->fp_flock;
1928         struct ocfs2_super *osb = OCFS2_SB(file->f_mapping->host->i_sb);
1929         struct ocfs2_mask_waiter mw;
1930
1931         ocfs2_init_mask_waiter(&mw);
1932
1933         if ((lockres->l_flags & OCFS2_LOCK_BUSY) ||
1934             (lockres->l_level > DLM_LOCK_NL)) {
1935                 mlog(ML_ERROR,
1936                      "File lock \"%s\" has busy or locked state: flags: 0x%lx, "
1937                      "level: %u\n", lockres->l_name, lockres->l_flags,
1938                      lockres->l_level);
1939                 return -EINVAL;
1940         }
1941
1942         spin_lock_irqsave(&lockres->l_lock, flags);
1943         if (!(lockres->l_flags & OCFS2_LOCK_ATTACHED)) {
1944                 lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BUSY, 0);
1945                 spin_unlock_irqrestore(&lockres->l_lock, flags);
1946
1947                 /*
1948                  * Get the lock at NLMODE to start - that way we
1949                  * can cancel the upconvert request if need be.
1950                  */
1951                 ret = ocfs2_lock_create(osb, lockres, DLM_LOCK_NL, 0);
1952                 if (ret < 0) {
1953                         mlog_errno(ret);
1954                         goto out;
1955                 }
1956
1957                 ret = ocfs2_wait_for_mask(&mw);
1958                 if (ret) {
1959                         mlog_errno(ret);
1960                         goto out;
1961                 }
1962                 spin_lock_irqsave(&lockres->l_lock, flags);
1963         }
1964
1965         lockres->l_action = OCFS2_AST_CONVERT;
1966         lkm_flags |= DLM_LKF_CONVERT;
1967         lockres->l_requested = level;
1968         lockres_or_flags(lockres, OCFS2_LOCK_BUSY);
1969
1970         lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BUSY, 0);
1971         spin_unlock_irqrestore(&lockres->l_lock, flags);
1972
1973         ret = ocfs2_dlm_lock(osb->cconn, level, &lockres->l_lksb, lkm_flags,
1974                              lockres->l_name, OCFS2_LOCK_ID_MAX_LEN - 1);
1975         if (ret) {
1976                 if (!trylock || (ret != -EAGAIN)) {
1977                         ocfs2_log_dlm_error("ocfs2_dlm_lock", ret, lockres);
1978                         ret = -EINVAL;
1979                 }
1980
1981                 ocfs2_recover_from_dlm_error(lockres, 1);
1982                 lockres_remove_mask_waiter(lockres, &mw);
1983                 goto out;
1984         }
1985
1986         ret = ocfs2_wait_for_mask_interruptible(&mw, lockres);
1987         if (ret == -ERESTARTSYS) {
1988                 /*
1989                  * Userspace can cause deadlock itself with
1990                  * flock(). Current behavior locally is to allow the
1991                  * deadlock, but abort the system call if a signal is
1992                  * received. We follow this example, otherwise a
1993                  * poorly written program could sit in kernel until
1994                  * reboot.
1995                  *
1996                  * Handling this is a bit more complicated for Ocfs2
1997                  * though. We can't exit this function with an
1998                  * outstanding lock request, so a cancel convert is
1999                  * required. We intentionally overwrite 'ret' - if the
2000                  * cancel fails and the lock was granted, it's easier
2001                  * to just bubble success back up to the user.
2002                  */
2003                 ret = ocfs2_flock_handle_signal(lockres, level);
2004         } else if (!ret && (level > lockres->l_level)) {
2005                 /* Trylock failed asynchronously */
2006                 BUG_ON(!trylock);
2007                 ret = -EAGAIN;
2008         }
2009
2010 out:
2011
2012         mlog(0, "Lock: \"%s\" ex: %d, trylock: %d, returns: %d\n",
2013              lockres->l_name, ex, trylock, ret);
2014         return ret;
2015 }
2016
2017 void ocfs2_file_unlock(struct file *file)
2018 {
2019         int ret;
2020         unsigned int gen;
2021         unsigned long flags;
2022         struct ocfs2_file_private *fp = file->private_data;
2023         struct ocfs2_lock_res *lockres = &fp->fp_flock;
2024         struct ocfs2_super *osb = OCFS2_SB(file->f_mapping->host->i_sb);
2025         struct ocfs2_mask_waiter mw;
2026
2027         ocfs2_init_mask_waiter(&mw);
2028
2029         if (!(lockres->l_flags & OCFS2_LOCK_ATTACHED))
2030                 return;
2031
2032         if (lockres->l_level == DLM_LOCK_NL)
2033                 return;
2034
2035         mlog(0, "Unlock: \"%s\" flags: 0x%lx, level: %d, act: %d\n",
2036              lockres->l_name, lockres->l_flags, lockres->l_level,
2037              lockres->l_action);
2038
2039         spin_lock_irqsave(&lockres->l_lock, flags);
2040         /*
2041          * Fake a blocking ast for the downconvert code.
2042          */
2043         lockres_or_flags(lockres, OCFS2_LOCK_BLOCKED);
2044         lockres->l_blocking = DLM_LOCK_EX;
2045
2046         gen = ocfs2_prepare_downconvert(lockres, DLM_LOCK_NL);
2047         lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_BUSY, 0);
2048         spin_unlock_irqrestore(&lockres->l_lock, flags);
2049
2050         ret = ocfs2_downconvert_lock(osb, lockres, DLM_LOCK_NL, 0, gen);
2051         if (ret) {
2052                 mlog_errno(ret);
2053                 return;
2054         }
2055
2056         ret = ocfs2_wait_for_mask(&mw);
2057         if (ret)
2058                 mlog_errno(ret);
2059 }
2060
2061 static void ocfs2_downconvert_on_unlock(struct ocfs2_super *osb,
2062                                         struct ocfs2_lock_res *lockres)
2063 {
2064         int kick = 0;
2065
2066         /* If we know that another node is waiting on our lock, kick
2067          * the downconvert thread * pre-emptively when we reach a release
2068          * condition. */
2069         if (lockres->l_flags & OCFS2_LOCK_BLOCKED) {
2070                 switch(lockres->l_blocking) {
2071                 case DLM_LOCK_EX:
2072                         if (!lockres->l_ex_holders && !lockres->l_ro_holders)
2073                                 kick = 1;
2074                         break;
2075                 case DLM_LOCK_PR:
2076                         if (!lockres->l_ex_holders)
2077                                 kick = 1;
2078                         break;
2079                 default:
2080                         BUG();
2081                 }
2082         }
2083
2084         if (kick)
2085                 ocfs2_wake_downconvert_thread(osb);
2086 }
2087
2088 #define OCFS2_SEC_BITS   34
2089 #define OCFS2_SEC_SHIFT  (64 - 34)
2090 #define OCFS2_NSEC_MASK  ((1ULL << OCFS2_SEC_SHIFT) - 1)
2091
2092 /* LVB only has room for 64 bits of time here so we pack it for
2093  * now. */
2094 static u64 ocfs2_pack_timespec(struct timespec *spec)
2095 {
2096         u64 res;
2097         u64 sec = spec->tv_sec;
2098         u32 nsec = spec->tv_nsec;
2099
2100         res = (sec << OCFS2_SEC_SHIFT) | (nsec & OCFS2_NSEC_MASK);
2101
2102         return res;
2103 }
2104
2105 /* Call this with the lockres locked. I am reasonably sure we don't
2106  * need ip_lock in this function as anyone who would be changing those
2107  * values is supposed to be blocked in ocfs2_inode_lock right now. */
2108 static void __ocfs2_stuff_meta_lvb(struct inode *inode)
2109 {
2110         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2111         struct ocfs2_lock_res *lockres = &oi->ip_inode_lockres;
2112         struct ocfs2_meta_lvb *lvb;
2113
2114         lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2115
2116         /*
2117          * Invalidate the LVB of a deleted inode - this way other
2118          * nodes are forced to go to disk and discover the new inode
2119          * status.
2120          */
2121         if (oi->ip_flags & OCFS2_INODE_DELETED) {
2122                 lvb->lvb_version = 0;
2123                 goto out;
2124         }
2125
2126         lvb->lvb_version   = OCFS2_LVB_VERSION;
2127         lvb->lvb_isize     = cpu_to_be64(i_size_read(inode));
2128         lvb->lvb_iclusters = cpu_to_be32(oi->ip_clusters);
2129         lvb->lvb_iuid      = cpu_to_be32(i_uid_read(inode));
2130         lvb->lvb_igid      = cpu_to_be32(i_gid_read(inode));
2131         lvb->lvb_imode     = cpu_to_be16(inode->i_mode);
2132         lvb->lvb_inlink    = cpu_to_be16(inode->i_nlink);
2133         lvb->lvb_iatime_packed  =
2134                 cpu_to_be64(ocfs2_pack_timespec(&inode->i_atime));
2135         lvb->lvb_ictime_packed =
2136                 cpu_to_be64(ocfs2_pack_timespec(&inode->i_ctime));
2137         lvb->lvb_imtime_packed =
2138                 cpu_to_be64(ocfs2_pack_timespec(&inode->i_mtime));
2139         lvb->lvb_iattr    = cpu_to_be32(oi->ip_attr);
2140         lvb->lvb_idynfeatures = cpu_to_be16(oi->ip_dyn_features);
2141         lvb->lvb_igeneration = cpu_to_be32(inode->i_generation);
2142
2143 out:
2144         mlog_meta_lvb(0, lockres);
2145 }
2146
2147 static void ocfs2_unpack_timespec(struct timespec *spec,
2148                                   u64 packed_time)
2149 {
2150         spec->tv_sec = packed_time >> OCFS2_SEC_SHIFT;
2151         spec->tv_nsec = packed_time & OCFS2_NSEC_MASK;
2152 }
2153
2154 static void ocfs2_refresh_inode_from_lvb(struct inode *inode)
2155 {
2156         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2157         struct ocfs2_lock_res *lockres = &oi->ip_inode_lockres;
2158         struct ocfs2_meta_lvb *lvb;
2159
2160         mlog_meta_lvb(0, lockres);
2161
2162         lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2163
2164         /* We're safe here without the lockres lock... */
2165         spin_lock(&oi->ip_lock);
2166         oi->ip_clusters = be32_to_cpu(lvb->lvb_iclusters);
2167         i_size_write(inode, be64_to_cpu(lvb->lvb_isize));
2168
2169         oi->ip_attr = be32_to_cpu(lvb->lvb_iattr);
2170         oi->ip_dyn_features = be16_to_cpu(lvb->lvb_idynfeatures);
2171         ocfs2_set_inode_flags(inode);
2172
2173         /* fast-symlinks are a special case */
2174         if (S_ISLNK(inode->i_mode) && !oi->ip_clusters)
2175                 inode->i_blocks = 0;
2176         else
2177                 inode->i_blocks = ocfs2_inode_sector_count(inode);
2178
2179         i_uid_write(inode, be32_to_cpu(lvb->lvb_iuid));
2180         i_gid_write(inode, be32_to_cpu(lvb->lvb_igid));
2181         inode->i_mode    = be16_to_cpu(lvb->lvb_imode);
2182         set_nlink(inode, be16_to_cpu(lvb->lvb_inlink));
2183         ocfs2_unpack_timespec(&inode->i_atime,
2184                               be64_to_cpu(lvb->lvb_iatime_packed));
2185         ocfs2_unpack_timespec(&inode->i_mtime,
2186                               be64_to_cpu(lvb->lvb_imtime_packed));
2187         ocfs2_unpack_timespec(&inode->i_ctime,
2188                               be64_to_cpu(lvb->lvb_ictime_packed));
2189         spin_unlock(&oi->ip_lock);
2190 }
2191
2192 static inline int ocfs2_meta_lvb_is_trustable(struct inode *inode,
2193                                               struct ocfs2_lock_res *lockres)
2194 {
2195         struct ocfs2_meta_lvb *lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2196
2197         if (ocfs2_dlm_lvb_valid(&lockres->l_lksb)
2198             && lvb->lvb_version == OCFS2_LVB_VERSION
2199             && be32_to_cpu(lvb->lvb_igeneration) == inode->i_generation)
2200                 return 1;
2201         return 0;
2202 }
2203
2204 /* Determine whether a lock resource needs to be refreshed, and
2205  * arbitrate who gets to refresh it.
2206  *
2207  *   0 means no refresh needed.
2208  *
2209  *   > 0 means you need to refresh this and you MUST call
2210  *   ocfs2_complete_lock_res_refresh afterwards. */
2211 static int ocfs2_should_refresh_lock_res(struct ocfs2_lock_res *lockres)
2212 {
2213         unsigned long flags;
2214         int status = 0;
2215
2216 refresh_check:
2217         spin_lock_irqsave(&lockres->l_lock, flags);
2218         if (!(lockres->l_flags & OCFS2_LOCK_NEEDS_REFRESH)) {
2219                 spin_unlock_irqrestore(&lockres->l_lock, flags);
2220                 goto bail;
2221         }
2222
2223         if (lockres->l_flags & OCFS2_LOCK_REFRESHING) {
2224                 spin_unlock_irqrestore(&lockres->l_lock, flags);
2225
2226                 ocfs2_wait_on_refreshing_lock(lockres);
2227                 goto refresh_check;
2228         }
2229
2230         /* Ok, I'll be the one to refresh this lock. */
2231         lockres_or_flags(lockres, OCFS2_LOCK_REFRESHING);
2232         spin_unlock_irqrestore(&lockres->l_lock, flags);
2233
2234         status = 1;
2235 bail:
2236         mlog(0, "status %d\n", status);
2237         return status;
2238 }
2239
2240 /* If status is non zero, I'll mark it as not being in refresh
2241  * anymroe, but i won't clear the needs refresh flag. */
2242 static inline void ocfs2_complete_lock_res_refresh(struct ocfs2_lock_res *lockres,
2243                                                    int status)
2244 {
2245         unsigned long flags;
2246
2247         spin_lock_irqsave(&lockres->l_lock, flags);
2248         lockres_clear_flags(lockres, OCFS2_LOCK_REFRESHING);
2249         if (!status)
2250                 lockres_clear_flags(lockres, OCFS2_LOCK_NEEDS_REFRESH);
2251         spin_unlock_irqrestore(&lockres->l_lock, flags);
2252
2253         wake_up(&lockres->l_event);
2254 }
2255
2256 /* may or may not return a bh if it went to disk. */
2257 static int ocfs2_inode_lock_update(struct inode *inode,
2258                                   struct buffer_head **bh)
2259 {
2260         int status = 0;
2261         struct ocfs2_inode_info *oi = OCFS2_I(inode);
2262         struct ocfs2_lock_res *lockres = &oi->ip_inode_lockres;
2263         struct ocfs2_dinode *fe;
2264         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2265
2266         if (ocfs2_mount_local(osb))
2267                 goto bail;
2268
2269         spin_lock(&oi->ip_lock);
2270         if (oi->ip_flags & OCFS2_INODE_DELETED) {
2271                 mlog(0, "Orphaned inode %llu was deleted while we "
2272                      "were waiting on a lock. ip_flags = 0x%x\n",
2273                      (unsigned long long)oi->ip_blkno, oi->ip_flags);
2274                 spin_unlock(&oi->ip_lock);
2275                 status = -ENOENT;
2276                 goto bail;
2277         }
2278         spin_unlock(&oi->ip_lock);
2279
2280         if (!ocfs2_should_refresh_lock_res(lockres))
2281                 goto bail;
2282
2283         /* This will discard any caching information we might have had
2284          * for the inode metadata. */
2285         ocfs2_metadata_cache_purge(INODE_CACHE(inode));
2286
2287         ocfs2_extent_map_trunc(inode, 0);
2288
2289         if (ocfs2_meta_lvb_is_trustable(inode, lockres)) {
2290                 mlog(0, "Trusting LVB on inode %llu\n",
2291                      (unsigned long long)oi->ip_blkno);
2292                 ocfs2_refresh_inode_from_lvb(inode);
2293         } else {
2294                 /* Boo, we have to go to disk. */
2295                 /* read bh, cast, ocfs2_refresh_inode */
2296                 status = ocfs2_read_inode_block(inode, bh);
2297                 if (status < 0) {
2298                         mlog_errno(status);
2299                         goto bail_refresh;
2300                 }
2301                 fe = (struct ocfs2_dinode *) (*bh)->b_data;
2302
2303                 /* This is a good chance to make sure we're not
2304                  * locking an invalid object.  ocfs2_read_inode_block()
2305                  * already checked that the inode block is sane.
2306                  *
2307                  * We bug on a stale inode here because we checked
2308                  * above whether it was wiped from disk. The wiping
2309                  * node provides a guarantee that we receive that
2310                  * message and can mark the inode before dropping any
2311                  * locks associated with it. */
2312                 mlog_bug_on_msg(inode->i_generation !=
2313                                 le32_to_cpu(fe->i_generation),
2314                                 "Invalid dinode %llu disk generation: %u "
2315                                 "inode->i_generation: %u\n",
2316                                 (unsigned long long)oi->ip_blkno,
2317                                 le32_to_cpu(fe->i_generation),
2318                                 inode->i_generation);
2319                 mlog_bug_on_msg(le64_to_cpu(fe->i_dtime) ||
2320                                 !(fe->i_flags & cpu_to_le32(OCFS2_VALID_FL)),
2321                                 "Stale dinode %llu dtime: %llu flags: 0x%x\n",
2322                                 (unsigned long long)oi->ip_blkno,
2323                                 (unsigned long long)le64_to_cpu(fe->i_dtime),
2324                                 le32_to_cpu(fe->i_flags));
2325
2326                 ocfs2_refresh_inode(inode, fe);
2327                 ocfs2_track_lock_refresh(lockres);
2328         }
2329
2330         status = 0;
2331 bail_refresh:
2332         ocfs2_complete_lock_res_refresh(lockres, status);
2333 bail:
2334         return status;
2335 }
2336
2337 static int ocfs2_assign_bh(struct inode *inode,
2338                            struct buffer_head **ret_bh,
2339                            struct buffer_head *passed_bh)
2340 {
2341         int status;
2342
2343         if (passed_bh) {
2344                 /* Ok, the update went to disk for us, use the
2345                  * returned bh. */
2346                 *ret_bh = passed_bh;
2347                 get_bh(*ret_bh);
2348
2349                 return 0;
2350         }
2351
2352         status = ocfs2_read_inode_block(inode, ret_bh);
2353         if (status < 0)
2354                 mlog_errno(status);
2355
2356         return status;
2357 }
2358
2359 /*
2360  * returns < 0 error if the callback will never be called, otherwise
2361  * the result of the lock will be communicated via the callback.
2362  */
2363 int ocfs2_inode_lock_full_nested(struct inode *inode,
2364                                  struct buffer_head **ret_bh,
2365                                  int ex,
2366                                  int arg_flags,
2367                                  int subclass)
2368 {
2369         int status, level, acquired;
2370         u32 dlm_flags;
2371         struct ocfs2_lock_res *lockres = NULL;
2372         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2373         struct buffer_head *local_bh = NULL;
2374
2375         BUG_ON(!inode);
2376
2377         mlog(0, "inode %llu, take %s META lock\n",
2378              (unsigned long long)OCFS2_I(inode)->ip_blkno,
2379              ex ? "EXMODE" : "PRMODE");
2380
2381         status = 0;
2382         acquired = 0;
2383         /* We'll allow faking a readonly metadata lock for
2384          * rodevices. */
2385         if (ocfs2_is_hard_readonly(osb)) {
2386                 if (ex)
2387                         status = -EROFS;
2388                 goto getbh;
2389         }
2390
2391         if ((arg_flags & OCFS2_META_LOCK_GETBH) ||
2392             ocfs2_mount_local(osb))
2393                 goto update;
2394
2395         if (!(arg_flags & OCFS2_META_LOCK_RECOVERY))
2396                 ocfs2_wait_for_recovery(osb);
2397
2398         lockres = &OCFS2_I(inode)->ip_inode_lockres;
2399         level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2400         dlm_flags = 0;
2401         if (arg_flags & OCFS2_META_LOCK_NOQUEUE)
2402                 dlm_flags |= DLM_LKF_NOQUEUE;
2403
2404         status = __ocfs2_cluster_lock(osb, lockres, level, dlm_flags,
2405                                       arg_flags, subclass, _RET_IP_);
2406         if (status < 0) {
2407                 if (status != -EAGAIN)
2408                         mlog_errno(status);
2409                 goto bail;
2410         }
2411
2412         /* Notify the error cleanup path to drop the cluster lock. */
2413         acquired = 1;
2414
2415         /* We wait twice because a node may have died while we were in
2416          * the lower dlm layers. The second time though, we've
2417          * committed to owning this lock so we don't allow signals to
2418          * abort the operation. */
2419         if (!(arg_flags & OCFS2_META_LOCK_RECOVERY))
2420                 ocfs2_wait_for_recovery(osb);
2421
2422 update:
2423         /*
2424          * We only see this flag if we're being called from
2425          * ocfs2_read_locked_inode(). It means we're locking an inode
2426          * which hasn't been populated yet, so clear the refresh flag
2427          * and let the caller handle it.
2428          */
2429         if (inode->i_state & I_NEW) {
2430                 status = 0;
2431                 if (lockres)
2432                         ocfs2_complete_lock_res_refresh(lockres, 0);
2433                 goto bail;
2434         }
2435
2436         /* This is fun. The caller may want a bh back, or it may
2437          * not. ocfs2_inode_lock_update definitely wants one in, but
2438          * may or may not read one, depending on what's in the
2439          * LVB. The result of all of this is that we've *only* gone to
2440          * disk if we have to, so the complexity is worthwhile. */
2441         status = ocfs2_inode_lock_update(inode, &local_bh);
2442         if (status < 0) {
2443                 if (status != -ENOENT)
2444                         mlog_errno(status);
2445                 goto bail;
2446         }
2447 getbh:
2448         if (ret_bh) {
2449                 status = ocfs2_assign_bh(inode, ret_bh, local_bh);
2450                 if (status < 0) {
2451                         mlog_errno(status);
2452                         goto bail;
2453                 }
2454         }
2455
2456 bail:
2457         if (status < 0) {
2458                 if (ret_bh && (*ret_bh)) {
2459                         brelse(*ret_bh);
2460                         *ret_bh = NULL;
2461                 }
2462                 if (acquired)
2463                         ocfs2_inode_unlock(inode, ex);
2464         }
2465
2466         if (local_bh)
2467                 brelse(local_bh);
2468
2469         return status;
2470 }
2471
2472 /*
2473  * This is working around a lock inversion between tasks acquiring DLM
2474  * locks while holding a page lock and the downconvert thread which
2475  * blocks dlm lock acquiry while acquiring page locks.
2476  *
2477  * ** These _with_page variantes are only intended to be called from aop
2478  * methods that hold page locks and return a very specific *positive* error
2479  * code that aop methods pass up to the VFS -- test for errors with != 0. **
2480  *
2481  * The DLM is called such that it returns -EAGAIN if it would have
2482  * blocked waiting for the downconvert thread.  In that case we unlock
2483  * our page so the downconvert thread can make progress.  Once we've
2484  * done this we have to return AOP_TRUNCATED_PAGE so the aop method
2485  * that called us can bubble that back up into the VFS who will then
2486  * immediately retry the aop call.
2487  *
2488  * We do a blocking lock and immediate unlock before returning, though, so that
2489  * the lock has a great chance of being cached on this node by the time the VFS
2490  * calls back to retry the aop.    This has a potential to livelock as nodes
2491  * ping locks back and forth, but that's a risk we're willing to take to avoid
2492  * the lock inversion simply.
2493  */
2494 int ocfs2_inode_lock_with_page(struct inode *inode,
2495                               struct buffer_head **ret_bh,
2496                               int ex,
2497                               struct page *page)
2498 {
2499         int ret;
2500
2501         ret = ocfs2_inode_lock_full(inode, ret_bh, ex, OCFS2_LOCK_NONBLOCK);
2502         if (ret == -EAGAIN) {
2503                 unlock_page(page);
2504                 if (ocfs2_inode_lock(inode, ret_bh, ex) == 0)
2505                         ocfs2_inode_unlock(inode, ex);
2506                 ret = AOP_TRUNCATED_PAGE;
2507         }
2508
2509         return ret;
2510 }
2511
2512 int ocfs2_inode_lock_atime(struct inode *inode,
2513                           struct vfsmount *vfsmnt,
2514                           int *level)
2515 {
2516         int ret;
2517
2518         ret = ocfs2_inode_lock(inode, NULL, 0);
2519         if (ret < 0) {
2520                 mlog_errno(ret);
2521                 return ret;
2522         }
2523
2524         /*
2525          * If we should update atime, we will get EX lock,
2526          * otherwise we just get PR lock.
2527          */
2528         if (ocfs2_should_update_atime(inode, vfsmnt)) {
2529                 struct buffer_head *bh = NULL;
2530
2531                 ocfs2_inode_unlock(inode, 0);
2532                 ret = ocfs2_inode_lock(inode, &bh, 1);
2533                 if (ret < 0) {
2534                         mlog_errno(ret);
2535                         return ret;
2536                 }
2537                 *level = 1;
2538                 if (ocfs2_should_update_atime(inode, vfsmnt))
2539                         ocfs2_update_inode_atime(inode, bh);
2540                 if (bh)
2541                         brelse(bh);
2542         } else
2543                 *level = 0;
2544
2545         return ret;
2546 }
2547
2548 void ocfs2_inode_unlock(struct inode *inode,
2549                        int ex)
2550 {
2551         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2552         struct ocfs2_lock_res *lockres = &OCFS2_I(inode)->ip_inode_lockres;
2553         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2554
2555         mlog(0, "inode %llu drop %s META lock\n",
2556              (unsigned long long)OCFS2_I(inode)->ip_blkno,
2557              ex ? "EXMODE" : "PRMODE");
2558
2559         if (!ocfs2_is_hard_readonly(OCFS2_SB(inode->i_sb)) &&
2560             !ocfs2_mount_local(osb))
2561                 ocfs2_cluster_unlock(OCFS2_SB(inode->i_sb), lockres, level);
2562 }
2563
2564 /*
2565  * This _tracker variantes are introduced to deal with the recursive cluster
2566  * locking issue. The idea is to keep track of a lock holder on the stack of
2567  * the current process. If there's a lock holder on the stack, we know the
2568  * task context is already protected by cluster locking. Currently, they're
2569  * used in some VFS entry routines.
2570  *
2571  * return < 0 on error, return == 0 if there's no lock holder on the stack
2572  * before this call, return == 1 if this call would be a recursive locking.
2573  */
2574 int ocfs2_inode_lock_tracker(struct inode *inode,
2575                              struct buffer_head **ret_bh,
2576                              int ex,
2577                              struct ocfs2_lock_holder *oh)
2578 {
2579         int status;
2580         int arg_flags = 0, has_locked;
2581         struct ocfs2_lock_res *lockres;
2582
2583         lockres = &OCFS2_I(inode)->ip_inode_lockres;
2584         has_locked = ocfs2_is_locked_by_me(lockres);
2585         /* Just get buffer head if the cluster lock has been taken */
2586         if (has_locked)
2587                 arg_flags = OCFS2_META_LOCK_GETBH;
2588
2589         if (likely(!has_locked || ret_bh)) {
2590                 status = ocfs2_inode_lock_full(inode, ret_bh, ex, arg_flags);
2591                 if (status < 0) {
2592                         if (status != -ENOENT)
2593                                 mlog_errno(status);
2594                         return status;
2595                 }
2596         }
2597         if (!has_locked)
2598                 ocfs2_add_holder(lockres, oh);
2599
2600         return has_locked;
2601 }
2602
2603 void ocfs2_inode_unlock_tracker(struct inode *inode,
2604                                 int ex,
2605                                 struct ocfs2_lock_holder *oh,
2606                                 int had_lock)
2607 {
2608         struct ocfs2_lock_res *lockres;
2609
2610         lockres = &OCFS2_I(inode)->ip_inode_lockres;
2611         if (!had_lock) {
2612                 ocfs2_remove_holder(lockres, oh);
2613                 ocfs2_inode_unlock(inode, ex);
2614         }
2615 }
2616
2617 int ocfs2_orphan_scan_lock(struct ocfs2_super *osb, u32 *seqno)
2618 {
2619         struct ocfs2_lock_res *lockres;
2620         struct ocfs2_orphan_scan_lvb *lvb;
2621         int status = 0;
2622
2623         if (ocfs2_is_hard_readonly(osb))
2624                 return -EROFS;
2625
2626         if (ocfs2_mount_local(osb))
2627                 return 0;
2628
2629         lockres = &osb->osb_orphan_scan.os_lockres;
2630         status = ocfs2_cluster_lock(osb, lockres, DLM_LOCK_EX, 0, 0);
2631         if (status < 0)
2632                 return status;
2633
2634         lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2635         if (ocfs2_dlm_lvb_valid(&lockres->l_lksb) &&
2636             lvb->lvb_version == OCFS2_ORPHAN_LVB_VERSION)
2637                 *seqno = be32_to_cpu(lvb->lvb_os_seqno);
2638         else
2639                 *seqno = osb->osb_orphan_scan.os_seqno + 1;
2640
2641         return status;
2642 }
2643
2644 void ocfs2_orphan_scan_unlock(struct ocfs2_super *osb, u32 seqno)
2645 {
2646         struct ocfs2_lock_res *lockres;
2647         struct ocfs2_orphan_scan_lvb *lvb;
2648
2649         if (!ocfs2_is_hard_readonly(osb) && !ocfs2_mount_local(osb)) {
2650                 lockres = &osb->osb_orphan_scan.os_lockres;
2651                 lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2652                 lvb->lvb_version = OCFS2_ORPHAN_LVB_VERSION;
2653                 lvb->lvb_os_seqno = cpu_to_be32(seqno);
2654                 ocfs2_cluster_unlock(osb, lockres, DLM_LOCK_EX);
2655         }
2656 }
2657
2658 int ocfs2_super_lock(struct ocfs2_super *osb,
2659                      int ex)
2660 {
2661         int status = 0;
2662         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2663         struct ocfs2_lock_res *lockres = &osb->osb_super_lockres;
2664
2665         if (ocfs2_is_hard_readonly(osb))
2666                 return -EROFS;
2667
2668         if (ocfs2_mount_local(osb))
2669                 goto bail;
2670
2671         status = ocfs2_cluster_lock(osb, lockres, level, 0, 0);
2672         if (status < 0) {
2673                 mlog_errno(status);
2674                 goto bail;
2675         }
2676
2677         /* The super block lock path is really in the best position to
2678          * know when resources covered by the lock need to be
2679          * refreshed, so we do it here. Of course, making sense of
2680          * everything is up to the caller :) */
2681         status = ocfs2_should_refresh_lock_res(lockres);
2682         if (status) {
2683                 status = ocfs2_refresh_slot_info(osb);
2684
2685                 ocfs2_complete_lock_res_refresh(lockres, status);
2686
2687                 if (status < 0) {
2688                         ocfs2_cluster_unlock(osb, lockres, level);
2689                         mlog_errno(status);
2690                 }
2691                 ocfs2_track_lock_refresh(lockres);
2692         }
2693 bail:
2694         return status;
2695 }
2696
2697 void ocfs2_super_unlock(struct ocfs2_super *osb,
2698                         int ex)
2699 {
2700         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2701         struct ocfs2_lock_res *lockres = &osb->osb_super_lockres;
2702
2703         if (!ocfs2_mount_local(osb))
2704                 ocfs2_cluster_unlock(osb, lockres, level);
2705 }
2706
2707 int ocfs2_rename_lock(struct ocfs2_super *osb)
2708 {
2709         int status;
2710         struct ocfs2_lock_res *lockres = &osb->osb_rename_lockres;
2711
2712         if (ocfs2_is_hard_readonly(osb))
2713                 return -EROFS;
2714
2715         if (ocfs2_mount_local(osb))
2716                 return 0;
2717
2718         status = ocfs2_cluster_lock(osb, lockres, DLM_LOCK_EX, 0, 0);
2719         if (status < 0)
2720                 mlog_errno(status);
2721
2722         return status;
2723 }
2724
2725 void ocfs2_rename_unlock(struct ocfs2_super *osb)
2726 {
2727         struct ocfs2_lock_res *lockres = &osb->osb_rename_lockres;
2728
2729         if (!ocfs2_mount_local(osb))
2730                 ocfs2_cluster_unlock(osb, lockres, DLM_LOCK_EX);
2731 }
2732
2733 int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex)
2734 {
2735         int status;
2736         struct ocfs2_lock_res *lockres = &osb->osb_nfs_sync_lockres;
2737
2738         if (ocfs2_is_hard_readonly(osb))
2739                 return -EROFS;
2740
2741         if (ocfs2_mount_local(osb))
2742                 return 0;
2743
2744         status = ocfs2_cluster_lock(osb, lockres, ex ? LKM_EXMODE : LKM_PRMODE,
2745                                     0, 0);
2746         if (status < 0)
2747                 mlog(ML_ERROR, "lock on nfs sync lock failed %d\n", status);
2748
2749         return status;
2750 }
2751
2752 void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex)
2753 {
2754         struct ocfs2_lock_res *lockres = &osb->osb_nfs_sync_lockres;
2755
2756         if (!ocfs2_mount_local(osb))
2757                 ocfs2_cluster_unlock(osb, lockres,
2758                                      ex ? LKM_EXMODE : LKM_PRMODE);
2759 }
2760
2761 int ocfs2_dentry_lock(struct dentry *dentry, int ex)
2762 {
2763         int ret;
2764         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2765         struct ocfs2_dentry_lock *dl = dentry->d_fsdata;
2766         struct ocfs2_super *osb = OCFS2_SB(dentry->d_sb);
2767
2768         BUG_ON(!dl);
2769
2770         if (ocfs2_is_hard_readonly(osb)) {
2771                 if (ex)
2772                         return -EROFS;
2773                 return 0;
2774         }
2775
2776         if (ocfs2_mount_local(osb))
2777                 return 0;
2778
2779         ret = ocfs2_cluster_lock(osb, &dl->dl_lockres, level, 0, 0);
2780         if (ret < 0)
2781                 mlog_errno(ret);
2782
2783         return ret;
2784 }
2785
2786 void ocfs2_dentry_unlock(struct dentry *dentry, int ex)
2787 {
2788         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
2789         struct ocfs2_dentry_lock *dl = dentry->d_fsdata;
2790         struct ocfs2_super *osb = OCFS2_SB(dentry->d_sb);
2791
2792         if (!ocfs2_is_hard_readonly(osb) && !ocfs2_mount_local(osb))
2793                 ocfs2_cluster_unlock(osb, &dl->dl_lockres, level);
2794 }
2795
2796 /* Reference counting of the dlm debug structure. We want this because
2797  * open references on the debug inodes can live on after a mount, so
2798  * we can't rely on the ocfs2_super to always exist. */
2799 static void ocfs2_dlm_debug_free(struct kref *kref)
2800 {
2801         struct ocfs2_dlm_debug *dlm_debug;
2802
2803         dlm_debug = container_of(kref, struct ocfs2_dlm_debug, d_refcnt);
2804
2805         kfree(dlm_debug);
2806 }
2807
2808 void ocfs2_put_dlm_debug(struct ocfs2_dlm_debug *dlm_debug)
2809 {
2810         if (dlm_debug)
2811                 kref_put(&dlm_debug->d_refcnt, ocfs2_dlm_debug_free);
2812 }
2813
2814 static void ocfs2_get_dlm_debug(struct ocfs2_dlm_debug *debug)
2815 {
2816         kref_get(&debug->d_refcnt);
2817 }
2818
2819 struct ocfs2_dlm_debug *ocfs2_new_dlm_debug(void)
2820 {
2821         struct ocfs2_dlm_debug *dlm_debug;
2822
2823         dlm_debug = kmalloc(sizeof(struct ocfs2_dlm_debug), GFP_KERNEL);
2824         if (!dlm_debug) {
2825                 mlog_errno(-ENOMEM);
2826                 goto out;
2827         }
2828
2829         kref_init(&dlm_debug->d_refcnt);
2830         INIT_LIST_HEAD(&dlm_debug->d_lockres_tracking);
2831         dlm_debug->d_locking_state = NULL;
2832 out:
2833         return dlm_debug;
2834 }
2835
2836 /* Access to this is arbitrated for us via seq_file->sem. */
2837 struct ocfs2_dlm_seq_priv {
2838         struct ocfs2_dlm_debug *p_dlm_debug;
2839         struct ocfs2_lock_res p_iter_res;
2840         struct ocfs2_lock_res p_tmp_res;
2841 };
2842
2843 static struct ocfs2_lock_res *ocfs2_dlm_next_res(struct ocfs2_lock_res *start,
2844                                                  struct ocfs2_dlm_seq_priv *priv)
2845 {
2846         struct ocfs2_lock_res *iter, *ret = NULL;
2847         struct ocfs2_dlm_debug *dlm_debug = priv->p_dlm_debug;
2848
2849         assert_spin_locked(&ocfs2_dlm_tracking_lock);
2850
2851         list_for_each_entry(iter, &start->l_debug_list, l_debug_list) {
2852                 /* discover the head of the list */
2853                 if (&iter->l_debug_list == &dlm_debug->d_lockres_tracking) {
2854                         mlog(0, "End of list found, %p\n", ret);
2855                         break;
2856                 }
2857
2858                 /* We track our "dummy" iteration lockres' by a NULL
2859                  * l_ops field. */
2860                 if (iter->l_ops != NULL) {
2861                         ret = iter;
2862                         break;
2863                 }
2864         }
2865
2866         return ret;
2867 }
2868
2869 static void *ocfs2_dlm_seq_start(struct seq_file *m, loff_t *pos)
2870 {
2871         struct ocfs2_dlm_seq_priv *priv = m->private;
2872         struct ocfs2_lock_res *iter;
2873
2874         spin_lock(&ocfs2_dlm_tracking_lock);
2875         iter = ocfs2_dlm_next_res(&priv->p_iter_res, priv);
2876         if (iter) {
2877                 /* Since lockres' have the lifetime of their container
2878                  * (which can be inodes, ocfs2_supers, etc) we want to
2879                  * copy this out to a temporary lockres while still
2880                  * under the spinlock. Obviously after this we can't
2881                  * trust any pointers on the copy returned, but that's
2882                  * ok as the information we want isn't typically held
2883                  * in them. */
2884                 priv->p_tmp_res = *iter;
2885                 iter = &priv->p_tmp_res;
2886         }
2887         spin_unlock(&ocfs2_dlm_tracking_lock);
2888
2889         return iter;
2890 }
2891
2892 static void ocfs2_dlm_seq_stop(struct seq_file *m, void *v)
2893 {
2894 }
2895
2896 static void *ocfs2_dlm_seq_next(struct seq_file *m, void *v, loff_t *pos)
2897 {
2898         struct ocfs2_dlm_seq_priv *priv = m->private;
2899         struct ocfs2_lock_res *iter = v;
2900         struct ocfs2_lock_res *dummy = &priv->p_iter_res;
2901
2902         spin_lock(&ocfs2_dlm_tracking_lock);
2903         iter = ocfs2_dlm_next_res(iter, priv);
2904         list_del_init(&dummy->l_debug_list);
2905         if (iter) {
2906                 list_add(&dummy->l_debug_list, &iter->l_debug_list);
2907                 priv->p_tmp_res = *iter;
2908                 iter = &priv->p_tmp_res;
2909         }
2910         spin_unlock(&ocfs2_dlm_tracking_lock);
2911
2912         return iter;
2913 }
2914
2915 /*
2916  * Version is used by debugfs.ocfs2 to determine the format being used
2917  *
2918  * New in version 2
2919  *      - Lock stats printed
2920  * New in version 3
2921  *      - Max time in lock stats is in usecs (instead of nsecs)
2922  */
2923 #define OCFS2_DLM_DEBUG_STR_VERSION 3
2924 static int ocfs2_dlm_seq_show(struct seq_file *m, void *v)
2925 {
2926         int i;
2927         char *lvb;
2928         struct ocfs2_lock_res *lockres = v;
2929
2930         if (!lockres)
2931                 return -EINVAL;
2932
2933         seq_printf(m, "0x%x\t", OCFS2_DLM_DEBUG_STR_VERSION);
2934
2935         if (lockres->l_type == OCFS2_LOCK_TYPE_DENTRY)
2936                 seq_printf(m, "%.*s%08x\t", OCFS2_DENTRY_LOCK_INO_START - 1,
2937                            lockres->l_name,
2938                            (unsigned int)ocfs2_get_dentry_lock_ino(lockres));
2939         else
2940                 seq_printf(m, "%.*s\t", OCFS2_LOCK_ID_MAX_LEN, lockres->l_name);
2941
2942         seq_printf(m, "%d\t"
2943                    "0x%lx\t"
2944                    "0x%x\t"
2945                    "0x%x\t"
2946                    "%u\t"
2947                    "%u\t"
2948                    "%d\t"
2949                    "%d\t",
2950                    lockres->l_level,
2951                    lockres->l_flags,
2952                    lockres->l_action,
2953                    lockres->l_unlock_action,
2954                    lockres->l_ro_holders,
2955                    lockres->l_ex_holders,
2956                    lockres->l_requested,
2957                    lockres->l_blocking);
2958
2959         /* Dump the raw LVB */
2960         lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
2961         for(i = 0; i < DLM_LVB_LEN; i++)
2962                 seq_printf(m, "0x%x\t", lvb[i]);
2963
2964 #ifdef CONFIG_OCFS2_FS_STATS
2965 # define lock_num_prmode(_l)            ((_l)->l_lock_prmode.ls_gets)
2966 # define lock_num_exmode(_l)            ((_l)->l_lock_exmode.ls_gets)
2967 # define lock_num_prmode_failed(_l)     ((_l)->l_lock_prmode.ls_fail)
2968 # define lock_num_exmode_failed(_l)     ((_l)->l_lock_exmode.ls_fail)
2969 # define lock_total_prmode(_l)          ((_l)->l_lock_prmode.ls_total)
2970 # define lock_total_exmode(_l)          ((_l)->l_lock_exmode.ls_total)
2971 # define lock_max_prmode(_l)            ((_l)->l_lock_prmode.ls_max)
2972 # define lock_max_exmode(_l)            ((_l)->l_lock_exmode.ls_max)
2973 # define lock_refresh(_l)               ((_l)->l_lock_refresh)
2974 #else
2975 # define lock_num_prmode(_l)            (0)
2976 # define lock_num_exmode(_l)            (0)
2977 # define lock_num_prmode_failed(_l)     (0)
2978 # define lock_num_exmode_failed(_l)     (0)
2979 # define lock_total_prmode(_l)          (0ULL)
2980 # define lock_total_exmode(_l)          (0ULL)
2981 # define lock_max_prmode(_l)            (0)
2982 # define lock_max_exmode(_l)            (0)
2983 # define lock_refresh(_l)               (0)
2984 #endif
2985         /* The following seq_print was added in version 2 of this output */
2986         seq_printf(m, "%u\t"
2987                    "%u\t"
2988                    "%u\t"
2989                    "%u\t"
2990                    "%llu\t"
2991                    "%llu\t"
2992                    "%u\t"
2993                    "%u\t"
2994                    "%u\t",
2995                    lock_num_prmode(lockres),
2996                    lock_num_exmode(lockres),
2997                    lock_num_prmode_failed(lockres),
2998                    lock_num_exmode_failed(lockres),
2999                    lock_total_prmode(lockres),
3000                    lock_total_exmode(lockres),
3001                    lock_max_prmode(lockres),
3002                    lock_max_exmode(lockres),
3003                    lock_refresh(lockres));
3004
3005         /* End the line */
3006         seq_printf(m, "\n");
3007         return 0;
3008 }
3009
3010 static const struct seq_operations ocfs2_dlm_seq_ops = {
3011         .start =        ocfs2_dlm_seq_start,
3012         .stop =         ocfs2_dlm_seq_stop,
3013         .next =         ocfs2_dlm_seq_next,
3014         .show =         ocfs2_dlm_seq_show,
3015 };
3016
3017 static int ocfs2_dlm_debug_release(struct inode *inode, struct file *file)
3018 {
3019         struct seq_file *seq = file->private_data;
3020         struct ocfs2_dlm_seq_priv *priv = seq->private;
3021         struct ocfs2_lock_res *res = &priv->p_iter_res;
3022
3023         ocfs2_remove_lockres_tracking(res);
3024         ocfs2_put_dlm_debug(priv->p_dlm_debug);
3025         return seq_release_private(inode, file);
3026 }
3027
3028 static int ocfs2_dlm_debug_open(struct inode *inode, struct file *file)
3029 {
3030         struct ocfs2_dlm_seq_priv *priv;
3031         struct ocfs2_super *osb;
3032
3033         priv = __seq_open_private(file, &ocfs2_dlm_seq_ops, sizeof(*priv));
3034         if (!priv) {
3035                 mlog_errno(-ENOMEM);
3036                 return -ENOMEM;
3037         }
3038
3039         osb = inode->i_private;
3040         ocfs2_get_dlm_debug(osb->osb_dlm_debug);
3041         priv->p_dlm_debug = osb->osb_dlm_debug;
3042         INIT_LIST_HEAD(&priv->p_iter_res.l_debug_list);
3043
3044         ocfs2_add_lockres_tracking(&priv->p_iter_res,
3045                                    priv->p_dlm_debug);
3046
3047         return 0;
3048 }
3049
3050 static const struct file_operations ocfs2_dlm_debug_fops = {
3051         .open =         ocfs2_dlm_debug_open,
3052         .release =      ocfs2_dlm_debug_release,
3053         .read =         seq_read,
3054         .llseek =       seq_lseek,
3055 };
3056
3057 static int ocfs2_dlm_init_debug(struct ocfs2_super *osb)
3058 {
3059         int ret = 0;
3060         struct ocfs2_dlm_debug *dlm_debug = osb->osb_dlm_debug;
3061
3062         dlm_debug->d_locking_state = debugfs_create_file("locking_state",
3063                                                          S_IFREG|S_IRUSR,
3064                                                          osb->osb_debug_root,
3065                                                          osb,
3066                                                          &ocfs2_dlm_debug_fops);
3067         if (!dlm_debug->d_locking_state) {
3068                 ret = -EINVAL;
3069                 mlog(ML_ERROR,
3070                      "Unable to create locking state debugfs file.\n");
3071                 goto out;
3072         }
3073
3074         ocfs2_get_dlm_debug(dlm_debug);
3075 out:
3076         return ret;
3077 }
3078
3079 static void ocfs2_dlm_shutdown_debug(struct ocfs2_super *osb)
3080 {
3081         struct ocfs2_dlm_debug *dlm_debug = osb->osb_dlm_debug;
3082
3083         if (dlm_debug) {
3084                 debugfs_remove(dlm_debug->d_locking_state);
3085                 ocfs2_put_dlm_debug(dlm_debug);
3086         }
3087 }
3088
3089 int ocfs2_dlm_init(struct ocfs2_super *osb)
3090 {
3091         int status = 0;
3092         struct ocfs2_cluster_connection *conn = NULL;
3093
3094         if (ocfs2_mount_local(osb)) {
3095                 osb->node_num = 0;
3096                 goto local;
3097         }
3098
3099         status = ocfs2_dlm_init_debug(osb);
3100         if (status < 0) {
3101                 mlog_errno(status);
3102                 goto bail;
3103         }
3104
3105         /* launch downconvert thread */
3106         osb->dc_task = kthread_run(ocfs2_downconvert_thread, osb, "ocfs2dc-%s",
3107                         osb->uuid_str);
3108         if (IS_ERR(osb->dc_task)) {
3109                 status = PTR_ERR(osb->dc_task);
3110                 osb->dc_task = NULL;
3111                 mlog_errno(status);
3112                 goto bail;
3113         }
3114
3115         /* for now, uuid == domain */
3116         status = ocfs2_cluster_connect(osb->osb_cluster_stack,
3117                                        osb->osb_cluster_name,
3118                                        strlen(osb->osb_cluster_name),
3119                                        osb->uuid_str,
3120                                        strlen(osb->uuid_str),
3121                                        &lproto, ocfs2_do_node_down, osb,
3122                                        &conn);
3123         if (status) {
3124                 mlog_errno(status);
3125                 goto bail;
3126         }
3127
3128         status = ocfs2_cluster_this_node(conn, &osb->node_num);
3129         if (status < 0) {
3130                 mlog_errno(status);
3131                 mlog(ML_ERROR,
3132                      "could not find this host's node number\n");
3133                 ocfs2_cluster_disconnect(conn, 0);
3134                 goto bail;
3135         }
3136
3137 local:
3138         ocfs2_super_lock_res_init(&osb->osb_super_lockres, osb);
3139         ocfs2_rename_lock_res_init(&osb->osb_rename_lockres, osb);
3140         ocfs2_nfs_sync_lock_res_init(&osb->osb_nfs_sync_lockres, osb);
3141         ocfs2_orphan_scan_lock_res_init(&osb->osb_orphan_scan.os_lockres, osb);
3142
3143         osb->cconn = conn;
3144 bail:
3145         if (status < 0) {
3146                 ocfs2_dlm_shutdown_debug(osb);
3147                 if (osb->dc_task)
3148                         kthread_stop(osb->dc_task);
3149         }
3150
3151         return status;
3152 }
3153
3154 void ocfs2_dlm_shutdown(struct ocfs2_super *osb,
3155                         int hangup_pending)
3156 {
3157         ocfs2_drop_osb_locks(osb);
3158
3159         /*
3160          * Now that we have dropped all locks and ocfs2_dismount_volume()
3161          * has disabled recovery, the DLM won't be talking to us.  It's
3162          * safe to tear things down before disconnecting the cluster.
3163          */
3164
3165         if (osb->dc_task) {
3166                 kthread_stop(osb->dc_task);
3167                 osb->dc_task = NULL;
3168         }
3169
3170         ocfs2_lock_res_free(&osb->osb_super_lockres);
3171         ocfs2_lock_res_free(&osb->osb_rename_lockres);
3172         ocfs2_lock_res_free(&osb->osb_nfs_sync_lockres);
3173         ocfs2_lock_res_free(&osb->osb_orphan_scan.os_lockres);
3174
3175         ocfs2_cluster_disconnect(osb->cconn, hangup_pending);
3176         osb->cconn = NULL;
3177
3178         ocfs2_dlm_shutdown_debug(osb);
3179 }
3180
3181 static int ocfs2_drop_lock(struct ocfs2_super *osb,
3182                            struct ocfs2_lock_res *lockres)
3183 {
3184         int ret;
3185         unsigned long flags;
3186         u32 lkm_flags = 0;
3187
3188         /* We didn't get anywhere near actually using this lockres. */
3189         if (!(lockres->l_flags & OCFS2_LOCK_INITIALIZED))
3190                 goto out;
3191
3192         if (lockres->l_ops->flags & LOCK_TYPE_USES_LVB)
3193                 lkm_flags |= DLM_LKF_VALBLK;
3194
3195         spin_lock_irqsave(&lockres->l_lock, flags);
3196
3197         mlog_bug_on_msg(!(lockres->l_flags & OCFS2_LOCK_FREEING),
3198                         "lockres %s, flags 0x%lx\n",
3199                         lockres->l_name, lockres->l_flags);
3200
3201         while (lockres->l_flags & OCFS2_LOCK_BUSY) {
3202                 mlog(0, "waiting on busy lock \"%s\": flags = %lx, action = "
3203                      "%u, unlock_action = %u\n",
3204                      lockres->l_name, lockres->l_flags, lockres->l_action,
3205                      lockres->l_unlock_action);
3206
3207                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3208
3209                 /* XXX: Today we just wait on any busy
3210                  * locks... Perhaps we need to cancel converts in the
3211                  * future? */
3212                 ocfs2_wait_on_busy_lock(lockres);
3213
3214                 spin_lock_irqsave(&lockres->l_lock, flags);
3215         }
3216
3217         if (lockres->l_ops->flags & LOCK_TYPE_USES_LVB) {
3218                 if (lockres->l_flags & OCFS2_LOCK_ATTACHED &&
3219                     lockres->l_level == DLM_LOCK_EX &&
3220                     !(lockres->l_flags & OCFS2_LOCK_NEEDS_REFRESH))
3221                         lockres->l_ops->set_lvb(lockres);
3222         }
3223
3224         if (lockres->l_flags & OCFS2_LOCK_BUSY)
3225                 mlog(ML_ERROR, "destroying busy lock: \"%s\"\n",
3226                      lockres->l_name);
3227         if (lockres->l_flags & OCFS2_LOCK_BLOCKED)
3228                 mlog(0, "destroying blocked lock: \"%s\"\n", lockres->l_name);
3229
3230         if (!(lockres->l_flags & OCFS2_LOCK_ATTACHED)) {
3231                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3232                 goto out;
3233         }
3234
3235         lockres_clear_flags(lockres, OCFS2_LOCK_ATTACHED);
3236
3237         /* make sure we never get here while waiting for an ast to
3238          * fire. */
3239         BUG_ON(lockres->l_action != OCFS2_AST_INVALID);
3240
3241         /* is this necessary? */
3242         lockres_or_flags(lockres, OCFS2_LOCK_BUSY);
3243         lockres->l_unlock_action = OCFS2_UNLOCK_DROP_LOCK;
3244         spin_unlock_irqrestore(&lockres->l_lock, flags);
3245
3246         mlog(0, "lock %s\n", lockres->l_name);
3247
3248         ret = ocfs2_dlm_unlock(osb->cconn, &lockres->l_lksb, lkm_flags);
3249         if (ret) {
3250                 ocfs2_log_dlm_error("ocfs2_dlm_unlock", ret, lockres);
3251                 mlog(ML_ERROR, "lockres flags: %lu\n", lockres->l_flags);
3252                 ocfs2_dlm_dump_lksb(&lockres->l_lksb);
3253                 BUG();
3254         }
3255         mlog(0, "lock %s, successful return from ocfs2_dlm_unlock\n",
3256              lockres->l_name);
3257
3258         ocfs2_wait_on_busy_lock(lockres);
3259 out:
3260         return 0;
3261 }
3262
3263 static void ocfs2_process_blocked_lock(struct ocfs2_super *osb,
3264                                        struct ocfs2_lock_res *lockres);
3265
3266 /* Mark the lockres as being dropped. It will no longer be
3267  * queued if blocking, but we still may have to wait on it
3268  * being dequeued from the downconvert thread before we can consider
3269  * it safe to drop.
3270  *
3271  * You can *not* attempt to call cluster_lock on this lockres anymore. */
3272 void ocfs2_mark_lockres_freeing(struct ocfs2_super *osb,
3273                                 struct ocfs2_lock_res *lockres)
3274 {
3275         int status;
3276         struct ocfs2_mask_waiter mw;
3277         unsigned long flags, flags2;
3278
3279         ocfs2_init_mask_waiter(&mw);
3280
3281         spin_lock_irqsave(&lockres->l_lock, flags);
3282         lockres->l_flags |= OCFS2_LOCK_FREEING;
3283         if (lockres->l_flags & OCFS2_LOCK_QUEUED && current == osb->dc_task) {
3284                 /*
3285                  * We know the downconvert is queued but not in progress
3286                  * because we are the downconvert thread and processing
3287                  * different lock. So we can just remove the lock from the
3288                  * queue. This is not only an optimization but also a way
3289                  * to avoid the following deadlock:
3290                  *   ocfs2_dentry_post_unlock()
3291                  *     ocfs2_dentry_lock_put()
3292                  *       ocfs2_drop_dentry_lock()
3293                  *         iput()
3294                  *           ocfs2_evict_inode()
3295                  *             ocfs2_clear_inode()
3296                  *               ocfs2_mark_lockres_freeing()
3297                  *                 ... blocks waiting for OCFS2_LOCK_QUEUED
3298                  *                 since we are the downconvert thread which
3299                  *                 should clear the flag.
3300                  */
3301                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3302                 spin_lock_irqsave(&osb->dc_task_lock, flags2);
3303                 list_del_init(&lockres->l_blocked_list);
3304                 osb->blocked_lock_count--;
3305                 spin_unlock_irqrestore(&osb->dc_task_lock, flags2);
3306                 /*
3307                  * Warn if we recurse into another post_unlock call.  Strictly
3308                  * speaking it isn't a problem but we need to be careful if
3309                  * that happens (stack overflow, deadlocks, ...) so warn if
3310                  * ocfs2 grows a path for which this can happen.
3311                  */
3312                 WARN_ON_ONCE(lockres->l_ops->post_unlock);
3313                 /* Since the lock is freeing we don't do much in the fn below */
3314                 ocfs2_process_blocked_lock(osb, lockres);
3315                 return;
3316         }
3317         while (lockres->l_flags & OCFS2_LOCK_QUEUED) {
3318                 lockres_add_mask_waiter(lockres, &mw, OCFS2_LOCK_QUEUED, 0);
3319                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3320
3321                 mlog(0, "Waiting on lockres %s\n", lockres->l_name);
3322
3323                 status = ocfs2_wait_for_mask(&mw);
3324                 if (status)
3325                         mlog_errno(status);
3326
3327                 spin_lock_irqsave(&lockres->l_lock, flags);
3328         }
3329         spin_unlock_irqrestore(&lockres->l_lock, flags);
3330 }
3331
3332 void ocfs2_simple_drop_lockres(struct ocfs2_super *osb,
3333                                struct ocfs2_lock_res *lockres)
3334 {
3335         int ret;
3336
3337         ocfs2_mark_lockres_freeing(osb, lockres);
3338         ret = ocfs2_drop_lock(osb, lockres);
3339         if (ret)
3340                 mlog_errno(ret);
3341 }
3342
3343 static void ocfs2_drop_osb_locks(struct ocfs2_super *osb)
3344 {
3345         ocfs2_simple_drop_lockres(osb, &osb->osb_super_lockres);
3346         ocfs2_simple_drop_lockres(osb, &osb->osb_rename_lockres);
3347         ocfs2_simple_drop_lockres(osb, &osb->osb_nfs_sync_lockres);
3348         ocfs2_simple_drop_lockres(osb, &osb->osb_orphan_scan.os_lockres);
3349 }
3350
3351 int ocfs2_drop_inode_locks(struct inode *inode)
3352 {
3353         int status, err;
3354
3355         /* No need to call ocfs2_mark_lockres_freeing here -
3356          * ocfs2_clear_inode has done it for us. */
3357
3358         err = ocfs2_drop_lock(OCFS2_SB(inode->i_sb),
3359                               &OCFS2_I(inode)->ip_open_lockres);
3360         if (err < 0)
3361                 mlog_errno(err);
3362
3363         status = err;
3364
3365         err = ocfs2_drop_lock(OCFS2_SB(inode->i_sb),
3366                               &OCFS2_I(inode)->ip_inode_lockres);
3367         if (err < 0)
3368                 mlog_errno(err);
3369         if (err < 0 && !status)
3370                 status = err;
3371
3372         err = ocfs2_drop_lock(OCFS2_SB(inode->i_sb),
3373                               &OCFS2_I(inode)->ip_rw_lockres);
3374         if (err < 0)
3375                 mlog_errno(err);
3376         if (err < 0 && !status)
3377                 status = err;
3378
3379         return status;
3380 }
3381
3382 static unsigned int ocfs2_prepare_downconvert(struct ocfs2_lock_res *lockres,
3383                                               int new_level)
3384 {
3385         assert_spin_locked(&lockres->l_lock);
3386
3387         BUG_ON(lockres->l_blocking <= DLM_LOCK_NL);
3388
3389         if (lockres->l_level <= new_level) {
3390                 mlog(ML_ERROR, "lockres %s, lvl %d <= %d, blcklst %d, mask %d, "
3391                      "type %d, flags 0x%lx, hold %d %d, act %d %d, req %d, "
3392                      "block %d, pgen %d\n", lockres->l_name, lockres->l_level,
3393                      new_level, list_empty(&lockres->l_blocked_list),
3394                      list_empty(&lockres->l_mask_waiters), lockres->l_type,
3395                      lockres->l_flags, lockres->l_ro_holders,
3396                      lockres->l_ex_holders, lockres->l_action,
3397                      lockres->l_unlock_action, lockres->l_requested,
3398                      lockres->l_blocking, lockres->l_pending_gen);
3399                 BUG();
3400         }
3401
3402         mlog(ML_BASTS, "lockres %s, level %d => %d, blocking %d\n",
3403              lockres->l_name, lockres->l_level, new_level, lockres->l_blocking);
3404
3405         lockres->l_action = OCFS2_AST_DOWNCONVERT;
3406         lockres->l_requested = new_level;
3407         lockres_or_flags(lockres, OCFS2_LOCK_BUSY);
3408         return lockres_set_pending(lockres);
3409 }
3410
3411 static int ocfs2_downconvert_lock(struct ocfs2_super *osb,
3412                                   struct ocfs2_lock_res *lockres,
3413                                   int new_level,
3414                                   int lvb,
3415                                   unsigned int generation)
3416 {
3417         int ret;
3418         u32 dlm_flags = DLM_LKF_CONVERT;
3419
3420         mlog(ML_BASTS, "lockres %s, level %d => %d\n", lockres->l_name,
3421              lockres->l_level, new_level);
3422
3423         /*
3424          * On DLM_LKF_VALBLK, fsdlm behaves differently with o2cb. It always
3425          * expects DLM_LKF_VALBLK being set if the LKB has LVB, so that
3426          * we can recover correctly from node failure. Otherwise, we may get
3427          * invalid LVB in LKB, but without DLM_SBF_VALNOTVALID being set.
3428          */
3429         if (ocfs2_userspace_stack(osb) &&
3430             lockres->l_ops->flags & LOCK_TYPE_USES_LVB)
3431                 lvb = 1;
3432
3433         if (lvb)
3434                 dlm_flags |= DLM_LKF_VALBLK;
3435
3436         ret = ocfs2_dlm_lock(osb->cconn,
3437                              new_level,
3438                              &lockres->l_lksb,
3439                              dlm_flags,
3440                              lockres->l_name,
3441                              OCFS2_LOCK_ID_MAX_LEN - 1);
3442         lockres_clear_pending(lockres, generation, osb);
3443         if (ret) {
3444                 ocfs2_log_dlm_error("ocfs2_dlm_lock", ret, lockres);
3445                 ocfs2_recover_from_dlm_error(lockres, 1);
3446                 goto bail;
3447         }
3448
3449         ret = 0;
3450 bail:
3451         return ret;
3452 }
3453
3454 /* returns 1 when the caller should unlock and call ocfs2_dlm_unlock */
3455 static int ocfs2_prepare_cancel_convert(struct ocfs2_super *osb,
3456                                         struct ocfs2_lock_res *lockres)
3457 {
3458         assert_spin_locked(&lockres->l_lock);
3459
3460         if (lockres->l_unlock_action == OCFS2_UNLOCK_CANCEL_CONVERT) {
3461                 /* If we're already trying to cancel a lock conversion
3462                  * then just drop the spinlock and allow the caller to
3463                  * requeue this lock. */
3464                 mlog(ML_BASTS, "lockres %s, skip convert\n", lockres->l_name);
3465                 return 0;
3466         }
3467
3468         /* were we in a convert when we got the bast fire? */
3469         BUG_ON(lockres->l_action != OCFS2_AST_CONVERT &&
3470                lockres->l_action != OCFS2_AST_DOWNCONVERT);
3471         /* set things up for the unlockast to know to just
3472          * clear out the ast_action and unset busy, etc. */
3473         lockres->l_unlock_action = OCFS2_UNLOCK_CANCEL_CONVERT;
3474
3475         mlog_bug_on_msg(!(lockres->l_flags & OCFS2_LOCK_BUSY),
3476                         "lock %s, invalid flags: 0x%lx\n",
3477                         lockres->l_name, lockres->l_flags);
3478
3479         mlog(ML_BASTS, "lockres %s\n", lockres->l_name);
3480
3481         return 1;
3482 }
3483
3484 static int ocfs2_cancel_convert(struct ocfs2_super *osb,
3485                                 struct ocfs2_lock_res *lockres)
3486 {
3487         int ret;
3488
3489         ret = ocfs2_dlm_unlock(osb->cconn, &lockres->l_lksb,
3490                                DLM_LKF_CANCEL);
3491         if (ret) {
3492                 ocfs2_log_dlm_error("ocfs2_dlm_unlock", ret, lockres);
3493                 ocfs2_recover_from_dlm_error(lockres, 0);
3494         }
3495
3496         mlog(ML_BASTS, "lockres %s\n", lockres->l_name);
3497
3498         return ret;
3499 }
3500
3501 static int ocfs2_unblock_lock(struct ocfs2_super *osb,
3502                               struct ocfs2_lock_res *lockres,
3503                               struct ocfs2_unblock_ctl *ctl)
3504 {
3505         unsigned long flags;
3506         int blocking;
3507         int new_level;
3508         int level;
3509         int ret = 0;
3510         int set_lvb = 0;
3511         unsigned int gen;
3512
3513         spin_lock_irqsave(&lockres->l_lock, flags);
3514
3515 recheck:
3516         /*
3517          * Is it still blocking? If not, we have no more work to do.
3518          */
3519         if (!(lockres->l_flags & OCFS2_LOCK_BLOCKED)) {
3520                 BUG_ON(lockres->l_blocking != DLM_LOCK_NL);
3521                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3522                 ret = 0;
3523                 goto leave;
3524         }
3525
3526         if (lockres->l_flags & OCFS2_LOCK_BUSY) {
3527                 /* XXX
3528                  * This is a *big* race.  The OCFS2_LOCK_PENDING flag
3529                  * exists entirely for one reason - another thread has set
3530                  * OCFS2_LOCK_BUSY, but has *NOT* yet called dlm_lock().
3531                  *
3532                  * If we do ocfs2_cancel_convert() before the other thread
3533                  * calls dlm_lock(), our cancel will do nothing.  We will
3534                  * get no ast, and we will have no way of knowing the
3535                  * cancel failed.  Meanwhile, the other thread will call
3536                  * into dlm_lock() and wait...forever.
3537                  *
3538                  * Why forever?  Because another node has asked for the
3539                  * lock first; that's why we're here in unblock_lock().
3540                  *
3541                  * The solution is OCFS2_LOCK_PENDING.  When PENDING is
3542                  * set, we just requeue the unblock.  Only when the other
3543                  * thread has called dlm_lock() and cleared PENDING will
3544                  * we then cancel their request.
3545                  *
3546                  * All callers of dlm_lock() must set OCFS2_DLM_PENDING
3547                  * at the same time they set OCFS2_DLM_BUSY.  They must
3548                  * clear OCFS2_DLM_PENDING after dlm_lock() returns.
3549                  */
3550                 if (lockres->l_flags & OCFS2_LOCK_PENDING) {
3551                         mlog(ML_BASTS, "lockres %s, ReQ: Pending\n",
3552                              lockres->l_name);
3553                         goto leave_requeue;
3554                 }
3555
3556                 ctl->requeue = 1;
3557                 ret = ocfs2_prepare_cancel_convert(osb, lockres);
3558                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3559                 if (ret) {
3560                         ret = ocfs2_cancel_convert(osb, lockres);
3561                         if (ret < 0)
3562                                 mlog_errno(ret);
3563                 }
3564                 goto leave;
3565         }
3566
3567         /*
3568          * This prevents livelocks. OCFS2_LOCK_UPCONVERT_FINISHING flag is
3569          * set when the ast is received for an upconvert just before the
3570          * OCFS2_LOCK_BUSY flag is cleared. Now if the fs received a bast
3571          * on the heels of the ast, we want to delay the downconvert just
3572          * enough to allow the up requestor to do its task. Because this
3573          * lock is in the blocked queue, the lock will be downconverted
3574          * as soon as the requestor is done with the lock.
3575          */
3576         if (lockres->l_flags & OCFS2_LOCK_UPCONVERT_FINISHING)
3577                 goto leave_requeue;
3578
3579         /*
3580          * How can we block and yet be at NL?  We were trying to upconvert
3581          * from NL and got canceled.  The code comes back here, and now
3582          * we notice and clear BLOCKING.
3583          */
3584         if (lockres->l_level == DLM_LOCK_NL) {
3585                 BUG_ON(lockres->l_ex_holders || lockres->l_ro_holders);
3586                 mlog(ML_BASTS, "lockres %s, Aborting dc\n", lockres->l_name);
3587                 lockres->l_blocking = DLM_LOCK_NL;
3588                 lockres_clear_flags(lockres, OCFS2_LOCK_BLOCKED);
3589                 spin_unlock_irqrestore(&lockres->l_lock, flags);
3590                 goto leave;
3591         }
3592
3593         /* if we're blocking an exclusive and we have *any* holders,
3594          * then requeue. */
3595         if ((lockres->l_blocking == DLM_LOCK_EX)
3596             && (lockres->l_ex_holders || lockres->l_ro_holders)) {
3597                 mlog(ML_BASTS, "lockres %s, ReQ: EX/PR Holders %u,%u\n",
3598                      lockres->l_name, lockres->l_ex_holders,
3599                      lockres->l_ro_holders);
3600                 goto leave_requeue;
3601         }
3602
3603         /* If it's a PR we're blocking, then only
3604          * requeue if we've got any EX holders */
3605         if (lockres->l_blocking == DLM_LOCK_PR &&
3606             lockres->l_ex_holders) {
3607                 mlog(ML_BASTS, "lockres %s, ReQ: EX Holders %u\n",
3608                      lockres->l_name, lockres->l_ex_holders);
3609                 goto leave_requeue;
3610         }
3611
3612         /*
3613          * Can we get a lock in this state if the holder counts are
3614          * zero? The meta data unblock code used to check this.
3615          */
3616         if ((lockres->l_ops->flags & LOCK_TYPE_REQUIRES_REFRESH)
3617             && (lockres->l_flags & OCFS2_LOCK_REFRESHING)) {
3618                 mlog(ML_BASTS, "lockres %s, ReQ: Lock Refreshing\n",
3619                      lockres->l_name);
3620                 goto leave_requeue;
3621         }
3622
3623         new_level = ocfs2_highest_compat_lock_level(lockres->l_blocking);
3624
3625         if (lockres->l_ops->check_downconvert
3626             && !lockres->l_ops->check_downconvert(lockres, new_level)) {
3627                 mlog(ML_BASTS, "lockres %s, ReQ: Checkpointing\n",
3628                      lockres->l_name);
3629                 goto leave_requeue;
3630         }
3631
3632         /* If we get here, then we know that there are no more
3633          * incompatible holders (and anyone asking for an incompatible
3634          * lock is blocked). We can now downconvert the lock */
3635         if (!lockres->l_ops->downconvert_worker)
3636                 goto downconvert;
3637
3638         /* Some lockres types want to do a bit of work before
3639          * downconverting a lock. Allow that here. The worker function
3640          * may sleep, so we save off a copy of what we're blocking as
3641          * it may change while we're not holding the spin lock. */
3642         blocking = lockres->l_blocking;
3643         level = lockres->l_level;
3644         spin_unlock_irqrestore(&lockres->l_lock, flags);
3645
3646         ctl->unblock_action = lockres->l_ops->downconvert_worker(lockres, blocking);
3647
3648         if (ctl->unblock_action == UNBLOCK_STOP_POST) {
3649                 mlog(ML_BASTS, "lockres %s, UNBLOCK_STOP_POST\n",
3650                      lockres->l_name);
3651                 goto leave;
3652         }
3653
3654         spin_lock_irqsave(&lockres->l_lock, flags);
3655         if ((blocking != lockres->l_blocking) || (level != lockres->l_level)) {
3656                 /* If this changed underneath us, then we can't drop
3657                  * it just yet. */
3658                 mlog(ML_BASTS, "lockres %s, block=%d:%d, level=%d:%d, "
3659                      "Recheck\n", lockres->l_name, blocking,
3660                      lockres->l_blocking, level, lockres->l_level);
3661                 goto recheck;
3662         }
3663
3664 downconvert:
3665         ctl->requeue = 0;
3666
3667         if (lockres->l_ops->flags & LOCK_TYPE_USES_LVB) {
3668                 if (lockres->l_level == DLM_LOCK_EX)
3669                         set_lvb = 1;
3670
3671                 /*
3672                  * We only set the lvb if the lock has been fully
3673                  * refreshed - otherwise we risk setting stale
3674                  * data. Otherwise, there's no need to actually clear
3675                  * out the lvb here as it's value is still valid.
3676                  */
3677                 if (set_lvb && !(lockres->l_flags & OCFS2_LOCK_NEEDS_REFRESH))
3678                         lockres->l_ops->set_lvb(lockres);
3679         }
3680
3681         gen = ocfs2_prepare_downconvert(lockres, new_level);
3682         spin_unlock_irqrestore(&lockres->l_lock, flags);
3683         ret = ocfs2_downconvert_lock(osb, lockres, new_level, set_lvb,
3684                                      gen);
3685
3686 leave:
3687         if (ret)
3688                 mlog_errno(ret);
3689         return ret;
3690
3691 leave_requeue:
3692         spin_unlock_irqrestore(&lockres->l_lock, flags);
3693         ctl->requeue = 1;
3694
3695         return 0;
3696 }
3697
3698 static int ocfs2_data_convert_worker(struct ocfs2_lock_res *lockres,
3699                                      int blocking)
3700 {
3701         struct inode *inode;
3702         struct address_space *mapping;
3703         struct ocfs2_inode_info *oi;
3704
3705         inode = ocfs2_lock_res_inode(lockres);
3706         mapping = inode->i_mapping;
3707
3708         if (S_ISDIR(inode->i_mode)) {
3709                 oi = OCFS2_I(inode);
3710                 oi->ip_dir_lock_gen++;
3711                 mlog(0, "generation: %u\n", oi->ip_dir_lock_gen);
3712                 goto out;
3713         }
3714
3715         if (!S_ISREG(inode->i_mode))
3716                 goto out;
3717
3718         /*
3719          * We need this before the filemap_fdatawrite() so that it can
3720          * transfer the dirty bit from the PTE to the
3721          * page. Unfortunately this means that even for EX->PR
3722          * downconverts, we'll lose our mappings and have to build
3723          * them up again.
3724          */
3725         unmap_mapping_range(mapping, 0, 0, 0);
3726
3727         if (filemap_fdatawrite(mapping)) {
3728                 mlog(ML_ERROR, "Could not sync inode %llu for downconvert!",
3729                      (unsigned long long)OCFS2_I(inode)->ip_blkno);
3730         }
3731         sync_mapping_buffers(mapping);
3732         if (blocking == DLM_LOCK_EX) {
3733                 truncate_inode_pages(mapping, 0);
3734         } else {
3735                 /* We only need to wait on the I/O if we're not also
3736                  * truncating pages because truncate_inode_pages waits
3737                  * for us above. We don't truncate pages if we're
3738                  * blocking anything < EXMODE because we want to keep
3739                  * them around in that case. */
3740                 filemap_fdatawait(mapping);
3741         }
3742
3743 out:
3744         return UNBLOCK_CONTINUE;
3745 }
3746
3747 static int ocfs2_ci_checkpointed(struct ocfs2_caching_info *ci,
3748                                  struct ocfs2_lock_res *lockres,
3749                                  int new_level)
3750 {
3751         int checkpointed = ocfs2_ci_fully_checkpointed(ci);
3752
3753         BUG_ON(new_level != DLM_LOCK_NL && new_level != DLM_LOCK_PR);
3754         BUG_ON(lockres->l_level != DLM_LOCK_EX && !checkpointed);
3755
3756         if (checkpointed)
3757                 return 1;
3758
3759         ocfs2_start_checkpoint(OCFS2_SB(ocfs2_metadata_cache_get_super(ci)));
3760         return 0;
3761 }
3762
3763 static int ocfs2_check_meta_downconvert(struct ocfs2_lock_res *lockres,
3764                                         int new_level)
3765 {
3766         struct inode *inode = ocfs2_lock_res_inode(lockres);
3767
3768         return ocfs2_ci_checkpointed(INODE_CACHE(inode), lockres, new_level);
3769 }
3770
3771 static void ocfs2_set_meta_lvb(struct ocfs2_lock_res *lockres)
3772 {
3773         struct inode *inode = ocfs2_lock_res_inode(lockres);
3774
3775         __ocfs2_stuff_meta_lvb(inode);
3776 }
3777
3778 /*
3779  * Does the final reference drop on our dentry lock. Right now this
3780  * happens in the downconvert thread, but we could choose to simplify the
3781  * dlmglue API and push these off to the ocfs2_wq in the future.
3782  */
3783 static void ocfs2_dentry_post_unlock(struct ocfs2_super *osb,
3784                                      struct ocfs2_lock_res *lockres)
3785 {
3786         struct ocfs2_dentry_lock *dl = ocfs2_lock_res_dl(lockres);
3787         ocfs2_dentry_lock_put(osb, dl);
3788 }
3789
3790 /*
3791  * d_delete() matching dentries before the lock downconvert.
3792  *
3793  * At this point, any process waiting to destroy the
3794  * dentry_lock due to last ref count is stopped by the
3795  * OCFS2_LOCK_QUEUED flag.
3796  *
3797  * We have two potential problems
3798  *
3799  * 1) If we do the last reference drop on our dentry_lock (via dput)
3800  *    we'll wind up in ocfs2_release_dentry_lock(), waiting on
3801  *    the downconvert to finish. Instead we take an elevated
3802  *    reference and push the drop until after we've completed our
3803  *    unblock processing.
3804  *
3805  * 2) There might be another process with a final reference,
3806  *    waiting on us to finish processing. If this is the case, we
3807  *    detect it and exit out - there's no more dentries anyway.
3808  */
3809 static int ocfs2_dentry_convert_worker(struct ocfs2_lock_res *lockres,
3810                                        int blocking)
3811 {
3812         struct ocfs2_dentry_lock *dl = ocfs2_lock_res_dl(lockres);
3813         struct ocfs2_inode_info *oi = OCFS2_I(dl->dl_inode);
3814         struct dentry *dentry;
3815         unsigned long flags;
3816         int extra_ref = 0;
3817
3818         /*
3819          * This node is blocking another node from getting a read
3820          * lock. This happens when we've renamed within a
3821          * directory. We've forced the other nodes to d_delete(), but
3822          * we never actually dropped our lock because it's still
3823          * valid. The downconvert code will retain a PR for this node,
3824          * so there's no further work to do.
3825          */
3826         if (blocking == DLM_LOCK_PR)
3827                 return UNBLOCK_CONTINUE;
3828
3829         /*
3830          * Mark this inode as potentially orphaned. The code in
3831          * ocfs2_delete_inode() will figure out whether it actually
3832          * needs to be freed or not.
3833          */
3834         spin_lock(&oi->ip_lock);
3835         oi->ip_flags |= OCFS2_INODE_MAYBE_ORPHANED;
3836         spin_unlock(&oi->ip_lock);
3837
3838         /*
3839          * Yuck. We need to make sure however that the check of
3840          * OCFS2_LOCK_FREEING and the extra reference are atomic with
3841          * respect to a reference decrement or the setting of that
3842          * flag.
3843          */
3844         spin_lock_irqsave(&lockres->l_lock, flags);
3845         spin_lock(&dentry_attach_lock);
3846         if (!(lockres->l_flags & OCFS2_LOCK_FREEING)
3847             && dl->dl_count) {
3848                 dl->dl_count++;
3849                 extra_ref = 1;
3850         }
3851         spin_unlock(&dentry_attach_lock);
3852         spin_unlock_irqrestore(&lockres->l_lock, flags);
3853
3854         mlog(0, "extra_ref = %d\n", extra_ref);
3855
3856         /*
3857          * We have a process waiting on us in ocfs2_dentry_iput(),
3858          * which means we can't have any more outstanding
3859          * aliases. There's no need to do any more work.
3860          */
3861         if (!extra_ref)
3862                 return UNBLOCK_CONTINUE;
3863
3864         spin_lock(&dentry_attach_lock);
3865         while (1) {
3866                 dentry = ocfs2_find_local_alias(dl->dl_inode,
3867                                                 dl->dl_parent_blkno, 1);
3868                 if (!dentry)
3869                         break;
3870                 spin_unlock(&dentry_attach_lock);
3871
3872                 if (S_ISDIR(dl->dl_inode->i_mode))
3873                         shrink_dcache_parent(dentry);
3874
3875                 mlog(0, "d_delete(%pd);\n", dentry);
3876
3877                 /*
3878                  * The following dcache calls may do an
3879                  * iput(). Normally we don't want that from the
3880                  * downconverting thread, but in this case it's ok
3881                  * because the requesting node already has an
3882                  * exclusive lock on the inode, so it can't be queued
3883                  * for a downconvert.
3884                  */
3885                 d_delete(dentry);
3886                 dput(dentry);
3887
3888                 spin_lock(&dentry_attach_lock);
3889         }
3890         spin_unlock(&dentry_attach_lock);
3891
3892         /*
3893          * If we are the last holder of this dentry lock, there is no
3894          * reason to downconvert so skip straight to the unlock.
3895          */
3896         if (dl->dl_count == 1)
3897                 return UNBLOCK_STOP_POST;
3898
3899         return UNBLOCK_CONTINUE_POST;
3900 }
3901
3902 static int ocfs2_check_refcount_downconvert(struct ocfs2_lock_res *lockres,
3903                                             int new_level)
3904 {
3905         struct ocfs2_refcount_tree *tree =
3906                                 ocfs2_lock_res_refcount_tree(lockres);
3907
3908         return ocfs2_ci_checkpointed(&tree->rf_ci, lockres, new_level);
3909 }
3910
3911 static int ocfs2_refcount_convert_worker(struct ocfs2_lock_res *lockres,
3912                                          int blocking)
3913 {
3914         struct ocfs2_refcount_tree *tree =
3915                                 ocfs2_lock_res_refcount_tree(lockres);
3916
3917         ocfs2_metadata_cache_purge(&tree->rf_ci);
3918
3919         return UNBLOCK_CONTINUE;
3920 }
3921
3922 static void ocfs2_set_qinfo_lvb(struct ocfs2_lock_res *lockres)
3923 {
3924         struct ocfs2_qinfo_lvb *lvb;
3925         struct ocfs2_mem_dqinfo *oinfo = ocfs2_lock_res_qinfo(lockres);
3926         struct mem_dqinfo *info = sb_dqinfo(oinfo->dqi_gi.dqi_sb,
3927                                             oinfo->dqi_gi.dqi_type);
3928
3929         lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
3930         lvb->lvb_version = OCFS2_QINFO_LVB_VERSION;
3931         lvb->lvb_bgrace = cpu_to_be32(info->dqi_bgrace);
3932         lvb->lvb_igrace = cpu_to_be32(info->dqi_igrace);
3933         lvb->lvb_syncms = cpu_to_be32(oinfo->dqi_syncms);
3934         lvb->lvb_blocks = cpu_to_be32(oinfo->dqi_gi.dqi_blocks);
3935         lvb->lvb_free_blk = cpu_to_be32(oinfo->dqi_gi.dqi_free_blk);
3936         lvb->lvb_free_entry = cpu_to_be32(oinfo->dqi_gi.dqi_free_entry);
3937 }
3938
3939 void ocfs2_qinfo_unlock(struct ocfs2_mem_dqinfo *oinfo, int ex)
3940 {
3941         struct ocfs2_lock_res *lockres = &oinfo->dqi_gqlock;
3942         struct ocfs2_super *osb = OCFS2_SB(oinfo->dqi_gi.dqi_sb);
3943         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
3944
3945         if (!ocfs2_is_hard_readonly(osb) && !ocfs2_mount_local(osb))
3946                 ocfs2_cluster_unlock(osb, lockres, level);
3947 }
3948
3949 static int ocfs2_refresh_qinfo(struct ocfs2_mem_dqinfo *oinfo)
3950 {
3951         struct mem_dqinfo *info = sb_dqinfo(oinfo->dqi_gi.dqi_sb,
3952                                             oinfo->dqi_gi.dqi_type);
3953         struct ocfs2_lock_res *lockres = &oinfo->dqi_gqlock;
3954         struct ocfs2_qinfo_lvb *lvb = ocfs2_dlm_lvb(&lockres->l_lksb);
3955         struct buffer_head *bh = NULL;
3956         struct ocfs2_global_disk_dqinfo *gdinfo;
3957         int status = 0;
3958
3959         if (ocfs2_dlm_lvb_valid(&lockres->l_lksb) &&
3960             lvb->lvb_version == OCFS2_QINFO_LVB_VERSION) {
3961                 info->dqi_bgrace = be32_to_cpu(lvb->lvb_bgrace);
3962                 info->dqi_igrace = be32_to_cpu(lvb->lvb_igrace);
3963                 oinfo->dqi_syncms = be32_to_cpu(lvb->lvb_syncms);
3964                 oinfo->dqi_gi.dqi_blocks = be32_to_cpu(lvb->lvb_blocks);
3965                 oinfo->dqi_gi.dqi_free_blk = be32_to_cpu(lvb->lvb_free_blk);
3966                 oinfo->dqi_gi.dqi_free_entry =
3967                                         be32_to_cpu(lvb->lvb_free_entry);
3968         } else {
3969                 status = ocfs2_read_quota_phys_block(oinfo->dqi_gqinode,
3970                                                      oinfo->dqi_giblk, &bh);
3971                 if (status) {
3972                         mlog_errno(status);
3973                         goto bail;
3974                 }
3975                 gdinfo = (struct ocfs2_global_disk_dqinfo *)
3976                                         (bh->b_data + OCFS2_GLOBAL_INFO_OFF);
3977                 info->dqi_bgrace = le32_to_cpu(gdinfo->dqi_bgrace);
3978                 info->dqi_igrace = le32_to_cpu(gdinfo->dqi_igrace);
3979                 oinfo->dqi_syncms = le32_to_cpu(gdinfo->dqi_syncms);
3980                 oinfo->dqi_gi.dqi_blocks = le32_to_cpu(gdinfo->dqi_blocks);
3981                 oinfo->dqi_gi.dqi_free_blk = le32_to_cpu(gdinfo->dqi_free_blk);
3982                 oinfo->dqi_gi.dqi_free_entry =
3983                                         le32_to_cpu(gdinfo->dqi_free_entry);
3984                 brelse(bh);
3985                 ocfs2_track_lock_refresh(lockres);
3986         }
3987
3988 bail:
3989         return status;
3990 }
3991
3992 /* Lock quota info, this function expects at least shared lock on the quota file
3993  * so that we can safely refresh quota info from disk. */
3994 int ocfs2_qinfo_lock(struct ocfs2_mem_dqinfo *oinfo, int ex)
3995 {
3996         struct ocfs2_lock_res *lockres = &oinfo->dqi_gqlock;
3997         struct ocfs2_super *osb = OCFS2_SB(oinfo->dqi_gi.dqi_sb);
3998         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
3999         int status = 0;
4000
4001         /* On RO devices, locking really isn't needed... */
4002         if (ocfs2_is_hard_readonly(osb)) {
4003                 if (ex)
4004                         status = -EROFS;
4005                 goto bail;
4006         }
4007         if (ocfs2_mount_local(osb))
4008                 goto bail;
4009
4010         status = ocfs2_cluster_lock(osb, lockres, level, 0, 0);
4011         if (status < 0) {
4012                 mlog_errno(status);
4013                 goto bail;
4014         }
4015         if (!ocfs2_should_refresh_lock_res(lockres))
4016                 goto bail;
4017         /* OK, we have the lock but we need to refresh the quota info */
4018         status = ocfs2_refresh_qinfo(oinfo);
4019         if (status)
4020                 ocfs2_qinfo_unlock(oinfo, ex);
4021         ocfs2_complete_lock_res_refresh(lockres, status);
4022 bail:
4023         return status;
4024 }
4025
4026 int ocfs2_refcount_lock(struct ocfs2_refcount_tree *ref_tree, int ex)
4027 {
4028         int status;
4029         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
4030         struct ocfs2_lock_res *lockres = &ref_tree->rf_lockres;
4031         struct ocfs2_super *osb = lockres->l_priv;
4032
4033
4034         if (ocfs2_is_hard_readonly(osb))
4035                 return -EROFS;
4036
4037         if (ocfs2_mount_local(osb))
4038                 return 0;
4039
4040         status = ocfs2_cluster_lock(osb, lockres, level, 0, 0);
4041         if (status < 0)
4042                 mlog_errno(status);
4043
4044         return status;
4045 }
4046
4047 void ocfs2_refcount_unlock(struct ocfs2_refcount_tree *ref_tree, int ex)
4048 {
4049         int level = ex ? DLM_LOCK_EX : DLM_LOCK_PR;
4050         struct ocfs2_lock_res *lockres = &ref_tree->rf_lockres;
4051         struct ocfs2_super *osb = lockres->l_priv;
4052
4053         if (!ocfs2_mount_local(osb))
4054                 ocfs2_cluster_unlock(osb, lockres, level);
4055 }
4056
4057 static void ocfs2_process_blocked_lock(struct ocfs2_super *osb,
4058                                        struct ocfs2_lock_res *lockres)
4059 {
4060         int status;
4061         struct ocfs2_unblock_ctl ctl = {0, 0,};
4062         unsigned long flags;
4063
4064         /* Our reference to the lockres in this function can be
4065          * considered valid until we remove the OCFS2_LOCK_QUEUED
4066          * flag. */
4067
4068         BUG_ON(!lockres);
4069         BUG_ON(!lockres->l_ops);
4070
4071         mlog(ML_BASTS, "lockres %s blocked\n", lockres->l_name);
4072
4073         /* Detect whether a lock has been marked as going away while
4074          * the downconvert thread was processing other things. A lock can
4075          * still be marked with OCFS2_LOCK_FREEING after this check,
4076          * but short circuiting here will still save us some
4077          * performance. */
4078         spin_lock_irqsave(&lockres->l_lock, flags);
4079         if (lockres->l_flags & OCFS2_LOCK_FREEING)
4080                 goto unqueue;
4081         spin_unlock_irqrestore(&lockres->l_lock, flags);
4082
4083         status = ocfs2_unblock_lock(osb, lockres, &ctl);
4084         if (status < 0)
4085                 mlog_errno(status);
4086
4087         spin_lock_irqsave(&lockres->l_lock, flags);
4088 unqueue:
4089         if (lockres->l_flags & OCFS2_LOCK_FREEING || !ctl.requeue) {
4090                 lockres_clear_flags(lockres, OCFS2_LOCK_QUEUED);
4091         } else
4092                 ocfs2_schedule_blocked_lock(osb, lockres);
4093
4094         mlog(ML_BASTS, "lockres %s, requeue = %s.\n", lockres->l_name,
4095              ctl.requeue ? "yes" : "no");
4096         spin_unlock_irqrestore(&lockres->l_lock, flags);
4097
4098         if (ctl.unblock_action != UNBLOCK_CONTINUE
4099             && lockres->l_ops->post_unlock)
4100                 lockres->l_ops->post_unlock(osb, lockres);
4101 }
4102
4103 static void ocfs2_schedule_blocked_lock(struct ocfs2_super *osb,
4104                                         struct ocfs2_lock_res *lockres)
4105 {
4106         unsigned long flags;
4107
4108         assert_spin_locked(&lockres->l_lock);
4109
4110         if (lockres->l_flags & OCFS2_LOCK_FREEING) {
4111                 /* Do not schedule a lock for downconvert when it's on
4112                  * the way to destruction - any nodes wanting access
4113                  * to the resource will get it soon. */
4114                 mlog(ML_BASTS, "lockres %s won't be scheduled: flags 0x%lx\n",
4115                      lockres->l_name, lockres->l_flags);
4116                 return;
4117         }
4118
4119         lockres_or_flags(lockres, OCFS2_LOCK_QUEUED);
4120
4121         spin_lock_irqsave(&osb->dc_task_lock, flags);
4122         if (list_empty(&lockres->l_blocked_list)) {
4123                 list_add_tail(&lockres->l_blocked_list,
4124                               &osb->blocked_lock_list);
4125                 osb->blocked_lock_count++;
4126         }
4127         spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4128 }
4129
4130 static void ocfs2_downconvert_thread_do_work(struct ocfs2_super *osb)
4131 {
4132         unsigned long processed;
4133         unsigned long flags;
4134         struct ocfs2_lock_res *lockres;
4135
4136         spin_lock_irqsave(&osb->dc_task_lock, flags);
4137         /* grab this early so we know to try again if a state change and
4138          * wake happens part-way through our work  */
4139         osb->dc_work_sequence = osb->dc_wake_sequence;
4140
4141         processed = osb->blocked_lock_count;
4142         /*
4143          * blocked lock processing in this loop might call iput which can
4144          * remove items off osb->blocked_lock_list. Downconvert up to
4145          * 'processed' number of locks, but stop short if we had some
4146          * removed in ocfs2_mark_lockres_freeing when downconverting.
4147          */
4148         while (processed && !list_empty(&osb->blocked_lock_list)) {
4149                 lockres = list_entry(osb->blocked_lock_list.next,
4150                                      struct ocfs2_lock_res, l_blocked_list);
4151                 list_del_init(&lockres->l_blocked_list);
4152                 osb->blocked_lock_count--;
4153                 spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4154
4155                 BUG_ON(!processed);
4156                 processed--;
4157
4158                 ocfs2_process_blocked_lock(osb, lockres);
4159
4160                 spin_lock_irqsave(&osb->dc_task_lock, flags);
4161         }
4162         spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4163 }
4164
4165 static int ocfs2_downconvert_thread_lists_empty(struct ocfs2_super *osb)
4166 {
4167         int empty = 0;
4168         unsigned long flags;
4169
4170         spin_lock_irqsave(&osb->dc_task_lock, flags);
4171         if (list_empty(&osb->blocked_lock_list))
4172                 empty = 1;
4173
4174         spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4175         return empty;
4176 }
4177
4178 static int ocfs2_downconvert_thread_should_wake(struct ocfs2_super *osb)
4179 {
4180         int should_wake = 0;
4181         unsigned long flags;
4182
4183         spin_lock_irqsave(&osb->dc_task_lock, flags);
4184         if (osb->dc_work_sequence != osb->dc_wake_sequence)
4185                 should_wake = 1;
4186         spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4187
4188         return should_wake;
4189 }
4190
4191 static int ocfs2_downconvert_thread(void *arg)
4192 {
4193         int status = 0;
4194         struct ocfs2_super *osb = arg;
4195
4196         /* only quit once we've been asked to stop and there is no more
4197          * work available */
4198         while (!(kthread_should_stop() &&
4199                 ocfs2_downconvert_thread_lists_empty(osb))) {
4200
4201                 wait_event_interruptible(osb->dc_event,
4202                                          ocfs2_downconvert_thread_should_wake(osb) ||
4203                                          kthread_should_stop());
4204
4205                 mlog(0, "downconvert_thread: awoken\n");
4206
4207                 ocfs2_downconvert_thread_do_work(osb);
4208         }
4209
4210         osb->dc_task = NULL;
4211         return status;
4212 }
4213
4214 void ocfs2_wake_downconvert_thread(struct ocfs2_super *osb)
4215 {
4216         unsigned long flags;
4217
4218         spin_lock_irqsave(&osb->dc_task_lock, flags);
4219         /* make sure the voting thread gets a swipe at whatever changes
4220          * the caller may have made to the voting state */
4221         osb->dc_wake_sequence++;
4222         spin_unlock_irqrestore(&osb->dc_task_lock, flags);
4223         wake_up(&osb->dc_event);
4224 }