xref: /openbmc/linux/fs/zonefs/super.c (revision b737eecd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Simple file system for zoned block devices exposing zones as files.
4  *
5  * Copyright (C) 2019 Western Digital Corporation or its affiliates.
6  */
7 #include <linux/module.h>
8 #include <linux/fs.h>
9 #include <linux/magic.h>
10 #include <linux/iomap.h>
11 #include <linux/init.h>
12 #include <linux/slab.h>
13 #include <linux/blkdev.h>
14 #include <linux/statfs.h>
15 #include <linux/writeback.h>
16 #include <linux/quotaops.h>
17 #include <linux/seq_file.h>
18 #include <linux/parser.h>
19 #include <linux/uio.h>
20 #include <linux/mman.h>
21 #include <linux/sched/mm.h>
22 #include <linux/crc32.h>
23 #include <linux/task_io_accounting_ops.h>
24 
25 #include "zonefs.h"
26 
27 #define CREATE_TRACE_POINTS
28 #include "trace.h"
29 
30 static inline int zonefs_zone_mgmt(struct inode *inode,
31 				   enum req_opf op)
32 {
33 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
34 	int ret;
35 
36 	lockdep_assert_held(&zi->i_truncate_mutex);
37 
38 	trace_zonefs_zone_mgmt(inode, op);
39 	ret = blkdev_zone_mgmt(inode->i_sb->s_bdev, op, zi->i_zsector,
40 			       zi->i_zone_size >> SECTOR_SHIFT, GFP_NOFS);
41 	if (ret) {
42 		zonefs_err(inode->i_sb,
43 			   "Zone management operation %s at %llu failed %d\n",
44 			   blk_op_str(op), zi->i_zsector, ret);
45 		return ret;
46 	}
47 
48 	return 0;
49 }
50 
51 static inline void zonefs_i_size_write(struct inode *inode, loff_t isize)
52 {
53 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
54 
55 	i_size_write(inode, isize);
56 	/*
57 	 * A full zone is no longer open/active and does not need
58 	 * explicit closing.
59 	 */
60 	if (isize >= zi->i_max_size)
61 		zi->i_flags &= ~ZONEFS_ZONE_OPEN;
62 }
63 
64 static int zonefs_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
65 			      unsigned int flags, struct iomap *iomap,
66 			      struct iomap *srcmap)
67 {
68 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
69 	struct super_block *sb = inode->i_sb;
70 	loff_t isize;
71 
72 	/* All I/Os should always be within the file maximum size */
73 	if (WARN_ON_ONCE(offset + length > zi->i_max_size))
74 		return -EIO;
75 
76 	/*
77 	 * Sequential zones can only accept direct writes. This is already
78 	 * checked when writes are issued, so warn if we see a page writeback
79 	 * operation.
80 	 */
81 	if (WARN_ON_ONCE(zi->i_ztype == ZONEFS_ZTYPE_SEQ &&
82 			 (flags & IOMAP_WRITE) && !(flags & IOMAP_DIRECT)))
83 		return -EIO;
84 
85 	/*
86 	 * For conventional zones, all blocks are always mapped. For sequential
87 	 * zones, all blocks after always mapped below the inode size (zone
88 	 * write pointer) and unwriten beyond.
89 	 */
90 	mutex_lock(&zi->i_truncate_mutex);
91 	isize = i_size_read(inode);
92 	if (offset >= isize)
93 		iomap->type = IOMAP_UNWRITTEN;
94 	else
95 		iomap->type = IOMAP_MAPPED;
96 	if (flags & IOMAP_WRITE)
97 		length = zi->i_max_size - offset;
98 	else
99 		length = min(length, isize - offset);
100 	mutex_unlock(&zi->i_truncate_mutex);
101 
102 	iomap->offset = ALIGN_DOWN(offset, sb->s_blocksize);
103 	iomap->length = ALIGN(offset + length, sb->s_blocksize) - iomap->offset;
104 	iomap->bdev = inode->i_sb->s_bdev;
105 	iomap->addr = (zi->i_zsector << SECTOR_SHIFT) + iomap->offset;
106 
107 	trace_zonefs_iomap_begin(inode, iomap);
108 
109 	return 0;
110 }
111 
112 static const struct iomap_ops zonefs_iomap_ops = {
113 	.iomap_begin	= zonefs_iomap_begin,
114 };
115 
116 static int zonefs_readpage(struct file *unused, struct page *page)
117 {
118 	return iomap_readpage(page, &zonefs_iomap_ops);
119 }
120 
121 static void zonefs_readahead(struct readahead_control *rac)
122 {
123 	iomap_readahead(rac, &zonefs_iomap_ops);
124 }
125 
126 /*
127  * Map blocks for page writeback. This is used only on conventional zone files,
128  * which implies that the page range can only be within the fixed inode size.
129  */
130 static int zonefs_map_blocks(struct iomap_writepage_ctx *wpc,
131 			     struct inode *inode, loff_t offset)
132 {
133 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
134 
135 	if (WARN_ON_ONCE(zi->i_ztype != ZONEFS_ZTYPE_CNV))
136 		return -EIO;
137 	if (WARN_ON_ONCE(offset >= i_size_read(inode)))
138 		return -EIO;
139 
140 	/* If the mapping is already OK, nothing needs to be done */
141 	if (offset >= wpc->iomap.offset &&
142 	    offset < wpc->iomap.offset + wpc->iomap.length)
143 		return 0;
144 
145 	return zonefs_iomap_begin(inode, offset, zi->i_max_size - offset,
146 				  IOMAP_WRITE, &wpc->iomap, NULL);
147 }
148 
149 static const struct iomap_writeback_ops zonefs_writeback_ops = {
150 	.map_blocks		= zonefs_map_blocks,
151 };
152 
153 static int zonefs_writepage(struct page *page, struct writeback_control *wbc)
154 {
155 	struct iomap_writepage_ctx wpc = { };
156 
157 	return iomap_writepage(page, wbc, &wpc, &zonefs_writeback_ops);
158 }
159 
160 static int zonefs_writepages(struct address_space *mapping,
161 			     struct writeback_control *wbc)
162 {
163 	struct iomap_writepage_ctx wpc = { };
164 
165 	return iomap_writepages(mapping, wbc, &wpc, &zonefs_writeback_ops);
166 }
167 
168 static int zonefs_swap_activate(struct swap_info_struct *sis,
169 				struct file *swap_file, sector_t *span)
170 {
171 	struct inode *inode = file_inode(swap_file);
172 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
173 
174 	if (zi->i_ztype != ZONEFS_ZTYPE_CNV) {
175 		zonefs_err(inode->i_sb,
176 			   "swap file: not a conventional zone file\n");
177 		return -EINVAL;
178 	}
179 
180 	return iomap_swapfile_activate(sis, swap_file, span, &zonefs_iomap_ops);
181 }
182 
183 static const struct address_space_operations zonefs_file_aops = {
184 	.readpage		= zonefs_readpage,
185 	.readahead		= zonefs_readahead,
186 	.writepage		= zonefs_writepage,
187 	.writepages		= zonefs_writepages,
188 	.set_page_dirty		= iomap_set_page_dirty,
189 	.releasepage		= iomap_releasepage,
190 	.invalidatepage		= iomap_invalidatepage,
191 	.migratepage		= iomap_migrate_page,
192 	.is_partially_uptodate	= iomap_is_partially_uptodate,
193 	.error_remove_page	= generic_error_remove_page,
194 	.direct_IO		= noop_direct_IO,
195 	.swap_activate		= zonefs_swap_activate,
196 };
197 
198 static void zonefs_update_stats(struct inode *inode, loff_t new_isize)
199 {
200 	struct super_block *sb = inode->i_sb;
201 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
202 	loff_t old_isize = i_size_read(inode);
203 	loff_t nr_blocks;
204 
205 	if (new_isize == old_isize)
206 		return;
207 
208 	spin_lock(&sbi->s_lock);
209 
210 	/*
211 	 * This may be called for an update after an IO error.
212 	 * So beware of the values seen.
213 	 */
214 	if (new_isize < old_isize) {
215 		nr_blocks = (old_isize - new_isize) >> sb->s_blocksize_bits;
216 		if (sbi->s_used_blocks > nr_blocks)
217 			sbi->s_used_blocks -= nr_blocks;
218 		else
219 			sbi->s_used_blocks = 0;
220 	} else {
221 		sbi->s_used_blocks +=
222 			(new_isize - old_isize) >> sb->s_blocksize_bits;
223 		if (sbi->s_used_blocks > sbi->s_blocks)
224 			sbi->s_used_blocks = sbi->s_blocks;
225 	}
226 
227 	spin_unlock(&sbi->s_lock);
228 }
229 
230 /*
231  * Check a zone condition and adjust its file inode access permissions for
232  * offline and readonly zones. Return the inode size corresponding to the
233  * amount of readable data in the zone.
234  */
235 static loff_t zonefs_check_zone_condition(struct inode *inode,
236 					  struct blk_zone *zone, bool warn,
237 					  bool mount)
238 {
239 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
240 
241 	switch (zone->cond) {
242 	case BLK_ZONE_COND_OFFLINE:
243 		/*
244 		 * Dead zone: make the inode immutable, disable all accesses
245 		 * and set the file size to 0 (zone wp set to zone start).
246 		 */
247 		if (warn)
248 			zonefs_warn(inode->i_sb, "inode %lu: offline zone\n",
249 				    inode->i_ino);
250 		inode->i_flags |= S_IMMUTABLE;
251 		inode->i_mode &= ~0777;
252 		zone->wp = zone->start;
253 		return 0;
254 	case BLK_ZONE_COND_READONLY:
255 		/*
256 		 * The write pointer of read-only zones is invalid. If such a
257 		 * zone is found during mount, the file size cannot be retrieved
258 		 * so we treat the zone as offline (mount == true case).
259 		 * Otherwise, keep the file size as it was when last updated
260 		 * so that the user can recover data. In both cases, writes are
261 		 * always disabled for the zone.
262 		 */
263 		if (warn)
264 			zonefs_warn(inode->i_sb, "inode %lu: read-only zone\n",
265 				    inode->i_ino);
266 		inode->i_flags |= S_IMMUTABLE;
267 		if (mount) {
268 			zone->cond = BLK_ZONE_COND_OFFLINE;
269 			inode->i_mode &= ~0777;
270 			zone->wp = zone->start;
271 			return 0;
272 		}
273 		inode->i_mode &= ~0222;
274 		return i_size_read(inode);
275 	case BLK_ZONE_COND_FULL:
276 		/* The write pointer of full zones is invalid. */
277 		return zi->i_max_size;
278 	default:
279 		if (zi->i_ztype == ZONEFS_ZTYPE_CNV)
280 			return zi->i_max_size;
281 		return (zone->wp - zone->start) << SECTOR_SHIFT;
282 	}
283 }
284 
285 struct zonefs_ioerr_data {
286 	struct inode	*inode;
287 	bool		write;
288 };
289 
290 static int zonefs_io_error_cb(struct blk_zone *zone, unsigned int idx,
291 			      void *data)
292 {
293 	struct zonefs_ioerr_data *err = data;
294 	struct inode *inode = err->inode;
295 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
296 	struct super_block *sb = inode->i_sb;
297 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
298 	loff_t isize, data_size;
299 
300 	/*
301 	 * Check the zone condition: if the zone is not "bad" (offline or
302 	 * read-only), read errors are simply signaled to the IO issuer as long
303 	 * as there is no inconsistency between the inode size and the amount of
304 	 * data writen in the zone (data_size).
305 	 */
306 	data_size = zonefs_check_zone_condition(inode, zone, true, false);
307 	isize = i_size_read(inode);
308 	if (zone->cond != BLK_ZONE_COND_OFFLINE &&
309 	    zone->cond != BLK_ZONE_COND_READONLY &&
310 	    !err->write && isize == data_size)
311 		return 0;
312 
313 	/*
314 	 * At this point, we detected either a bad zone or an inconsistency
315 	 * between the inode size and the amount of data written in the zone.
316 	 * For the latter case, the cause may be a write IO error or an external
317 	 * action on the device. Two error patterns exist:
318 	 * 1) The inode size is lower than the amount of data in the zone:
319 	 *    a write operation partially failed and data was writen at the end
320 	 *    of the file. This can happen in the case of a large direct IO
321 	 *    needing several BIOs and/or write requests to be processed.
322 	 * 2) The inode size is larger than the amount of data in the zone:
323 	 *    this can happen with a deferred write error with the use of the
324 	 *    device side write cache after getting successful write IO
325 	 *    completions. Other possibilities are (a) an external corruption,
326 	 *    e.g. an application reset the zone directly, or (b) the device
327 	 *    has a serious problem (e.g. firmware bug).
328 	 *
329 	 * In all cases, warn about inode size inconsistency and handle the
330 	 * IO error according to the zone condition and to the mount options.
331 	 */
332 	if (zi->i_ztype == ZONEFS_ZTYPE_SEQ && isize != data_size)
333 		zonefs_warn(sb, "inode %lu: invalid size %lld (should be %lld)\n",
334 			    inode->i_ino, isize, data_size);
335 
336 	/*
337 	 * First handle bad zones signaled by hardware. The mount options
338 	 * errors=zone-ro and errors=zone-offline result in changing the
339 	 * zone condition to read-only and offline respectively, as if the
340 	 * condition was signaled by the hardware.
341 	 */
342 	if (zone->cond == BLK_ZONE_COND_OFFLINE ||
343 	    sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZOL) {
344 		zonefs_warn(sb, "inode %lu: read/write access disabled\n",
345 			    inode->i_ino);
346 		if (zone->cond != BLK_ZONE_COND_OFFLINE) {
347 			zone->cond = BLK_ZONE_COND_OFFLINE;
348 			data_size = zonefs_check_zone_condition(inode, zone,
349 								false, false);
350 		}
351 	} else if (zone->cond == BLK_ZONE_COND_READONLY ||
352 		   sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZRO) {
353 		zonefs_warn(sb, "inode %lu: write access disabled\n",
354 			    inode->i_ino);
355 		if (zone->cond != BLK_ZONE_COND_READONLY) {
356 			zone->cond = BLK_ZONE_COND_READONLY;
357 			data_size = zonefs_check_zone_condition(inode, zone,
358 								false, false);
359 		}
360 	}
361 
362 	/*
363 	 * If the filesystem is mounted with the explicit-open mount option, we
364 	 * need to clear the ZONEFS_ZONE_OPEN flag if the zone transitioned to
365 	 * the read-only or offline condition, to avoid attempting an explicit
366 	 * close of the zone when the inode file is closed.
367 	 */
368 	if ((sbi->s_mount_opts & ZONEFS_MNTOPT_EXPLICIT_OPEN) &&
369 	    (zone->cond == BLK_ZONE_COND_OFFLINE ||
370 	     zone->cond == BLK_ZONE_COND_READONLY))
371 		zi->i_flags &= ~ZONEFS_ZONE_OPEN;
372 
373 	/*
374 	 * If error=remount-ro was specified, any error result in remounting
375 	 * the volume as read-only.
376 	 */
377 	if ((sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_RO) && !sb_rdonly(sb)) {
378 		zonefs_warn(sb, "remounting filesystem read-only\n");
379 		sb->s_flags |= SB_RDONLY;
380 	}
381 
382 	/*
383 	 * Update block usage stats and the inode size  to prevent access to
384 	 * invalid data.
385 	 */
386 	zonefs_update_stats(inode, data_size);
387 	zonefs_i_size_write(inode, data_size);
388 	zi->i_wpoffset = data_size;
389 
390 	return 0;
391 }
392 
393 /*
394  * When an file IO error occurs, check the file zone to see if there is a change
395  * in the zone condition (e.g. offline or read-only). For a failed write to a
396  * sequential zone, the zone write pointer position must also be checked to
397  * eventually correct the file size and zonefs inode write pointer offset
398  * (which can be out of sync with the drive due to partial write failures).
399  */
400 static void __zonefs_io_error(struct inode *inode, bool write)
401 {
402 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
403 	struct super_block *sb = inode->i_sb;
404 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
405 	unsigned int noio_flag;
406 	unsigned int nr_zones =
407 		zi->i_zone_size >> (sbi->s_zone_sectors_shift + SECTOR_SHIFT);
408 	struct zonefs_ioerr_data err = {
409 		.inode = inode,
410 		.write = write,
411 	};
412 	int ret;
413 
414 	/*
415 	 * Memory allocations in blkdev_report_zones() can trigger a memory
416 	 * reclaim which may in turn cause a recursion into zonefs as well as
417 	 * struct request allocations for the same device. The former case may
418 	 * end up in a deadlock on the inode truncate mutex, while the latter
419 	 * may prevent IO forward progress. Executing the report zones under
420 	 * the GFP_NOIO context avoids both problems.
421 	 */
422 	noio_flag = memalloc_noio_save();
423 	ret = blkdev_report_zones(sb->s_bdev, zi->i_zsector, nr_zones,
424 				  zonefs_io_error_cb, &err);
425 	if (ret != nr_zones)
426 		zonefs_err(sb, "Get inode %lu zone information failed %d\n",
427 			   inode->i_ino, ret);
428 	memalloc_noio_restore(noio_flag);
429 }
430 
431 static void zonefs_io_error(struct inode *inode, bool write)
432 {
433 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
434 
435 	mutex_lock(&zi->i_truncate_mutex);
436 	__zonefs_io_error(inode, write);
437 	mutex_unlock(&zi->i_truncate_mutex);
438 }
439 
440 static int zonefs_file_truncate(struct inode *inode, loff_t isize)
441 {
442 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
443 	loff_t old_isize;
444 	enum req_opf op;
445 	int ret = 0;
446 
447 	/*
448 	 * Only sequential zone files can be truncated and truncation is allowed
449 	 * only down to a 0 size, which is equivalent to a zone reset, and to
450 	 * the maximum file size, which is equivalent to a zone finish.
451 	 */
452 	if (zi->i_ztype != ZONEFS_ZTYPE_SEQ)
453 		return -EPERM;
454 
455 	if (!isize)
456 		op = REQ_OP_ZONE_RESET;
457 	else if (isize == zi->i_max_size)
458 		op = REQ_OP_ZONE_FINISH;
459 	else
460 		return -EPERM;
461 
462 	inode_dio_wait(inode);
463 
464 	/* Serialize against page faults */
465 	down_write(&zi->i_mmap_sem);
466 
467 	/* Serialize against zonefs_iomap_begin() */
468 	mutex_lock(&zi->i_truncate_mutex);
469 
470 	old_isize = i_size_read(inode);
471 	if (isize == old_isize)
472 		goto unlock;
473 
474 	ret = zonefs_zone_mgmt(inode, op);
475 	if (ret)
476 		goto unlock;
477 
478 	/*
479 	 * If the mount option ZONEFS_MNTOPT_EXPLICIT_OPEN is set,
480 	 * take care of open zones.
481 	 */
482 	if (zi->i_flags & ZONEFS_ZONE_OPEN) {
483 		/*
484 		 * Truncating a zone to EMPTY or FULL is the equivalent of
485 		 * closing the zone. For a truncation to 0, we need to
486 		 * re-open the zone to ensure new writes can be processed.
487 		 * For a truncation to the maximum file size, the zone is
488 		 * closed and writes cannot be accepted anymore, so clear
489 		 * the open flag.
490 		 */
491 		if (!isize)
492 			ret = zonefs_zone_mgmt(inode, REQ_OP_ZONE_OPEN);
493 		else
494 			zi->i_flags &= ~ZONEFS_ZONE_OPEN;
495 	}
496 
497 	zonefs_update_stats(inode, isize);
498 	truncate_setsize(inode, isize);
499 	zi->i_wpoffset = isize;
500 
501 unlock:
502 	mutex_unlock(&zi->i_truncate_mutex);
503 	up_write(&zi->i_mmap_sem);
504 
505 	return ret;
506 }
507 
508 static int zonefs_inode_setattr(struct user_namespace *mnt_userns,
509 				struct dentry *dentry, struct iattr *iattr)
510 {
511 	struct inode *inode = d_inode(dentry);
512 	int ret;
513 
514 	if (unlikely(IS_IMMUTABLE(inode)))
515 		return -EPERM;
516 
517 	ret = setattr_prepare(&init_user_ns, dentry, iattr);
518 	if (ret)
519 		return ret;
520 
521 	/*
522 	 * Since files and directories cannot be created nor deleted, do not
523 	 * allow setting any write attributes on the sub-directories grouping
524 	 * files by zone type.
525 	 */
526 	if ((iattr->ia_valid & ATTR_MODE) && S_ISDIR(inode->i_mode) &&
527 	    (iattr->ia_mode & 0222))
528 		return -EPERM;
529 
530 	if (((iattr->ia_valid & ATTR_UID) &&
531 	     !uid_eq(iattr->ia_uid, inode->i_uid)) ||
532 	    ((iattr->ia_valid & ATTR_GID) &&
533 	     !gid_eq(iattr->ia_gid, inode->i_gid))) {
534 		ret = dquot_transfer(inode, iattr);
535 		if (ret)
536 			return ret;
537 	}
538 
539 	if (iattr->ia_valid & ATTR_SIZE) {
540 		ret = zonefs_file_truncate(inode, iattr->ia_size);
541 		if (ret)
542 			return ret;
543 	}
544 
545 	setattr_copy(&init_user_ns, inode, iattr);
546 
547 	return 0;
548 }
549 
550 static const struct inode_operations zonefs_file_inode_operations = {
551 	.setattr	= zonefs_inode_setattr,
552 };
553 
554 static int zonefs_file_fsync(struct file *file, loff_t start, loff_t end,
555 			     int datasync)
556 {
557 	struct inode *inode = file_inode(file);
558 	int ret = 0;
559 
560 	if (unlikely(IS_IMMUTABLE(inode)))
561 		return -EPERM;
562 
563 	/*
564 	 * Since only direct writes are allowed in sequential files, page cache
565 	 * flush is needed only for conventional zone files.
566 	 */
567 	if (ZONEFS_I(inode)->i_ztype == ZONEFS_ZTYPE_CNV)
568 		ret = file_write_and_wait_range(file, start, end);
569 	if (!ret)
570 		ret = blkdev_issue_flush(inode->i_sb->s_bdev);
571 
572 	if (ret)
573 		zonefs_io_error(inode, true);
574 
575 	return ret;
576 }
577 
578 static vm_fault_t zonefs_filemap_fault(struct vm_fault *vmf)
579 {
580 	struct zonefs_inode_info *zi = ZONEFS_I(file_inode(vmf->vma->vm_file));
581 	vm_fault_t ret;
582 
583 	down_read(&zi->i_mmap_sem);
584 	ret = filemap_fault(vmf);
585 	up_read(&zi->i_mmap_sem);
586 
587 	return ret;
588 }
589 
590 static vm_fault_t zonefs_filemap_page_mkwrite(struct vm_fault *vmf)
591 {
592 	struct inode *inode = file_inode(vmf->vma->vm_file);
593 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
594 	vm_fault_t ret;
595 
596 	if (unlikely(IS_IMMUTABLE(inode)))
597 		return VM_FAULT_SIGBUS;
598 
599 	/*
600 	 * Sanity check: only conventional zone files can have shared
601 	 * writeable mappings.
602 	 */
603 	if (WARN_ON_ONCE(zi->i_ztype != ZONEFS_ZTYPE_CNV))
604 		return VM_FAULT_NOPAGE;
605 
606 	sb_start_pagefault(inode->i_sb);
607 	file_update_time(vmf->vma->vm_file);
608 
609 	/* Serialize against truncates */
610 	down_read(&zi->i_mmap_sem);
611 	ret = iomap_page_mkwrite(vmf, &zonefs_iomap_ops);
612 	up_read(&zi->i_mmap_sem);
613 
614 	sb_end_pagefault(inode->i_sb);
615 	return ret;
616 }
617 
618 static const struct vm_operations_struct zonefs_file_vm_ops = {
619 	.fault		= zonefs_filemap_fault,
620 	.map_pages	= filemap_map_pages,
621 	.page_mkwrite	= zonefs_filemap_page_mkwrite,
622 };
623 
624 static int zonefs_file_mmap(struct file *file, struct vm_area_struct *vma)
625 {
626 	/*
627 	 * Conventional zones accept random writes, so their files can support
628 	 * shared writable mappings. For sequential zone files, only read
629 	 * mappings are possible since there are no guarantees for write
630 	 * ordering between msync() and page cache writeback.
631 	 */
632 	if (ZONEFS_I(file_inode(file))->i_ztype == ZONEFS_ZTYPE_SEQ &&
633 	    (vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
634 		return -EINVAL;
635 
636 	file_accessed(file);
637 	vma->vm_ops = &zonefs_file_vm_ops;
638 
639 	return 0;
640 }
641 
642 static loff_t zonefs_file_llseek(struct file *file, loff_t offset, int whence)
643 {
644 	loff_t isize = i_size_read(file_inode(file));
645 
646 	/*
647 	 * Seeks are limited to below the zone size for conventional zones
648 	 * and below the zone write pointer for sequential zones. In both
649 	 * cases, this limit is the inode size.
650 	 */
651 	return generic_file_llseek_size(file, offset, whence, isize, isize);
652 }
653 
654 static int zonefs_file_write_dio_end_io(struct kiocb *iocb, ssize_t size,
655 					int error, unsigned int flags)
656 {
657 	struct inode *inode = file_inode(iocb->ki_filp);
658 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
659 
660 	if (error) {
661 		zonefs_io_error(inode, true);
662 		return error;
663 	}
664 
665 	if (size && zi->i_ztype != ZONEFS_ZTYPE_CNV) {
666 		/*
667 		 * Note that we may be seeing completions out of order,
668 		 * but that is not a problem since a write completed
669 		 * successfully necessarily means that all preceding writes
670 		 * were also successful. So we can safely increase the inode
671 		 * size to the write end location.
672 		 */
673 		mutex_lock(&zi->i_truncate_mutex);
674 		if (i_size_read(inode) < iocb->ki_pos + size) {
675 			zonefs_update_stats(inode, iocb->ki_pos + size);
676 			zonefs_i_size_write(inode, iocb->ki_pos + size);
677 		}
678 		mutex_unlock(&zi->i_truncate_mutex);
679 	}
680 
681 	return 0;
682 }
683 
684 static const struct iomap_dio_ops zonefs_write_dio_ops = {
685 	.end_io			= zonefs_file_write_dio_end_io,
686 };
687 
688 static ssize_t zonefs_file_dio_append(struct kiocb *iocb, struct iov_iter *from)
689 {
690 	struct inode *inode = file_inode(iocb->ki_filp);
691 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
692 	struct block_device *bdev = inode->i_sb->s_bdev;
693 	unsigned int max;
694 	struct bio *bio;
695 	ssize_t size;
696 	int nr_pages;
697 	ssize_t ret;
698 
699 	max = queue_max_zone_append_sectors(bdev_get_queue(bdev));
700 	max = ALIGN_DOWN(max << SECTOR_SHIFT, inode->i_sb->s_blocksize);
701 	iov_iter_truncate(from, max);
702 
703 	nr_pages = iov_iter_npages(from, BIO_MAX_VECS);
704 	if (!nr_pages)
705 		return 0;
706 
707 	bio = bio_alloc(GFP_NOFS, nr_pages);
708 	if (!bio)
709 		return -ENOMEM;
710 
711 	bio_set_dev(bio, bdev);
712 	bio->bi_iter.bi_sector = zi->i_zsector;
713 	bio->bi_write_hint = iocb->ki_hint;
714 	bio->bi_ioprio = iocb->ki_ioprio;
715 	bio->bi_opf = REQ_OP_ZONE_APPEND | REQ_SYNC | REQ_IDLE;
716 	if (iocb->ki_flags & IOCB_DSYNC)
717 		bio->bi_opf |= REQ_FUA;
718 
719 	ret = bio_iov_iter_get_pages(bio, from);
720 	if (unlikely(ret))
721 		goto out_release;
722 
723 	size = bio->bi_iter.bi_size;
724 	task_io_account_write(size);
725 
726 	if (iocb->ki_flags & IOCB_HIPRI)
727 		bio_set_polled(bio, iocb);
728 
729 	ret = submit_bio_wait(bio);
730 
731 	zonefs_file_write_dio_end_io(iocb, size, ret, 0);
732 	trace_zonefs_file_dio_append(inode, size, ret);
733 
734 out_release:
735 	bio_release_pages(bio, false);
736 	bio_put(bio);
737 
738 	if (ret >= 0) {
739 		iocb->ki_pos += size;
740 		return size;
741 	}
742 
743 	return ret;
744 }
745 
746 /*
747  * Do not exceed the LFS limits nor the file zone size. If pos is under the
748  * limit it becomes a short access. If it exceeds the limit, return -EFBIG.
749  */
750 static loff_t zonefs_write_check_limits(struct file *file, loff_t pos,
751 					loff_t count)
752 {
753 	struct inode *inode = file_inode(file);
754 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
755 	loff_t limit = rlimit(RLIMIT_FSIZE);
756 	loff_t max_size = zi->i_max_size;
757 
758 	if (limit != RLIM_INFINITY) {
759 		if (pos >= limit) {
760 			send_sig(SIGXFSZ, current, 0);
761 			return -EFBIG;
762 		}
763 		count = min(count, limit - pos);
764 	}
765 
766 	if (!(file->f_flags & O_LARGEFILE))
767 		max_size = min_t(loff_t, MAX_NON_LFS, max_size);
768 
769 	if (unlikely(pos >= max_size))
770 		return -EFBIG;
771 
772 	return min(count, max_size - pos);
773 }
774 
775 static ssize_t zonefs_write_checks(struct kiocb *iocb, struct iov_iter *from)
776 {
777 	struct file *file = iocb->ki_filp;
778 	struct inode *inode = file_inode(file);
779 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
780 	loff_t count;
781 
782 	if (IS_SWAPFILE(inode))
783 		return -ETXTBSY;
784 
785 	if (!iov_iter_count(from))
786 		return 0;
787 
788 	if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
789 		return -EINVAL;
790 
791 	if (iocb->ki_flags & IOCB_APPEND) {
792 		if (zi->i_ztype != ZONEFS_ZTYPE_SEQ)
793 			return -EINVAL;
794 		mutex_lock(&zi->i_truncate_mutex);
795 		iocb->ki_pos = zi->i_wpoffset;
796 		mutex_unlock(&zi->i_truncate_mutex);
797 	}
798 
799 	count = zonefs_write_check_limits(file, iocb->ki_pos,
800 					  iov_iter_count(from));
801 	if (count < 0)
802 		return count;
803 
804 	iov_iter_truncate(from, count);
805 	return iov_iter_count(from);
806 }
807 
808 /*
809  * Handle direct writes. For sequential zone files, this is the only possible
810  * write path. For these files, check that the user is issuing writes
811  * sequentially from the end of the file. This code assumes that the block layer
812  * delivers write requests to the device in sequential order. This is always the
813  * case if a block IO scheduler implementing the ELEVATOR_F_ZBD_SEQ_WRITE
814  * elevator feature is being used (e.g. mq-deadline). The block layer always
815  * automatically select such an elevator for zoned block devices during the
816  * device initialization.
817  */
818 static ssize_t zonefs_file_dio_write(struct kiocb *iocb, struct iov_iter *from)
819 {
820 	struct inode *inode = file_inode(iocb->ki_filp);
821 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
822 	struct super_block *sb = inode->i_sb;
823 	bool sync = is_sync_kiocb(iocb);
824 	bool append = false;
825 	ssize_t ret, count;
826 
827 	/*
828 	 * For async direct IOs to sequential zone files, refuse IOCB_NOWAIT
829 	 * as this can cause write reordering (e.g. the first aio gets EAGAIN
830 	 * on the inode lock but the second goes through but is now unaligned).
831 	 */
832 	if (zi->i_ztype == ZONEFS_ZTYPE_SEQ && !sync &&
833 	    (iocb->ki_flags & IOCB_NOWAIT))
834 		return -EOPNOTSUPP;
835 
836 	if (iocb->ki_flags & IOCB_NOWAIT) {
837 		if (!inode_trylock(inode))
838 			return -EAGAIN;
839 	} else {
840 		inode_lock(inode);
841 	}
842 
843 	count = zonefs_write_checks(iocb, from);
844 	if (count <= 0) {
845 		ret = count;
846 		goto inode_unlock;
847 	}
848 
849 	if ((iocb->ki_pos | count) & (sb->s_blocksize - 1)) {
850 		ret = -EINVAL;
851 		goto inode_unlock;
852 	}
853 
854 	/* Enforce sequential writes (append only) in sequential zones */
855 	if (zi->i_ztype == ZONEFS_ZTYPE_SEQ) {
856 		mutex_lock(&zi->i_truncate_mutex);
857 		if (iocb->ki_pos != zi->i_wpoffset) {
858 			mutex_unlock(&zi->i_truncate_mutex);
859 			ret = -EINVAL;
860 			goto inode_unlock;
861 		}
862 		mutex_unlock(&zi->i_truncate_mutex);
863 		append = sync;
864 	}
865 
866 	if (append)
867 		ret = zonefs_file_dio_append(iocb, from);
868 	else
869 		ret = iomap_dio_rw(iocb, from, &zonefs_iomap_ops,
870 				   &zonefs_write_dio_ops, 0);
871 	if (zi->i_ztype == ZONEFS_ZTYPE_SEQ &&
872 	    (ret > 0 || ret == -EIOCBQUEUED)) {
873 		if (ret > 0)
874 			count = ret;
875 		mutex_lock(&zi->i_truncate_mutex);
876 		zi->i_wpoffset += count;
877 		mutex_unlock(&zi->i_truncate_mutex);
878 	}
879 
880 inode_unlock:
881 	inode_unlock(inode);
882 
883 	return ret;
884 }
885 
886 static ssize_t zonefs_file_buffered_write(struct kiocb *iocb,
887 					  struct iov_iter *from)
888 {
889 	struct inode *inode = file_inode(iocb->ki_filp);
890 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
891 	ssize_t ret;
892 
893 	/*
894 	 * Direct IO writes are mandatory for sequential zone files so that the
895 	 * write IO issuing order is preserved.
896 	 */
897 	if (zi->i_ztype != ZONEFS_ZTYPE_CNV)
898 		return -EIO;
899 
900 	if (iocb->ki_flags & IOCB_NOWAIT) {
901 		if (!inode_trylock(inode))
902 			return -EAGAIN;
903 	} else {
904 		inode_lock(inode);
905 	}
906 
907 	ret = zonefs_write_checks(iocb, from);
908 	if (ret <= 0)
909 		goto inode_unlock;
910 
911 	ret = iomap_file_buffered_write(iocb, from, &zonefs_iomap_ops);
912 	if (ret > 0)
913 		iocb->ki_pos += ret;
914 	else if (ret == -EIO)
915 		zonefs_io_error(inode, true);
916 
917 inode_unlock:
918 	inode_unlock(inode);
919 	if (ret > 0)
920 		ret = generic_write_sync(iocb, ret);
921 
922 	return ret;
923 }
924 
925 static ssize_t zonefs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
926 {
927 	struct inode *inode = file_inode(iocb->ki_filp);
928 
929 	if (unlikely(IS_IMMUTABLE(inode)))
930 		return -EPERM;
931 
932 	if (sb_rdonly(inode->i_sb))
933 		return -EROFS;
934 
935 	/* Write operations beyond the zone size are not allowed */
936 	if (iocb->ki_pos >= ZONEFS_I(inode)->i_max_size)
937 		return -EFBIG;
938 
939 	if (iocb->ki_flags & IOCB_DIRECT) {
940 		ssize_t ret = zonefs_file_dio_write(iocb, from);
941 		if (ret != -ENOTBLK)
942 			return ret;
943 	}
944 
945 	return zonefs_file_buffered_write(iocb, from);
946 }
947 
948 static int zonefs_file_read_dio_end_io(struct kiocb *iocb, ssize_t size,
949 				       int error, unsigned int flags)
950 {
951 	if (error) {
952 		zonefs_io_error(file_inode(iocb->ki_filp), false);
953 		return error;
954 	}
955 
956 	return 0;
957 }
958 
959 static const struct iomap_dio_ops zonefs_read_dio_ops = {
960 	.end_io			= zonefs_file_read_dio_end_io,
961 };
962 
963 static ssize_t zonefs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
964 {
965 	struct inode *inode = file_inode(iocb->ki_filp);
966 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
967 	struct super_block *sb = inode->i_sb;
968 	loff_t isize;
969 	ssize_t ret;
970 
971 	/* Offline zones cannot be read */
972 	if (unlikely(IS_IMMUTABLE(inode) && !(inode->i_mode & 0777)))
973 		return -EPERM;
974 
975 	if (iocb->ki_pos >= zi->i_max_size)
976 		return 0;
977 
978 	if (iocb->ki_flags & IOCB_NOWAIT) {
979 		if (!inode_trylock_shared(inode))
980 			return -EAGAIN;
981 	} else {
982 		inode_lock_shared(inode);
983 	}
984 
985 	/* Limit read operations to written data */
986 	mutex_lock(&zi->i_truncate_mutex);
987 	isize = i_size_read(inode);
988 	if (iocb->ki_pos >= isize) {
989 		mutex_unlock(&zi->i_truncate_mutex);
990 		ret = 0;
991 		goto inode_unlock;
992 	}
993 	iov_iter_truncate(to, isize - iocb->ki_pos);
994 	mutex_unlock(&zi->i_truncate_mutex);
995 
996 	if (iocb->ki_flags & IOCB_DIRECT) {
997 		size_t count = iov_iter_count(to);
998 
999 		if ((iocb->ki_pos | count) & (sb->s_blocksize - 1)) {
1000 			ret = -EINVAL;
1001 			goto inode_unlock;
1002 		}
1003 		file_accessed(iocb->ki_filp);
1004 		ret = iomap_dio_rw(iocb, to, &zonefs_iomap_ops,
1005 				   &zonefs_read_dio_ops, 0);
1006 	} else {
1007 		ret = generic_file_read_iter(iocb, to);
1008 		if (ret == -EIO)
1009 			zonefs_io_error(inode, false);
1010 	}
1011 
1012 inode_unlock:
1013 	inode_unlock_shared(inode);
1014 
1015 	return ret;
1016 }
1017 
1018 static inline bool zonefs_file_use_exp_open(struct inode *inode, struct file *file)
1019 {
1020 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
1021 	struct zonefs_sb_info *sbi = ZONEFS_SB(inode->i_sb);
1022 
1023 	if (!(sbi->s_mount_opts & ZONEFS_MNTOPT_EXPLICIT_OPEN))
1024 		return false;
1025 
1026 	if (zi->i_ztype != ZONEFS_ZTYPE_SEQ)
1027 		return false;
1028 
1029 	if (!(file->f_mode & FMODE_WRITE))
1030 		return false;
1031 
1032 	return true;
1033 }
1034 
1035 static int zonefs_open_zone(struct inode *inode)
1036 {
1037 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
1038 	struct zonefs_sb_info *sbi = ZONEFS_SB(inode->i_sb);
1039 	int ret = 0;
1040 
1041 	mutex_lock(&zi->i_truncate_mutex);
1042 
1043 	if (!zi->i_wr_refcnt) {
1044 		if (atomic_inc_return(&sbi->s_open_zones) > sbi->s_max_open_zones) {
1045 			atomic_dec(&sbi->s_open_zones);
1046 			ret = -EBUSY;
1047 			goto unlock;
1048 		}
1049 
1050 		if (i_size_read(inode) < zi->i_max_size) {
1051 			ret = zonefs_zone_mgmt(inode, REQ_OP_ZONE_OPEN);
1052 			if (ret) {
1053 				atomic_dec(&sbi->s_open_zones);
1054 				goto unlock;
1055 			}
1056 			zi->i_flags |= ZONEFS_ZONE_OPEN;
1057 		}
1058 	}
1059 
1060 	zi->i_wr_refcnt++;
1061 
1062 unlock:
1063 	mutex_unlock(&zi->i_truncate_mutex);
1064 
1065 	return ret;
1066 }
1067 
1068 static int zonefs_file_open(struct inode *inode, struct file *file)
1069 {
1070 	int ret;
1071 
1072 	ret = generic_file_open(inode, file);
1073 	if (ret)
1074 		return ret;
1075 
1076 	if (zonefs_file_use_exp_open(inode, file))
1077 		return zonefs_open_zone(inode);
1078 
1079 	return 0;
1080 }
1081 
1082 static void zonefs_close_zone(struct inode *inode)
1083 {
1084 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
1085 	int ret = 0;
1086 
1087 	mutex_lock(&zi->i_truncate_mutex);
1088 	zi->i_wr_refcnt--;
1089 	if (!zi->i_wr_refcnt) {
1090 		struct zonefs_sb_info *sbi = ZONEFS_SB(inode->i_sb);
1091 		struct super_block *sb = inode->i_sb;
1092 
1093 		/*
1094 		 * If the file zone is full, it is not open anymore and we only
1095 		 * need to decrement the open count.
1096 		 */
1097 		if (!(zi->i_flags & ZONEFS_ZONE_OPEN))
1098 			goto dec;
1099 
1100 		ret = zonefs_zone_mgmt(inode, REQ_OP_ZONE_CLOSE);
1101 		if (ret) {
1102 			__zonefs_io_error(inode, false);
1103 			/*
1104 			 * Leaving zones explicitly open may lead to a state
1105 			 * where most zones cannot be written (zone resources
1106 			 * exhausted). So take preventive action by remounting
1107 			 * read-only.
1108 			 */
1109 			if (zi->i_flags & ZONEFS_ZONE_OPEN &&
1110 			    !(sb->s_flags & SB_RDONLY)) {
1111 				zonefs_warn(sb, "closing zone failed, remounting filesystem read-only\n");
1112 				sb->s_flags |= SB_RDONLY;
1113 			}
1114 		}
1115 		zi->i_flags &= ~ZONEFS_ZONE_OPEN;
1116 dec:
1117 		atomic_dec(&sbi->s_open_zones);
1118 	}
1119 	mutex_unlock(&zi->i_truncate_mutex);
1120 }
1121 
1122 static int zonefs_file_release(struct inode *inode, struct file *file)
1123 {
1124 	/*
1125 	 * If we explicitly open a zone we must close it again as well, but the
1126 	 * zone management operation can fail (either due to an IO error or as
1127 	 * the zone has gone offline or read-only). Make sure we don't fail the
1128 	 * close(2) for user-space.
1129 	 */
1130 	if (zonefs_file_use_exp_open(inode, file))
1131 		zonefs_close_zone(inode);
1132 
1133 	return 0;
1134 }
1135 
1136 static const struct file_operations zonefs_file_operations = {
1137 	.open		= zonefs_file_open,
1138 	.release	= zonefs_file_release,
1139 	.fsync		= zonefs_file_fsync,
1140 	.mmap		= zonefs_file_mmap,
1141 	.llseek		= zonefs_file_llseek,
1142 	.read_iter	= zonefs_file_read_iter,
1143 	.write_iter	= zonefs_file_write_iter,
1144 	.splice_read	= generic_file_splice_read,
1145 	.splice_write	= iter_file_splice_write,
1146 	.iopoll		= iomap_dio_iopoll,
1147 };
1148 
1149 static struct kmem_cache *zonefs_inode_cachep;
1150 
1151 static struct inode *zonefs_alloc_inode(struct super_block *sb)
1152 {
1153 	struct zonefs_inode_info *zi;
1154 
1155 	zi = kmem_cache_alloc(zonefs_inode_cachep, GFP_KERNEL);
1156 	if (!zi)
1157 		return NULL;
1158 
1159 	inode_init_once(&zi->i_vnode);
1160 	mutex_init(&zi->i_truncate_mutex);
1161 	init_rwsem(&zi->i_mmap_sem);
1162 	zi->i_wr_refcnt = 0;
1163 
1164 	return &zi->i_vnode;
1165 }
1166 
1167 static void zonefs_free_inode(struct inode *inode)
1168 {
1169 	kmem_cache_free(zonefs_inode_cachep, ZONEFS_I(inode));
1170 }
1171 
1172 /*
1173  * File system stat.
1174  */
1175 static int zonefs_statfs(struct dentry *dentry, struct kstatfs *buf)
1176 {
1177 	struct super_block *sb = dentry->d_sb;
1178 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1179 	enum zonefs_ztype t;
1180 	u64 fsid;
1181 
1182 	buf->f_type = ZONEFS_MAGIC;
1183 	buf->f_bsize = sb->s_blocksize;
1184 	buf->f_namelen = ZONEFS_NAME_MAX;
1185 
1186 	spin_lock(&sbi->s_lock);
1187 
1188 	buf->f_blocks = sbi->s_blocks;
1189 	if (WARN_ON(sbi->s_used_blocks > sbi->s_blocks))
1190 		buf->f_bfree = 0;
1191 	else
1192 		buf->f_bfree = buf->f_blocks - sbi->s_used_blocks;
1193 	buf->f_bavail = buf->f_bfree;
1194 
1195 	for (t = 0; t < ZONEFS_ZTYPE_MAX; t++) {
1196 		if (sbi->s_nr_files[t])
1197 			buf->f_files += sbi->s_nr_files[t] + 1;
1198 	}
1199 	buf->f_ffree = 0;
1200 
1201 	spin_unlock(&sbi->s_lock);
1202 
1203 	fsid = le64_to_cpup((void *)sbi->s_uuid.b) ^
1204 		le64_to_cpup((void *)sbi->s_uuid.b + sizeof(u64));
1205 	buf->f_fsid = u64_to_fsid(fsid);
1206 
1207 	return 0;
1208 }
1209 
1210 enum {
1211 	Opt_errors_ro, Opt_errors_zro, Opt_errors_zol, Opt_errors_repair,
1212 	Opt_explicit_open, Opt_err,
1213 };
1214 
1215 static const match_table_t tokens = {
1216 	{ Opt_errors_ro,	"errors=remount-ro"},
1217 	{ Opt_errors_zro,	"errors=zone-ro"},
1218 	{ Opt_errors_zol,	"errors=zone-offline"},
1219 	{ Opt_errors_repair,	"errors=repair"},
1220 	{ Opt_explicit_open,	"explicit-open" },
1221 	{ Opt_err,		NULL}
1222 };
1223 
1224 static int zonefs_parse_options(struct super_block *sb, char *options)
1225 {
1226 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1227 	substring_t args[MAX_OPT_ARGS];
1228 	char *p;
1229 
1230 	if (!options)
1231 		return 0;
1232 
1233 	while ((p = strsep(&options, ",")) != NULL) {
1234 		int token;
1235 
1236 		if (!*p)
1237 			continue;
1238 
1239 		token = match_token(p, tokens, args);
1240 		switch (token) {
1241 		case Opt_errors_ro:
1242 			sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
1243 			sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_RO;
1244 			break;
1245 		case Opt_errors_zro:
1246 			sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
1247 			sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_ZRO;
1248 			break;
1249 		case Opt_errors_zol:
1250 			sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
1251 			sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_ZOL;
1252 			break;
1253 		case Opt_errors_repair:
1254 			sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
1255 			sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_REPAIR;
1256 			break;
1257 		case Opt_explicit_open:
1258 			sbi->s_mount_opts |= ZONEFS_MNTOPT_EXPLICIT_OPEN;
1259 			break;
1260 		default:
1261 			return -EINVAL;
1262 		}
1263 	}
1264 
1265 	return 0;
1266 }
1267 
1268 static int zonefs_show_options(struct seq_file *seq, struct dentry *root)
1269 {
1270 	struct zonefs_sb_info *sbi = ZONEFS_SB(root->d_sb);
1271 
1272 	if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_RO)
1273 		seq_puts(seq, ",errors=remount-ro");
1274 	if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZRO)
1275 		seq_puts(seq, ",errors=zone-ro");
1276 	if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZOL)
1277 		seq_puts(seq, ",errors=zone-offline");
1278 	if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_REPAIR)
1279 		seq_puts(seq, ",errors=repair");
1280 
1281 	return 0;
1282 }
1283 
1284 static int zonefs_remount(struct super_block *sb, int *flags, char *data)
1285 {
1286 	sync_filesystem(sb);
1287 
1288 	return zonefs_parse_options(sb, data);
1289 }
1290 
1291 static const struct super_operations zonefs_sops = {
1292 	.alloc_inode	= zonefs_alloc_inode,
1293 	.free_inode	= zonefs_free_inode,
1294 	.statfs		= zonefs_statfs,
1295 	.remount_fs	= zonefs_remount,
1296 	.show_options	= zonefs_show_options,
1297 };
1298 
1299 static const struct inode_operations zonefs_dir_inode_operations = {
1300 	.lookup		= simple_lookup,
1301 	.setattr	= zonefs_inode_setattr,
1302 };
1303 
1304 static void zonefs_init_dir_inode(struct inode *parent, struct inode *inode,
1305 				  enum zonefs_ztype type)
1306 {
1307 	struct super_block *sb = parent->i_sb;
1308 
1309 	inode->i_ino = blkdev_nr_zones(sb->s_bdev->bd_disk) + type + 1;
1310 	inode_init_owner(&init_user_ns, inode, parent, S_IFDIR | 0555);
1311 	inode->i_op = &zonefs_dir_inode_operations;
1312 	inode->i_fop = &simple_dir_operations;
1313 	set_nlink(inode, 2);
1314 	inc_nlink(parent);
1315 }
1316 
1317 static void zonefs_init_file_inode(struct inode *inode, struct blk_zone *zone,
1318 				   enum zonefs_ztype type)
1319 {
1320 	struct super_block *sb = inode->i_sb;
1321 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1322 	struct zonefs_inode_info *zi = ZONEFS_I(inode);
1323 
1324 	inode->i_ino = zone->start >> sbi->s_zone_sectors_shift;
1325 	inode->i_mode = S_IFREG | sbi->s_perm;
1326 
1327 	zi->i_ztype = type;
1328 	zi->i_zsector = zone->start;
1329 	zi->i_zone_size = zone->len << SECTOR_SHIFT;
1330 
1331 	zi->i_max_size = min_t(loff_t, MAX_LFS_FILESIZE,
1332 			       zone->capacity << SECTOR_SHIFT);
1333 	zi->i_wpoffset = zonefs_check_zone_condition(inode, zone, true, true);
1334 
1335 	inode->i_uid = sbi->s_uid;
1336 	inode->i_gid = sbi->s_gid;
1337 	inode->i_size = zi->i_wpoffset;
1338 	inode->i_blocks = zi->i_max_size >> SECTOR_SHIFT;
1339 
1340 	inode->i_op = &zonefs_file_inode_operations;
1341 	inode->i_fop = &zonefs_file_operations;
1342 	inode->i_mapping->a_ops = &zonefs_file_aops;
1343 
1344 	sb->s_maxbytes = max(zi->i_max_size, sb->s_maxbytes);
1345 	sbi->s_blocks += zi->i_max_size >> sb->s_blocksize_bits;
1346 	sbi->s_used_blocks += zi->i_wpoffset >> sb->s_blocksize_bits;
1347 }
1348 
1349 static struct dentry *zonefs_create_inode(struct dentry *parent,
1350 					const char *name, struct blk_zone *zone,
1351 					enum zonefs_ztype type)
1352 {
1353 	struct inode *dir = d_inode(parent);
1354 	struct dentry *dentry;
1355 	struct inode *inode;
1356 
1357 	dentry = d_alloc_name(parent, name);
1358 	if (!dentry)
1359 		return NULL;
1360 
1361 	inode = new_inode(parent->d_sb);
1362 	if (!inode)
1363 		goto dput;
1364 
1365 	inode->i_ctime = inode->i_mtime = inode->i_atime = dir->i_ctime;
1366 	if (zone)
1367 		zonefs_init_file_inode(inode, zone, type);
1368 	else
1369 		zonefs_init_dir_inode(dir, inode, type);
1370 	d_add(dentry, inode);
1371 	dir->i_size++;
1372 
1373 	return dentry;
1374 
1375 dput:
1376 	dput(dentry);
1377 
1378 	return NULL;
1379 }
1380 
1381 struct zonefs_zone_data {
1382 	struct super_block	*sb;
1383 	unsigned int		nr_zones[ZONEFS_ZTYPE_MAX];
1384 	struct blk_zone		*zones;
1385 };
1386 
1387 /*
1388  * Create a zone group and populate it with zone files.
1389  */
1390 static int zonefs_create_zgroup(struct zonefs_zone_data *zd,
1391 				enum zonefs_ztype type)
1392 {
1393 	struct super_block *sb = zd->sb;
1394 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1395 	struct blk_zone *zone, *next, *end;
1396 	const char *zgroup_name;
1397 	char *file_name;
1398 	struct dentry *dir;
1399 	unsigned int n = 0;
1400 	int ret;
1401 
1402 	/* If the group is empty, there is nothing to do */
1403 	if (!zd->nr_zones[type])
1404 		return 0;
1405 
1406 	file_name = kmalloc(ZONEFS_NAME_MAX, GFP_KERNEL);
1407 	if (!file_name)
1408 		return -ENOMEM;
1409 
1410 	if (type == ZONEFS_ZTYPE_CNV)
1411 		zgroup_name = "cnv";
1412 	else
1413 		zgroup_name = "seq";
1414 
1415 	dir = zonefs_create_inode(sb->s_root, zgroup_name, NULL, type);
1416 	if (!dir) {
1417 		ret = -ENOMEM;
1418 		goto free;
1419 	}
1420 
1421 	/*
1422 	 * The first zone contains the super block: skip it.
1423 	 */
1424 	end = zd->zones + blkdev_nr_zones(sb->s_bdev->bd_disk);
1425 	for (zone = &zd->zones[1]; zone < end; zone = next) {
1426 
1427 		next = zone + 1;
1428 		if (zonefs_zone_type(zone) != type)
1429 			continue;
1430 
1431 		/*
1432 		 * For conventional zones, contiguous zones can be aggregated
1433 		 * together to form larger files. Note that this overwrites the
1434 		 * length of the first zone of the set of contiguous zones
1435 		 * aggregated together. If one offline or read-only zone is
1436 		 * found, assume that all zones aggregated have the same
1437 		 * condition.
1438 		 */
1439 		if (type == ZONEFS_ZTYPE_CNV &&
1440 		    (sbi->s_features & ZONEFS_F_AGGRCNV)) {
1441 			for (; next < end; next++) {
1442 				if (zonefs_zone_type(next) != type)
1443 					break;
1444 				zone->len += next->len;
1445 				zone->capacity += next->capacity;
1446 				if (next->cond == BLK_ZONE_COND_READONLY &&
1447 				    zone->cond != BLK_ZONE_COND_OFFLINE)
1448 					zone->cond = BLK_ZONE_COND_READONLY;
1449 				else if (next->cond == BLK_ZONE_COND_OFFLINE)
1450 					zone->cond = BLK_ZONE_COND_OFFLINE;
1451 			}
1452 			if (zone->capacity != zone->len) {
1453 				zonefs_err(sb, "Invalid conventional zone capacity\n");
1454 				ret = -EINVAL;
1455 				goto free;
1456 			}
1457 		}
1458 
1459 		/*
1460 		 * Use the file number within its group as file name.
1461 		 */
1462 		snprintf(file_name, ZONEFS_NAME_MAX - 1, "%u", n);
1463 		if (!zonefs_create_inode(dir, file_name, zone, type)) {
1464 			ret = -ENOMEM;
1465 			goto free;
1466 		}
1467 
1468 		n++;
1469 	}
1470 
1471 	zonefs_info(sb, "Zone group \"%s\" has %u file%s\n",
1472 		    zgroup_name, n, n > 1 ? "s" : "");
1473 
1474 	sbi->s_nr_files[type] = n;
1475 	ret = 0;
1476 
1477 free:
1478 	kfree(file_name);
1479 
1480 	return ret;
1481 }
1482 
1483 static int zonefs_get_zone_info_cb(struct blk_zone *zone, unsigned int idx,
1484 				   void *data)
1485 {
1486 	struct zonefs_zone_data *zd = data;
1487 
1488 	/*
1489 	 * Count the number of usable zones: the first zone at index 0 contains
1490 	 * the super block and is ignored.
1491 	 */
1492 	switch (zone->type) {
1493 	case BLK_ZONE_TYPE_CONVENTIONAL:
1494 		zone->wp = zone->start + zone->len;
1495 		if (idx)
1496 			zd->nr_zones[ZONEFS_ZTYPE_CNV]++;
1497 		break;
1498 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
1499 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
1500 		if (idx)
1501 			zd->nr_zones[ZONEFS_ZTYPE_SEQ]++;
1502 		break;
1503 	default:
1504 		zonefs_err(zd->sb, "Unsupported zone type 0x%x\n",
1505 			   zone->type);
1506 		return -EIO;
1507 	}
1508 
1509 	memcpy(&zd->zones[idx], zone, sizeof(struct blk_zone));
1510 
1511 	return 0;
1512 }
1513 
1514 static int zonefs_get_zone_info(struct zonefs_zone_data *zd)
1515 {
1516 	struct block_device *bdev = zd->sb->s_bdev;
1517 	int ret;
1518 
1519 	zd->zones = kvcalloc(blkdev_nr_zones(bdev->bd_disk),
1520 			     sizeof(struct blk_zone), GFP_KERNEL);
1521 	if (!zd->zones)
1522 		return -ENOMEM;
1523 
1524 	/* Get zones information from the device */
1525 	ret = blkdev_report_zones(bdev, 0, BLK_ALL_ZONES,
1526 				  zonefs_get_zone_info_cb, zd);
1527 	if (ret < 0) {
1528 		zonefs_err(zd->sb, "Zone report failed %d\n", ret);
1529 		return ret;
1530 	}
1531 
1532 	if (ret != blkdev_nr_zones(bdev->bd_disk)) {
1533 		zonefs_err(zd->sb, "Invalid zone report (%d/%u zones)\n",
1534 			   ret, blkdev_nr_zones(bdev->bd_disk));
1535 		return -EIO;
1536 	}
1537 
1538 	return 0;
1539 }
1540 
1541 static inline void zonefs_cleanup_zone_info(struct zonefs_zone_data *zd)
1542 {
1543 	kvfree(zd->zones);
1544 }
1545 
1546 /*
1547  * Read super block information from the device.
1548  */
1549 static int zonefs_read_super(struct super_block *sb)
1550 {
1551 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1552 	struct zonefs_super *super;
1553 	u32 crc, stored_crc;
1554 	struct page *page;
1555 	struct bio_vec bio_vec;
1556 	struct bio bio;
1557 	int ret;
1558 
1559 	page = alloc_page(GFP_KERNEL);
1560 	if (!page)
1561 		return -ENOMEM;
1562 
1563 	bio_init(&bio, &bio_vec, 1);
1564 	bio.bi_iter.bi_sector = 0;
1565 	bio.bi_opf = REQ_OP_READ;
1566 	bio_set_dev(&bio, sb->s_bdev);
1567 	bio_add_page(&bio, page, PAGE_SIZE, 0);
1568 
1569 	ret = submit_bio_wait(&bio);
1570 	if (ret)
1571 		goto free_page;
1572 
1573 	super = kmap(page);
1574 
1575 	ret = -EINVAL;
1576 	if (le32_to_cpu(super->s_magic) != ZONEFS_MAGIC)
1577 		goto unmap;
1578 
1579 	stored_crc = le32_to_cpu(super->s_crc);
1580 	super->s_crc = 0;
1581 	crc = crc32(~0U, (unsigned char *)super, sizeof(struct zonefs_super));
1582 	if (crc != stored_crc) {
1583 		zonefs_err(sb, "Invalid checksum (Expected 0x%08x, got 0x%08x)",
1584 			   crc, stored_crc);
1585 		goto unmap;
1586 	}
1587 
1588 	sbi->s_features = le64_to_cpu(super->s_features);
1589 	if (sbi->s_features & ~ZONEFS_F_DEFINED_FEATURES) {
1590 		zonefs_err(sb, "Unknown features set 0x%llx\n",
1591 			   sbi->s_features);
1592 		goto unmap;
1593 	}
1594 
1595 	if (sbi->s_features & ZONEFS_F_UID) {
1596 		sbi->s_uid = make_kuid(current_user_ns(),
1597 				       le32_to_cpu(super->s_uid));
1598 		if (!uid_valid(sbi->s_uid)) {
1599 			zonefs_err(sb, "Invalid UID feature\n");
1600 			goto unmap;
1601 		}
1602 	}
1603 
1604 	if (sbi->s_features & ZONEFS_F_GID) {
1605 		sbi->s_gid = make_kgid(current_user_ns(),
1606 				       le32_to_cpu(super->s_gid));
1607 		if (!gid_valid(sbi->s_gid)) {
1608 			zonefs_err(sb, "Invalid GID feature\n");
1609 			goto unmap;
1610 		}
1611 	}
1612 
1613 	if (sbi->s_features & ZONEFS_F_PERM)
1614 		sbi->s_perm = le32_to_cpu(super->s_perm);
1615 
1616 	if (memchr_inv(super->s_reserved, 0, sizeof(super->s_reserved))) {
1617 		zonefs_err(sb, "Reserved area is being used\n");
1618 		goto unmap;
1619 	}
1620 
1621 	import_uuid(&sbi->s_uuid, super->s_uuid);
1622 	ret = 0;
1623 
1624 unmap:
1625 	kunmap(page);
1626 free_page:
1627 	__free_page(page);
1628 
1629 	return ret;
1630 }
1631 
1632 /*
1633  * Check that the device is zoned. If it is, get the list of zones and create
1634  * sub-directories and files according to the device zone configuration and
1635  * format options.
1636  */
1637 static int zonefs_fill_super(struct super_block *sb, void *data, int silent)
1638 {
1639 	struct zonefs_zone_data zd;
1640 	struct zonefs_sb_info *sbi;
1641 	struct inode *inode;
1642 	enum zonefs_ztype t;
1643 	int ret;
1644 
1645 	if (!bdev_is_zoned(sb->s_bdev)) {
1646 		zonefs_err(sb, "Not a zoned block device\n");
1647 		return -EINVAL;
1648 	}
1649 
1650 	/*
1651 	 * Initialize super block information: the maximum file size is updated
1652 	 * when the zone files are created so that the format option
1653 	 * ZONEFS_F_AGGRCNV which increases the maximum file size of a file
1654 	 * beyond the zone size is taken into account.
1655 	 */
1656 	sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
1657 	if (!sbi)
1658 		return -ENOMEM;
1659 
1660 	spin_lock_init(&sbi->s_lock);
1661 	sb->s_fs_info = sbi;
1662 	sb->s_magic = ZONEFS_MAGIC;
1663 	sb->s_maxbytes = 0;
1664 	sb->s_op = &zonefs_sops;
1665 	sb->s_time_gran	= 1;
1666 
1667 	/*
1668 	 * The block size is set to the device zone write granularity to ensure
1669 	 * that write operations are always aligned according to the device
1670 	 * interface constraints.
1671 	 */
1672 	sb_set_blocksize(sb, bdev_zone_write_granularity(sb->s_bdev));
1673 	sbi->s_zone_sectors_shift = ilog2(bdev_zone_sectors(sb->s_bdev));
1674 	sbi->s_uid = GLOBAL_ROOT_UID;
1675 	sbi->s_gid = GLOBAL_ROOT_GID;
1676 	sbi->s_perm = 0640;
1677 	sbi->s_mount_opts = ZONEFS_MNTOPT_ERRORS_RO;
1678 	sbi->s_max_open_zones = bdev_max_open_zones(sb->s_bdev);
1679 	atomic_set(&sbi->s_open_zones, 0);
1680 	if (!sbi->s_max_open_zones &&
1681 	    sbi->s_mount_opts & ZONEFS_MNTOPT_EXPLICIT_OPEN) {
1682 		zonefs_info(sb, "No open zones limit. Ignoring explicit_open mount option\n");
1683 		sbi->s_mount_opts &= ~ZONEFS_MNTOPT_EXPLICIT_OPEN;
1684 	}
1685 
1686 	ret = zonefs_read_super(sb);
1687 	if (ret)
1688 		return ret;
1689 
1690 	ret = zonefs_parse_options(sb, data);
1691 	if (ret)
1692 		return ret;
1693 
1694 	memset(&zd, 0, sizeof(struct zonefs_zone_data));
1695 	zd.sb = sb;
1696 	ret = zonefs_get_zone_info(&zd);
1697 	if (ret)
1698 		goto cleanup;
1699 
1700 	zonefs_info(sb, "Mounting %u zones",
1701 		    blkdev_nr_zones(sb->s_bdev->bd_disk));
1702 
1703 	/* Create root directory inode */
1704 	ret = -ENOMEM;
1705 	inode = new_inode(sb);
1706 	if (!inode)
1707 		goto cleanup;
1708 
1709 	inode->i_ino = blkdev_nr_zones(sb->s_bdev->bd_disk);
1710 	inode->i_mode = S_IFDIR | 0555;
1711 	inode->i_ctime = inode->i_mtime = inode->i_atime = current_time(inode);
1712 	inode->i_op = &zonefs_dir_inode_operations;
1713 	inode->i_fop = &simple_dir_operations;
1714 	set_nlink(inode, 2);
1715 
1716 	sb->s_root = d_make_root(inode);
1717 	if (!sb->s_root)
1718 		goto cleanup;
1719 
1720 	/* Create and populate files in zone groups directories */
1721 	for (t = 0; t < ZONEFS_ZTYPE_MAX; t++) {
1722 		ret = zonefs_create_zgroup(&zd, t);
1723 		if (ret)
1724 			break;
1725 	}
1726 
1727 cleanup:
1728 	zonefs_cleanup_zone_info(&zd);
1729 
1730 	return ret;
1731 }
1732 
1733 static struct dentry *zonefs_mount(struct file_system_type *fs_type,
1734 				   int flags, const char *dev_name, void *data)
1735 {
1736 	return mount_bdev(fs_type, flags, dev_name, data, zonefs_fill_super);
1737 }
1738 
1739 static void zonefs_kill_super(struct super_block *sb)
1740 {
1741 	struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1742 
1743 	if (sb->s_root)
1744 		d_genocide(sb->s_root);
1745 	kill_block_super(sb);
1746 	kfree(sbi);
1747 }
1748 
1749 /*
1750  * File system definition and registration.
1751  */
1752 static struct file_system_type zonefs_type = {
1753 	.owner		= THIS_MODULE,
1754 	.name		= "zonefs",
1755 	.mount		= zonefs_mount,
1756 	.kill_sb	= zonefs_kill_super,
1757 	.fs_flags	= FS_REQUIRES_DEV,
1758 };
1759 
1760 static int __init zonefs_init_inodecache(void)
1761 {
1762 	zonefs_inode_cachep = kmem_cache_create("zonefs_inode_cache",
1763 			sizeof(struct zonefs_inode_info), 0,
1764 			(SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT),
1765 			NULL);
1766 	if (zonefs_inode_cachep == NULL)
1767 		return -ENOMEM;
1768 	return 0;
1769 }
1770 
1771 static void zonefs_destroy_inodecache(void)
1772 {
1773 	/*
1774 	 * Make sure all delayed rcu free inodes are flushed before we
1775 	 * destroy the inode cache.
1776 	 */
1777 	rcu_barrier();
1778 	kmem_cache_destroy(zonefs_inode_cachep);
1779 }
1780 
1781 static int __init zonefs_init(void)
1782 {
1783 	int ret;
1784 
1785 	BUILD_BUG_ON(sizeof(struct zonefs_super) != ZONEFS_SUPER_SIZE);
1786 
1787 	ret = zonefs_init_inodecache();
1788 	if (ret)
1789 		return ret;
1790 
1791 	ret = register_filesystem(&zonefs_type);
1792 	if (ret) {
1793 		zonefs_destroy_inodecache();
1794 		return ret;
1795 	}
1796 
1797 	return 0;
1798 }
1799 
1800 static void __exit zonefs_exit(void)
1801 {
1802 	zonefs_destroy_inodecache();
1803 	unregister_filesystem(&zonefs_type);
1804 }
1805 
1806 MODULE_AUTHOR("Damien Le Moal");
1807 MODULE_DESCRIPTION("Zone file system for zoned block devices");
1808 MODULE_LICENSE("GPL");
1809 module_init(zonefs_init);
1810 module_exit(zonefs_exit);
1811