GNU Linux-libre 6.1.24-gnu
[releases.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 /*
31  * Get the name of a zone group directory.
32  */
33 static const char *zonefs_zgroup_name(enum zonefs_ztype ztype)
34 {
35         switch (ztype) {
36         case ZONEFS_ZTYPE_CNV:
37                 return "cnv";
38         case ZONEFS_ZTYPE_SEQ:
39                 return "seq";
40         default:
41                 WARN_ON_ONCE(1);
42                 return "???";
43         }
44 }
45
46 /*
47  * Manage the active zone count.
48  */
49 static void zonefs_account_active(struct super_block *sb,
50                                   struct zonefs_zone *z)
51 {
52         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
53
54         if (zonefs_zone_is_cnv(z))
55                 return;
56
57         /*
58          * For zones that transitioned to the offline or readonly condition,
59          * we only need to clear the active state.
60          */
61         if (z->z_flags & (ZONEFS_ZONE_OFFLINE | ZONEFS_ZONE_READONLY))
62                 goto out;
63
64         /*
65          * If the zone is active, that is, if it is explicitly open or
66          * partially written, check if it was already accounted as active.
67          */
68         if ((z->z_flags & ZONEFS_ZONE_OPEN) ||
69             (z->z_wpoffset > 0 && z->z_wpoffset < z->z_capacity)) {
70                 if (!(z->z_flags & ZONEFS_ZONE_ACTIVE)) {
71                         z->z_flags |= ZONEFS_ZONE_ACTIVE;
72                         atomic_inc(&sbi->s_active_seq_files);
73                 }
74                 return;
75         }
76
77 out:
78         /* The zone is not active. If it was, update the active count */
79         if (z->z_flags & ZONEFS_ZONE_ACTIVE) {
80                 z->z_flags &= ~ZONEFS_ZONE_ACTIVE;
81                 atomic_dec(&sbi->s_active_seq_files);
82         }
83 }
84
85 /*
86  * Manage the active zone count. Called with zi->i_truncate_mutex held.
87  */
88 void zonefs_inode_account_active(struct inode *inode)
89 {
90         lockdep_assert_held(&ZONEFS_I(inode)->i_truncate_mutex);
91
92         return zonefs_account_active(inode->i_sb, zonefs_inode_zone(inode));
93 }
94
95 /*
96  * Execute a zone management operation.
97  */
98 static int zonefs_zone_mgmt(struct super_block *sb,
99                             struct zonefs_zone *z, enum req_op op)
100 {
101         int ret;
102
103         /*
104          * With ZNS drives, closing an explicitly open zone that has not been
105          * written will change the zone state to "closed", that is, the zone
106          * will remain active. Since this can then cause failure of explicit
107          * open operation on other zones if the drive active zone resources
108          * are exceeded, make sure that the zone does not remain active by
109          * resetting it.
110          */
111         if (op == REQ_OP_ZONE_CLOSE && !z->z_wpoffset)
112                 op = REQ_OP_ZONE_RESET;
113
114         trace_zonefs_zone_mgmt(sb, z, op);
115         ret = blkdev_zone_mgmt(sb->s_bdev, op, z->z_sector,
116                                z->z_size >> SECTOR_SHIFT, GFP_NOFS);
117         if (ret) {
118                 zonefs_err(sb,
119                            "Zone management operation %s at %llu failed %d\n",
120                            blk_op_str(op), z->z_sector, ret);
121                 return ret;
122         }
123
124         return 0;
125 }
126
127 int zonefs_inode_zone_mgmt(struct inode *inode, enum req_op op)
128 {
129         lockdep_assert_held(&ZONEFS_I(inode)->i_truncate_mutex);
130
131         return zonefs_zone_mgmt(inode->i_sb, zonefs_inode_zone(inode), op);
132 }
133
134 void zonefs_i_size_write(struct inode *inode, loff_t isize)
135 {
136         struct zonefs_zone *z = zonefs_inode_zone(inode);
137
138         i_size_write(inode, isize);
139
140         /*
141          * A full zone is no longer open/active and does not need
142          * explicit closing.
143          */
144         if (isize >= z->z_capacity) {
145                 struct zonefs_sb_info *sbi = ZONEFS_SB(inode->i_sb);
146
147                 if (z->z_flags & ZONEFS_ZONE_ACTIVE)
148                         atomic_dec(&sbi->s_active_seq_files);
149                 z->z_flags &= ~(ZONEFS_ZONE_OPEN | ZONEFS_ZONE_ACTIVE);
150         }
151 }
152
153 void zonefs_update_stats(struct inode *inode, loff_t new_isize)
154 {
155         struct super_block *sb = inode->i_sb;
156         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
157         loff_t old_isize = i_size_read(inode);
158         loff_t nr_blocks;
159
160         if (new_isize == old_isize)
161                 return;
162
163         spin_lock(&sbi->s_lock);
164
165         /*
166          * This may be called for an update after an IO error.
167          * So beware of the values seen.
168          */
169         if (new_isize < old_isize) {
170                 nr_blocks = (old_isize - new_isize) >> sb->s_blocksize_bits;
171                 if (sbi->s_used_blocks > nr_blocks)
172                         sbi->s_used_blocks -= nr_blocks;
173                 else
174                         sbi->s_used_blocks = 0;
175         } else {
176                 sbi->s_used_blocks +=
177                         (new_isize - old_isize) >> sb->s_blocksize_bits;
178                 if (sbi->s_used_blocks > sbi->s_blocks)
179                         sbi->s_used_blocks = sbi->s_blocks;
180         }
181
182         spin_unlock(&sbi->s_lock);
183 }
184
185 /*
186  * Check a zone condition. Return the amount of written (and still readable)
187  * data in the zone.
188  */
189 static loff_t zonefs_check_zone_condition(struct super_block *sb,
190                                           struct zonefs_zone *z,
191                                           struct blk_zone *zone)
192 {
193         switch (zone->cond) {
194         case BLK_ZONE_COND_OFFLINE:
195                 zonefs_warn(sb, "Zone %llu: offline zone\n",
196                             z->z_sector);
197                 z->z_flags |= ZONEFS_ZONE_OFFLINE;
198                 return 0;
199         case BLK_ZONE_COND_READONLY:
200                 /*
201                  * The write pointer of read-only zones is invalid, so we cannot
202                  * determine the zone wpoffset (inode size). We thus keep the
203                  * zone wpoffset as is, which leads to an empty file
204                  * (wpoffset == 0) on mount. For a runtime error, this keeps
205                  * the inode size as it was when last updated so that the user
206                  * can recover data.
207                  */
208                 zonefs_warn(sb, "Zone %llu: read-only zone\n",
209                             z->z_sector);
210                 z->z_flags |= ZONEFS_ZONE_READONLY;
211                 if (zonefs_zone_is_cnv(z))
212                         return z->z_capacity;
213                 return z->z_wpoffset;
214         case BLK_ZONE_COND_FULL:
215                 /* The write pointer of full zones is invalid. */
216                 return z->z_capacity;
217         default:
218                 if (zonefs_zone_is_cnv(z))
219                         return z->z_capacity;
220                 return (zone->wp - zone->start) << SECTOR_SHIFT;
221         }
222 }
223
224 /*
225  * Check a zone condition and adjust its inode access permissions for
226  * offline and readonly zones.
227  */
228 static void zonefs_inode_update_mode(struct inode *inode)
229 {
230         struct zonefs_zone *z = zonefs_inode_zone(inode);
231
232         if (z->z_flags & ZONEFS_ZONE_OFFLINE) {
233                 /* Offline zones cannot be read nor written */
234                 inode->i_flags |= S_IMMUTABLE;
235                 inode->i_mode &= ~0777;
236         } else if (z->z_flags & ZONEFS_ZONE_READONLY) {
237                 /* Readonly zones cannot be written */
238                 inode->i_flags |= S_IMMUTABLE;
239                 if (z->z_flags & ZONEFS_ZONE_INIT_MODE)
240                         inode->i_mode &= ~0777;
241                 else
242                         inode->i_mode &= ~0222;
243         }
244
245         z->z_flags &= ~ZONEFS_ZONE_INIT_MODE;
246 }
247
248 struct zonefs_ioerr_data {
249         struct inode    *inode;
250         bool            write;
251 };
252
253 static int zonefs_io_error_cb(struct blk_zone *zone, unsigned int idx,
254                               void *data)
255 {
256         struct zonefs_ioerr_data *err = data;
257         struct inode *inode = err->inode;
258         struct zonefs_zone *z = zonefs_inode_zone(inode);
259         struct super_block *sb = inode->i_sb;
260         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
261         loff_t isize, data_size;
262
263         /*
264          * Check the zone condition: if the zone is not "bad" (offline or
265          * read-only), read errors are simply signaled to the IO issuer as long
266          * as there is no inconsistency between the inode size and the amount of
267          * data writen in the zone (data_size).
268          */
269         data_size = zonefs_check_zone_condition(sb, z, zone);
270         isize = i_size_read(inode);
271         if (!(z->z_flags & (ZONEFS_ZONE_READONLY | ZONEFS_ZONE_OFFLINE)) &&
272             !err->write && isize == data_size)
273                 return 0;
274
275         /*
276          * At this point, we detected either a bad zone or an inconsistency
277          * between the inode size and the amount of data written in the zone.
278          * For the latter case, the cause may be a write IO error or an external
279          * action on the device. Two error patterns exist:
280          * 1) The inode size is lower than the amount of data in the zone:
281          *    a write operation partially failed and data was writen at the end
282          *    of the file. This can happen in the case of a large direct IO
283          *    needing several BIOs and/or write requests to be processed.
284          * 2) The inode size is larger than the amount of data in the zone:
285          *    this can happen with a deferred write error with the use of the
286          *    device side write cache after getting successful write IO
287          *    completions. Other possibilities are (a) an external corruption,
288          *    e.g. an application reset the zone directly, or (b) the device
289          *    has a serious problem (e.g. firmware bug).
290          *
291          * In all cases, warn about inode size inconsistency and handle the
292          * IO error according to the zone condition and to the mount options.
293          */
294         if (zonefs_zone_is_seq(z) && isize != data_size)
295                 zonefs_warn(sb,
296                             "inode %lu: invalid size %lld (should be %lld)\n",
297                             inode->i_ino, isize, data_size);
298
299         /*
300          * First handle bad zones signaled by hardware. The mount options
301          * errors=zone-ro and errors=zone-offline result in changing the
302          * zone condition to read-only and offline respectively, as if the
303          * condition was signaled by the hardware.
304          */
305         if ((z->z_flags & ZONEFS_ZONE_OFFLINE) ||
306             (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZOL)) {
307                 zonefs_warn(sb, "inode %lu: read/write access disabled\n",
308                             inode->i_ino);
309                 if (!(z->z_flags & ZONEFS_ZONE_OFFLINE))
310                         z->z_flags |= ZONEFS_ZONE_OFFLINE;
311                 zonefs_inode_update_mode(inode);
312                 data_size = 0;
313         } else if ((z->z_flags & ZONEFS_ZONE_READONLY) ||
314                    (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZRO)) {
315                 zonefs_warn(sb, "inode %lu: write access disabled\n",
316                             inode->i_ino);
317                 if (!(z->z_flags & ZONEFS_ZONE_READONLY))
318                         z->z_flags |= ZONEFS_ZONE_READONLY;
319                 zonefs_inode_update_mode(inode);
320                 data_size = isize;
321         } else if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_RO &&
322                    data_size > isize) {
323                 /* Do not expose garbage data */
324                 data_size = isize;
325         }
326
327         /*
328          * If the filesystem is mounted with the explicit-open mount option, we
329          * need to clear the ZONEFS_ZONE_OPEN flag if the zone transitioned to
330          * the read-only or offline condition, to avoid attempting an explicit
331          * close of the zone when the inode file is closed.
332          */
333         if ((sbi->s_mount_opts & ZONEFS_MNTOPT_EXPLICIT_OPEN) &&
334             (z->z_flags & (ZONEFS_ZONE_READONLY | ZONEFS_ZONE_OFFLINE)))
335                 z->z_flags &= ~ZONEFS_ZONE_OPEN;
336
337         /*
338          * If error=remount-ro was specified, any error result in remounting
339          * the volume as read-only.
340          */
341         if ((sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_RO) && !sb_rdonly(sb)) {
342                 zonefs_warn(sb, "remounting filesystem read-only\n");
343                 sb->s_flags |= SB_RDONLY;
344         }
345
346         /*
347          * Update block usage stats and the inode size  to prevent access to
348          * invalid data.
349          */
350         zonefs_update_stats(inode, data_size);
351         zonefs_i_size_write(inode, data_size);
352         z->z_wpoffset = data_size;
353         zonefs_inode_account_active(inode);
354
355         return 0;
356 }
357
358 /*
359  * When an file IO error occurs, check the file zone to see if there is a change
360  * in the zone condition (e.g. offline or read-only). For a failed write to a
361  * sequential zone, the zone write pointer position must also be checked to
362  * eventually correct the file size and zonefs inode write pointer offset
363  * (which can be out of sync with the drive due to partial write failures).
364  */
365 void __zonefs_io_error(struct inode *inode, bool write)
366 {
367         struct zonefs_zone *z = zonefs_inode_zone(inode);
368         struct super_block *sb = inode->i_sb;
369         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
370         unsigned int noio_flag;
371         unsigned int nr_zones = 1;
372         struct zonefs_ioerr_data err = {
373                 .inode = inode,
374                 .write = write,
375         };
376         int ret;
377
378         /*
379          * The only files that have more than one zone are conventional zone
380          * files with aggregated conventional zones, for which the inode zone
381          * size is always larger than the device zone size.
382          */
383         if (z->z_size > bdev_zone_sectors(sb->s_bdev))
384                 nr_zones = z->z_size >>
385                         (sbi->s_zone_sectors_shift + SECTOR_SHIFT);
386
387         /*
388          * Memory allocations in blkdev_report_zones() can trigger a memory
389          * reclaim which may in turn cause a recursion into zonefs as well as
390          * struct request allocations for the same device. The former case may
391          * end up in a deadlock on the inode truncate mutex, while the latter
392          * may prevent IO forward progress. Executing the report zones under
393          * the GFP_NOIO context avoids both problems.
394          */
395         noio_flag = memalloc_noio_save();
396         ret = blkdev_report_zones(sb->s_bdev, z->z_sector, nr_zones,
397                                   zonefs_io_error_cb, &err);
398         if (ret != nr_zones)
399                 zonefs_err(sb, "Get inode %lu zone information failed %d\n",
400                            inode->i_ino, ret);
401         memalloc_noio_restore(noio_flag);
402 }
403
404 static struct kmem_cache *zonefs_inode_cachep;
405
406 static struct inode *zonefs_alloc_inode(struct super_block *sb)
407 {
408         struct zonefs_inode_info *zi;
409
410         zi = alloc_inode_sb(sb, zonefs_inode_cachep, GFP_KERNEL);
411         if (!zi)
412                 return NULL;
413
414         inode_init_once(&zi->i_vnode);
415         mutex_init(&zi->i_truncate_mutex);
416         zi->i_wr_refcnt = 0;
417
418         return &zi->i_vnode;
419 }
420
421 static void zonefs_free_inode(struct inode *inode)
422 {
423         kmem_cache_free(zonefs_inode_cachep, ZONEFS_I(inode));
424 }
425
426 /*
427  * File system stat.
428  */
429 static int zonefs_statfs(struct dentry *dentry, struct kstatfs *buf)
430 {
431         struct super_block *sb = dentry->d_sb;
432         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
433         enum zonefs_ztype t;
434
435         buf->f_type = ZONEFS_MAGIC;
436         buf->f_bsize = sb->s_blocksize;
437         buf->f_namelen = ZONEFS_NAME_MAX;
438
439         spin_lock(&sbi->s_lock);
440
441         buf->f_blocks = sbi->s_blocks;
442         if (WARN_ON(sbi->s_used_blocks > sbi->s_blocks))
443                 buf->f_bfree = 0;
444         else
445                 buf->f_bfree = buf->f_blocks - sbi->s_used_blocks;
446         buf->f_bavail = buf->f_bfree;
447
448         for (t = 0; t < ZONEFS_ZTYPE_MAX; t++) {
449                 if (sbi->s_zgroup[t].g_nr_zones)
450                         buf->f_files += sbi->s_zgroup[t].g_nr_zones + 1;
451         }
452         buf->f_ffree = 0;
453
454         spin_unlock(&sbi->s_lock);
455
456         buf->f_fsid = uuid_to_fsid(sbi->s_uuid.b);
457
458         return 0;
459 }
460
461 enum {
462         Opt_errors_ro, Opt_errors_zro, Opt_errors_zol, Opt_errors_repair,
463         Opt_explicit_open, Opt_err,
464 };
465
466 static const match_table_t tokens = {
467         { Opt_errors_ro,        "errors=remount-ro"},
468         { Opt_errors_zro,       "errors=zone-ro"},
469         { Opt_errors_zol,       "errors=zone-offline"},
470         { Opt_errors_repair,    "errors=repair"},
471         { Opt_explicit_open,    "explicit-open" },
472         { Opt_err,              NULL}
473 };
474
475 static int zonefs_parse_options(struct super_block *sb, char *options)
476 {
477         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
478         substring_t args[MAX_OPT_ARGS];
479         char *p;
480
481         if (!options)
482                 return 0;
483
484         while ((p = strsep(&options, ",")) != NULL) {
485                 int token;
486
487                 if (!*p)
488                         continue;
489
490                 token = match_token(p, tokens, args);
491                 switch (token) {
492                 case Opt_errors_ro:
493                         sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
494                         sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_RO;
495                         break;
496                 case Opt_errors_zro:
497                         sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
498                         sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_ZRO;
499                         break;
500                 case Opt_errors_zol:
501                         sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
502                         sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_ZOL;
503                         break;
504                 case Opt_errors_repair:
505                         sbi->s_mount_opts &= ~ZONEFS_MNTOPT_ERRORS_MASK;
506                         sbi->s_mount_opts |= ZONEFS_MNTOPT_ERRORS_REPAIR;
507                         break;
508                 case Opt_explicit_open:
509                         sbi->s_mount_opts |= ZONEFS_MNTOPT_EXPLICIT_OPEN;
510                         break;
511                 default:
512                         return -EINVAL;
513                 }
514         }
515
516         return 0;
517 }
518
519 static int zonefs_show_options(struct seq_file *seq, struct dentry *root)
520 {
521         struct zonefs_sb_info *sbi = ZONEFS_SB(root->d_sb);
522
523         if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_RO)
524                 seq_puts(seq, ",errors=remount-ro");
525         if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZRO)
526                 seq_puts(seq, ",errors=zone-ro");
527         if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_ZOL)
528                 seq_puts(seq, ",errors=zone-offline");
529         if (sbi->s_mount_opts & ZONEFS_MNTOPT_ERRORS_REPAIR)
530                 seq_puts(seq, ",errors=repair");
531
532         return 0;
533 }
534
535 static int zonefs_remount(struct super_block *sb, int *flags, char *data)
536 {
537         sync_filesystem(sb);
538
539         return zonefs_parse_options(sb, data);
540 }
541
542 static int zonefs_inode_setattr(struct user_namespace *mnt_userns,
543                                 struct dentry *dentry, struct iattr *iattr)
544 {
545         struct inode *inode = d_inode(dentry);
546         int ret;
547
548         if (unlikely(IS_IMMUTABLE(inode)))
549                 return -EPERM;
550
551         ret = setattr_prepare(&init_user_ns, dentry, iattr);
552         if (ret)
553                 return ret;
554
555         /*
556          * Since files and directories cannot be created nor deleted, do not
557          * allow setting any write attributes on the sub-directories grouping
558          * files by zone type.
559          */
560         if ((iattr->ia_valid & ATTR_MODE) && S_ISDIR(inode->i_mode) &&
561             (iattr->ia_mode & 0222))
562                 return -EPERM;
563
564         if (((iattr->ia_valid & ATTR_UID) &&
565              !uid_eq(iattr->ia_uid, inode->i_uid)) ||
566             ((iattr->ia_valid & ATTR_GID) &&
567              !gid_eq(iattr->ia_gid, inode->i_gid))) {
568                 ret = dquot_transfer(mnt_userns, inode, iattr);
569                 if (ret)
570                         return ret;
571         }
572
573         if (iattr->ia_valid & ATTR_SIZE) {
574                 ret = zonefs_file_truncate(inode, iattr->ia_size);
575                 if (ret)
576                         return ret;
577         }
578
579         setattr_copy(&init_user_ns, inode, iattr);
580
581         return 0;
582 }
583
584 static const struct inode_operations zonefs_dir_inode_operations = {
585         .lookup         = simple_lookup,
586         .setattr        = zonefs_inode_setattr,
587 };
588
589 static void zonefs_init_dir_inode(struct inode *parent, struct inode *inode,
590                                   enum zonefs_ztype ztype)
591 {
592         struct super_block *sb = parent->i_sb;
593
594         inode->i_ino = bdev_nr_zones(sb->s_bdev) + ztype + 1;
595         inode_init_owner(&init_user_ns, inode, parent, S_IFDIR | 0555);
596         inode->i_op = &zonefs_dir_inode_operations;
597         inode->i_fop = &simple_dir_operations;
598         set_nlink(inode, 2);
599         inc_nlink(parent);
600 }
601
602 static const struct inode_operations zonefs_file_inode_operations = {
603         .setattr        = zonefs_inode_setattr,
604 };
605
606 static void zonefs_init_file_inode(struct inode *inode,
607                                    struct zonefs_zone *z)
608 {
609         struct super_block *sb = inode->i_sb;
610         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
611
612         inode->i_private = z;
613
614         inode->i_ino = z->z_sector >> sbi->s_zone_sectors_shift;
615         inode->i_mode = S_IFREG | sbi->s_perm;
616         inode->i_uid = sbi->s_uid;
617         inode->i_gid = sbi->s_gid;
618         inode->i_size = z->z_wpoffset;
619         inode->i_blocks = z->z_capacity >> SECTOR_SHIFT;
620
621         inode->i_op = &zonefs_file_inode_operations;
622         inode->i_fop = &zonefs_file_operations;
623         inode->i_mapping->a_ops = &zonefs_file_aops;
624
625         /* Update the inode access rights depending on the zone condition */
626         z->z_flags |= ZONEFS_ZONE_INIT_MODE;
627         zonefs_inode_update_mode(inode);
628 }
629
630 static struct dentry *zonefs_create_inode(struct dentry *parent,
631                                           const char *name,
632                                           struct zonefs_zone *z,
633                                           enum zonefs_ztype ztype)
634 {
635         struct inode *dir = d_inode(parent);
636         struct dentry *dentry;
637         struct inode *inode;
638         int ret = -ENOMEM;
639
640         dentry = d_alloc_name(parent, name);
641         if (!dentry)
642                 return ERR_PTR(ret);
643
644         inode = new_inode(parent->d_sb);
645         if (!inode)
646                 goto dput;
647
648         inode->i_ctime = inode->i_mtime = inode->i_atime = dir->i_ctime;
649         if (z)
650                 zonefs_init_file_inode(inode, z);
651         else
652                 zonefs_init_dir_inode(dir, inode, ztype);
653
654         d_add(dentry, inode);
655         dir->i_size++;
656
657         return dentry;
658
659 dput:
660         dput(dentry);
661
662         return ERR_PTR(ret);
663 }
664
665 struct zonefs_zone_data {
666         struct super_block      *sb;
667         unsigned int            nr_zones[ZONEFS_ZTYPE_MAX];
668         sector_t                cnv_zone_start;
669         struct blk_zone         *zones;
670 };
671
672 /*
673  * Create the inodes for a zone group.
674  */
675 static int zonefs_create_zgroup_inodes(struct super_block *sb,
676                                        enum zonefs_ztype ztype)
677 {
678         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
679         struct zonefs_zone_group *zgroup = &sbi->s_zgroup[ztype];
680         struct dentry *dir, *dent;
681         char *file_name;
682         int i, ret = 0;
683
684         if (!zgroup)
685                 return -ENOMEM;
686
687         /* If the group is empty, there is nothing to do */
688         if (!zgroup->g_nr_zones)
689                 return 0;
690
691         file_name = kmalloc(ZONEFS_NAME_MAX, GFP_KERNEL);
692         if (!file_name)
693                 return -ENOMEM;
694
695         dir = zonefs_create_inode(sb->s_root, zonefs_zgroup_name(ztype),
696                                   NULL, ztype);
697         if (IS_ERR(dir)) {
698                 ret = PTR_ERR(dir);
699                 goto free;
700         }
701
702         for (i = 0; i < zgroup->g_nr_zones; i++) {
703                 /* Use the zone number within its group as the file name */
704                 snprintf(file_name, ZONEFS_NAME_MAX - 1, "%u", i);
705                 dent = zonefs_create_inode(dir, file_name,
706                                            &zgroup->g_zones[i], ztype);
707                 if (IS_ERR(dent)) {
708                         ret = PTR_ERR(dent);
709                         break;
710                 }
711         }
712
713 free:
714         kfree(file_name);
715
716         return ret;
717 }
718
719 static int zonefs_get_zone_info_cb(struct blk_zone *zone, unsigned int idx,
720                                    void *data)
721 {
722         struct zonefs_zone_data *zd = data;
723         struct super_block *sb = zd->sb;
724         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
725
726         /*
727          * We do not care about the first zone: it contains the super block
728          * and not exposed as a file.
729          */
730         if (!idx)
731                 return 0;
732
733         /*
734          * Count the number of zones that will be exposed as files.
735          * For sequential zones, we always have as many files as zones.
736          * FOr conventional zones, the number of files depends on if we have
737          * conventional zones aggregation enabled.
738          */
739         switch (zone->type) {
740         case BLK_ZONE_TYPE_CONVENTIONAL:
741                 if (sbi->s_features & ZONEFS_F_AGGRCNV) {
742                         /* One file per set of contiguous conventional zones */
743                         if (!(sbi->s_zgroup[ZONEFS_ZTYPE_CNV].g_nr_zones) ||
744                             zone->start != zd->cnv_zone_start)
745                                 sbi->s_zgroup[ZONEFS_ZTYPE_CNV].g_nr_zones++;
746                         zd->cnv_zone_start = zone->start + zone->len;
747                 } else {
748                         /* One file per zone */
749                         sbi->s_zgroup[ZONEFS_ZTYPE_CNV].g_nr_zones++;
750                 }
751                 break;
752         case BLK_ZONE_TYPE_SEQWRITE_REQ:
753         case BLK_ZONE_TYPE_SEQWRITE_PREF:
754                 sbi->s_zgroup[ZONEFS_ZTYPE_SEQ].g_nr_zones++;
755                 break;
756         default:
757                 zonefs_err(zd->sb, "Unsupported zone type 0x%x\n",
758                            zone->type);
759                 return -EIO;
760         }
761
762         memcpy(&zd->zones[idx], zone, sizeof(struct blk_zone));
763
764         return 0;
765 }
766
767 static int zonefs_get_zone_info(struct zonefs_zone_data *zd)
768 {
769         struct block_device *bdev = zd->sb->s_bdev;
770         int ret;
771
772         zd->zones = kvcalloc(bdev_nr_zones(bdev), sizeof(struct blk_zone),
773                              GFP_KERNEL);
774         if (!zd->zones)
775                 return -ENOMEM;
776
777         /* Get zones information from the device */
778         ret = blkdev_report_zones(bdev, 0, BLK_ALL_ZONES,
779                                   zonefs_get_zone_info_cb, zd);
780         if (ret < 0) {
781                 zonefs_err(zd->sb, "Zone report failed %d\n", ret);
782                 return ret;
783         }
784
785         if (ret != bdev_nr_zones(bdev)) {
786                 zonefs_err(zd->sb, "Invalid zone report (%d/%u zones)\n",
787                            ret, bdev_nr_zones(bdev));
788                 return -EIO;
789         }
790
791         return 0;
792 }
793
794 static inline void zonefs_free_zone_info(struct zonefs_zone_data *zd)
795 {
796         kvfree(zd->zones);
797 }
798
799 /*
800  * Create a zone group and populate it with zone files.
801  */
802 static int zonefs_init_zgroup(struct super_block *sb,
803                               struct zonefs_zone_data *zd,
804                               enum zonefs_ztype ztype)
805 {
806         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
807         struct zonefs_zone_group *zgroup = &sbi->s_zgroup[ztype];
808         struct blk_zone *zone, *next, *end;
809         struct zonefs_zone *z;
810         unsigned int n = 0;
811         int ret;
812
813         /* Allocate the zone group. If it is empty, we have nothing to do. */
814         if (!zgroup->g_nr_zones)
815                 return 0;
816
817         zgroup->g_zones = kvcalloc(zgroup->g_nr_zones,
818                                    sizeof(struct zonefs_zone), GFP_KERNEL);
819         if (!zgroup->g_zones)
820                 return -ENOMEM;
821
822         /*
823          * Initialize the zone groups using the device zone information.
824          * We always skip the first zone as it contains the super block
825          * and is not use to back a file.
826          */
827         end = zd->zones + bdev_nr_zones(sb->s_bdev);
828         for (zone = &zd->zones[1]; zone < end; zone = next) {
829
830                 next = zone + 1;
831                 if (zonefs_zone_type(zone) != ztype)
832                         continue;
833
834                 if (WARN_ON_ONCE(n >= zgroup->g_nr_zones))
835                         return -EINVAL;
836
837                 /*
838                  * For conventional zones, contiguous zones can be aggregated
839                  * together to form larger files. Note that this overwrites the
840                  * length of the first zone of the set of contiguous zones
841                  * aggregated together. If one offline or read-only zone is
842                  * found, assume that all zones aggregated have the same
843                  * condition.
844                  */
845                 if (ztype == ZONEFS_ZTYPE_CNV &&
846                     (sbi->s_features & ZONEFS_F_AGGRCNV)) {
847                         for (; next < end; next++) {
848                                 if (zonefs_zone_type(next) != ztype)
849                                         break;
850                                 zone->len += next->len;
851                                 zone->capacity += next->capacity;
852                                 if (next->cond == BLK_ZONE_COND_READONLY &&
853                                     zone->cond != BLK_ZONE_COND_OFFLINE)
854                                         zone->cond = BLK_ZONE_COND_READONLY;
855                                 else if (next->cond == BLK_ZONE_COND_OFFLINE)
856                                         zone->cond = BLK_ZONE_COND_OFFLINE;
857                         }
858                 }
859
860                 z = &zgroup->g_zones[n];
861                 if (ztype == ZONEFS_ZTYPE_CNV)
862                         z->z_flags |= ZONEFS_ZONE_CNV;
863                 z->z_sector = zone->start;
864                 z->z_size = zone->len << SECTOR_SHIFT;
865                 if (z->z_size > bdev_zone_sectors(sb->s_bdev) << SECTOR_SHIFT &&
866                     !(sbi->s_features & ZONEFS_F_AGGRCNV)) {
867                         zonefs_err(sb,
868                                 "Invalid zone size %llu (device zone sectors %llu)\n",
869                                 z->z_size,
870                                 bdev_zone_sectors(sb->s_bdev) << SECTOR_SHIFT);
871                         return -EINVAL;
872                 }
873
874                 z->z_capacity = min_t(loff_t, MAX_LFS_FILESIZE,
875                                       zone->capacity << SECTOR_SHIFT);
876                 z->z_wpoffset = zonefs_check_zone_condition(sb, z, zone);
877
878                 sb->s_maxbytes = max(z->z_capacity, sb->s_maxbytes);
879                 sbi->s_blocks += z->z_capacity >> sb->s_blocksize_bits;
880                 sbi->s_used_blocks += z->z_wpoffset >> sb->s_blocksize_bits;
881
882                 /*
883                  * For sequential zones, make sure that any open zone is closed
884                  * first to ensure that the initial number of open zones is 0,
885                  * in sync with the open zone accounting done when the mount
886                  * option ZONEFS_MNTOPT_EXPLICIT_OPEN is used.
887                  */
888                 if (ztype == ZONEFS_ZTYPE_SEQ &&
889                     (zone->cond == BLK_ZONE_COND_IMP_OPEN ||
890                      zone->cond == BLK_ZONE_COND_EXP_OPEN)) {
891                         ret = zonefs_zone_mgmt(sb, z, REQ_OP_ZONE_CLOSE);
892                         if (ret)
893                                 return ret;
894                 }
895
896                 zonefs_account_active(sb, z);
897
898                 n++;
899         }
900
901         if (WARN_ON_ONCE(n != zgroup->g_nr_zones))
902                 return -EINVAL;
903
904         zonefs_info(sb, "Zone group \"%s\" has %u file%s\n",
905                     zonefs_zgroup_name(ztype),
906                     zgroup->g_nr_zones,
907                     zgroup->g_nr_zones > 1 ? "s" : "");
908
909         return 0;
910 }
911
912 static void zonefs_free_zgroups(struct super_block *sb)
913 {
914         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
915         enum zonefs_ztype ztype;
916
917         if (!sbi)
918                 return;
919
920         for (ztype = 0; ztype < ZONEFS_ZTYPE_MAX; ztype++) {
921                 kvfree(sbi->s_zgroup[ztype].g_zones);
922                 sbi->s_zgroup[ztype].g_zones = NULL;
923         }
924 }
925
926 /*
927  * Create a zone group and populate it with zone files.
928  */
929 static int zonefs_init_zgroups(struct super_block *sb)
930 {
931         struct zonefs_zone_data zd;
932         enum zonefs_ztype ztype;
933         int ret;
934
935         /* First get the device zone information */
936         memset(&zd, 0, sizeof(struct zonefs_zone_data));
937         zd.sb = sb;
938         ret = zonefs_get_zone_info(&zd);
939         if (ret)
940                 goto cleanup;
941
942         /* Allocate and initialize the zone groups */
943         for (ztype = 0; ztype < ZONEFS_ZTYPE_MAX; ztype++) {
944                 ret = zonefs_init_zgroup(sb, &zd, ztype);
945                 if (ret) {
946                         zonefs_info(sb,
947                                     "Zone group \"%s\" initialization failed\n",
948                                     zonefs_zgroup_name(ztype));
949                         break;
950                 }
951         }
952
953 cleanup:
954         zonefs_free_zone_info(&zd);
955         if (ret)
956                 zonefs_free_zgroups(sb);
957
958         return ret;
959 }
960
961 /*
962  * Read super block information from the device.
963  */
964 static int zonefs_read_super(struct super_block *sb)
965 {
966         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
967         struct zonefs_super *super;
968         u32 crc, stored_crc;
969         struct page *page;
970         struct bio_vec bio_vec;
971         struct bio bio;
972         int ret;
973
974         page = alloc_page(GFP_KERNEL);
975         if (!page)
976                 return -ENOMEM;
977
978         bio_init(&bio, sb->s_bdev, &bio_vec, 1, REQ_OP_READ);
979         bio.bi_iter.bi_sector = 0;
980         bio_add_page(&bio, page, PAGE_SIZE, 0);
981
982         ret = submit_bio_wait(&bio);
983         if (ret)
984                 goto free_page;
985
986         super = page_address(page);
987
988         ret = -EINVAL;
989         if (le32_to_cpu(super->s_magic) != ZONEFS_MAGIC)
990                 goto free_page;
991
992         stored_crc = le32_to_cpu(super->s_crc);
993         super->s_crc = 0;
994         crc = crc32(~0U, (unsigned char *)super, sizeof(struct zonefs_super));
995         if (crc != stored_crc) {
996                 zonefs_err(sb, "Invalid checksum (Expected 0x%08x, got 0x%08x)",
997                            crc, stored_crc);
998                 goto free_page;
999         }
1000
1001         sbi->s_features = le64_to_cpu(super->s_features);
1002         if (sbi->s_features & ~ZONEFS_F_DEFINED_FEATURES) {
1003                 zonefs_err(sb, "Unknown features set 0x%llx\n",
1004                            sbi->s_features);
1005                 goto free_page;
1006         }
1007
1008         if (sbi->s_features & ZONEFS_F_UID) {
1009                 sbi->s_uid = make_kuid(current_user_ns(),
1010                                        le32_to_cpu(super->s_uid));
1011                 if (!uid_valid(sbi->s_uid)) {
1012                         zonefs_err(sb, "Invalid UID feature\n");
1013                         goto free_page;
1014                 }
1015         }
1016
1017         if (sbi->s_features & ZONEFS_F_GID) {
1018                 sbi->s_gid = make_kgid(current_user_ns(),
1019                                        le32_to_cpu(super->s_gid));
1020                 if (!gid_valid(sbi->s_gid)) {
1021                         zonefs_err(sb, "Invalid GID feature\n");
1022                         goto free_page;
1023                 }
1024         }
1025
1026         if (sbi->s_features & ZONEFS_F_PERM)
1027                 sbi->s_perm = le32_to_cpu(super->s_perm);
1028
1029         if (memchr_inv(super->s_reserved, 0, sizeof(super->s_reserved))) {
1030                 zonefs_err(sb, "Reserved area is being used\n");
1031                 goto free_page;
1032         }
1033
1034         import_uuid(&sbi->s_uuid, super->s_uuid);
1035         ret = 0;
1036
1037 free_page:
1038         __free_page(page);
1039
1040         return ret;
1041 }
1042
1043 static const struct super_operations zonefs_sops = {
1044         .alloc_inode    = zonefs_alloc_inode,
1045         .free_inode     = zonefs_free_inode,
1046         .statfs         = zonefs_statfs,
1047         .remount_fs     = zonefs_remount,
1048         .show_options   = zonefs_show_options,
1049 };
1050
1051 /*
1052  * Check that the device is zoned. If it is, get the list of zones and create
1053  * sub-directories and files according to the device zone configuration and
1054  * format options.
1055  */
1056 static int zonefs_fill_super(struct super_block *sb, void *data, int silent)
1057 {
1058         struct zonefs_sb_info *sbi;
1059         struct inode *inode;
1060         enum zonefs_ztype t;
1061         int ret;
1062
1063         if (!bdev_is_zoned(sb->s_bdev)) {
1064                 zonefs_err(sb, "Not a zoned block device\n");
1065                 return -EINVAL;
1066         }
1067
1068         /*
1069          * Initialize super block information: the maximum file size is updated
1070          * when the zone files are created so that the format option
1071          * ZONEFS_F_AGGRCNV which increases the maximum file size of a file
1072          * beyond the zone size is taken into account.
1073          */
1074         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
1075         if (!sbi)
1076                 return -ENOMEM;
1077
1078         spin_lock_init(&sbi->s_lock);
1079         sb->s_fs_info = sbi;
1080         sb->s_magic = ZONEFS_MAGIC;
1081         sb->s_maxbytes = 0;
1082         sb->s_op = &zonefs_sops;
1083         sb->s_time_gran = 1;
1084
1085         /*
1086          * The block size is set to the device zone write granularity to ensure
1087          * that write operations are always aligned according to the device
1088          * interface constraints.
1089          */
1090         sb_set_blocksize(sb, bdev_zone_write_granularity(sb->s_bdev));
1091         sbi->s_zone_sectors_shift = ilog2(bdev_zone_sectors(sb->s_bdev));
1092         sbi->s_uid = GLOBAL_ROOT_UID;
1093         sbi->s_gid = GLOBAL_ROOT_GID;
1094         sbi->s_perm = 0640;
1095         sbi->s_mount_opts = ZONEFS_MNTOPT_ERRORS_RO;
1096
1097         atomic_set(&sbi->s_wro_seq_files, 0);
1098         sbi->s_max_wro_seq_files = bdev_max_open_zones(sb->s_bdev);
1099         atomic_set(&sbi->s_active_seq_files, 0);
1100         sbi->s_max_active_seq_files = bdev_max_active_zones(sb->s_bdev);
1101
1102         ret = zonefs_read_super(sb);
1103         if (ret)
1104                 return ret;
1105
1106         ret = zonefs_parse_options(sb, data);
1107         if (ret)
1108                 return ret;
1109
1110         zonefs_info(sb, "Mounting %u zones", bdev_nr_zones(sb->s_bdev));
1111
1112         if (!sbi->s_max_wro_seq_files &&
1113             !sbi->s_max_active_seq_files &&
1114             sbi->s_mount_opts & ZONEFS_MNTOPT_EXPLICIT_OPEN) {
1115                 zonefs_info(sb,
1116                         "No open and active zone limits. Ignoring explicit_open mount option\n");
1117                 sbi->s_mount_opts &= ~ZONEFS_MNTOPT_EXPLICIT_OPEN;
1118         }
1119
1120         /* Initialize the zone groups */
1121         ret = zonefs_init_zgroups(sb);
1122         if (ret)
1123                 goto cleanup;
1124
1125         /* Create root directory inode */
1126         ret = -ENOMEM;
1127         inode = new_inode(sb);
1128         if (!inode)
1129                 goto cleanup;
1130
1131         inode->i_ino = bdev_nr_zones(sb->s_bdev);
1132         inode->i_mode = S_IFDIR | 0555;
1133         inode->i_ctime = inode->i_mtime = inode->i_atime = current_time(inode);
1134         inode->i_op = &zonefs_dir_inode_operations;
1135         inode->i_fop = &simple_dir_operations;
1136         set_nlink(inode, 2);
1137
1138         sb->s_root = d_make_root(inode);
1139         if (!sb->s_root)
1140                 goto cleanup;
1141
1142         /* Create and populate files in zone groups directories */
1143         for (t = 0; t < ZONEFS_ZTYPE_MAX; t++) {
1144                 ret = zonefs_create_zgroup_inodes(sb, t);
1145                 if (ret)
1146                         goto cleanup;
1147         }
1148
1149         ret = zonefs_sysfs_register(sb);
1150         if (ret)
1151                 goto cleanup;
1152
1153         return 0;
1154
1155 cleanup:
1156         zonefs_free_zgroups(sb);
1157
1158         return ret;
1159 }
1160
1161 static struct dentry *zonefs_mount(struct file_system_type *fs_type,
1162                                    int flags, const char *dev_name, void *data)
1163 {
1164         return mount_bdev(fs_type, flags, dev_name, data, zonefs_fill_super);
1165 }
1166
1167 static void zonefs_kill_super(struct super_block *sb)
1168 {
1169         struct zonefs_sb_info *sbi = ZONEFS_SB(sb);
1170
1171         if (sb->s_root)
1172                 d_genocide(sb->s_root);
1173
1174         zonefs_sysfs_unregister(sb);
1175         zonefs_free_zgroups(sb);
1176         kill_block_super(sb);
1177         kfree(sbi);
1178 }
1179
1180 /*
1181  * File system definition and registration.
1182  */
1183 static struct file_system_type zonefs_type = {
1184         .owner          = THIS_MODULE,
1185         .name           = "zonefs",
1186         .mount          = zonefs_mount,
1187         .kill_sb        = zonefs_kill_super,
1188         .fs_flags       = FS_REQUIRES_DEV,
1189 };
1190
1191 static int __init zonefs_init_inodecache(void)
1192 {
1193         zonefs_inode_cachep = kmem_cache_create("zonefs_inode_cache",
1194                         sizeof(struct zonefs_inode_info), 0,
1195                         (SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT),
1196                         NULL);
1197         if (zonefs_inode_cachep == NULL)
1198                 return -ENOMEM;
1199         return 0;
1200 }
1201
1202 static void zonefs_destroy_inodecache(void)
1203 {
1204         /*
1205          * Make sure all delayed rcu free inodes are flushed before we
1206          * destroy the inode cache.
1207          */
1208         rcu_barrier();
1209         kmem_cache_destroy(zonefs_inode_cachep);
1210 }
1211
1212 static int __init zonefs_init(void)
1213 {
1214         int ret;
1215
1216         BUILD_BUG_ON(sizeof(struct zonefs_super) != ZONEFS_SUPER_SIZE);
1217
1218         ret = zonefs_init_inodecache();
1219         if (ret)
1220                 return ret;
1221
1222         ret = zonefs_sysfs_init();
1223         if (ret)
1224                 goto destroy_inodecache;
1225
1226         ret = register_filesystem(&zonefs_type);
1227         if (ret)
1228                 goto sysfs_exit;
1229
1230         return 0;
1231
1232 sysfs_exit:
1233         zonefs_sysfs_exit();
1234 destroy_inodecache:
1235         zonefs_destroy_inodecache();
1236
1237         return ret;
1238 }
1239
1240 static void __exit zonefs_exit(void)
1241 {
1242         unregister_filesystem(&zonefs_type);
1243         zonefs_sysfs_exit();
1244         zonefs_destroy_inodecache();
1245 }
1246
1247 MODULE_AUTHOR("Damien Le Moal");
1248 MODULE_DESCRIPTION("Zone file system for zoned block devices");
1249 MODULE_LICENSE("GPL");
1250 MODULE_ALIAS_FS("zonefs");
1251 module_init(zonefs_init);
1252 module_exit(zonefs_exit);