Merge branch 'misc' into devel
[sfrench/cifs-2.6.git] / fs / ocfs2 / file.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * file.c
5  *
6  * File open, close, extend, truncate
7  *
8  * Copyright (C) 2002, 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/capability.h>
27 #include <linux/fs.h>
28 #include <linux/types.h>
29 #include <linux/slab.h>
30 #include <linux/highmem.h>
31 #include <linux/pagemap.h>
32 #include <linux/uio.h>
33 #include <linux/sched.h>
34 #include <linux/splice.h>
35 #include <linux/mount.h>
36 #include <linux/writeback.h>
37 #include <linux/falloc.h>
38 #include <linux/quotaops.h>
39
40 #define MLOG_MASK_PREFIX ML_INODE
41 #include <cluster/masklog.h>
42
43 #include "ocfs2.h"
44
45 #include "alloc.h"
46 #include "aops.h"
47 #include "dir.h"
48 #include "dlmglue.h"
49 #include "extent_map.h"
50 #include "file.h"
51 #include "sysfile.h"
52 #include "inode.h"
53 #include "ioctl.h"
54 #include "journal.h"
55 #include "locks.h"
56 #include "mmap.h"
57 #include "suballoc.h"
58 #include "super.h"
59 #include "xattr.h"
60 #include "acl.h"
61 #include "quota.h"
62 #include "refcounttree.h"
63
64 #include "buffer_head_io.h"
65
66 static int ocfs2_sync_inode(struct inode *inode)
67 {
68         filemap_fdatawrite(inode->i_mapping);
69         return sync_mapping_buffers(inode->i_mapping);
70 }
71
72 static int ocfs2_init_file_private(struct inode *inode, struct file *file)
73 {
74         struct ocfs2_file_private *fp;
75
76         fp = kzalloc(sizeof(struct ocfs2_file_private), GFP_KERNEL);
77         if (!fp)
78                 return -ENOMEM;
79
80         fp->fp_file = file;
81         mutex_init(&fp->fp_mutex);
82         ocfs2_file_lock_res_init(&fp->fp_flock, fp);
83         file->private_data = fp;
84
85         return 0;
86 }
87
88 static void ocfs2_free_file_private(struct inode *inode, struct file *file)
89 {
90         struct ocfs2_file_private *fp = file->private_data;
91         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
92
93         if (fp) {
94                 ocfs2_simple_drop_lockres(osb, &fp->fp_flock);
95                 ocfs2_lock_res_free(&fp->fp_flock);
96                 kfree(fp);
97                 file->private_data = NULL;
98         }
99 }
100
101 static int ocfs2_file_open(struct inode *inode, struct file *file)
102 {
103         int status;
104         int mode = file->f_flags;
105         struct ocfs2_inode_info *oi = OCFS2_I(inode);
106
107         mlog_entry("(0x%p, 0x%p, '%.*s')\n", inode, file,
108                    file->f_path.dentry->d_name.len, file->f_path.dentry->d_name.name);
109
110         if (file->f_mode & FMODE_WRITE)
111                 dquot_initialize(inode);
112
113         spin_lock(&oi->ip_lock);
114
115         /* Check that the inode hasn't been wiped from disk by another
116          * node. If it hasn't then we're safe as long as we hold the
117          * spin lock until our increment of open count. */
118         if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_DELETED) {
119                 spin_unlock(&oi->ip_lock);
120
121                 status = -ENOENT;
122                 goto leave;
123         }
124
125         if (mode & O_DIRECT)
126                 oi->ip_flags |= OCFS2_INODE_OPEN_DIRECT;
127
128         oi->ip_open_count++;
129         spin_unlock(&oi->ip_lock);
130
131         status = ocfs2_init_file_private(inode, file);
132         if (status) {
133                 /*
134                  * We want to set open count back if we're failing the
135                  * open.
136                  */
137                 spin_lock(&oi->ip_lock);
138                 oi->ip_open_count--;
139                 spin_unlock(&oi->ip_lock);
140         }
141
142 leave:
143         mlog_exit(status);
144         return status;
145 }
146
147 static int ocfs2_file_release(struct inode *inode, struct file *file)
148 {
149         struct ocfs2_inode_info *oi = OCFS2_I(inode);
150
151         mlog_entry("(0x%p, 0x%p, '%.*s')\n", inode, file,
152                        file->f_path.dentry->d_name.len,
153                        file->f_path.dentry->d_name.name);
154
155         spin_lock(&oi->ip_lock);
156         if (!--oi->ip_open_count)
157                 oi->ip_flags &= ~OCFS2_INODE_OPEN_DIRECT;
158         spin_unlock(&oi->ip_lock);
159
160         ocfs2_free_file_private(inode, file);
161
162         mlog_exit(0);
163
164         return 0;
165 }
166
167 static int ocfs2_dir_open(struct inode *inode, struct file *file)
168 {
169         return ocfs2_init_file_private(inode, file);
170 }
171
172 static int ocfs2_dir_release(struct inode *inode, struct file *file)
173 {
174         ocfs2_free_file_private(inode, file);
175         return 0;
176 }
177
178 static int ocfs2_sync_file(struct file *file, int datasync)
179 {
180         int err = 0;
181         journal_t *journal;
182         struct dentry *dentry = file->f_path.dentry;
183         struct inode *inode = file->f_mapping->host;
184         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
185
186         mlog_entry("(0x%p, 0x%p, %d, '%.*s')\n", file, dentry, datasync,
187                    dentry->d_name.len, dentry->d_name.name);
188
189         err = ocfs2_sync_inode(dentry->d_inode);
190         if (err)
191                 goto bail;
192
193         if (datasync && !(inode->i_state & I_DIRTY_DATASYNC))
194                 goto bail;
195
196         journal = osb->journal->j_journal;
197         err = jbd2_journal_force_commit(journal);
198
199 bail:
200         mlog_exit(err);
201
202         return (err < 0) ? -EIO : 0;
203 }
204
205 int ocfs2_should_update_atime(struct inode *inode,
206                               struct vfsmount *vfsmnt)
207 {
208         struct timespec now;
209         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
210
211         if (ocfs2_is_hard_readonly(osb) || ocfs2_is_soft_readonly(osb))
212                 return 0;
213
214         if ((inode->i_flags & S_NOATIME) ||
215             ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode)))
216                 return 0;
217
218         /*
219          * We can be called with no vfsmnt structure - NFSD will
220          * sometimes do this.
221          *
222          * Note that our action here is different than touch_atime() -
223          * if we can't tell whether this is a noatime mount, then we
224          * don't know whether to trust the value of s_atime_quantum.
225          */
226         if (vfsmnt == NULL)
227                 return 0;
228
229         if ((vfsmnt->mnt_flags & MNT_NOATIME) ||
230             ((vfsmnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode)))
231                 return 0;
232
233         if (vfsmnt->mnt_flags & MNT_RELATIME) {
234                 if ((timespec_compare(&inode->i_atime, &inode->i_mtime) <= 0) ||
235                     (timespec_compare(&inode->i_atime, &inode->i_ctime) <= 0))
236                         return 1;
237
238                 return 0;
239         }
240
241         now = CURRENT_TIME;
242         if ((now.tv_sec - inode->i_atime.tv_sec <= osb->s_atime_quantum))
243                 return 0;
244         else
245                 return 1;
246 }
247
248 int ocfs2_update_inode_atime(struct inode *inode,
249                              struct buffer_head *bh)
250 {
251         int ret;
252         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
253         handle_t *handle;
254         struct ocfs2_dinode *di = (struct ocfs2_dinode *) bh->b_data;
255
256         mlog_entry_void();
257
258         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
259         if (IS_ERR(handle)) {
260                 ret = PTR_ERR(handle);
261                 mlog_errno(ret);
262                 goto out;
263         }
264
265         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), bh,
266                                       OCFS2_JOURNAL_ACCESS_WRITE);
267         if (ret) {
268                 mlog_errno(ret);
269                 goto out_commit;
270         }
271
272         /*
273          * Don't use ocfs2_mark_inode_dirty() here as we don't always
274          * have i_mutex to guard against concurrent changes to other
275          * inode fields.
276          */
277         inode->i_atime = CURRENT_TIME;
278         di->i_atime = cpu_to_le64(inode->i_atime.tv_sec);
279         di->i_atime_nsec = cpu_to_le32(inode->i_atime.tv_nsec);
280         ocfs2_journal_dirty(handle, bh);
281
282 out_commit:
283         ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
284 out:
285         mlog_exit(ret);
286         return ret;
287 }
288
289 static int ocfs2_set_inode_size(handle_t *handle,
290                                 struct inode *inode,
291                                 struct buffer_head *fe_bh,
292                                 u64 new_i_size)
293 {
294         int status;
295
296         mlog_entry_void();
297         i_size_write(inode, new_i_size);
298         inode->i_blocks = ocfs2_inode_sector_count(inode);
299         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
300
301         status = ocfs2_mark_inode_dirty(handle, inode, fe_bh);
302         if (status < 0) {
303                 mlog_errno(status);
304                 goto bail;
305         }
306
307 bail:
308         mlog_exit(status);
309         return status;
310 }
311
312 int ocfs2_simple_size_update(struct inode *inode,
313                              struct buffer_head *di_bh,
314                              u64 new_i_size)
315 {
316         int ret;
317         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
318         handle_t *handle = NULL;
319
320         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
321         if (IS_ERR(handle)) {
322                 ret = PTR_ERR(handle);
323                 mlog_errno(ret);
324                 goto out;
325         }
326
327         ret = ocfs2_set_inode_size(handle, inode, di_bh,
328                                    new_i_size);
329         if (ret < 0)
330                 mlog_errno(ret);
331
332         ocfs2_commit_trans(osb, handle);
333 out:
334         return ret;
335 }
336
337 static int ocfs2_cow_file_pos(struct inode *inode,
338                               struct buffer_head *fe_bh,
339                               u64 offset)
340 {
341         int status;
342         u32 phys, cpos = offset >> OCFS2_SB(inode->i_sb)->s_clustersize_bits;
343         unsigned int num_clusters = 0;
344         unsigned int ext_flags = 0;
345
346         /*
347          * If the new offset is aligned to the range of the cluster, there is
348          * no space for ocfs2_zero_range_for_truncate to fill, so no need to
349          * CoW either.
350          */
351         if ((offset & (OCFS2_SB(inode->i_sb)->s_clustersize - 1)) == 0)
352                 return 0;
353
354         status = ocfs2_get_clusters(inode, cpos, &phys,
355                                     &num_clusters, &ext_flags);
356         if (status) {
357                 mlog_errno(status);
358                 goto out;
359         }
360
361         if (!(ext_flags & OCFS2_EXT_REFCOUNTED))
362                 goto out;
363
364         return ocfs2_refcount_cow(inode, fe_bh, cpos, 1, cpos+1);
365
366 out:
367         return status;
368 }
369
370 static int ocfs2_orphan_for_truncate(struct ocfs2_super *osb,
371                                      struct inode *inode,
372                                      struct buffer_head *fe_bh,
373                                      u64 new_i_size)
374 {
375         int status;
376         handle_t *handle;
377         struct ocfs2_dinode *di;
378         u64 cluster_bytes;
379
380         mlog_entry_void();
381
382         /*
383          * We need to CoW the cluster contains the offset if it is reflinked
384          * since we will call ocfs2_zero_range_for_truncate later which will
385          * write "0" from offset to the end of the cluster.
386          */
387         status = ocfs2_cow_file_pos(inode, fe_bh, new_i_size);
388         if (status) {
389                 mlog_errno(status);
390                 return status;
391         }
392
393         /* TODO: This needs to actually orphan the inode in this
394          * transaction. */
395
396         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
397         if (IS_ERR(handle)) {
398                 status = PTR_ERR(handle);
399                 mlog_errno(status);
400                 goto out;
401         }
402
403         status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), fe_bh,
404                                          OCFS2_JOURNAL_ACCESS_WRITE);
405         if (status < 0) {
406                 mlog_errno(status);
407                 goto out_commit;
408         }
409
410         /*
411          * Do this before setting i_size.
412          */
413         cluster_bytes = ocfs2_align_bytes_to_clusters(inode->i_sb, new_i_size);
414         status = ocfs2_zero_range_for_truncate(inode, handle, new_i_size,
415                                                cluster_bytes);
416         if (status) {
417                 mlog_errno(status);
418                 goto out_commit;
419         }
420
421         i_size_write(inode, new_i_size);
422         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
423
424         di = (struct ocfs2_dinode *) fe_bh->b_data;
425         di->i_size = cpu_to_le64(new_i_size);
426         di->i_ctime = di->i_mtime = cpu_to_le64(inode->i_ctime.tv_sec);
427         di->i_ctime_nsec = di->i_mtime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
428
429         ocfs2_journal_dirty(handle, fe_bh);
430
431 out_commit:
432         ocfs2_commit_trans(osb, handle);
433 out:
434
435         mlog_exit(status);
436         return status;
437 }
438
439 static int ocfs2_truncate_file(struct inode *inode,
440                                struct buffer_head *di_bh,
441                                u64 new_i_size)
442 {
443         int status = 0;
444         struct ocfs2_dinode *fe = NULL;
445         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
446
447         mlog_entry("(inode = %llu, new_i_size = %llu\n",
448                    (unsigned long long)OCFS2_I(inode)->ip_blkno,
449                    (unsigned long long)new_i_size);
450
451         /* We trust di_bh because it comes from ocfs2_inode_lock(), which
452          * already validated it */
453         fe = (struct ocfs2_dinode *) di_bh->b_data;
454
455         mlog_bug_on_msg(le64_to_cpu(fe->i_size) != i_size_read(inode),
456                         "Inode %llu, inode i_size = %lld != di "
457                         "i_size = %llu, i_flags = 0x%x\n",
458                         (unsigned long long)OCFS2_I(inode)->ip_blkno,
459                         i_size_read(inode),
460                         (unsigned long long)le64_to_cpu(fe->i_size),
461                         le32_to_cpu(fe->i_flags));
462
463         if (new_i_size > le64_to_cpu(fe->i_size)) {
464                 mlog(0, "asked to truncate file with size (%llu) to size (%llu)!\n",
465                      (unsigned long long)le64_to_cpu(fe->i_size),
466                      (unsigned long long)new_i_size);
467                 status = -EINVAL;
468                 mlog_errno(status);
469                 goto bail;
470         }
471
472         mlog(0, "inode %llu, i_size = %llu, new_i_size = %llu\n",
473              (unsigned long long)le64_to_cpu(fe->i_blkno),
474              (unsigned long long)le64_to_cpu(fe->i_size),
475              (unsigned long long)new_i_size);
476
477         /* lets handle the simple truncate cases before doing any more
478          * cluster locking. */
479         if (new_i_size == le64_to_cpu(fe->i_size))
480                 goto bail;
481
482         down_write(&OCFS2_I(inode)->ip_alloc_sem);
483
484         ocfs2_resv_discard(&osb->osb_la_resmap,
485                            &OCFS2_I(inode)->ip_la_data_resv);
486
487         /*
488          * The inode lock forced other nodes to sync and drop their
489          * pages, which (correctly) happens even if we have a truncate
490          * without allocation change - ocfs2 cluster sizes can be much
491          * greater than page size, so we have to truncate them
492          * anyway.
493          */
494         unmap_mapping_range(inode->i_mapping, new_i_size + PAGE_SIZE - 1, 0, 1);
495         truncate_inode_pages(inode->i_mapping, new_i_size);
496
497         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
498                 status = ocfs2_truncate_inline(inode, di_bh, new_i_size,
499                                                i_size_read(inode), 1);
500                 if (status)
501                         mlog_errno(status);
502
503                 goto bail_unlock_sem;
504         }
505
506         /* alright, we're going to need to do a full blown alloc size
507          * change. Orphan the inode so that recovery can complete the
508          * truncate if necessary. This does the task of marking
509          * i_size. */
510         status = ocfs2_orphan_for_truncate(osb, inode, di_bh, new_i_size);
511         if (status < 0) {
512                 mlog_errno(status);
513                 goto bail_unlock_sem;
514         }
515
516         status = ocfs2_commit_truncate(osb, inode, di_bh);
517         if (status < 0) {
518                 mlog_errno(status);
519                 goto bail_unlock_sem;
520         }
521
522         /* TODO: orphan dir cleanup here. */
523 bail_unlock_sem:
524         up_write(&OCFS2_I(inode)->ip_alloc_sem);
525
526 bail:
527         if (!status && OCFS2_I(inode)->ip_clusters == 0)
528                 status = ocfs2_try_remove_refcount_tree(inode, di_bh);
529
530         mlog_exit(status);
531         return status;
532 }
533
534 /*
535  * extend file allocation only here.
536  * we'll update all the disk stuff, and oip->alloc_size
537  *
538  * expect stuff to be locked, a transaction started and enough data /
539  * metadata reservations in the contexts.
540  *
541  * Will return -EAGAIN, and a reason if a restart is needed.
542  * If passed in, *reason will always be set, even in error.
543  */
544 int ocfs2_add_inode_data(struct ocfs2_super *osb,
545                          struct inode *inode,
546                          u32 *logical_offset,
547                          u32 clusters_to_add,
548                          int mark_unwritten,
549                          struct buffer_head *fe_bh,
550                          handle_t *handle,
551                          struct ocfs2_alloc_context *data_ac,
552                          struct ocfs2_alloc_context *meta_ac,
553                          enum ocfs2_alloc_restarted *reason_ret)
554 {
555         int ret;
556         struct ocfs2_extent_tree et;
557
558         ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), fe_bh);
559         ret = ocfs2_add_clusters_in_btree(handle, &et, logical_offset,
560                                           clusters_to_add, mark_unwritten,
561                                           data_ac, meta_ac, reason_ret);
562
563         return ret;
564 }
565
566 static int __ocfs2_extend_allocation(struct inode *inode, u32 logical_start,
567                                      u32 clusters_to_add, int mark_unwritten)
568 {
569         int status = 0;
570         int restart_func = 0;
571         int credits;
572         u32 prev_clusters;
573         struct buffer_head *bh = NULL;
574         struct ocfs2_dinode *fe = NULL;
575         handle_t *handle = NULL;
576         struct ocfs2_alloc_context *data_ac = NULL;
577         struct ocfs2_alloc_context *meta_ac = NULL;
578         enum ocfs2_alloc_restarted why;
579         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
580         struct ocfs2_extent_tree et;
581         int did_quota = 0;
582
583         mlog_entry("(clusters_to_add = %u)\n", clusters_to_add);
584
585         /*
586          * This function only exists for file systems which don't
587          * support holes.
588          */
589         BUG_ON(mark_unwritten && !ocfs2_sparse_alloc(osb));
590
591         status = ocfs2_read_inode_block(inode, &bh);
592         if (status < 0) {
593                 mlog_errno(status);
594                 goto leave;
595         }
596         fe = (struct ocfs2_dinode *) bh->b_data;
597
598 restart_all:
599         BUG_ON(le32_to_cpu(fe->i_clusters) != OCFS2_I(inode)->ip_clusters);
600
601         mlog(0, "extend inode %llu, i_size = %lld, di->i_clusters = %u, "
602              "clusters_to_add = %u\n",
603              (unsigned long long)OCFS2_I(inode)->ip_blkno,
604              (long long)i_size_read(inode), le32_to_cpu(fe->i_clusters),
605              clusters_to_add);
606         ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), bh);
607         status = ocfs2_lock_allocators(inode, &et, clusters_to_add, 0,
608                                        &data_ac, &meta_ac);
609         if (status) {
610                 mlog_errno(status);
611                 goto leave;
612         }
613
614         credits = ocfs2_calc_extend_credits(osb->sb, &fe->id2.i_list,
615                                             clusters_to_add);
616         handle = ocfs2_start_trans(osb, credits);
617         if (IS_ERR(handle)) {
618                 status = PTR_ERR(handle);
619                 handle = NULL;
620                 mlog_errno(status);
621                 goto leave;
622         }
623
624 restarted_transaction:
625         status = dquot_alloc_space_nodirty(inode,
626                         ocfs2_clusters_to_bytes(osb->sb, clusters_to_add));
627         if (status)
628                 goto leave;
629         did_quota = 1;
630
631         /* reserve a write to the file entry early on - that we if we
632          * run out of credits in the allocation path, we can still
633          * update i_size. */
634         status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), bh,
635                                          OCFS2_JOURNAL_ACCESS_WRITE);
636         if (status < 0) {
637                 mlog_errno(status);
638                 goto leave;
639         }
640
641         prev_clusters = OCFS2_I(inode)->ip_clusters;
642
643         status = ocfs2_add_inode_data(osb,
644                                       inode,
645                                       &logical_start,
646                                       clusters_to_add,
647                                       mark_unwritten,
648                                       bh,
649                                       handle,
650                                       data_ac,
651                                       meta_ac,
652                                       &why);
653         if ((status < 0) && (status != -EAGAIN)) {
654                 if (status != -ENOSPC)
655                         mlog_errno(status);
656                 goto leave;
657         }
658
659         ocfs2_journal_dirty(handle, bh);
660
661         spin_lock(&OCFS2_I(inode)->ip_lock);
662         clusters_to_add -= (OCFS2_I(inode)->ip_clusters - prev_clusters);
663         spin_unlock(&OCFS2_I(inode)->ip_lock);
664         /* Release unused quota reservation */
665         dquot_free_space(inode,
666                         ocfs2_clusters_to_bytes(osb->sb, clusters_to_add));
667         did_quota = 0;
668
669         if (why != RESTART_NONE && clusters_to_add) {
670                 if (why == RESTART_META) {
671                         mlog(0, "restarting function.\n");
672                         restart_func = 1;
673                         status = 0;
674                 } else {
675                         BUG_ON(why != RESTART_TRANS);
676
677                         mlog(0, "restarting transaction.\n");
678                         /* TODO: This can be more intelligent. */
679                         credits = ocfs2_calc_extend_credits(osb->sb,
680                                                             &fe->id2.i_list,
681                                                             clusters_to_add);
682                         status = ocfs2_extend_trans(handle, credits);
683                         if (status < 0) {
684                                 /* handle still has to be committed at
685                                  * this point. */
686                                 status = -ENOMEM;
687                                 mlog_errno(status);
688                                 goto leave;
689                         }
690                         goto restarted_transaction;
691                 }
692         }
693
694         mlog(0, "fe: i_clusters = %u, i_size=%llu\n",
695              le32_to_cpu(fe->i_clusters),
696              (unsigned long long)le64_to_cpu(fe->i_size));
697         mlog(0, "inode: ip_clusters=%u, i_size=%lld\n",
698              OCFS2_I(inode)->ip_clusters, (long long)i_size_read(inode));
699
700 leave:
701         if (status < 0 && did_quota)
702                 dquot_free_space(inode,
703                         ocfs2_clusters_to_bytes(osb->sb, clusters_to_add));
704         if (handle) {
705                 ocfs2_commit_trans(osb, handle);
706                 handle = NULL;
707         }
708         if (data_ac) {
709                 ocfs2_free_alloc_context(data_ac);
710                 data_ac = NULL;
711         }
712         if (meta_ac) {
713                 ocfs2_free_alloc_context(meta_ac);
714                 meta_ac = NULL;
715         }
716         if ((!status) && restart_func) {
717                 restart_func = 0;
718                 goto restart_all;
719         }
720         brelse(bh);
721         bh = NULL;
722
723         mlog_exit(status);
724         return status;
725 }
726
727 /*
728  * While a write will already be ordering the data, a truncate will not.
729  * Thus, we need to explicitly order the zeroed pages.
730  */
731 static handle_t *ocfs2_zero_start_ordered_transaction(struct inode *inode)
732 {
733         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
734         handle_t *handle = NULL;
735         int ret = 0;
736
737         if (!ocfs2_should_order_data(inode))
738                 goto out;
739
740         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
741         if (IS_ERR(handle)) {
742                 ret = -ENOMEM;
743                 mlog_errno(ret);
744                 goto out;
745         }
746
747         ret = ocfs2_jbd2_file_inode(handle, inode);
748         if (ret < 0)
749                 mlog_errno(ret);
750
751 out:
752         if (ret) {
753                 if (!IS_ERR(handle))
754                         ocfs2_commit_trans(osb, handle);
755                 handle = ERR_PTR(ret);
756         }
757         return handle;
758 }
759
760 /* Some parts of this taken from generic_cont_expand, which turned out
761  * to be too fragile to do exactly what we need without us having to
762  * worry about recursive locking in ->write_begin() and ->write_end(). */
763 static int ocfs2_write_zero_page(struct inode *inode, u64 abs_from,
764                                  u64 abs_to)
765 {
766         struct address_space *mapping = inode->i_mapping;
767         struct page *page;
768         unsigned long index = abs_from >> PAGE_CACHE_SHIFT;
769         handle_t *handle = NULL;
770         int ret = 0;
771         unsigned zero_from, zero_to, block_start, block_end;
772
773         BUG_ON(abs_from >= abs_to);
774         BUG_ON(abs_to > (((u64)index + 1) << PAGE_CACHE_SHIFT));
775         BUG_ON(abs_from & (inode->i_blkbits - 1));
776
777         page = grab_cache_page(mapping, index);
778         if (!page) {
779                 ret = -ENOMEM;
780                 mlog_errno(ret);
781                 goto out;
782         }
783
784         /* Get the offsets within the page that we want to zero */
785         zero_from = abs_from & (PAGE_CACHE_SIZE - 1);
786         zero_to = abs_to & (PAGE_CACHE_SIZE - 1);
787         if (!zero_to)
788                 zero_to = PAGE_CACHE_SIZE;
789
790         mlog(0,
791              "abs_from = %llu, abs_to = %llu, index = %lu, zero_from = %u, zero_to = %u\n",
792              (unsigned long long)abs_from, (unsigned long long)abs_to,
793              index, zero_from, zero_to);
794
795         /* We know that zero_from is block aligned */
796         for (block_start = zero_from; block_start < zero_to;
797              block_start = block_end) {
798                 block_end = block_start + (1 << inode->i_blkbits);
799
800                 /*
801                  * block_start is block-aligned.  Bump it by one to
802                  * force ocfs2_{prepare,commit}_write() to zero the
803                  * whole block.
804                  */
805                 ret = ocfs2_prepare_write_nolock(inode, page,
806                                                  block_start + 1,
807                                                  block_start + 1);
808                 if (ret < 0) {
809                         mlog_errno(ret);
810                         goto out_unlock;
811                 }
812
813                 if (!handle) {
814                         handle = ocfs2_zero_start_ordered_transaction(inode);
815                         if (IS_ERR(handle)) {
816                                 ret = PTR_ERR(handle);
817                                 handle = NULL;
818                                 break;
819                         }
820                 }
821
822                 /* must not update i_size! */
823                 ret = block_commit_write(page, block_start + 1,
824                                          block_start + 1);
825                 if (ret < 0)
826                         mlog_errno(ret);
827                 else
828                         ret = 0;
829         }
830
831         if (handle)
832                 ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
833
834 out_unlock:
835         unlock_page(page);
836         page_cache_release(page);
837 out:
838         return ret;
839 }
840
841 /*
842  * Find the next range to zero.  We do this in terms of bytes because
843  * that's what ocfs2_zero_extend() wants, and it is dealing with the
844  * pagecache.  We may return multiple extents.
845  *
846  * zero_start and zero_end are ocfs2_zero_extend()s current idea of what
847  * needs to be zeroed.  range_start and range_end return the next zeroing
848  * range.  A subsequent call should pass the previous range_end as its
849  * zero_start.  If range_end is 0, there's nothing to do.
850  *
851  * Unwritten extents are skipped over.  Refcounted extents are CoWd.
852  */
853 static int ocfs2_zero_extend_get_range(struct inode *inode,
854                                        struct buffer_head *di_bh,
855                                        u64 zero_start, u64 zero_end,
856                                        u64 *range_start, u64 *range_end)
857 {
858         int rc = 0, needs_cow = 0;
859         u32 p_cpos, zero_clusters = 0;
860         u32 zero_cpos =
861                 zero_start >> OCFS2_SB(inode->i_sb)->s_clustersize_bits;
862         u32 last_cpos = ocfs2_clusters_for_bytes(inode->i_sb, zero_end);
863         unsigned int num_clusters = 0;
864         unsigned int ext_flags = 0;
865
866         while (zero_cpos < last_cpos) {
867                 rc = ocfs2_get_clusters(inode, zero_cpos, &p_cpos,
868                                         &num_clusters, &ext_flags);
869                 if (rc) {
870                         mlog_errno(rc);
871                         goto out;
872                 }
873
874                 if (p_cpos && !(ext_flags & OCFS2_EXT_UNWRITTEN)) {
875                         zero_clusters = num_clusters;
876                         if (ext_flags & OCFS2_EXT_REFCOUNTED)
877                                 needs_cow = 1;
878                         break;
879                 }
880
881                 zero_cpos += num_clusters;
882         }
883         if (!zero_clusters) {
884                 *range_end = 0;
885                 goto out;
886         }
887
888         while ((zero_cpos + zero_clusters) < last_cpos) {
889                 rc = ocfs2_get_clusters(inode, zero_cpos + zero_clusters,
890                                         &p_cpos, &num_clusters,
891                                         &ext_flags);
892                 if (rc) {
893                         mlog_errno(rc);
894                         goto out;
895                 }
896
897                 if (!p_cpos || (ext_flags & OCFS2_EXT_UNWRITTEN))
898                         break;
899                 if (ext_flags & OCFS2_EXT_REFCOUNTED)
900                         needs_cow = 1;
901                 zero_clusters += num_clusters;
902         }
903         if ((zero_cpos + zero_clusters) > last_cpos)
904                 zero_clusters = last_cpos - zero_cpos;
905
906         if (needs_cow) {
907                 rc = ocfs2_refcount_cow(inode, di_bh, zero_cpos, zero_clusters,
908                                         UINT_MAX);
909                 if (rc) {
910                         mlog_errno(rc);
911                         goto out;
912                 }
913         }
914
915         *range_start = ocfs2_clusters_to_bytes(inode->i_sb, zero_cpos);
916         *range_end = ocfs2_clusters_to_bytes(inode->i_sb,
917                                              zero_cpos + zero_clusters);
918
919 out:
920         return rc;
921 }
922
923 /*
924  * Zero one range returned from ocfs2_zero_extend_get_range().  The caller
925  * has made sure that the entire range needs zeroing.
926  */
927 static int ocfs2_zero_extend_range(struct inode *inode, u64 range_start,
928                                    u64 range_end)
929 {
930         int rc = 0;
931         u64 next_pos;
932         u64 zero_pos = range_start;
933
934         mlog(0, "range_start = %llu, range_end = %llu\n",
935              (unsigned long long)range_start,
936              (unsigned long long)range_end);
937         BUG_ON(range_start >= range_end);
938
939         while (zero_pos < range_end) {
940                 next_pos = (zero_pos & PAGE_CACHE_MASK) + PAGE_CACHE_SIZE;
941                 if (next_pos > range_end)
942                         next_pos = range_end;
943                 rc = ocfs2_write_zero_page(inode, zero_pos, next_pos);
944                 if (rc < 0) {
945                         mlog_errno(rc);
946                         break;
947                 }
948                 zero_pos = next_pos;
949
950                 /*
951                  * Very large extends have the potential to lock up
952                  * the cpu for extended periods of time.
953                  */
954                 cond_resched();
955         }
956
957         return rc;
958 }
959
960 int ocfs2_zero_extend(struct inode *inode, struct buffer_head *di_bh,
961                       loff_t zero_to_size)
962 {
963         int ret = 0;
964         u64 zero_start, range_start = 0, range_end = 0;
965         struct super_block *sb = inode->i_sb;
966
967         zero_start = ocfs2_align_bytes_to_blocks(sb, i_size_read(inode));
968         mlog(0, "zero_start %llu for i_size %llu\n",
969              (unsigned long long)zero_start,
970              (unsigned long long)i_size_read(inode));
971         while (zero_start < zero_to_size) {
972                 ret = ocfs2_zero_extend_get_range(inode, di_bh, zero_start,
973                                                   zero_to_size,
974                                                   &range_start,
975                                                   &range_end);
976                 if (ret) {
977                         mlog_errno(ret);
978                         break;
979                 }
980                 if (!range_end)
981                         break;
982                 /* Trim the ends */
983                 if (range_start < zero_start)
984                         range_start = zero_start;
985                 if (range_end > zero_to_size)
986                         range_end = zero_to_size;
987
988                 ret = ocfs2_zero_extend_range(inode, range_start,
989                                               range_end);
990                 if (ret) {
991                         mlog_errno(ret);
992                         break;
993                 }
994                 zero_start = range_end;
995         }
996
997         return ret;
998 }
999
1000 int ocfs2_extend_no_holes(struct inode *inode, struct buffer_head *di_bh,
1001                           u64 new_i_size, u64 zero_to)
1002 {
1003         int ret;
1004         u32 clusters_to_add;
1005         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1006
1007         /*
1008          * Only quota files call this without a bh, and they can't be
1009          * refcounted.
1010          */
1011         BUG_ON(!di_bh && (oi->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL));
1012         BUG_ON(!di_bh && !(oi->ip_flags & OCFS2_INODE_SYSTEM_FILE));
1013
1014         clusters_to_add = ocfs2_clusters_for_bytes(inode->i_sb, new_i_size);
1015         if (clusters_to_add < oi->ip_clusters)
1016                 clusters_to_add = 0;
1017         else
1018                 clusters_to_add -= oi->ip_clusters;
1019
1020         if (clusters_to_add) {
1021                 ret = __ocfs2_extend_allocation(inode, oi->ip_clusters,
1022                                                 clusters_to_add, 0);
1023                 if (ret) {
1024                         mlog_errno(ret);
1025                         goto out;
1026                 }
1027         }
1028
1029         /*
1030          * Call this even if we don't add any clusters to the tree. We
1031          * still need to zero the area between the old i_size and the
1032          * new i_size.
1033          */
1034         ret = ocfs2_zero_extend(inode, di_bh, zero_to);
1035         if (ret < 0)
1036                 mlog_errno(ret);
1037
1038 out:
1039         return ret;
1040 }
1041
1042 static int ocfs2_extend_file(struct inode *inode,
1043                              struct buffer_head *di_bh,
1044                              u64 new_i_size)
1045 {
1046         int ret = 0;
1047         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1048
1049         BUG_ON(!di_bh);
1050
1051         /* setattr sometimes calls us like this. */
1052         if (new_i_size == 0)
1053                 goto out;
1054
1055         if (i_size_read(inode) == new_i_size)
1056                 goto out;
1057         BUG_ON(new_i_size < i_size_read(inode));
1058
1059         /*
1060          * The alloc sem blocks people in read/write from reading our
1061          * allocation until we're done changing it. We depend on
1062          * i_mutex to block other extend/truncate calls while we're
1063          * here.  We even have to hold it for sparse files because there
1064          * might be some tail zeroing.
1065          */
1066         down_write(&oi->ip_alloc_sem);
1067
1068         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1069                 /*
1070                  * We can optimize small extends by keeping the inodes
1071                  * inline data.
1072                  */
1073                 if (ocfs2_size_fits_inline_data(di_bh, new_i_size)) {
1074                         up_write(&oi->ip_alloc_sem);
1075                         goto out_update_size;
1076                 }
1077
1078                 ret = ocfs2_convert_inline_data_to_extents(inode, di_bh);
1079                 if (ret) {
1080                         up_write(&oi->ip_alloc_sem);
1081                         mlog_errno(ret);
1082                         goto out;
1083                 }
1084         }
1085
1086         if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))
1087                 ret = ocfs2_zero_extend(inode, di_bh, new_i_size);
1088         else
1089                 ret = ocfs2_extend_no_holes(inode, di_bh, new_i_size,
1090                                             new_i_size);
1091
1092         up_write(&oi->ip_alloc_sem);
1093
1094         if (ret < 0) {
1095                 mlog_errno(ret);
1096                 goto out;
1097         }
1098
1099 out_update_size:
1100         ret = ocfs2_simple_size_update(inode, di_bh, new_i_size);
1101         if (ret < 0)
1102                 mlog_errno(ret);
1103
1104 out:
1105         return ret;
1106 }
1107
1108 int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)
1109 {
1110         int status = 0, size_change;
1111         struct inode *inode = dentry->d_inode;
1112         struct super_block *sb = inode->i_sb;
1113         struct ocfs2_super *osb = OCFS2_SB(sb);
1114         struct buffer_head *bh = NULL;
1115         handle_t *handle = NULL;
1116         struct dquot *transfer_to[MAXQUOTAS] = { };
1117         int qtype;
1118
1119         mlog_entry("(0x%p, '%.*s')\n", dentry,
1120                    dentry->d_name.len, dentry->d_name.name);
1121
1122         /* ensuring we don't even attempt to truncate a symlink */
1123         if (S_ISLNK(inode->i_mode))
1124                 attr->ia_valid &= ~ATTR_SIZE;
1125
1126         if (attr->ia_valid & ATTR_MODE)
1127                 mlog(0, "mode change: %d\n", attr->ia_mode);
1128         if (attr->ia_valid & ATTR_UID)
1129                 mlog(0, "uid change: %d\n", attr->ia_uid);
1130         if (attr->ia_valid & ATTR_GID)
1131                 mlog(0, "gid change: %d\n", attr->ia_gid);
1132         if (attr->ia_valid & ATTR_SIZE)
1133                 mlog(0, "size change...\n");
1134         if (attr->ia_valid & (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME))
1135                 mlog(0, "time change...\n");
1136
1137 #define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \
1138                            | ATTR_GID | ATTR_UID | ATTR_MODE)
1139         if (!(attr->ia_valid & OCFS2_VALID_ATTRS)) {
1140                 mlog(0, "can't handle attrs: 0x%x\n", attr->ia_valid);
1141                 return 0;
1142         }
1143
1144         status = inode_change_ok(inode, attr);
1145         if (status)
1146                 return status;
1147
1148         if (is_quota_modification(inode, attr))
1149                 dquot_initialize(inode);
1150         size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
1151         if (size_change) {
1152                 status = ocfs2_rw_lock(inode, 1);
1153                 if (status < 0) {
1154                         mlog_errno(status);
1155                         goto bail;
1156                 }
1157         }
1158
1159         status = ocfs2_inode_lock(inode, &bh, 1);
1160         if (status < 0) {
1161                 if (status != -ENOENT)
1162                         mlog_errno(status);
1163                 goto bail_unlock_rw;
1164         }
1165
1166         if (size_change && attr->ia_size != i_size_read(inode)) {
1167                 status = inode_newsize_ok(inode, attr->ia_size);
1168                 if (status)
1169                         goto bail_unlock;
1170
1171                 if (i_size_read(inode) > attr->ia_size) {
1172                         if (ocfs2_should_order_data(inode)) {
1173                                 status = ocfs2_begin_ordered_truncate(inode,
1174                                                                       attr->ia_size);
1175                                 if (status)
1176                                         goto bail_unlock;
1177                         }
1178                         status = ocfs2_truncate_file(inode, bh, attr->ia_size);
1179                 } else
1180                         status = ocfs2_extend_file(inode, bh, attr->ia_size);
1181                 if (status < 0) {
1182                         if (status != -ENOSPC)
1183                                 mlog_errno(status);
1184                         status = -ENOSPC;
1185                         goto bail_unlock;
1186                 }
1187         }
1188
1189         if ((attr->ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
1190             (attr->ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
1191                 /*
1192                  * Gather pointers to quota structures so that allocation /
1193                  * freeing of quota structures happens here and not inside
1194                  * dquot_transfer() where we have problems with lock ordering
1195                  */
1196                 if (attr->ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid
1197                     && OCFS2_HAS_RO_COMPAT_FEATURE(sb,
1198                     OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
1199                         transfer_to[USRQUOTA] = dqget(sb, attr->ia_uid,
1200                                                       USRQUOTA);
1201                         if (!transfer_to[USRQUOTA]) {
1202                                 status = -ESRCH;
1203                                 goto bail_unlock;
1204                         }
1205                 }
1206                 if (attr->ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid
1207                     && OCFS2_HAS_RO_COMPAT_FEATURE(sb,
1208                     OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
1209                         transfer_to[GRPQUOTA] = dqget(sb, attr->ia_gid,
1210                                                       GRPQUOTA);
1211                         if (!transfer_to[GRPQUOTA]) {
1212                                 status = -ESRCH;
1213                                 goto bail_unlock;
1214                         }
1215                 }
1216                 handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +
1217                                            2 * ocfs2_quota_trans_credits(sb));
1218                 if (IS_ERR(handle)) {
1219                         status = PTR_ERR(handle);
1220                         mlog_errno(status);
1221                         goto bail_unlock;
1222                 }
1223                 status = __dquot_transfer(inode, transfer_to);
1224                 if (status < 0)
1225                         goto bail_commit;
1226         } else {
1227                 handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1228                 if (IS_ERR(handle)) {
1229                         status = PTR_ERR(handle);
1230                         mlog_errno(status);
1231                         goto bail_unlock;
1232                 }
1233         }
1234
1235         /*
1236          * This will intentionally not wind up calling simple_setsize(),
1237          * since all the work for a size change has been done above.
1238          * Otherwise, we could get into problems with truncate as
1239          * ip_alloc_sem is used there to protect against i_size
1240          * changes.
1241          */
1242         status = inode_setattr(inode, attr);
1243         if (status < 0) {
1244                 mlog_errno(status);
1245                 goto bail_commit;
1246         }
1247
1248         status = ocfs2_mark_inode_dirty(handle, inode, bh);
1249         if (status < 0)
1250                 mlog_errno(status);
1251
1252 bail_commit:
1253         ocfs2_commit_trans(osb, handle);
1254 bail_unlock:
1255         ocfs2_inode_unlock(inode, 1);
1256 bail_unlock_rw:
1257         if (size_change)
1258                 ocfs2_rw_unlock(inode, 1);
1259 bail:
1260         brelse(bh);
1261
1262         /* Release quota pointers in case we acquired them */
1263         for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1264                 dqput(transfer_to[qtype]);
1265
1266         if (!status && attr->ia_valid & ATTR_MODE) {
1267                 status = ocfs2_acl_chmod(inode);
1268                 if (status < 0)
1269                         mlog_errno(status);
1270         }
1271
1272         mlog_exit(status);
1273         return status;
1274 }
1275
1276 int ocfs2_getattr(struct vfsmount *mnt,
1277                   struct dentry *dentry,
1278                   struct kstat *stat)
1279 {
1280         struct inode *inode = dentry->d_inode;
1281         struct super_block *sb = dentry->d_inode->i_sb;
1282         struct ocfs2_super *osb = sb->s_fs_info;
1283         int err;
1284
1285         mlog_entry_void();
1286
1287         err = ocfs2_inode_revalidate(dentry);
1288         if (err) {
1289                 if (err != -ENOENT)
1290                         mlog_errno(err);
1291                 goto bail;
1292         }
1293
1294         generic_fillattr(inode, stat);
1295
1296         /* We set the blksize from the cluster size for performance */
1297         stat->blksize = osb->s_clustersize;
1298
1299 bail:
1300         mlog_exit(err);
1301
1302         return err;
1303 }
1304
1305 int ocfs2_permission(struct inode *inode, int mask)
1306 {
1307         int ret;
1308
1309         mlog_entry_void();
1310
1311         ret = ocfs2_inode_lock(inode, NULL, 0);
1312         if (ret) {
1313                 if (ret != -ENOENT)
1314                         mlog_errno(ret);
1315                 goto out;
1316         }
1317
1318         ret = generic_permission(inode, mask, ocfs2_check_acl);
1319
1320         ocfs2_inode_unlock(inode, 0);
1321 out:
1322         mlog_exit(ret);
1323         return ret;
1324 }
1325
1326 static int __ocfs2_write_remove_suid(struct inode *inode,
1327                                      struct buffer_head *bh)
1328 {
1329         int ret;
1330         handle_t *handle;
1331         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1332         struct ocfs2_dinode *di;
1333
1334         mlog_entry("(Inode %llu, mode 0%o)\n",
1335                    (unsigned long long)OCFS2_I(inode)->ip_blkno, inode->i_mode);
1336
1337         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1338         if (IS_ERR(handle)) {
1339                 ret = PTR_ERR(handle);
1340                 mlog_errno(ret);
1341                 goto out;
1342         }
1343
1344         ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), bh,
1345                                       OCFS2_JOURNAL_ACCESS_WRITE);
1346         if (ret < 0) {
1347                 mlog_errno(ret);
1348                 goto out_trans;
1349         }
1350
1351         inode->i_mode &= ~S_ISUID;
1352         if ((inode->i_mode & S_ISGID) && (inode->i_mode & S_IXGRP))
1353                 inode->i_mode &= ~S_ISGID;
1354
1355         di = (struct ocfs2_dinode *) bh->b_data;
1356         di->i_mode = cpu_to_le16(inode->i_mode);
1357
1358         ocfs2_journal_dirty(handle, bh);
1359
1360 out_trans:
1361         ocfs2_commit_trans(osb, handle);
1362 out:
1363         mlog_exit(ret);
1364         return ret;
1365 }
1366
1367 /*
1368  * Will look for holes and unwritten extents in the range starting at
1369  * pos for count bytes (inclusive).
1370  */
1371 static int ocfs2_check_range_for_holes(struct inode *inode, loff_t pos,
1372                                        size_t count)
1373 {
1374         int ret = 0;
1375         unsigned int extent_flags;
1376         u32 cpos, clusters, extent_len, phys_cpos;
1377         struct super_block *sb = inode->i_sb;
1378
1379         cpos = pos >> OCFS2_SB(sb)->s_clustersize_bits;
1380         clusters = ocfs2_clusters_for_bytes(sb, pos + count) - cpos;
1381
1382         while (clusters) {
1383                 ret = ocfs2_get_clusters(inode, cpos, &phys_cpos, &extent_len,
1384                                          &extent_flags);
1385                 if (ret < 0) {
1386                         mlog_errno(ret);
1387                         goto out;
1388                 }
1389
1390                 if (phys_cpos == 0 || (extent_flags & OCFS2_EXT_UNWRITTEN)) {
1391                         ret = 1;
1392                         break;
1393                 }
1394
1395                 if (extent_len > clusters)
1396                         extent_len = clusters;
1397
1398                 clusters -= extent_len;
1399                 cpos += extent_len;
1400         }
1401 out:
1402         return ret;
1403 }
1404
1405 static int ocfs2_write_remove_suid(struct inode *inode)
1406 {
1407         int ret;
1408         struct buffer_head *bh = NULL;
1409
1410         ret = ocfs2_read_inode_block(inode, &bh);
1411         if (ret < 0) {
1412                 mlog_errno(ret);
1413                 goto out;
1414         }
1415
1416         ret =  __ocfs2_write_remove_suid(inode, bh);
1417 out:
1418         brelse(bh);
1419         return ret;
1420 }
1421
1422 /*
1423  * Allocate enough extents to cover the region starting at byte offset
1424  * start for len bytes. Existing extents are skipped, any extents
1425  * added are marked as "unwritten".
1426  */
1427 static int ocfs2_allocate_unwritten_extents(struct inode *inode,
1428                                             u64 start, u64 len)
1429 {
1430         int ret;
1431         u32 cpos, phys_cpos, clusters, alloc_size;
1432         u64 end = start + len;
1433         struct buffer_head *di_bh = NULL;
1434
1435         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1436                 ret = ocfs2_read_inode_block(inode, &di_bh);
1437                 if (ret) {
1438                         mlog_errno(ret);
1439                         goto out;
1440                 }
1441
1442                 /*
1443                  * Nothing to do if the requested reservation range
1444                  * fits within the inode.
1445                  */
1446                 if (ocfs2_size_fits_inline_data(di_bh, end))
1447                         goto out;
1448
1449                 ret = ocfs2_convert_inline_data_to_extents(inode, di_bh);
1450                 if (ret) {
1451                         mlog_errno(ret);
1452                         goto out;
1453                 }
1454         }
1455
1456         /*
1457          * We consider both start and len to be inclusive.
1458          */
1459         cpos = start >> OCFS2_SB(inode->i_sb)->s_clustersize_bits;
1460         clusters = ocfs2_clusters_for_bytes(inode->i_sb, start + len);
1461         clusters -= cpos;
1462
1463         while (clusters) {
1464                 ret = ocfs2_get_clusters(inode, cpos, &phys_cpos,
1465                                          &alloc_size, NULL);
1466                 if (ret) {
1467                         mlog_errno(ret);
1468                         goto out;
1469                 }
1470
1471                 /*
1472                  * Hole or existing extent len can be arbitrary, so
1473                  * cap it to our own allocation request.
1474                  */
1475                 if (alloc_size > clusters)
1476                         alloc_size = clusters;
1477
1478                 if (phys_cpos) {
1479                         /*
1480                          * We already have an allocation at this
1481                          * region so we can safely skip it.
1482                          */
1483                         goto next;
1484                 }
1485
1486                 ret = __ocfs2_extend_allocation(inode, cpos, alloc_size, 1);
1487                 if (ret) {
1488                         if (ret != -ENOSPC)
1489                                 mlog_errno(ret);
1490                         goto out;
1491                 }
1492
1493 next:
1494                 cpos += alloc_size;
1495                 clusters -= alloc_size;
1496         }
1497
1498         ret = 0;
1499 out:
1500
1501         brelse(di_bh);
1502         return ret;
1503 }
1504
1505 /*
1506  * Truncate a byte range, avoiding pages within partial clusters. This
1507  * preserves those pages for the zeroing code to write to.
1508  */
1509 static void ocfs2_truncate_cluster_pages(struct inode *inode, u64 byte_start,
1510                                          u64 byte_len)
1511 {
1512         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1513         loff_t start, end;
1514         struct address_space *mapping = inode->i_mapping;
1515
1516         start = (loff_t)ocfs2_align_bytes_to_clusters(inode->i_sb, byte_start);
1517         end = byte_start + byte_len;
1518         end = end & ~(osb->s_clustersize - 1);
1519
1520         if (start < end) {
1521                 unmap_mapping_range(mapping, start, end - start, 0);
1522                 truncate_inode_pages_range(mapping, start, end - 1);
1523         }
1524 }
1525
1526 static int ocfs2_zero_partial_clusters(struct inode *inode,
1527                                        u64 start, u64 len)
1528 {
1529         int ret = 0;
1530         u64 tmpend, end = start + len;
1531         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1532         unsigned int csize = osb->s_clustersize;
1533         handle_t *handle;
1534
1535         /*
1536          * The "start" and "end" values are NOT necessarily part of
1537          * the range whose allocation is being deleted. Rather, this
1538          * is what the user passed in with the request. We must zero
1539          * partial clusters here. There's no need to worry about
1540          * physical allocation - the zeroing code knows to skip holes.
1541          */
1542         mlog(0, "byte start: %llu, end: %llu\n",
1543              (unsigned long long)start, (unsigned long long)end);
1544
1545         /*
1546          * If both edges are on a cluster boundary then there's no
1547          * zeroing required as the region is part of the allocation to
1548          * be truncated.
1549          */
1550         if ((start & (csize - 1)) == 0 && (end & (csize - 1)) == 0)
1551                 goto out;
1552
1553         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1554         if (IS_ERR(handle)) {
1555                 ret = PTR_ERR(handle);
1556                 mlog_errno(ret);
1557                 goto out;
1558         }
1559
1560         /*
1561          * We want to get the byte offset of the end of the 1st cluster.
1562          */
1563         tmpend = (u64)osb->s_clustersize + (start & ~(osb->s_clustersize - 1));
1564         if (tmpend > end)
1565                 tmpend = end;
1566
1567         mlog(0, "1st range: start: %llu, tmpend: %llu\n",
1568              (unsigned long long)start, (unsigned long long)tmpend);
1569
1570         ret = ocfs2_zero_range_for_truncate(inode, handle, start, tmpend);
1571         if (ret)
1572                 mlog_errno(ret);
1573
1574         if (tmpend < end) {
1575                 /*
1576                  * This may make start and end equal, but the zeroing
1577                  * code will skip any work in that case so there's no
1578                  * need to catch it up here.
1579                  */
1580                 start = end & ~(osb->s_clustersize - 1);
1581
1582                 mlog(0, "2nd range: start: %llu, end: %llu\n",
1583                      (unsigned long long)start, (unsigned long long)end);
1584
1585                 ret = ocfs2_zero_range_for_truncate(inode, handle, start, end);
1586                 if (ret)
1587                         mlog_errno(ret);
1588         }
1589
1590         ocfs2_commit_trans(osb, handle);
1591 out:
1592         return ret;
1593 }
1594
1595 static int ocfs2_find_rec(struct ocfs2_extent_list *el, u32 pos)
1596 {
1597         int i;
1598         struct ocfs2_extent_rec *rec = NULL;
1599
1600         for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
1601
1602                 rec = &el->l_recs[i];
1603
1604                 if (le32_to_cpu(rec->e_cpos) < pos)
1605                         break;
1606         }
1607
1608         return i;
1609 }
1610
1611 /*
1612  * Helper to calculate the punching pos and length in one run, we handle the
1613  * following three cases in order:
1614  *
1615  * - remove the entire record
1616  * - remove a partial record
1617  * - no record needs to be removed (hole-punching completed)
1618 */
1619 static void ocfs2_calc_trunc_pos(struct inode *inode,
1620                                  struct ocfs2_extent_list *el,
1621                                  struct ocfs2_extent_rec *rec,
1622                                  u32 trunc_start, u32 *trunc_cpos,
1623                                  u32 *trunc_len, u32 *trunc_end,
1624                                  u64 *blkno, int *done)
1625 {
1626         int ret = 0;
1627         u32 coff, range;
1628
1629         range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
1630
1631         if (le32_to_cpu(rec->e_cpos) >= trunc_start) {
1632                 *trunc_cpos = le32_to_cpu(rec->e_cpos);
1633                 /*
1634                  * Skip holes if any.
1635                  */
1636                 if (range < *trunc_end)
1637                         *trunc_end = range;
1638                 *trunc_len = *trunc_end - le32_to_cpu(rec->e_cpos);
1639                 *blkno = le64_to_cpu(rec->e_blkno);
1640                 *trunc_end = le32_to_cpu(rec->e_cpos);
1641         } else if (range > trunc_start) {
1642                 *trunc_cpos = trunc_start;
1643                 *trunc_len = *trunc_end - trunc_start;
1644                 coff = trunc_start - le32_to_cpu(rec->e_cpos);
1645                 *blkno = le64_to_cpu(rec->e_blkno) +
1646                                 ocfs2_clusters_to_blocks(inode->i_sb, coff);
1647                 *trunc_end = trunc_start;
1648         } else {
1649                 /*
1650                  * It may have two following possibilities:
1651                  *
1652                  * - last record has been removed
1653                  * - trunc_start was within a hole
1654                  *
1655                  * both two cases mean the completion of hole punching.
1656                  */
1657                 ret = 1;
1658         }
1659
1660         *done = ret;
1661 }
1662
1663 static int ocfs2_remove_inode_range(struct inode *inode,
1664                                     struct buffer_head *di_bh, u64 byte_start,
1665                                     u64 byte_len)
1666 {
1667         int ret = 0, flags = 0, done = 0, i;
1668         u32 trunc_start, trunc_len, trunc_end, trunc_cpos, phys_cpos;
1669         u32 cluster_in_el;
1670         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1671         struct ocfs2_cached_dealloc_ctxt dealloc;
1672         struct address_space *mapping = inode->i_mapping;
1673         struct ocfs2_extent_tree et;
1674         struct ocfs2_path *path = NULL;
1675         struct ocfs2_extent_list *el = NULL;
1676         struct ocfs2_extent_rec *rec = NULL;
1677         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1678         u64 blkno, refcount_loc = le64_to_cpu(di->i_refcount_loc);
1679
1680         ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh);
1681         ocfs2_init_dealloc_ctxt(&dealloc);
1682
1683         if (byte_len == 0)
1684                 return 0;
1685
1686         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1687                 ret = ocfs2_truncate_inline(inode, di_bh, byte_start,
1688                                             byte_start + byte_len, 0);
1689                 if (ret) {
1690                         mlog_errno(ret);
1691                         goto out;
1692                 }
1693                 /*
1694                  * There's no need to get fancy with the page cache
1695                  * truncate of an inline-data inode. We're talking
1696                  * about less than a page here, which will be cached
1697                  * in the dinode buffer anyway.
1698                  */
1699                 unmap_mapping_range(mapping, 0, 0, 0);
1700                 truncate_inode_pages(mapping, 0);
1701                 goto out;
1702         }
1703
1704         /*
1705          * For reflinks, we may need to CoW 2 clusters which might be
1706          * partially zero'd later, if hole's start and end offset were
1707          * within one cluster(means is not exactly aligned to clustersize).
1708          */
1709
1710         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL) {
1711
1712                 ret = ocfs2_cow_file_pos(inode, di_bh, byte_start);
1713                 if (ret) {
1714                         mlog_errno(ret);
1715                         goto out;
1716                 }
1717
1718                 ret = ocfs2_cow_file_pos(inode, di_bh, byte_start + byte_len);
1719                 if (ret) {
1720                         mlog_errno(ret);
1721                         goto out;
1722                 }
1723         }
1724
1725         trunc_start = ocfs2_clusters_for_bytes(osb->sb, byte_start);
1726         trunc_end = (byte_start + byte_len) >> osb->s_clustersize_bits;
1727         cluster_in_el = trunc_end;
1728
1729         mlog(0, "Inode: %llu, start: %llu, len: %llu, cstart: %u, cend: %u\n",
1730              (unsigned long long)OCFS2_I(inode)->ip_blkno,
1731              (unsigned long long)byte_start,
1732              (unsigned long long)byte_len, trunc_start, trunc_end);
1733
1734         ret = ocfs2_zero_partial_clusters(inode, byte_start, byte_len);
1735         if (ret) {
1736                 mlog_errno(ret);
1737                 goto out;
1738         }
1739
1740         path = ocfs2_new_path_from_et(&et);
1741         if (!path) {
1742                 ret = -ENOMEM;
1743                 mlog_errno(ret);
1744                 goto out;
1745         }
1746
1747         while (trunc_end > trunc_start) {
1748
1749                 ret = ocfs2_find_path(INODE_CACHE(inode), path,
1750                                       cluster_in_el);
1751                 if (ret) {
1752                         mlog_errno(ret);
1753                         goto out;
1754                 }
1755
1756                 el = path_leaf_el(path);
1757
1758                 i = ocfs2_find_rec(el, trunc_end);
1759                 /*
1760                  * Need to go to previous extent block.
1761                  */
1762                 if (i < 0) {
1763                         if (path->p_tree_depth == 0)
1764                                 break;
1765
1766                         ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb,
1767                                                             path,
1768                                                             &cluster_in_el);
1769                         if (ret) {
1770                                 mlog_errno(ret);
1771                                 goto out;
1772                         }
1773
1774                         /*
1775                          * We've reached the leftmost extent block,
1776                          * it's safe to leave.
1777                          */
1778                         if (cluster_in_el == 0)
1779                                 break;
1780
1781                         /*
1782                          * The 'pos' searched for previous extent block is
1783                          * always one cluster less than actual trunc_end.
1784                          */
1785                         trunc_end = cluster_in_el + 1;
1786
1787                         ocfs2_reinit_path(path, 1);
1788
1789                         continue;
1790
1791                 } else
1792                         rec = &el->l_recs[i];
1793
1794                 ocfs2_calc_trunc_pos(inode, el, rec, trunc_start, &trunc_cpos,
1795                                      &trunc_len, &trunc_end, &blkno, &done);
1796                 if (done)
1797                         break;
1798
1799                 flags = rec->e_flags;
1800                 phys_cpos = ocfs2_blocks_to_clusters(inode->i_sb, blkno);
1801
1802                 ret = ocfs2_remove_btree_range(inode, &et, trunc_cpos,
1803                                                phys_cpos, trunc_len, flags,
1804                                                &dealloc, refcount_loc);
1805                 if (ret < 0) {
1806                         mlog_errno(ret);
1807                         goto out;
1808                 }
1809
1810                 cluster_in_el = trunc_end;
1811
1812                 ocfs2_reinit_path(path, 1);
1813         }
1814
1815         ocfs2_truncate_cluster_pages(inode, byte_start, byte_len);
1816
1817 out:
1818         ocfs2_schedule_truncate_log_flush(osb, 1);
1819         ocfs2_run_deallocs(osb, &dealloc);
1820
1821         return ret;
1822 }
1823
1824 /*
1825  * Parts of this function taken from xfs_change_file_space()
1826  */
1827 static int __ocfs2_change_file_space(struct file *file, struct inode *inode,
1828                                      loff_t f_pos, unsigned int cmd,
1829                                      struct ocfs2_space_resv *sr,
1830                                      int change_size)
1831 {
1832         int ret;
1833         s64 llen;
1834         loff_t size;
1835         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1836         struct buffer_head *di_bh = NULL;
1837         handle_t *handle;
1838         unsigned long long max_off = inode->i_sb->s_maxbytes;
1839
1840         if (ocfs2_is_hard_readonly(osb) || ocfs2_is_soft_readonly(osb))
1841                 return -EROFS;
1842
1843         mutex_lock(&inode->i_mutex);
1844
1845         /*
1846          * This prevents concurrent writes on other nodes
1847          */
1848         ret = ocfs2_rw_lock(inode, 1);
1849         if (ret) {
1850                 mlog_errno(ret);
1851                 goto out;
1852         }
1853
1854         ret = ocfs2_inode_lock(inode, &di_bh, 1);
1855         if (ret) {
1856                 mlog_errno(ret);
1857                 goto out_rw_unlock;
1858         }
1859
1860         if (inode->i_flags & (S_IMMUTABLE|S_APPEND)) {
1861                 ret = -EPERM;
1862                 goto out_inode_unlock;
1863         }
1864
1865         switch (sr->l_whence) {
1866         case 0: /*SEEK_SET*/
1867                 break;
1868         case 1: /*SEEK_CUR*/
1869                 sr->l_start += f_pos;
1870                 break;
1871         case 2: /*SEEK_END*/
1872                 sr->l_start += i_size_read(inode);
1873                 break;
1874         default:
1875                 ret = -EINVAL;
1876                 goto out_inode_unlock;
1877         }
1878         sr->l_whence = 0;
1879
1880         llen = sr->l_len > 0 ? sr->l_len - 1 : sr->l_len;
1881
1882         if (sr->l_start < 0
1883             || sr->l_start > max_off
1884             || (sr->l_start + llen) < 0
1885             || (sr->l_start + llen) > max_off) {
1886                 ret = -EINVAL;
1887                 goto out_inode_unlock;
1888         }
1889         size = sr->l_start + sr->l_len;
1890
1891         if (cmd == OCFS2_IOC_RESVSP || cmd == OCFS2_IOC_RESVSP64) {
1892                 if (sr->l_len <= 0) {
1893                         ret = -EINVAL;
1894                         goto out_inode_unlock;
1895                 }
1896         }
1897
1898         if (file && should_remove_suid(file->f_path.dentry)) {
1899                 ret = __ocfs2_write_remove_suid(inode, di_bh);
1900                 if (ret) {
1901                         mlog_errno(ret);
1902                         goto out_inode_unlock;
1903                 }
1904         }
1905
1906         down_write(&OCFS2_I(inode)->ip_alloc_sem);
1907         switch (cmd) {
1908         case OCFS2_IOC_RESVSP:
1909         case OCFS2_IOC_RESVSP64:
1910                 /*
1911                  * This takes unsigned offsets, but the signed ones we
1912                  * pass have been checked against overflow above.
1913                  */
1914                 ret = ocfs2_allocate_unwritten_extents(inode, sr->l_start,
1915                                                        sr->l_len);
1916                 break;
1917         case OCFS2_IOC_UNRESVSP:
1918         case OCFS2_IOC_UNRESVSP64:
1919                 ret = ocfs2_remove_inode_range(inode, di_bh, sr->l_start,
1920                                                sr->l_len);
1921                 break;
1922         default:
1923                 ret = -EINVAL;
1924         }
1925         up_write(&OCFS2_I(inode)->ip_alloc_sem);
1926         if (ret) {
1927                 mlog_errno(ret);
1928                 goto out_inode_unlock;
1929         }
1930
1931         /*
1932          * We update c/mtime for these changes
1933          */
1934         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1935         if (IS_ERR(handle)) {
1936                 ret = PTR_ERR(handle);
1937                 mlog_errno(ret);
1938                 goto out_inode_unlock;
1939         }
1940
1941         if (change_size && i_size_read(inode) < size)
1942                 i_size_write(inode, size);
1943
1944         inode->i_ctime = inode->i_mtime = CURRENT_TIME;
1945         ret = ocfs2_mark_inode_dirty(handle, inode, di_bh);
1946         if (ret < 0)
1947                 mlog_errno(ret);
1948
1949         ocfs2_commit_trans(osb, handle);
1950
1951 out_inode_unlock:
1952         brelse(di_bh);
1953         ocfs2_inode_unlock(inode, 1);
1954 out_rw_unlock:
1955         ocfs2_rw_unlock(inode, 1);
1956
1957 out:
1958         mutex_unlock(&inode->i_mutex);
1959         return ret;
1960 }
1961
1962 int ocfs2_change_file_space(struct file *file, unsigned int cmd,
1963                             struct ocfs2_space_resv *sr)
1964 {
1965         struct inode *inode = file->f_path.dentry->d_inode;
1966         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1967
1968         if ((cmd == OCFS2_IOC_RESVSP || cmd == OCFS2_IOC_RESVSP64) &&
1969             !ocfs2_writes_unwritten_extents(osb))
1970                 return -ENOTTY;
1971         else if ((cmd == OCFS2_IOC_UNRESVSP || cmd == OCFS2_IOC_UNRESVSP64) &&
1972                  !ocfs2_sparse_alloc(osb))
1973                 return -ENOTTY;
1974
1975         if (!S_ISREG(inode->i_mode))
1976                 return -EINVAL;
1977
1978         if (!(file->f_mode & FMODE_WRITE))
1979                 return -EBADF;
1980
1981         return __ocfs2_change_file_space(file, inode, file->f_pos, cmd, sr, 0);
1982 }
1983
1984 static long ocfs2_fallocate(struct inode *inode, int mode, loff_t offset,
1985                             loff_t len)
1986 {
1987         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1988         struct ocfs2_space_resv sr;
1989         int change_size = 1;
1990
1991         if (!ocfs2_writes_unwritten_extents(osb))
1992                 return -EOPNOTSUPP;
1993
1994         if (S_ISDIR(inode->i_mode))
1995                 return -ENODEV;
1996
1997         if (mode & FALLOC_FL_KEEP_SIZE)
1998                 change_size = 0;
1999
2000         sr.l_whence = 0;
2001         sr.l_start = (s64)offset;
2002         sr.l_len = (s64)len;
2003
2004         return __ocfs2_change_file_space(NULL, inode, offset,
2005                                          OCFS2_IOC_RESVSP64, &sr, change_size);
2006 }
2007
2008 int ocfs2_check_range_for_refcount(struct inode *inode, loff_t pos,
2009                                    size_t count)
2010 {
2011         int ret = 0;
2012         unsigned int extent_flags;
2013         u32 cpos, clusters, extent_len, phys_cpos;
2014         struct super_block *sb = inode->i_sb;
2015
2016         if (!ocfs2_refcount_tree(OCFS2_SB(inode->i_sb)) ||
2017             !(OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL) ||
2018             OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
2019                 return 0;
2020
2021         cpos = pos >> OCFS2_SB(sb)->s_clustersize_bits;
2022         clusters = ocfs2_clusters_for_bytes(sb, pos + count) - cpos;
2023
2024         while (clusters) {
2025                 ret = ocfs2_get_clusters(inode, cpos, &phys_cpos, &extent_len,
2026                                          &extent_flags);
2027                 if (ret < 0) {
2028                         mlog_errno(ret);
2029                         goto out;
2030                 }
2031
2032                 if (phys_cpos && (extent_flags & OCFS2_EXT_REFCOUNTED)) {
2033                         ret = 1;
2034                         break;
2035                 }
2036
2037                 if (extent_len > clusters)
2038                         extent_len = clusters;
2039
2040                 clusters -= extent_len;
2041                 cpos += extent_len;
2042         }
2043 out:
2044         return ret;
2045 }
2046
2047 static int ocfs2_prepare_inode_for_refcount(struct inode *inode,
2048                                             loff_t pos, size_t count,
2049                                             int *meta_level)
2050 {
2051         int ret;
2052         struct buffer_head *di_bh = NULL;
2053         u32 cpos = pos >> OCFS2_SB(inode->i_sb)->s_clustersize_bits;
2054         u32 clusters =
2055                 ocfs2_clusters_for_bytes(inode->i_sb, pos + count) - cpos;
2056
2057         ret = ocfs2_inode_lock(inode, &di_bh, 1);
2058         if (ret) {
2059                 mlog_errno(ret);
2060                 goto out;
2061         }
2062
2063         *meta_level = 1;
2064
2065         ret = ocfs2_refcount_cow(inode, di_bh, cpos, clusters, UINT_MAX);
2066         if (ret)
2067                 mlog_errno(ret);
2068 out:
2069         brelse(di_bh);
2070         return ret;
2071 }
2072
2073 static int ocfs2_prepare_inode_for_write(struct dentry *dentry,
2074                                          loff_t *ppos,
2075                                          size_t count,
2076                                          int appending,
2077                                          int *direct_io,
2078                                          int *has_refcount)
2079 {
2080         int ret = 0, meta_level = 0;
2081         struct inode *inode = dentry->d_inode;
2082         loff_t saved_pos, end;
2083
2084         /*
2085          * We start with a read level meta lock and only jump to an ex
2086          * if we need to make modifications here.
2087          */
2088         for(;;) {
2089                 ret = ocfs2_inode_lock(inode, NULL, meta_level);
2090                 if (ret < 0) {
2091                         meta_level = -1;
2092                         mlog_errno(ret);
2093                         goto out;
2094                 }
2095
2096                 /* Clear suid / sgid if necessary. We do this here
2097                  * instead of later in the write path because
2098                  * remove_suid() calls ->setattr without any hint that
2099                  * we may have already done our cluster locking. Since
2100                  * ocfs2_setattr() *must* take cluster locks to
2101                  * proceeed, this will lead us to recursively lock the
2102                  * inode. There's also the dinode i_size state which
2103                  * can be lost via setattr during extending writes (we
2104                  * set inode->i_size at the end of a write. */
2105                 if (should_remove_suid(dentry)) {
2106                         if (meta_level == 0) {
2107                                 ocfs2_inode_unlock(inode, meta_level);
2108                                 meta_level = 1;
2109                                 continue;
2110                         }
2111
2112                         ret = ocfs2_write_remove_suid(inode);
2113                         if (ret < 0) {
2114                                 mlog_errno(ret);
2115                                 goto out_unlock;
2116                         }
2117                 }
2118
2119                 /* work on a copy of ppos until we're sure that we won't have
2120                  * to recalculate it due to relocking. */
2121                 if (appending) {
2122                         saved_pos = i_size_read(inode);
2123                         mlog(0, "O_APPEND: inode->i_size=%llu\n", saved_pos);
2124                 } else {
2125                         saved_pos = *ppos;
2126                 }
2127
2128                 end = saved_pos + count;
2129
2130                 ret = ocfs2_check_range_for_refcount(inode, saved_pos, count);
2131                 if (ret == 1) {
2132                         ocfs2_inode_unlock(inode, meta_level);
2133                         meta_level = -1;
2134
2135                         ret = ocfs2_prepare_inode_for_refcount(inode,
2136                                                                saved_pos,
2137                                                                count,
2138                                                                &meta_level);
2139                         if (has_refcount)
2140                                 *has_refcount = 1;
2141                         if (direct_io)
2142                                 *direct_io = 0;
2143                 }
2144
2145                 if (ret < 0) {
2146                         mlog_errno(ret);
2147                         goto out_unlock;
2148                 }
2149
2150                 /*
2151                  * Skip the O_DIRECT checks if we don't need
2152                  * them.
2153                  */
2154                 if (!direct_io || !(*direct_io))
2155                         break;
2156
2157                 /*
2158                  * There's no sane way to do direct writes to an inode
2159                  * with inline data.
2160                  */
2161                 if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
2162                         *direct_io = 0;
2163                         break;
2164                 }
2165
2166                 /*
2167                  * Allowing concurrent direct writes means
2168                  * i_size changes wouldn't be synchronized, so
2169                  * one node could wind up truncating another
2170                  * nodes writes.
2171                  */
2172                 if (end > i_size_read(inode)) {
2173                         *direct_io = 0;
2174                         break;
2175                 }
2176
2177                 /*
2178                  * We don't fill holes during direct io, so
2179                  * check for them here. If any are found, the
2180                  * caller will have to retake some cluster
2181                  * locks and initiate the io as buffered.
2182                  */
2183                 ret = ocfs2_check_range_for_holes(inode, saved_pos, count);
2184                 if (ret == 1) {
2185                         *direct_io = 0;
2186                         ret = 0;
2187                 } else if (ret < 0)
2188                         mlog_errno(ret);
2189                 break;
2190         }
2191
2192         if (appending)
2193                 *ppos = saved_pos;
2194
2195 out_unlock:
2196         if (meta_level >= 0)
2197                 ocfs2_inode_unlock(inode, meta_level);
2198
2199 out:
2200         return ret;
2201 }
2202
2203 static ssize_t ocfs2_file_aio_write(struct kiocb *iocb,
2204                                     const struct iovec *iov,
2205                                     unsigned long nr_segs,
2206                                     loff_t pos)
2207 {
2208         int ret, direct_io, appending, rw_level, have_alloc_sem  = 0;
2209         int can_do_direct, has_refcount = 0;
2210         ssize_t written = 0;
2211         size_t ocount;          /* original count */
2212         size_t count;           /* after file limit checks */
2213         loff_t old_size, *ppos = &iocb->ki_pos;
2214         u32 old_clusters;
2215         struct file *file = iocb->ki_filp;
2216         struct inode *inode = file->f_path.dentry->d_inode;
2217         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2218
2219         mlog_entry("(0x%p, %u, '%.*s')\n", file,
2220                    (unsigned int)nr_segs,
2221                    file->f_path.dentry->d_name.len,
2222                    file->f_path.dentry->d_name.name);
2223
2224         if (iocb->ki_left == 0)
2225                 return 0;
2226
2227         vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2228
2229         appending = file->f_flags & O_APPEND ? 1 : 0;
2230         direct_io = file->f_flags & O_DIRECT ? 1 : 0;
2231
2232         mutex_lock(&inode->i_mutex);
2233
2234 relock:
2235         /* to match setattr's i_mutex -> i_alloc_sem -> rw_lock ordering */
2236         if (direct_io) {
2237                 down_read(&inode->i_alloc_sem);
2238                 have_alloc_sem = 1;
2239         }
2240
2241         /* concurrent O_DIRECT writes are allowed */
2242         rw_level = !direct_io;
2243         ret = ocfs2_rw_lock(inode, rw_level);
2244         if (ret < 0) {
2245                 mlog_errno(ret);
2246                 goto out_sems;
2247         }
2248
2249         can_do_direct = direct_io;
2250         ret = ocfs2_prepare_inode_for_write(file->f_path.dentry, ppos,
2251                                             iocb->ki_left, appending,
2252                                             &can_do_direct, &has_refcount);
2253         if (ret < 0) {
2254                 mlog_errno(ret);
2255                 goto out;
2256         }
2257
2258         /*
2259          * We can't complete the direct I/O as requested, fall back to
2260          * buffered I/O.
2261          */
2262         if (direct_io && !can_do_direct) {
2263                 ocfs2_rw_unlock(inode, rw_level);
2264                 up_read(&inode->i_alloc_sem);
2265
2266                 have_alloc_sem = 0;
2267                 rw_level = -1;
2268
2269                 direct_io = 0;
2270                 goto relock;
2271         }
2272
2273         /*
2274          * To later detect whether a journal commit for sync writes is
2275          * necessary, we sample i_size, and cluster count here.
2276          */
2277         old_size = i_size_read(inode);
2278         old_clusters = OCFS2_I(inode)->ip_clusters;
2279
2280         /* communicate with ocfs2_dio_end_io */
2281         ocfs2_iocb_set_rw_locked(iocb, rw_level);
2282
2283         ret = generic_segment_checks(iov, &nr_segs, &ocount,
2284                                      VERIFY_READ);
2285         if (ret)
2286                 goto out_dio;
2287
2288         count = ocount;
2289         ret = generic_write_checks(file, ppos, &count,
2290                                    S_ISBLK(inode->i_mode));
2291         if (ret)
2292                 goto out_dio;
2293
2294         if (direct_io) {
2295                 written = generic_file_direct_write(iocb, iov, &nr_segs, *ppos,
2296                                                     ppos, count, ocount);
2297                 if (written < 0) {
2298                         /*
2299                          * direct write may have instantiated a few
2300                          * blocks outside i_size. Trim these off again.
2301                          * Don't need i_size_read because we hold i_mutex.
2302                          *
2303                          * XXX(hch): this looks buggy because ocfs2 did not
2304                          * actually implement ->truncate.  Take a look at
2305                          * the new truncate sequence and update this accordingly
2306                          */
2307                         if (*ppos + count > inode->i_size)
2308                                 simple_setsize(inode, inode->i_size);
2309                         ret = written;
2310                         goto out_dio;
2311                 }
2312         } else {
2313                 current->backing_dev_info = file->f_mapping->backing_dev_info;
2314                 written = generic_file_buffered_write(iocb, iov, nr_segs, *ppos,
2315                                                       ppos, count, 0);
2316                 current->backing_dev_info = NULL;
2317         }
2318
2319 out_dio:
2320         /* buffered aio wouldn't have proper lock coverage today */
2321         BUG_ON(ret == -EIOCBQUEUED && !(file->f_flags & O_DIRECT));
2322
2323         if (((file->f_flags & O_DSYNC) && !direct_io) || IS_SYNC(inode) ||
2324             ((file->f_flags & O_DIRECT) && has_refcount)) {
2325                 ret = filemap_fdatawrite_range(file->f_mapping, pos,
2326                                                pos + count - 1);
2327                 if (ret < 0)
2328                         written = ret;
2329
2330                 if (!ret && ((old_size != i_size_read(inode)) ||
2331                              (old_clusters != OCFS2_I(inode)->ip_clusters) ||
2332                              has_refcount)) {
2333                         ret = jbd2_journal_force_commit(osb->journal->j_journal);
2334                         if (ret < 0)
2335                                 written = ret;
2336                 }
2337
2338                 if (!ret)
2339                         ret = filemap_fdatawait_range(file->f_mapping, pos,
2340                                                       pos + count - 1);
2341         }
2342
2343         /*
2344          * deep in g_f_a_w_n()->ocfs2_direct_IO we pass in a ocfs2_dio_end_io
2345          * function pointer which is called when o_direct io completes so that
2346          * it can unlock our rw lock.  (it's the clustered equivalent of
2347          * i_alloc_sem; protects truncate from racing with pending ios).
2348          * Unfortunately there are error cases which call end_io and others
2349          * that don't.  so we don't have to unlock the rw_lock if either an
2350          * async dio is going to do it in the future or an end_io after an
2351          * error has already done it.
2352          */
2353         if ((ret == -EIOCBQUEUED) || (!ocfs2_iocb_is_rw_locked(iocb))) {
2354                 rw_level = -1;
2355                 have_alloc_sem = 0;
2356         }
2357
2358 out:
2359         if (rw_level != -1)
2360                 ocfs2_rw_unlock(inode, rw_level);
2361
2362 out_sems:
2363         if (have_alloc_sem)
2364                 up_read(&inode->i_alloc_sem);
2365
2366         mutex_unlock(&inode->i_mutex);
2367
2368         if (written)
2369                 ret = written;
2370         mlog_exit(ret);
2371         return ret;
2372 }
2373
2374 static int ocfs2_splice_to_file(struct pipe_inode_info *pipe,
2375                                 struct file *out,
2376                                 struct splice_desc *sd)
2377 {
2378         int ret;
2379
2380         ret = ocfs2_prepare_inode_for_write(out->f_path.dentry, &sd->pos,
2381                                             sd->total_len, 0, NULL, NULL);
2382         if (ret < 0) {
2383                 mlog_errno(ret);
2384                 return ret;
2385         }
2386
2387         return splice_from_pipe_feed(pipe, sd, pipe_to_file);
2388 }
2389
2390 static ssize_t ocfs2_file_splice_write(struct pipe_inode_info *pipe,
2391                                        struct file *out,
2392                                        loff_t *ppos,
2393                                        size_t len,
2394                                        unsigned int flags)
2395 {
2396         int ret;
2397         struct address_space *mapping = out->f_mapping;
2398         struct inode *inode = mapping->host;
2399         struct splice_desc sd = {
2400                 .total_len = len,
2401                 .flags = flags,
2402                 .pos = *ppos,
2403                 .u.file = out,
2404         };
2405
2406         mlog_entry("(0x%p, 0x%p, %u, '%.*s')\n", out, pipe,
2407                    (unsigned int)len,
2408                    out->f_path.dentry->d_name.len,
2409                    out->f_path.dentry->d_name.name);
2410
2411         if (pipe->inode)
2412                 mutex_lock_nested(&pipe->inode->i_mutex, I_MUTEX_PARENT);
2413
2414         splice_from_pipe_begin(&sd);
2415         do {
2416                 ret = splice_from_pipe_next(pipe, &sd);
2417                 if (ret <= 0)
2418                         break;
2419
2420                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2421                 ret = ocfs2_rw_lock(inode, 1);
2422                 if (ret < 0)
2423                         mlog_errno(ret);
2424                 else {
2425                         ret = ocfs2_splice_to_file(pipe, out, &sd);
2426                         ocfs2_rw_unlock(inode, 1);
2427                 }
2428                 mutex_unlock(&inode->i_mutex);
2429         } while (ret > 0);
2430         splice_from_pipe_end(pipe, &sd);
2431
2432         if (pipe->inode)
2433                 mutex_unlock(&pipe->inode->i_mutex);
2434
2435         if (sd.num_spliced)
2436                 ret = sd.num_spliced;
2437
2438         if (ret > 0) {
2439                 unsigned long nr_pages;
2440                 int err;
2441
2442                 nr_pages = (ret + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
2443
2444                 err = generic_write_sync(out, *ppos, ret);
2445                 if (err)
2446                         ret = err;
2447                 else
2448                         *ppos += ret;
2449
2450                 balance_dirty_pages_ratelimited_nr(mapping, nr_pages);
2451         }
2452
2453         mlog_exit(ret);
2454         return ret;
2455 }
2456
2457 static ssize_t ocfs2_file_splice_read(struct file *in,
2458                                       loff_t *ppos,
2459                                       struct pipe_inode_info *pipe,
2460                                       size_t len,
2461                                       unsigned int flags)
2462 {
2463         int ret = 0, lock_level = 0;
2464         struct inode *inode = in->f_path.dentry->d_inode;
2465
2466         mlog_entry("(0x%p, 0x%p, %u, '%.*s')\n", in, pipe,
2467                    (unsigned int)len,
2468                    in->f_path.dentry->d_name.len,
2469                    in->f_path.dentry->d_name.name);
2470
2471         /*
2472          * See the comment in ocfs2_file_aio_read()
2473          */
2474         ret = ocfs2_inode_lock_atime(inode, in->f_vfsmnt, &lock_level);
2475         if (ret < 0) {
2476                 mlog_errno(ret);
2477                 goto bail;
2478         }
2479         ocfs2_inode_unlock(inode, lock_level);
2480
2481         ret = generic_file_splice_read(in, ppos, pipe, len, flags);
2482
2483 bail:
2484         mlog_exit(ret);
2485         return ret;
2486 }
2487
2488 static ssize_t ocfs2_file_aio_read(struct kiocb *iocb,
2489                                    const struct iovec *iov,
2490                                    unsigned long nr_segs,
2491                                    loff_t pos)
2492 {
2493         int ret = 0, rw_level = -1, have_alloc_sem = 0, lock_level = 0;
2494         struct file *filp = iocb->ki_filp;
2495         struct inode *inode = filp->f_path.dentry->d_inode;
2496
2497         mlog_entry("(0x%p, %u, '%.*s')\n", filp,
2498                    (unsigned int)nr_segs,
2499                    filp->f_path.dentry->d_name.len,
2500                    filp->f_path.dentry->d_name.name);
2501
2502         if (!inode) {
2503                 ret = -EINVAL;
2504                 mlog_errno(ret);
2505                 goto bail;
2506         }
2507
2508         /*
2509          * buffered reads protect themselves in ->readpage().  O_DIRECT reads
2510          * need locks to protect pending reads from racing with truncate.
2511          */
2512         if (filp->f_flags & O_DIRECT) {
2513                 down_read(&inode->i_alloc_sem);
2514                 have_alloc_sem = 1;
2515
2516                 ret = ocfs2_rw_lock(inode, 0);
2517                 if (ret < 0) {
2518                         mlog_errno(ret);
2519                         goto bail;
2520                 }
2521                 rw_level = 0;
2522                 /* communicate with ocfs2_dio_end_io */
2523                 ocfs2_iocb_set_rw_locked(iocb, rw_level);
2524         }
2525
2526         /*
2527          * We're fine letting folks race truncates and extending
2528          * writes with read across the cluster, just like they can
2529          * locally. Hence no rw_lock during read.
2530          *
2531          * Take and drop the meta data lock to update inode fields
2532          * like i_size. This allows the checks down below
2533          * generic_file_aio_read() a chance of actually working.
2534          */
2535         ret = ocfs2_inode_lock_atime(inode, filp->f_vfsmnt, &lock_level);
2536         if (ret < 0) {
2537                 mlog_errno(ret);
2538                 goto bail;
2539         }
2540         ocfs2_inode_unlock(inode, lock_level);
2541
2542         ret = generic_file_aio_read(iocb, iov, nr_segs, iocb->ki_pos);
2543         if (ret == -EINVAL)
2544                 mlog(0, "generic_file_aio_read returned -EINVAL\n");
2545
2546         /* buffered aio wouldn't have proper lock coverage today */
2547         BUG_ON(ret == -EIOCBQUEUED && !(filp->f_flags & O_DIRECT));
2548
2549         /* see ocfs2_file_aio_write */
2550         if (ret == -EIOCBQUEUED || !ocfs2_iocb_is_rw_locked(iocb)) {
2551                 rw_level = -1;
2552                 have_alloc_sem = 0;
2553         }
2554
2555 bail:
2556         if (have_alloc_sem)
2557                 up_read(&inode->i_alloc_sem);
2558         if (rw_level != -1)
2559                 ocfs2_rw_unlock(inode, rw_level);
2560         mlog_exit(ret);
2561
2562         return ret;
2563 }
2564
2565 const struct inode_operations ocfs2_file_iops = {
2566         .setattr        = ocfs2_setattr,
2567         .getattr        = ocfs2_getattr,
2568         .permission     = ocfs2_permission,
2569         .setxattr       = generic_setxattr,
2570         .getxattr       = generic_getxattr,
2571         .listxattr      = ocfs2_listxattr,
2572         .removexattr    = generic_removexattr,
2573         .fallocate      = ocfs2_fallocate,
2574         .fiemap         = ocfs2_fiemap,
2575 };
2576
2577 const struct inode_operations ocfs2_special_file_iops = {
2578         .setattr        = ocfs2_setattr,
2579         .getattr        = ocfs2_getattr,
2580         .permission     = ocfs2_permission,
2581 };
2582
2583 /*
2584  * Other than ->lock, keep ocfs2_fops and ocfs2_dops in sync with
2585  * ocfs2_fops_no_plocks and ocfs2_dops_no_plocks!
2586  */
2587 const struct file_operations ocfs2_fops = {
2588         .llseek         = generic_file_llseek,
2589         .read           = do_sync_read,
2590         .write          = do_sync_write,
2591         .mmap           = ocfs2_mmap,
2592         .fsync          = ocfs2_sync_file,
2593         .release        = ocfs2_file_release,
2594         .open           = ocfs2_file_open,
2595         .aio_read       = ocfs2_file_aio_read,
2596         .aio_write      = ocfs2_file_aio_write,
2597         .unlocked_ioctl = ocfs2_ioctl,
2598 #ifdef CONFIG_COMPAT
2599         .compat_ioctl   = ocfs2_compat_ioctl,
2600 #endif
2601         .lock           = ocfs2_lock,
2602         .flock          = ocfs2_flock,
2603         .splice_read    = ocfs2_file_splice_read,
2604         .splice_write   = ocfs2_file_splice_write,
2605 };
2606
2607 const struct file_operations ocfs2_dops = {
2608         .llseek         = generic_file_llseek,
2609         .read           = generic_read_dir,
2610         .readdir        = ocfs2_readdir,
2611         .fsync          = ocfs2_sync_file,
2612         .release        = ocfs2_dir_release,
2613         .open           = ocfs2_dir_open,
2614         .unlocked_ioctl = ocfs2_ioctl,
2615 #ifdef CONFIG_COMPAT
2616         .compat_ioctl   = ocfs2_compat_ioctl,
2617 #endif
2618         .lock           = ocfs2_lock,
2619         .flock          = ocfs2_flock,
2620 };
2621
2622 /*
2623  * POSIX-lockless variants of our file_operations.
2624  *
2625  * These will be used if the underlying cluster stack does not support
2626  * posix file locking, if the user passes the "localflocks" mount
2627  * option, or if we have a local-only fs.
2628  *
2629  * ocfs2_flock is in here because all stacks handle UNIX file locks,
2630  * so we still want it in the case of no stack support for
2631  * plocks. Internally, it will do the right thing when asked to ignore
2632  * the cluster.
2633  */
2634 const struct file_operations ocfs2_fops_no_plocks = {
2635         .llseek         = generic_file_llseek,
2636         .read           = do_sync_read,
2637         .write          = do_sync_write,
2638         .mmap           = ocfs2_mmap,
2639         .fsync          = ocfs2_sync_file,
2640         .release        = ocfs2_file_release,
2641         .open           = ocfs2_file_open,
2642         .aio_read       = ocfs2_file_aio_read,
2643         .aio_write      = ocfs2_file_aio_write,
2644         .unlocked_ioctl = ocfs2_ioctl,
2645 #ifdef CONFIG_COMPAT
2646         .compat_ioctl   = ocfs2_compat_ioctl,
2647 #endif
2648         .flock          = ocfs2_flock,
2649         .splice_read    = ocfs2_file_splice_read,
2650         .splice_write   = ocfs2_file_splice_write,
2651 };
2652
2653 const struct file_operations ocfs2_dops_no_plocks = {
2654         .llseek         = generic_file_llseek,
2655         .read           = generic_read_dir,
2656         .readdir        = ocfs2_readdir,
2657         .fsync          = ocfs2_sync_file,
2658         .release        = ocfs2_dir_release,
2659         .open           = ocfs2_dir_open,
2660         .unlocked_ioctl = ocfs2_ioctl,
2661 #ifdef CONFIG_COMPAT
2662         .compat_ioctl   = ocfs2_compat_ioctl,
2663 #endif
2664         .flock          = ocfs2_flock,
2665 };