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