xref: /linux/fs/gfs2/file.c (revision 910a00830bc151d6fd8e515c834149080c4c4940)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) Sistina Software, Inc.  1997-2003 All rights reserved.
4  * Copyright (C) 2004-2006 Red Hat, Inc.  All rights reserved.
5  */
6 
7 #include <linux/slab.h>
8 #include <linux/spinlock.h>
9 #include <linux/compat.h>
10 #include <linux/completion.h>
11 #include <linux/buffer_head.h>
12 #include <linux/pagemap.h>
13 #include <linux/uio.h>
14 #include <linux/blkdev.h>
15 #include <linux/mm.h>
16 #include <linux/mount.h>
17 #include <linux/fs.h>
18 #include <linux/filelock.h>
19 #include <linux/gfs2_ondisk.h>
20 #include <linux/falloc.h>
21 #include <linux/swap.h>
22 #include <linux/crc32.h>
23 #include <linux/writeback.h>
24 #include <linux/uaccess.h>
25 #include <linux/dlm.h>
26 #include <linux/dlm_plock.h>
27 #include <linux/delay.h>
28 #include <linux/backing-dev.h>
29 #include <linux/fileattr.h>
30 
31 #include "gfs2.h"
32 #include "incore.h"
33 #include "bmap.h"
34 #include "aops.h"
35 #include "dir.h"
36 #include "glock.h"
37 #include "glops.h"
38 #include "inode.h"
39 #include "log.h"
40 #include "meta_io.h"
41 #include "quota.h"
42 #include "rgrp.h"
43 #include "trans.h"
44 #include "util.h"
45 
46 /**
47  * gfs2_llseek - seek to a location in a file
48  * @file: the file
49  * @offset: the offset
50  * @whence: Where to seek from (SEEK_SET, SEEK_CUR, or SEEK_END)
51  *
52  * SEEK_END requires the glock for the file because it references the
53  * file's size.
54  *
55  * Returns: The new offset, or errno
56  */
57 
58 static loff_t gfs2_llseek(struct file *file, loff_t offset, int whence)
59 {
60 	struct gfs2_glock *gl = gfs2_inode_glock(file->f_mapping->host);
61 	struct gfs2_holder i_gh;
62 	loff_t error;
63 
64 	switch (whence) {
65 	case SEEK_END:
66 		error = gfs2_glock_nq_init(gl, LM_ST_SHARED, LM_FLAG_ANY,
67 					   &i_gh);
68 		if (!error) {
69 			error = generic_file_llseek(file, offset, whence);
70 			gfs2_glock_dq_uninit(&i_gh);
71 		}
72 		break;
73 
74 	case SEEK_DATA:
75 		error = gfs2_seek_data(file, offset);
76 		break;
77 
78 	case SEEK_HOLE:
79 		error = gfs2_seek_hole(file, offset);
80 		break;
81 
82 	case SEEK_CUR:
83 	case SEEK_SET:
84 		/*
85 		 * These don't reference inode->i_size and don't depend on the
86 		 * block mapping, so we don't need the glock.
87 		 */
88 		error = generic_file_llseek(file, offset, whence);
89 		break;
90 	default:
91 		error = -EINVAL;
92 	}
93 
94 	return error;
95 }
96 
97 /**
98  * gfs2_readdir - Iterator for a directory
99  * @file: The directory to read from
100  * @ctx: What to feed directory entries to
101  *
102  * Returns: errno
103  */
104 
105 static int gfs2_readdir(struct file *file, struct dir_context *ctx)
106 {
107 	struct inode *dir = file->f_mapping->host;
108 	struct gfs2_glock *gl = gfs2_inode_glock(dir);
109 	struct gfs2_holder d_gh;
110 	int error;
111 
112 	error = gfs2_glock_nq_init(gl, LM_ST_SHARED, 0, &d_gh);
113 	if (error)
114 		return error;
115 
116 	error = gfs2_dir_read(dir, ctx, &file->f_ra);
117 
118 	gfs2_glock_dq_uninit(&d_gh);
119 
120 	return error;
121 }
122 
123 /*
124  * struct fsflag_gfs2flag
125  *
126  * The FS_JOURNAL_DATA_FL flag maps to GFS2_DIF_INHERIT_JDATA for directories,
127  * and to GFS2_DIF_JDATA for non-directories.
128  */
129 static struct {
130 	u32 fsflag;
131 	u32 gfsflag;
132 } fsflag_gfs2flag[] = {
133 	{FS_SYNC_FL, GFS2_DIF_SYNC},
134 	{FS_IMMUTABLE_FL, GFS2_DIF_IMMUTABLE},
135 	{FS_APPEND_FL, GFS2_DIF_APPENDONLY},
136 	{FS_NOATIME_FL, GFS2_DIF_NOATIME},
137 	{FS_INDEX_FL, GFS2_DIF_EXHASH},
138 	{FS_TOPDIR_FL, GFS2_DIF_TOPDIR},
139 	{FS_JOURNAL_DATA_FL, GFS2_DIF_JDATA | GFS2_DIF_INHERIT_JDATA},
140 };
141 
142 static inline u32 gfs2_gfsflags_to_fsflags(struct inode *inode, u32 gfsflags)
143 {
144 	int i;
145 	u32 fsflags = 0;
146 
147 	if (S_ISDIR(inode->i_mode))
148 		gfsflags &= ~GFS2_DIF_JDATA;
149 	else
150 		gfsflags &= ~GFS2_DIF_INHERIT_JDATA;
151 
152 	for (i = 0; i < ARRAY_SIZE(fsflag_gfs2flag); i++)
153 		if (gfsflags & fsflag_gfs2flag[i].gfsflag)
154 			fsflags |= fsflag_gfs2flag[i].fsflag;
155 	return fsflags;
156 }
157 
158 int gfs2_fileattr_get(struct dentry *dentry, struct file_kattr *fa)
159 {
160 	struct inode *inode = d_inode(dentry);
161 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
162 	struct gfs2_inode *ip = GFS2_I(inode);
163 	struct gfs2_holder gh;
164 	int error;
165 	u32 fsflags;
166 
167 	if (d_is_special(dentry))
168 		return -ENOTTY;
169 
170 	gfs2_holder_init(gl, LM_ST_SHARED, 0, &gh);
171 	error = gfs2_glock_nq(&gh);
172 	if (error)
173 		goto out_uninit;
174 
175 	fsflags = gfs2_gfsflags_to_fsflags(inode, ip->i_diskflags);
176 
177 	fileattr_fill_flags(fa, fsflags);
178 
179 	gfs2_glock_dq(&gh);
180 out_uninit:
181 	gfs2_holder_uninit(&gh);
182 	return error;
183 }
184 
185 void gfs2_set_inode_flags(struct inode *inode)
186 {
187 	struct gfs2_inode *ip = GFS2_I(inode);
188 	unsigned int flags = inode->i_flags;
189 
190 	flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_NOSEC);
191 	if ((ip->i_eattr == 0) && !is_sxid(inode->i_mode))
192 		flags |= S_NOSEC;
193 	if (ip->i_diskflags & GFS2_DIF_IMMUTABLE)
194 		flags |= S_IMMUTABLE;
195 	if (ip->i_diskflags & GFS2_DIF_APPENDONLY)
196 		flags |= S_APPEND;
197 	if (ip->i_diskflags & GFS2_DIF_NOATIME)
198 		flags |= S_NOATIME;
199 	if (ip->i_diskflags & GFS2_DIF_SYNC)
200 		flags |= S_SYNC;
201 	inode->i_flags = flags;
202 }
203 
204 /* Flags that can be set by user space */
205 #define GFS2_FLAGS_USER_SET (GFS2_DIF_JDATA|			\
206 			     GFS2_DIF_IMMUTABLE|		\
207 			     GFS2_DIF_APPENDONLY|		\
208 			     GFS2_DIF_NOATIME|			\
209 			     GFS2_DIF_SYNC|			\
210 			     GFS2_DIF_TOPDIR|			\
211 			     GFS2_DIF_INHERIT_JDATA)
212 
213 /**
214  * do_gfs2_set_flags - set flags on an inode
215  * @inode: The inode
216  * @reqflags: The flags to set
217  * @mask: Indicates which flags are valid
218  *
219  */
220 static int do_gfs2_set_flags(struct inode *inode, u32 reqflags, u32 mask)
221 {
222 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
223 	struct gfs2_inode *ip = GFS2_I(inode);
224 	struct gfs2_sbd *sdp = GFS2_SB(inode);
225 	struct buffer_head *bh;
226 	struct gfs2_holder gh;
227 	int error;
228 	u32 new_flags, flags;
229 
230 	error = gfs2_glock_nq_init(gl, LM_ST_EXCLUSIVE, 0, &gh);
231 	if (error)
232 		return error;
233 
234 	error = 0;
235 	flags = ip->i_diskflags;
236 	new_flags = (flags & ~mask) | (reqflags & mask);
237 	if ((new_flags ^ flags) == 0)
238 		goto out;
239 
240 	if (!IS_IMMUTABLE(inode)) {
241 		error = gfs2_permission(&nop_mnt_idmap, inode, MAY_WRITE);
242 		if (error)
243 			goto out;
244 	}
245 	if ((flags ^ new_flags) & GFS2_DIF_JDATA) {
246 		if (new_flags & GFS2_DIF_JDATA)
247 			gfs2_log_flush(sdp, gl,
248 				       GFS2_LOG_HEAD_FLUSH_NORMAL |
249 				       GFS2_LFC_SET_FLAGS);
250 		error = filemap_fdatawrite(inode->i_mapping);
251 		if (error)
252 			goto out;
253 		error = filemap_fdatawait(inode->i_mapping);
254 		if (error)
255 			goto out;
256 		truncate_inode_pages(inode->i_mapping, 0);
257 		if (new_flags & GFS2_DIF_JDATA)
258 			gfs2_ordered_del_inode(ip);
259 	}
260 	error = gfs2_trans_begin(sdp, RES_DINODE, 0);
261 	if (error)
262 		goto out;
263 	error = gfs2_meta_inode_buffer(ip, &bh);
264 	if (error)
265 		goto out_trans_end;
266 	inode_set_ctime_current(inode);
267 	gfs2_trans_add_meta(gl, bh);
268 	ip->i_diskflags = new_flags;
269 	gfs2_dinode_out(ip, bh->b_data);
270 	brelse(bh);
271 	gfs2_set_inode_flags(inode);
272 	gfs2_set_aops(inode);
273 out_trans_end:
274 	gfs2_trans_end(sdp);
275 out:
276 	gfs2_glock_dq_uninit(&gh);
277 	return error;
278 }
279 
280 int gfs2_fileattr_set(const struct mnt_idmap *idmap,
281 		      struct dentry *dentry, struct file_kattr *fa)
282 {
283 	struct inode *inode = d_inode(dentry);
284 	u32 fsflags = fa->flags, gfsflags = 0;
285 	u32 mask;
286 	int i;
287 
288 	if (d_is_special(dentry))
289 		return -ENOTTY;
290 
291 	if (fileattr_has_fsx(fa))
292 		return -EOPNOTSUPP;
293 
294 	for (i = 0; i < ARRAY_SIZE(fsflag_gfs2flag); i++) {
295 		if (fsflags & fsflag_gfs2flag[i].fsflag) {
296 			fsflags &= ~fsflag_gfs2flag[i].fsflag;
297 			gfsflags |= fsflag_gfs2flag[i].gfsflag;
298 		}
299 	}
300 	if (fsflags || gfsflags & ~GFS2_FLAGS_USER_SET)
301 		return -EINVAL;
302 
303 	mask = GFS2_FLAGS_USER_SET;
304 	if (S_ISDIR(inode->i_mode)) {
305 		mask &= ~GFS2_DIF_JDATA;
306 	} else {
307 		/* The GFS2_DIF_TOPDIR flag is only valid for directories. */
308 		if (gfsflags & GFS2_DIF_TOPDIR)
309 			return -EINVAL;
310 		mask &= ~(GFS2_DIF_TOPDIR | GFS2_DIF_INHERIT_JDATA);
311 	}
312 
313 	return do_gfs2_set_flags(inode, gfsflags, mask);
314 }
315 
316 static int gfs2_getlabel(struct file *filp, char __user *label)
317 {
318 	struct inode *inode = file_inode(filp);
319 	struct gfs2_sbd *sdp = GFS2_SB(inode);
320 
321 	if (copy_to_user(label, sdp->sd_sb.sb_locktable, GFS2_LOCKNAME_LEN))
322 		return -EFAULT;
323 
324 	return 0;
325 }
326 
327 static long gfs2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
328 {
329 	switch(cmd) {
330 	case FITRIM:
331 		return gfs2_fitrim(filp, (void __user *)arg);
332 	case FS_IOC_GETFSLABEL:
333 		return gfs2_getlabel(filp, (char __user *)arg);
334 	}
335 
336 	return -ENOTTY;
337 }
338 
339 #ifdef CONFIG_COMPAT
340 static long gfs2_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
341 {
342 	switch(cmd) {
343 	/* Keep this list in sync with gfs2_ioctl */
344 	case FITRIM:
345 	case FS_IOC_GETFSLABEL:
346 		break;
347 	default:
348 		return -ENOIOCTLCMD;
349 	}
350 
351 	return gfs2_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
352 }
353 #else
354 #define gfs2_compat_ioctl NULL
355 #endif
356 
357 /**
358  * gfs2_size_hint - Give a hint to the size of a write request
359  * @filep: The struct file
360  * @offset: The file offset of the write
361  * @size: The length of the write
362  *
363  * When we are about to do a write, this function records the total
364  * write size in order to provide a suitable hint to the lower layers
365  * about how many blocks will be required.
366  *
367  */
368 
369 static void gfs2_size_hint(struct file *filep, loff_t offset, size_t size)
370 {
371 	struct inode *inode = file_inode(filep);
372 	struct gfs2_sbd *sdp = GFS2_SB(inode);
373 	struct gfs2_inode *ip = GFS2_I(inode);
374 	size_t blks = (size + sdp->sd_sb.sb_bsize - 1) >> sdp->sd_sb.sb_bsize_shift;
375 	int hint = min_t(size_t, INT_MAX, blks);
376 
377 	if (hint > atomic_read(&ip->i_sizehint))
378 		atomic_set(&ip->i_sizehint, hint);
379 }
380 
381 /**
382  * gfs2_allocate_folio_backing - Allocate blocks for a write fault
383  * @folio: The (locked) folio to allocate backing for
384  * @length: Size of the allocation
385  *
386  * We try to allocate all the blocks required for the folio in one go.  This
387  * might fail for various reasons, so we keep trying until all the blocks to
388  * back this folio are allocated.  If some of the blocks are already allocated,
389  * that is ok too.
390  */
391 static int gfs2_allocate_folio_backing(struct folio *folio, size_t length)
392 {
393 	u64 pos = folio_pos(folio);
394 
395 	do {
396 		struct iomap iomap = { };
397 
398 		if (gfs2_iomap_alloc(folio->mapping->host, pos, length, &iomap))
399 			return -EIO;
400 
401 		if (length < iomap.length)
402 			iomap.length = length;
403 		length -= iomap.length;
404 		pos += iomap.length;
405 	} while (length > 0);
406 
407 	return 0;
408 }
409 
410 /**
411  * gfs2_page_mkwrite - Make a shared, mmap()ed, page writable
412  * @vmf: The virtual memory fault containing the page to become writable
413  *
414  * When the page becomes writable, we need to ensure that we have
415  * blocks allocated on disk to back that page.
416  */
417 
418 static vm_fault_t gfs2_page_mkwrite(struct vm_fault *vmf)
419 {
420 	struct folio *folio = page_folio(vmf->page);
421 	struct inode *inode = file_inode(vmf->vma->vm_file);
422 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
423 	struct gfs2_inode *ip = GFS2_I(inode);
424 	struct gfs2_sbd *sdp = GFS2_SB(inode);
425 	struct gfs2_alloc_parms ap = {};
426 	u64 pos = folio_pos(folio);
427 	unsigned int data_blocks, ind_blocks, rblocks;
428 	vm_fault_t ret = VM_FAULT_LOCKED;
429 	struct gfs2_holder gh;
430 	size_t length;
431 	loff_t size;
432 	int err;
433 
434 	sb_start_pagefault(inode->i_sb);
435 
436 	gfs2_holder_init(gl, LM_ST_EXCLUSIVE, 0, &gh);
437 	err = gfs2_glock_nq(&gh);
438 	if (err) {
439 		ret = vmf_fs_error(err);
440 		goto out_uninit;
441 	}
442 
443 	/* Check folio index against inode size */
444 	size = i_size_read(inode);
445 	if (pos >= size) {
446 		ret = VM_FAULT_SIGBUS;
447 		goto out_unlock;
448 	}
449 
450 	/* Update file times before taking folio lock */
451 	file_update_time(vmf->vma->vm_file);
452 
453 	/* folio is wholly or partially inside EOF */
454 	if (size - pos < folio_size(folio))
455 		length = size - pos;
456 	else
457 		length = folio_size(folio);
458 
459 	gfs2_size_hint(vmf->vma->vm_file, pos, length);
460 
461 	set_bit(GLF_DIRTY, &gl->gl_flags);
462 	set_bit(GIF_SW_PAGED, &ip->i_flags);
463 
464 	/*
465 	 * iomap_writepage / iomap_writepages currently don't support inline
466 	 * files, so always unstuff here.
467 	 */
468 
469 	if (!gfs2_is_stuffed(ip) &&
470 	    !gfs2_write_alloc_required(ip, pos, length)) {
471 		folio_lock(folio);
472 		if (!folio_test_uptodate(folio) ||
473 		    folio->mapping != inode->i_mapping) {
474 			ret = VM_FAULT_NOPAGE;
475 			folio_unlock(folio);
476 		}
477 		goto out_unlock;
478 	}
479 
480 	err = gfs2_rindex_update(sdp);
481 	if (err) {
482 		ret = vmf_fs_error(err);
483 		goto out_unlock;
484 	}
485 
486 	gfs2_write_calc_reserv(ip, length, &data_blocks, &ind_blocks);
487 	ap.target = data_blocks + ind_blocks;
488 	err = gfs2_quota_lock_check(ip, &ap);
489 	if (err) {
490 		ret = vmf_fs_error(err);
491 		goto out_unlock;
492 	}
493 	err = gfs2_inplace_reserve(ip, &ap);
494 	if (err) {
495 		ret = vmf_fs_error(err);
496 		goto out_quota_unlock;
497 	}
498 
499 	rblocks = RES_DINODE + ind_blocks;
500 	if (gfs2_is_jdata(ip))
501 		rblocks += data_blocks ? data_blocks : 1;
502 	if (ind_blocks || data_blocks) {
503 		rblocks += RES_STATFS + RES_QUOTA;
504 		rblocks += gfs2_rg_blocks(ip, data_blocks + ind_blocks);
505 	}
506 	err = gfs2_trans_begin(sdp, rblocks, 0);
507 	if (err) {
508 		ret = vmf_fs_error(err);
509 		goto out_trans_fail;
510 	}
511 
512 	/* Unstuff, if required, and allocate backing blocks for folio */
513 	if (gfs2_is_stuffed(ip)) {
514 		err = gfs2_unstuff_dinode(ip);
515 		if (err) {
516 			ret = vmf_fs_error(err);
517 			goto out_trans_end;
518 		}
519 	}
520 
521 	folio_lock(folio);
522 	/* If truncated, we must retry the operation, we may have raced
523 	 * with the glock demotion code.
524 	 */
525 	if (!folio_test_uptodate(folio) || folio->mapping != inode->i_mapping) {
526 		ret = VM_FAULT_NOPAGE;
527 		goto out_page_locked;
528 	}
529 
530 	err = gfs2_allocate_folio_backing(folio, length);
531 	if (err)
532 		ret = vmf_fs_error(err);
533 
534 out_page_locked:
535 	if (ret != VM_FAULT_LOCKED)
536 		folio_unlock(folio);
537 out_trans_end:
538 	gfs2_trans_end(sdp);
539 out_trans_fail:
540 	gfs2_inplace_release(ip);
541 out_quota_unlock:
542 	gfs2_quota_unlock(ip);
543 out_unlock:
544 	gfs2_glock_dq(&gh);
545 out_uninit:
546 	gfs2_holder_uninit(&gh);
547 	if (ret == VM_FAULT_LOCKED) {
548 		folio_mark_dirty(folio);
549 		folio_wait_stable(folio);
550 	}
551 	sb_end_pagefault(inode->i_sb);
552 	return ret;
553 }
554 
555 static vm_fault_t gfs2_fault(struct vm_fault *vmf)
556 {
557 	struct inode *inode = file_inode(vmf->vma->vm_file);
558 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
559 	struct gfs2_holder gh;
560 	vm_fault_t ret;
561 	int err;
562 
563 	gfs2_holder_init(gl, LM_ST_SHARED, 0, &gh);
564 	err = gfs2_glock_nq(&gh);
565 	if (err) {
566 		ret = vmf_fs_error(err);
567 		goto out_uninit;
568 	}
569 	ret = filemap_fault(vmf);
570 	gfs2_glock_dq(&gh);
571 out_uninit:
572 	gfs2_holder_uninit(&gh);
573 	return ret;
574 }
575 
576 static const struct vm_operations_struct gfs2_vm_ops = {
577 	.fault = gfs2_fault,
578 	.map_pages = filemap_map_pages,
579 	.page_mkwrite = gfs2_page_mkwrite,
580 };
581 
582 /**
583  * gfs2_mmap
584  * @file: The file to map
585  * @vma: The VMA which described the mapping
586  *
587  * There is no need to get a lock here unless we should be updating
588  * atime. We ignore any locking errors since the only consequence is
589  * a missed atime update (which will just be deferred until later).
590  *
591  * Returns: 0
592  */
593 
594 static int gfs2_mmap(struct file *file, struct vm_area_struct *vma)
595 {
596 	struct gfs2_glock *gl = gfs2_inode_glock(file->f_mapping->host);
597 	struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
598 
599 	if (!(file->f_flags & O_NOATIME) &&
600 	    !IS_NOATIME(&ip->i_inode)) {
601 		struct gfs2_holder i_gh;
602 		int error;
603 
604 		error = gfs2_glock_nq_init(gl, LM_ST_SHARED, LM_FLAG_ANY,
605 					   &i_gh);
606 		if (error)
607 			return error;
608 		/* grab lock to update inode */
609 		gfs2_glock_dq_uninit(&i_gh);
610 		file_accessed(file);
611 	}
612 	vma->vm_ops = &gfs2_vm_ops;
613 
614 	return 0;
615 }
616 
617 /**
618  * gfs2_open_common - This is common to open and atomic_open
619  * @inode: The inode being opened
620  * @file: The file being opened
621  *
622  * This maybe called under a glock or not depending upon how it has
623  * been called. We must always be called under a glock for regular
624  * files, however. For other file types, it does not matter whether
625  * we hold the glock or not.
626  *
627  * Returns: Error code or 0 for success
628  */
629 
630 int gfs2_open_common(struct inode *inode, struct file *file)
631 {
632 	struct gfs2_file *fp;
633 	int ret;
634 
635 	if (S_ISREG(inode->i_mode)) {
636 		ret = generic_file_open(inode, file);
637 		if (ret)
638 			return ret;
639 
640 		if (!gfs2_is_jdata(GFS2_I(inode)))
641 			file->f_mode |= FMODE_CAN_ODIRECT;
642 	}
643 
644 	fp = kzalloc_obj(struct gfs2_file, GFP_NOFS);
645 	if (!fp)
646 		return -ENOMEM;
647 
648 	mutex_init(&fp->f_fl_mutex);
649 
650 	gfs2_assert_warn(GFS2_SB(inode), !file->private_data);
651 	file->private_data = fp;
652 	if (file->f_mode & FMODE_WRITE) {
653 		ret = gfs2_qa_get(GFS2_I(inode));
654 		if (ret)
655 			goto fail;
656 	}
657 	return 0;
658 
659 fail:
660 	kfree(file->private_data);
661 	file->private_data = NULL;
662 	return ret;
663 }
664 
665 /**
666  * gfs2_open - open a file
667  * @inode: the inode to open
668  * @file: the struct file for this opening
669  *
670  * After atomic_open, this function is only used for opening files
671  * which are already cached. We must still get the glock for regular
672  * files to ensure that we have the file size uptodate for the large
673  * file check which is in the common code. That is only an issue for
674  * regular files though.
675  *
676  * Returns: errno
677  */
678 
679 static int gfs2_open(struct inode *inode, struct file *file)
680 {
681 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
682 	struct gfs2_inode *ip = GFS2_I(inode);
683 	struct gfs2_holder i_gh;
684 	int error;
685 	bool need_unlock = false;
686 
687 	if (S_ISREG(ip->i_inode.i_mode)) {
688 		error = gfs2_glock_nq_init(gl, LM_ST_SHARED, LM_FLAG_ANY,
689 					   &i_gh);
690 		if (error)
691 			return error;
692 		need_unlock = true;
693 	}
694 
695 	error = gfs2_open_common(inode, file);
696 
697 	if (need_unlock)
698 		gfs2_glock_dq_uninit(&i_gh);
699 
700 	return error;
701 }
702 
703 /**
704  * gfs2_release - called to close a struct file
705  * @inode: the inode the struct file belongs to
706  * @file: the struct file being closed
707  *
708  * Returns: errno
709  */
710 
711 static int gfs2_release(struct inode *inode, struct file *file)
712 {
713 	struct gfs2_inode *ip = GFS2_I(inode);
714 
715 	kfree(file->private_data);
716 	file->private_data = NULL;
717 
718 	if (file->f_mode & FMODE_WRITE) {
719 		if (gfs2_rs_active(&ip->i_res))
720 			gfs2_rs_delete(ip);
721 		gfs2_qa_put(ip);
722 	}
723 	return 0;
724 }
725 
726 /**
727  * gfs2_fsync - sync the dirty data for a file (across the cluster)
728  * @file: the file that points to the dentry
729  * @start: the start position in the file to sync
730  * @end: the end position in the file to sync
731  * @datasync: set if we can ignore timestamp changes
732  *
733  * We split the data flushing here so that we don't wait for the data
734  * until after we've also sent the metadata to disk. Note that for
735  * data=ordered, we will write & wait for the data at the log flush
736  * stage anyway, so this is unlikely to make much of a difference
737  * except in the data=writeback case.
738  *
739  * If the fdatawrite fails due to any reason except -EIO, we will
740  * continue the remainder of the fsync, although we'll still report
741  * the error at the end. This is to match filemap_write_and_wait_range()
742  * behaviour.
743  *
744  * Returns: errno
745  */
746 
747 static int gfs2_fsync(struct file *file, loff_t start, loff_t end,
748 		      int datasync)
749 {
750 	struct address_space *mapping = file->f_mapping;
751 	struct inode *inode = mapping->host;
752 	int sync_state = inode_state_read_once(inode) & I_DIRTY;
753 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
754 	struct gfs2_inode *ip = GFS2_I(inode);
755 	int ret = 0, ret1 = 0;
756 
757 	if (mapping->nrpages) {
758 		ret1 = filemap_fdatawrite_range(mapping, start, end);
759 		if (ret1 == -EIO)
760 			return ret1;
761 	}
762 
763 	if (!gfs2_is_jdata(ip))
764 		sync_state &= ~I_DIRTY_PAGES;
765 	if (datasync)
766 		sync_state &= ~I_DIRTY_SYNC;
767 
768 	if (sync_state) {
769 		ret = sync_inode_metadata(inode, 1);
770 		if (ret)
771 			return ret;
772 		if (gfs2_is_jdata(ip))
773 			ret = file_write_and_wait(file);
774 		if (ret)
775 			return ret;
776 		gfs2_ail_flush(gl, 1);
777 	}
778 
779 	if (mapping->nrpages)
780 		ret = file_fdatawait_range(file, start, end);
781 
782 	return ret ? ret : ret1;
783 }
784 
785 static inline bool should_fault_in_pages(struct iov_iter *i,
786 					 struct kiocb *iocb,
787 					 size_t *prev_count,
788 					 size_t *window_size)
789 {
790 	size_t count = iov_iter_count(i);
791 	size_t size, offs;
792 
793 	if (!count)
794 		return false;
795 	if (!user_backed_iter(i))
796 		return false;
797 
798 	/*
799 	 * Try to fault in multiple pages initially.  When that doesn't result
800 	 * in any progress, fall back to a single page.
801 	 */
802 	size = PAGE_SIZE;
803 	offs = offset_in_page(iocb->ki_pos);
804 	if (*prev_count != count) {
805 		size_t nr_dirtied;
806 
807 		nr_dirtied = max(current->nr_dirtied_pause -
808 				 current->nr_dirtied, 8);
809 		size = min_t(size_t, SZ_1M, nr_dirtied << PAGE_SHIFT);
810 	}
811 
812 	*prev_count = count;
813 	*window_size = size - offs;
814 	return true;
815 }
816 
817 static ssize_t gfs2_file_direct_read(struct kiocb *iocb, struct iov_iter *to,
818 				     struct gfs2_holder *gh)
819 {
820 	struct file *file = iocb->ki_filp;
821 	struct inode *inode = file->f_mapping->host;
822 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
823 	size_t prev_count = 0, window_size = 0;
824 	size_t read = 0;
825 	ssize_t ret;
826 
827 	/*
828 	 * In this function, we disable page faults when we're holding the
829 	 * inode glock while doing I/O.  If a page fault occurs, we indicate
830 	 * that the inode glock should be dropped, fault in the pages manually,
831 	 * and retry.
832 	 *
833 	 * Unlike generic_file_read_iter, for reads, iomap_dio_rw can trigger
834 	 * physical as well as manual page faults, and we need to disable both
835 	 * kinds.
836 	 *
837 	 * For direct I/O, gfs2 takes the inode glock in deferred mode.  This
838 	 * locking mode is compatible with other deferred holders, so multiple
839 	 * processes and nodes can do direct I/O to a file at the same time.
840 	 * There's no guarantee that reads or writes will be atomic.  Any
841 	 * coordination among readers and writers needs to happen externally.
842 	 */
843 
844 	if (!iov_iter_count(to))
845 		return 0; /* skip atime */
846 
847 	gfs2_holder_init(gl, LM_ST_DEFERRED, 0, gh);
848 retry:
849 	ret = gfs2_glock_nq(gh);
850 	if (ret)
851 		goto out_uninit;
852 	pagefault_disable();
853 	to->nofault = true;
854 	ret = iomap_dio_rw(iocb, to, &gfs2_iomap_ops, NULL,
855 			   IOMAP_DIO_PARTIAL, NULL, read);
856 	to->nofault = false;
857 	pagefault_enable();
858 	if (ret <= 0 && ret != -EFAULT)
859 		goto out_unlock;
860 	/* No increment (+=) because iomap_dio_rw returns a cumulative value. */
861 	if (ret > 0)
862 		read = ret;
863 
864 	if (should_fault_in_pages(to, iocb, &prev_count, &window_size)) {
865 		gfs2_glock_dq(gh);
866 		window_size -= fault_in_iov_iter_writeable(to, window_size);
867 		if (window_size)
868 			goto retry;
869 	}
870 out_unlock:
871 	if (gfs2_holder_queued(gh))
872 		gfs2_glock_dq(gh);
873 out_uninit:
874 	gfs2_holder_uninit(gh);
875 	/* User space doesn't expect partial success. */
876 	if (ret < 0)
877 		return ret;
878 	return read;
879 }
880 
881 static ssize_t gfs2_file_direct_write(struct kiocb *iocb, struct iov_iter *from,
882 				      struct gfs2_holder *gh)
883 {
884 	struct file *file = iocb->ki_filp;
885 	struct inode *inode = file->f_mapping->host;
886 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
887 	size_t prev_count = 0, window_size = 0;
888 	size_t written = 0;
889 	bool enough_retries;
890 	ssize_t ret;
891 
892 	/*
893 	 * In this function, we disable page faults when we're holding the
894 	 * inode glock while doing I/O.  If a page fault occurs, we indicate
895 	 * that the inode glock should be dropped, fault in the pages manually,
896 	 * and retry.
897 	 *
898 	 * For writes, iomap_dio_rw only triggers manual page faults, so we
899 	 * don't need to disable physical ones.
900 	 */
901 
902 	/*
903 	 * Deferred lock, even if its a write, since we do no allocation on
904 	 * this path. All we need to change is the atime, and this lock mode
905 	 * ensures that other nodes have flushed their buffered read caches
906 	 * (i.e. their page cache entries for this inode). We do not,
907 	 * unfortunately, have the option of only flushing a range like the
908 	 * VFS does.
909 	 */
910 	gfs2_holder_init(gl, LM_ST_DEFERRED, 0, gh);
911 retry:
912 	ret = gfs2_glock_nq(gh);
913 	if (ret)
914 		goto out_uninit;
915 	/* Silently fall back to buffered I/O when writing beyond EOF */
916 	if (iocb->ki_pos + iov_iter_count(from) > i_size_read(inode))
917 		goto out_unlock;
918 
919 	from->nofault = true;
920 	ret = iomap_dio_rw(iocb, from, &gfs2_iomap_ops, NULL,
921 			   IOMAP_DIO_PARTIAL, NULL, written);
922 	from->nofault = false;
923 	if (ret <= 0) {
924 		if (ret == -ENOTBLK)
925 			ret = 0;
926 		if (ret != -EFAULT)
927 			goto out_unlock;
928 	}
929 	/* No increment (+=) because iomap_dio_rw returns a cumulative value. */
930 	if (ret > 0)
931 		written = ret;
932 
933 	enough_retries = prev_count == iov_iter_count(from) &&
934 			 window_size <= PAGE_SIZE;
935 	if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
936 		gfs2_glock_dq(gh);
937 		window_size -= fault_in_iov_iter_readable(from, window_size);
938 		if (window_size) {
939 			if (!enough_retries)
940 				goto retry;
941 			/* fall back to buffered I/O */
942 			ret = 0;
943 		}
944 	}
945 out_unlock:
946 	if (gfs2_holder_queued(gh))
947 		gfs2_glock_dq(gh);
948 out_uninit:
949 	gfs2_holder_uninit(gh);
950 	/* User space doesn't expect partial success. */
951 	if (ret < 0)
952 		return ret;
953 	return written;
954 }
955 
956 static ssize_t gfs2_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
957 {
958 	struct gfs2_glock *gl;
959 	struct gfs2_holder gh;
960 	size_t prev_count = 0, window_size = 0;
961 	size_t read = 0;
962 	ssize_t ret;
963 
964 	/*
965 	 * In this function, we disable page faults when we're holding the
966 	 * inode glock while doing I/O.  If a page fault occurs, we indicate
967 	 * that the inode glock should be dropped, fault in the pages manually,
968 	 * and retry.
969 	 */
970 
971 	if (iocb->ki_flags & IOCB_DIRECT)
972 		return gfs2_file_direct_read(iocb, to, &gh);
973 
974 	pagefault_disable();
975 	iocb->ki_flags |= IOCB_NOIO;
976 	ret = generic_file_read_iter(iocb, to);
977 	iocb->ki_flags &= ~IOCB_NOIO;
978 	pagefault_enable();
979 	if (ret >= 0) {
980 		if (!iov_iter_count(to))
981 			return ret;
982 		read = ret;
983 	} else if (ret != -EFAULT) {
984 		if (ret != -EAGAIN)
985 			return ret;
986 		if (iocb->ki_flags & IOCB_NOWAIT)
987 			return ret;
988 	}
989 	gl = gfs2_inode_glock(iocb->ki_filp->f_mapping->host);
990 	gfs2_holder_init(gl, LM_ST_SHARED, 0, &gh);
991 retry:
992 	ret = gfs2_glock_nq(&gh);
993 	if (ret)
994 		goto out_uninit;
995 	pagefault_disable();
996 	ret = generic_file_read_iter(iocb, to);
997 	pagefault_enable();
998 	if (ret <= 0 && ret != -EFAULT)
999 		goto out_unlock;
1000 	if (ret > 0)
1001 		read += ret;
1002 
1003 	if (should_fault_in_pages(to, iocb, &prev_count, &window_size)) {
1004 		gfs2_glock_dq(&gh);
1005 		window_size -= fault_in_iov_iter_writeable(to, window_size);
1006 		if (window_size)
1007 			goto retry;
1008 	}
1009 out_unlock:
1010 	if (gfs2_holder_queued(&gh))
1011 		gfs2_glock_dq(&gh);
1012 out_uninit:
1013 	gfs2_holder_uninit(&gh);
1014 	return read ? read : ret;
1015 }
1016 
1017 static ssize_t gfs2_file_buffered_write(struct kiocb *iocb,
1018 					struct iov_iter *from,
1019 					struct gfs2_holder *gh)
1020 {
1021 	struct file *file = iocb->ki_filp;
1022 	struct inode *inode = file_inode(file);
1023 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
1024 	struct gfs2_sbd *sdp = GFS2_SB(inode);
1025 	struct gfs2_holder *statfs_gh = NULL;
1026 	size_t prev_count = 0, window_size = 0;
1027 	size_t orig_count = iov_iter_count(from);
1028 	size_t written = 0;
1029 	ssize_t ret;
1030 
1031 	/*
1032 	 * In this function, we disable page faults when we're holding the
1033 	 * inode glock while doing I/O.  If a page fault occurs, we indicate
1034 	 * that the inode glock should be dropped, fault in the pages manually,
1035 	 * and retry.
1036 	 */
1037 
1038 	if (inode == sdp->sd_rindex) {
1039 		statfs_gh = kmalloc_obj(*statfs_gh, GFP_NOFS);
1040 		if (!statfs_gh)
1041 			return -ENOMEM;
1042 	}
1043 
1044 	gfs2_holder_init(gl, LM_ST_EXCLUSIVE, 0, gh);
1045 	if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
1046 retry:
1047 		window_size -= fault_in_iov_iter_readable(from, window_size);
1048 		if (!window_size) {
1049 			ret = -EFAULT;
1050 			goto out_uninit;
1051 		}
1052 		from->count = min(from->count, window_size);
1053 	}
1054 	ret = gfs2_glock_nq(gh);
1055 	if (ret)
1056 		goto out_uninit;
1057 
1058 	if (inode == sdp->sd_rindex) {
1059 		struct gfs2_glock *m_gl = gfs2_inode_glock(sdp->sd_statfs_inode);
1060 
1061 		ret = gfs2_glock_nq_init(m_gl, LM_ST_EXCLUSIVE,
1062 					 GL_NOCACHE, statfs_gh);
1063 		if (ret)
1064 			goto out_unlock;
1065 	}
1066 
1067 	ret = gfs2_clear_beyond_eof(inode, iocb->ki_pos);
1068 	if (ret)
1069 		goto out_unlock;
1070 
1071 	pagefault_disable();
1072 	ret = iomap_file_buffered_write(iocb, from, &gfs2_iomap_ops,
1073 			&gfs2_iomap_write_ops, NULL);
1074 	pagefault_enable();
1075 	if (ret > 0)
1076 		written += ret;
1077 
1078 	if (inode == sdp->sd_rindex)
1079 		gfs2_glock_dq_uninit(statfs_gh);
1080 
1081 	if (ret <= 0 && ret != -EFAULT)
1082 		goto out_unlock;
1083 
1084 	from->count = orig_count - written;
1085 	if (should_fault_in_pages(from, iocb, &prev_count, &window_size)) {
1086 		gfs2_glock_dq(gh);
1087 		goto retry;
1088 	}
1089 out_unlock:
1090 	if (gfs2_holder_queued(gh))
1091 		gfs2_glock_dq(gh);
1092 out_uninit:
1093 	gfs2_holder_uninit(gh);
1094 	kfree(statfs_gh);
1095 	from->count = orig_count - written;
1096 	return written ? written : ret;
1097 }
1098 
1099 /**
1100  * gfs2_file_write_iter - Perform a write to a file
1101  * @iocb: The io context
1102  * @from: The data to write
1103  *
1104  * We have to do a lock/unlock here to refresh the inode size for
1105  * O_APPEND writes, otherwise we can land up writing at the wrong
1106  * offset. There is still a race, but provided the app is using its
1107  * own file locking, this will make O_APPEND work as expected.
1108  *
1109  */
1110 
1111 static ssize_t gfs2_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1112 {
1113 	struct file *file = iocb->ki_filp;
1114 	struct inode *inode = file_inode(file);
1115 	struct gfs2_holder gh;
1116 	ssize_t ret;
1117 
1118 	gfs2_size_hint(file, iocb->ki_pos, iov_iter_count(from));
1119 
1120 	if (iocb->ki_flags & IOCB_APPEND) {
1121 		struct gfs2_glock *gl = gfs2_inode_glock(inode);
1122 
1123 		ret = gfs2_glock_nq_init(gl, LM_ST_SHARED, 0, &gh);
1124 		if (ret)
1125 			return ret;
1126 		gfs2_glock_dq_uninit(&gh);
1127 	}
1128 
1129 	inode_lock(inode);
1130 	ret = generic_write_checks(iocb, from);
1131 	if (ret <= 0)
1132 		goto out_unlock;
1133 
1134 	ret = file_remove_privs(file);
1135 	if (ret)
1136 		goto out_unlock;
1137 
1138 	if (iocb->ki_flags & IOCB_DIRECT) {
1139 		struct address_space *mapping = file->f_mapping;
1140 		ssize_t buffered, ret2;
1141 
1142 		/*
1143 		 * Note that under direct I/O, we don't allow and inode
1144 		 * timestamp updates, so we're not calling file_update_time()
1145 		 * here.
1146 		 */
1147 
1148 		ret = gfs2_file_direct_write(iocb, from, &gh);
1149 		if (ret < 0 || !iov_iter_count(from))
1150 			goto out_unlock;
1151 
1152 		iocb->ki_flags |= IOCB_DSYNC;
1153 		buffered = gfs2_file_buffered_write(iocb, from, &gh);
1154 		if (unlikely(buffered <= 0)) {
1155 			if (!ret)
1156 				ret = buffered;
1157 			goto out_unlock;
1158 		}
1159 
1160 		/*
1161 		 * We need to ensure that the page cache pages are written to
1162 		 * disk and invalidated to preserve the expected O_DIRECT
1163 		 * semantics.  If the writeback or invalidate fails, only report
1164 		 * the direct I/O range as we don't know if the buffered pages
1165 		 * made it to disk.
1166 		 */
1167 		ret2 = generic_write_sync(iocb, buffered);
1168 		invalidate_mapping_pages(mapping,
1169 				(iocb->ki_pos - buffered) >> PAGE_SHIFT,
1170 				(iocb->ki_pos - 1) >> PAGE_SHIFT);
1171 		if (!ret || ret2 > 0)
1172 			ret += ret2;
1173 	} else {
1174 		ret = file_update_time(file);
1175 		if (ret)
1176 			goto out_unlock;
1177 
1178 		ret = gfs2_file_buffered_write(iocb, from, &gh);
1179 		if (likely(ret > 0))
1180 			ret = generic_write_sync(iocb, ret);
1181 	}
1182 
1183 out_unlock:
1184 	inode_unlock(inode);
1185 	return ret;
1186 }
1187 
1188 static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len)
1189 {
1190 	struct super_block *sb = inode->i_sb;
1191 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
1192 	struct gfs2_inode *ip = GFS2_I(inode);
1193 	loff_t end = offset + len;
1194 	struct buffer_head *dibh;
1195 	int error;
1196 
1197 	error = gfs2_meta_inode_buffer(ip, &dibh);
1198 	if (unlikely(error))
1199 		return error;
1200 
1201 	gfs2_trans_add_meta(gl, dibh);
1202 
1203 	if (gfs2_is_stuffed(ip)) {
1204 		error = gfs2_unstuff_dinode(ip);
1205 		if (unlikely(error))
1206 			goto out;
1207 	}
1208 
1209 	while (offset < end) {
1210 		struct iomap iomap = { };
1211 
1212 		error = gfs2_iomap_alloc(inode, offset, end - offset, &iomap);
1213 		if (error)
1214 			goto out;
1215 		offset = iomap.offset + iomap.length;
1216 		if (!(iomap.flags & IOMAP_F_NEW))
1217 			continue;
1218 		error = sb_issue_zeroout(sb, iomap.addr >> inode->i_blkbits,
1219 					 iomap.length >> inode->i_blkbits,
1220 					 GFP_NOFS);
1221 		if (error) {
1222 			fs_err(GFS2_SB(inode), "Failed to zero data buffers\n");
1223 			goto out;
1224 		}
1225 	}
1226 out:
1227 	brelse(dibh);
1228 	return error;
1229 }
1230 
1231 /**
1232  * calc_max_reserv() - Reverse of write_calc_reserv. Given a number of
1233  *                     blocks, determine how many bytes can be written.
1234  * @ip:          The inode in question.
1235  * @len:         Max cap of bytes. What we return in *len must be <= this.
1236  * @data_blocks: Compute and return the number of data blocks needed
1237  * @ind_blocks:  Compute and return the number of indirect blocks needed
1238  * @max_blocks:  The total blocks available to work with.
1239  *
1240  * Returns: void, but @len, @data_blocks and @ind_blocks are filled in.
1241  */
1242 static void calc_max_reserv(struct gfs2_inode *ip, loff_t *len,
1243 			    unsigned int *data_blocks, unsigned int *ind_blocks,
1244 			    unsigned int max_blocks)
1245 {
1246 	loff_t max = *len;
1247 	const struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1248 	unsigned int tmp, max_data = max_blocks - 3 * (sdp->sd_max_height - 1);
1249 
1250 	for (tmp = max_data; tmp > sdp->sd_diptrs;) {
1251 		tmp = DIV_ROUND_UP(tmp, sdp->sd_inptrs);
1252 		max_data -= tmp;
1253 	}
1254 
1255 	*data_blocks = max_data;
1256 	*ind_blocks = max_blocks - max_data;
1257 	*len = ((loff_t)max_data - 3) << sdp->sd_sb.sb_bsize_shift;
1258 	if (*len > max) {
1259 		*len = max;
1260 		gfs2_write_calc_reserv(ip, max, data_blocks, ind_blocks);
1261 	}
1262 }
1263 
1264 static long __gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
1265 {
1266 	struct inode *inode = file_inode(file);
1267 	struct gfs2_sbd *sdp = GFS2_SB(inode);
1268 	struct gfs2_inode *ip = GFS2_I(inode);
1269 	struct gfs2_alloc_parms ap = {};
1270 	unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
1271 	loff_t bytes, max_bytes, max_blks;
1272 	int error;
1273 	const loff_t pos = offset;
1274 	const loff_t count = len;
1275 	loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1);
1276 	loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift;
1277 	loff_t max_chunk_size = UINT_MAX & bsize_mask;
1278 
1279 	next = (next + 1) << sdp->sd_sb.sb_bsize_shift;
1280 
1281 	if (!(mode & FALLOC_FL_KEEP_SIZE)) {
1282 		error = gfs2_clear_beyond_eof(inode, offset + len);
1283 		if (error)
1284 			return error;
1285 	}
1286 
1287 	offset &= bsize_mask;
1288 
1289 	len = next - offset;
1290 	bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2;
1291 	if (!bytes)
1292 		bytes = UINT_MAX;
1293 	bytes &= bsize_mask;
1294 	if (bytes == 0)
1295 		bytes = sdp->sd_sb.sb_bsize;
1296 
1297 	gfs2_size_hint(file, offset, len);
1298 
1299 	gfs2_write_calc_reserv(ip, PAGE_SIZE, &data_blocks, &ind_blocks);
1300 	ap.min_target = data_blocks + ind_blocks;
1301 
1302 	while (len > 0) {
1303 		if (len < bytes)
1304 			bytes = len;
1305 		if (!gfs2_write_alloc_required(ip, offset, bytes)) {
1306 			len -= bytes;
1307 			offset += bytes;
1308 			continue;
1309 		}
1310 
1311 		/* We need to determine how many bytes we can actually
1312 		 * fallocate without exceeding quota or going over the
1313 		 * end of the fs. We start off optimistically by assuming
1314 		 * we can write max_bytes */
1315 		max_bytes = (len > max_chunk_size) ? max_chunk_size : len;
1316 
1317 		/* Since max_bytes is most likely a theoretical max, we
1318 		 * calculate a more realistic 'bytes' to serve as a good
1319 		 * starting point for the number of bytes we may be able
1320 		 * to write */
1321 		gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks);
1322 		ap.target = data_blocks + ind_blocks;
1323 
1324 		error = gfs2_quota_lock_check(ip, &ap);
1325 		if (error)
1326 			return error;
1327 		/* ap.allowed tells us how many blocks quota will allow
1328 		 * us to write. Check if this reduces max_blks */
1329 		max_blks = UINT_MAX;
1330 		if (ap.allowed)
1331 			max_blks = ap.allowed;
1332 
1333 		error = gfs2_inplace_reserve(ip, &ap);
1334 		if (error)
1335 			goto out_qunlock;
1336 
1337 		/* check if the selected rgrp limits our max_blks further */
1338 		if (ip->i_res.rs_reserved < max_blks)
1339 			max_blks = ip->i_res.rs_reserved;
1340 
1341 		/* Almost done. Calculate bytes that can be written using
1342 		 * max_blks. We also recompute max_bytes, data_blocks and
1343 		 * ind_blocks */
1344 		calc_max_reserv(ip, &max_bytes, &data_blocks,
1345 				&ind_blocks, max_blks);
1346 
1347 		rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +
1348 			  RES_RG_HDR + gfs2_rg_blocks(ip, data_blocks + ind_blocks);
1349 		if (gfs2_is_jdata(ip))
1350 			rblocks += data_blocks ? data_blocks : 1;
1351 
1352 		error = gfs2_trans_begin(sdp, rblocks,
1353 					 PAGE_SIZE >> inode->i_blkbits);
1354 		if (error)
1355 			goto out_trans_fail;
1356 
1357 		error = fallocate_chunk(inode, offset, max_bytes);
1358 		gfs2_trans_end(sdp);
1359 
1360 		if (error)
1361 			goto out_trans_fail;
1362 
1363 		len -= max_bytes;
1364 		offset += max_bytes;
1365 		gfs2_inplace_release(ip);
1366 		gfs2_quota_unlock(ip);
1367 	}
1368 
1369 	if (!(mode & FALLOC_FL_KEEP_SIZE) && (pos + count) > inode->i_size)
1370 		i_size_write(inode, pos + count);
1371 	file_update_time(file);
1372 	mark_inode_dirty(inode);
1373 
1374 	if ((file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host))
1375 		return vfs_fsync_range(file, pos, pos + count - 1,
1376 			       (file->f_flags & __O_SYNC) ? 0 : 1);
1377 	return 0;
1378 
1379 out_trans_fail:
1380 	gfs2_inplace_release(ip);
1381 out_qunlock:
1382 	gfs2_quota_unlock(ip);
1383 	return error;
1384 }
1385 
1386 static long gfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
1387 {
1388 	struct inode *inode = file_inode(file);
1389 	struct gfs2_sbd *sdp = GFS2_SB(inode);
1390 	struct gfs2_glock *gl = gfs2_inode_glock(inode);
1391 	struct gfs2_inode *ip = GFS2_I(inode);
1392 	struct gfs2_holder gh;
1393 	int ret;
1394 
1395 	if (mode & ~(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE))
1396 		return -EOPNOTSUPP;
1397 	/* fallocate is needed by gfs2_grow to reserve space in the rindex */
1398 	if (gfs2_is_jdata(ip) && inode != sdp->sd_rindex)
1399 		return -EOPNOTSUPP;
1400 
1401 	inode_lock(inode);
1402 
1403 	gfs2_holder_init(gl, LM_ST_EXCLUSIVE, 0, &gh);
1404 	ret = gfs2_glock_nq(&gh);
1405 	if (ret)
1406 		goto out_uninit;
1407 
1408 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
1409 	    (offset + len) > inode->i_size) {
1410 		ret = inode_newsize_ok(inode, offset + len);
1411 		if (ret)
1412 			goto out_unlock;
1413 	}
1414 
1415 	ret = get_write_access(inode);
1416 	if (ret)
1417 		goto out_unlock;
1418 
1419 	if (mode & FALLOC_FL_PUNCH_HOLE) {
1420 		ret = __gfs2_punch_hole(file, offset, len);
1421 	} else {
1422 		ret = __gfs2_fallocate(file, mode, offset, len);
1423 		if (ret)
1424 			gfs2_rs_deltree(&ip->i_res);
1425 	}
1426 
1427 	put_write_access(inode);
1428 out_unlock:
1429 	gfs2_glock_dq(&gh);
1430 out_uninit:
1431 	gfs2_holder_uninit(&gh);
1432 	inode_unlock(inode);
1433 	return ret;
1434 }
1435 
1436 static ssize_t gfs2_file_splice_write(struct pipe_inode_info *pipe,
1437 				      struct file *out, loff_t *ppos,
1438 				      size_t len, unsigned int flags)
1439 {
1440 	ssize_t ret;
1441 
1442 	gfs2_size_hint(out, *ppos, len);
1443 
1444 	ret = iter_file_splice_write(pipe, out, ppos, len, flags);
1445 	return ret;
1446 }
1447 
1448 #ifdef CONFIG_GFS2_FS_LOCKING_DLM
1449 
1450 /**
1451  * gfs2_lock - acquire/release a posix lock on a file
1452  * @file: the file pointer
1453  * @cmd: either modify or retrieve lock state, possibly wait
1454  * @fl: type and range of lock
1455  *
1456  * Returns: errno
1457  */
1458 
1459 static int gfs2_lock(struct file *file, int cmd, struct file_lock *fl)
1460 {
1461 	struct gfs2_inode *ip = GFS2_I(file->f_mapping->host);
1462 	struct gfs2_sbd *sdp = GFS2_SB(file->f_mapping->host);
1463 	struct lm_lockstruct *ls = &sdp->sd_lockstruct;
1464 	int ret;
1465 
1466 	if (!(fl->c.flc_flags & FL_POSIX))
1467 		return -ENOLCK;
1468 	if (gfs2_withdrawn(sdp)) {
1469 		if (lock_is_unlock(fl))
1470 			locks_lock_file_wait(file, fl);
1471 		return -EIO;
1472 	}
1473 	down_read(&ls->ls_sem);
1474 	ret = -ENODEV;
1475 	if (likely(ls->ls_dlm != NULL)) {
1476 		if (cmd == F_CANCELLK)
1477 			ret = dlm_posix_cancel(ls->ls_dlm, ip->i_no_addr, file, fl);
1478 		else if (IS_GETLK(cmd))
1479 			ret = dlm_posix_get(ls->ls_dlm, ip->i_no_addr, file, fl);
1480 		else if (lock_is_unlock(fl))
1481 			ret = dlm_posix_unlock(ls->ls_dlm, ip->i_no_addr, file, fl);
1482 		else
1483 			ret = dlm_posix_lock(ls->ls_dlm, ip->i_no_addr, file, cmd, fl);
1484 	}
1485 	up_read(&ls->ls_sem);
1486 	return ret;
1487 }
1488 
1489 static void __flock_holder_uninit(struct file *file, struct gfs2_holder *fl_gh)
1490 {
1491 	struct gfs2_glock *gl = gfs2_glock_hold(fl_gh->gh_gl);
1492 
1493 	/*
1494 	 * Make sure gfs2_glock_put() won't sleep under the file->f_lock
1495 	 * spinlock.
1496 	 */
1497 
1498 	spin_lock(&file->f_lock);
1499 	gfs2_holder_uninit(fl_gh);
1500 	spin_unlock(&file->f_lock);
1501 	gfs2_glock_put(gl);
1502 }
1503 
1504 static int do_flock(struct file *file, int cmd, struct file_lock *fl)
1505 {
1506 	struct gfs2_file *fp = file->private_data;
1507 	struct gfs2_holder *fl_gh = &fp->f_fl_gh;
1508 	struct gfs2_inode *ip = GFS2_I(file_inode(file));
1509 	struct gfs2_glock *gl;
1510 	unsigned int state;
1511 	u16 flags;
1512 	int error = 0;
1513 	int sleeptime;
1514 
1515 	state = lock_is_write(fl) ? LM_ST_EXCLUSIVE : LM_ST_SHARED;
1516 	flags = GL_EXACT | GL_NOPID;
1517 	if (!IS_SETLKW(cmd))
1518 		flags |= LM_FLAG_TRY_1CB;
1519 
1520 	mutex_lock(&fp->f_fl_mutex);
1521 
1522 	if (gfs2_holder_initialized(fl_gh)) {
1523 		struct file_lock request;
1524 		if (fl_gh->gh_state == state)
1525 			goto out;
1526 		locks_init_lock(&request);
1527 		request.c.flc_type = F_UNLCK;
1528 		request.c.flc_flags = FL_FLOCK;
1529 		locks_lock_file_wait(file, &request);
1530 		gfs2_glock_dq(fl_gh);
1531 		gfs2_holder_reinit(state, flags, fl_gh);
1532 	} else {
1533 		error = gfs2_glock_get(GFS2_SB(&ip->i_inode), ip->i_no_addr,
1534 				       &gfs2_flock_glops, CREATE, &gl);
1535 		if (error)
1536 			goto out;
1537 		spin_lock(&file->f_lock);
1538 		gfs2_holder_init(gl, state, flags, fl_gh);
1539 		spin_unlock(&file->f_lock);
1540 		gfs2_glock_put(gl);
1541 	}
1542 	for (sleeptime = 1; sleeptime <= 4; sleeptime <<= 1) {
1543 		error = gfs2_glock_nq(fl_gh);
1544 		if (error != GLR_TRYFAILED)
1545 			break;
1546 		fl_gh->gh_flags &= ~LM_FLAG_TRY_1CB;
1547 		fl_gh->gh_flags |= LM_FLAG_TRY;
1548 		msleep(sleeptime);
1549 	}
1550 	if (error) {
1551 		__flock_holder_uninit(file, fl_gh);
1552 		if (error == GLR_TRYFAILED)
1553 			error = -EAGAIN;
1554 	} else {
1555 		error = locks_lock_file_wait(file, fl);
1556 		gfs2_assert_warn(GFS2_SB(&ip->i_inode), !error);
1557 	}
1558 
1559 out:
1560 	mutex_unlock(&fp->f_fl_mutex);
1561 	return error;
1562 }
1563 
1564 static void do_unflock(struct file *file, struct file_lock *fl)
1565 {
1566 	struct gfs2_file *fp = file->private_data;
1567 	struct gfs2_holder *fl_gh = &fp->f_fl_gh;
1568 
1569 	mutex_lock(&fp->f_fl_mutex);
1570 	locks_lock_file_wait(file, fl);
1571 	if (gfs2_holder_initialized(fl_gh)) {
1572 		gfs2_glock_dq(fl_gh);
1573 		__flock_holder_uninit(file, fl_gh);
1574 	}
1575 	mutex_unlock(&fp->f_fl_mutex);
1576 }
1577 
1578 /**
1579  * gfs2_flock - acquire/release a flock lock on a file
1580  * @file: the file pointer
1581  * @cmd: either modify or retrieve lock state, possibly wait
1582  * @fl: type and range of lock
1583  *
1584  * Returns: errno
1585  */
1586 
1587 static int gfs2_flock(struct file *file, int cmd, struct file_lock *fl)
1588 {
1589 	if (!(fl->c.flc_flags & FL_FLOCK))
1590 		return -ENOLCK;
1591 
1592 	if (lock_is_unlock(fl)) {
1593 		do_unflock(file, fl);
1594 		return 0;
1595 	} else {
1596 		return do_flock(file, cmd, fl);
1597 	}
1598 }
1599 
1600 const struct file_operations gfs2_file_fops = {
1601 	.llseek		= gfs2_llseek,
1602 	.read_iter	= gfs2_file_read_iter,
1603 	.write_iter	= gfs2_file_write_iter,
1604 	.iopoll		= iocb_bio_iopoll,
1605 	.unlocked_ioctl	= gfs2_ioctl,
1606 	.compat_ioctl	= gfs2_compat_ioctl,
1607 	.mmap		= gfs2_mmap,
1608 	.open		= gfs2_open,
1609 	.release	= gfs2_release,
1610 	.fsync		= gfs2_fsync,
1611 	.lock		= gfs2_lock,
1612 	.flock		= gfs2_flock,
1613 	.splice_read	= copy_splice_read,
1614 	.splice_write	= gfs2_file_splice_write,
1615 	.fallocate	= gfs2_fallocate,
1616 	.fop_flags	= FOP_ASYNC_LOCK,
1617 };
1618 
1619 const struct file_operations gfs2_dir_fops = {
1620 	.iterate_shared	= gfs2_readdir,
1621 	.unlocked_ioctl	= gfs2_ioctl,
1622 	.compat_ioctl	= gfs2_compat_ioctl,
1623 	.open		= gfs2_open,
1624 	.release	= gfs2_release,
1625 	.fsync		= gfs2_fsync,
1626 	.lock		= gfs2_lock,
1627 	.flock		= gfs2_flock,
1628 	.llseek		= default_llseek,
1629 	.fop_flags	= FOP_ASYNC_LOCK,
1630 };
1631 
1632 #endif /* CONFIG_GFS2_FS_LOCKING_DLM */
1633 
1634 const struct file_operations gfs2_file_fops_nolock = {
1635 	.llseek		= gfs2_llseek,
1636 	.read_iter	= gfs2_file_read_iter,
1637 	.write_iter	= gfs2_file_write_iter,
1638 	.iopoll		= iocb_bio_iopoll,
1639 	.unlocked_ioctl	= gfs2_ioctl,
1640 	.compat_ioctl	= gfs2_compat_ioctl,
1641 	.mmap		= gfs2_mmap,
1642 	.open		= gfs2_open,
1643 	.release	= gfs2_release,
1644 	.fsync		= gfs2_fsync,
1645 	.splice_read	= copy_splice_read,
1646 	.splice_write	= gfs2_file_splice_write,
1647 	.setlease	= generic_setlease,
1648 	.fallocate	= gfs2_fallocate,
1649 };
1650 
1651 const struct file_operations gfs2_dir_fops_nolock = {
1652 	.iterate_shared	= gfs2_readdir,
1653 	.unlocked_ioctl	= gfs2_ioctl,
1654 	.compat_ioctl	= gfs2_compat_ioctl,
1655 	.open		= gfs2_open,
1656 	.release	= gfs2_release,
1657 	.fsync		= gfs2_fsync,
1658 	.llseek		= default_llseek,
1659 	.setlease	= generic_setlease,
1660 };
1661 
1662