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