Merge branch 'freespace-tree' into for-linus-4.5
[cascardo/linux.git] / fs / btrfs / super.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/blkdev.h>
20 #include <linux/module.h>
21 #include <linux/buffer_head.h>
22 #include <linux/fs.h>
23 #include <linux/pagemap.h>
24 #include <linux/highmem.h>
25 #include <linux/time.h>
26 #include <linux/init.h>
27 #include <linux/seq_file.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mount.h>
31 #include <linux/mpage.h>
32 #include <linux/swap.h>
33 #include <linux/writeback.h>
34 #include <linux/statfs.h>
35 #include <linux/compat.h>
36 #include <linux/parser.h>
37 #include <linux/ctype.h>
38 #include <linux/namei.h>
39 #include <linux/miscdevice.h>
40 #include <linux/magic.h>
41 #include <linux/slab.h>
42 #include <linux/cleancache.h>
43 #include <linux/ratelimit.h>
44 #include <linux/btrfs.h>
45 #include "delayed-inode.h"
46 #include "ctree.h"
47 #include "disk-io.h"
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "hash.h"
52 #include "props.h"
53 #include "xattr.h"
54 #include "volumes.h"
55 #include "export.h"
56 #include "compression.h"
57 #include "rcu-string.h"
58 #include "dev-replace.h"
59 #include "free-space-cache.h"
60 #include "backref.h"
61 #include "tests/btrfs-tests.h"
62
63 #include "qgroup.h"
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/btrfs.h>
66
67 static const struct super_operations btrfs_super_ops;
68 static struct file_system_type btrfs_fs_type;
69
70 static int btrfs_remount(struct super_block *sb, int *flags, char *data);
71
72 const char *btrfs_decode_error(int errno)
73 {
74         char *errstr = "unknown";
75
76         switch (errno) {
77         case -EIO:
78                 errstr = "IO failure";
79                 break;
80         case -ENOMEM:
81                 errstr = "Out of memory";
82                 break;
83         case -EROFS:
84                 errstr = "Readonly filesystem";
85                 break;
86         case -EEXIST:
87                 errstr = "Object already exists";
88                 break;
89         case -ENOSPC:
90                 errstr = "No space left";
91                 break;
92         case -ENOENT:
93                 errstr = "No such entry";
94                 break;
95         }
96
97         return errstr;
98 }
99
100 static void save_error_info(struct btrfs_fs_info *fs_info)
101 {
102         /*
103          * today we only save the error info into ram.  Long term we'll
104          * also send it down to the disk
105          */
106         set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
107 }
108
109 /* btrfs handle error by forcing the filesystem readonly */
110 static void btrfs_handle_error(struct btrfs_fs_info *fs_info)
111 {
112         struct super_block *sb = fs_info->sb;
113
114         if (sb->s_flags & MS_RDONLY)
115                 return;
116
117         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
118                 sb->s_flags |= MS_RDONLY;
119                 btrfs_info(fs_info, "forced readonly");
120                 /*
121                  * Note that a running device replace operation is not
122                  * canceled here although there is no way to update
123                  * the progress. It would add the risk of a deadlock,
124                  * therefore the canceling is ommited. The only penalty
125                  * is that some I/O remains active until the procedure
126                  * completes. The next time when the filesystem is
127                  * mounted writeable again, the device replace
128                  * operation continues.
129                  */
130         }
131 }
132
133 /*
134  * __btrfs_std_error decodes expected errors from the caller and
135  * invokes the approciate error response.
136  */
137 __cold
138 void __btrfs_std_error(struct btrfs_fs_info *fs_info, const char *function,
139                        unsigned int line, int errno, const char *fmt, ...)
140 {
141         struct super_block *sb = fs_info->sb;
142 #ifdef CONFIG_PRINTK
143         const char *errstr;
144 #endif
145
146         /*
147          * Special case: if the error is EROFS, and we're already
148          * under MS_RDONLY, then it is safe here.
149          */
150         if (errno == -EROFS && (sb->s_flags & MS_RDONLY))
151                 return;
152
153 #ifdef CONFIG_PRINTK
154         errstr = btrfs_decode_error(errno);
155         if (fmt) {
156                 struct va_format vaf;
157                 va_list args;
158
159                 va_start(args, fmt);
160                 vaf.fmt = fmt;
161                 vaf.va = &args;
162
163                 printk(KERN_CRIT
164                         "BTRFS: error (device %s) in %s:%d: errno=%d %s (%pV)\n",
165                         sb->s_id, function, line, errno, errstr, &vaf);
166                 va_end(args);
167         } else {
168                 printk(KERN_CRIT "BTRFS: error (device %s) in %s:%d: errno=%d %s\n",
169                         sb->s_id, function, line, errno, errstr);
170         }
171 #endif
172
173         /* Don't go through full error handling during mount */
174         save_error_info(fs_info);
175         if (sb->s_flags & MS_BORN)
176                 btrfs_handle_error(fs_info);
177 }
178
179 #ifdef CONFIG_PRINTK
180 static const char * const logtypes[] = {
181         "emergency",
182         "alert",
183         "critical",
184         "error",
185         "warning",
186         "notice",
187         "info",
188         "debug",
189 };
190
191 void btrfs_printk(const struct btrfs_fs_info *fs_info, const char *fmt, ...)
192 {
193         struct super_block *sb = fs_info->sb;
194         char lvl[4];
195         struct va_format vaf;
196         va_list args;
197         const char *type = logtypes[4];
198         int kern_level;
199
200         va_start(args, fmt);
201
202         kern_level = printk_get_level(fmt);
203         if (kern_level) {
204                 size_t size = printk_skip_level(fmt) - fmt;
205                 memcpy(lvl, fmt,  size);
206                 lvl[size] = '\0';
207                 fmt += size;
208                 type = logtypes[kern_level - '0'];
209         } else
210                 *lvl = '\0';
211
212         vaf.fmt = fmt;
213         vaf.va = &args;
214
215         printk("%sBTRFS %s (device %s): %pV\n", lvl, type, sb->s_id, &vaf);
216
217         va_end(args);
218 }
219 #endif
220
221 /*
222  * We only mark the transaction aborted and then set the file system read-only.
223  * This will prevent new transactions from starting or trying to join this
224  * one.
225  *
226  * This means that error recovery at the call site is limited to freeing
227  * any local memory allocations and passing the error code up without
228  * further cleanup. The transaction should complete as it normally would
229  * in the call path but will return -EIO.
230  *
231  * We'll complete the cleanup in btrfs_end_transaction and
232  * btrfs_commit_transaction.
233  */
234 __cold
235 void __btrfs_abort_transaction(struct btrfs_trans_handle *trans,
236                                struct btrfs_root *root, const char *function,
237                                unsigned int line, int errno)
238 {
239         trans->aborted = errno;
240         /* Nothing used. The other threads that have joined this
241          * transaction may be able to continue. */
242         if (!trans->blocks_used && list_empty(&trans->new_bgs)) {
243                 const char *errstr;
244
245                 errstr = btrfs_decode_error(errno);
246                 btrfs_warn(root->fs_info,
247                            "%s:%d: Aborting unused transaction(%s).",
248                            function, line, errstr);
249                 return;
250         }
251         ACCESS_ONCE(trans->transaction->aborted) = errno;
252         /* Wake up anybody who may be waiting on this transaction */
253         wake_up(&root->fs_info->transaction_wait);
254         wake_up(&root->fs_info->transaction_blocked_wait);
255         __btrfs_std_error(root->fs_info, function, line, errno, NULL);
256 }
257 /*
258  * __btrfs_panic decodes unexpected, fatal errors from the caller,
259  * issues an alert, and either panics or BUGs, depending on mount options.
260  */
261 __cold
262 void __btrfs_panic(struct btrfs_fs_info *fs_info, const char *function,
263                    unsigned int line, int errno, const char *fmt, ...)
264 {
265         char *s_id = "<unknown>";
266         const char *errstr;
267         struct va_format vaf = { .fmt = fmt };
268         va_list args;
269
270         if (fs_info)
271                 s_id = fs_info->sb->s_id;
272
273         va_start(args, fmt);
274         vaf.va = &args;
275
276         errstr = btrfs_decode_error(errno);
277         if (fs_info && (fs_info->mount_opt & BTRFS_MOUNT_PANIC_ON_FATAL_ERROR))
278                 panic(KERN_CRIT "BTRFS panic (device %s) in %s:%d: %pV (errno=%d %s)\n",
279                         s_id, function, line, &vaf, errno, errstr);
280
281         btrfs_crit(fs_info, "panic in %s:%d: %pV (errno=%d %s)",
282                    function, line, &vaf, errno, errstr);
283         va_end(args);
284         /* Caller calls BUG() */
285 }
286
287 static void btrfs_put_super(struct super_block *sb)
288 {
289         close_ctree(btrfs_sb(sb)->tree_root);
290 }
291
292 enum {
293         Opt_degraded, Opt_subvol, Opt_subvolid, Opt_device, Opt_nodatasum,
294         Opt_nodatacow, Opt_max_inline, Opt_alloc_start, Opt_nobarrier, Opt_ssd,
295         Opt_nossd, Opt_ssd_spread, Opt_thread_pool, Opt_noacl, Opt_compress,
296         Opt_compress_type, Opt_compress_force, Opt_compress_force_type,
297         Opt_notreelog, Opt_ratio, Opt_flushoncommit, Opt_discard,
298         Opt_space_cache, Opt_space_cache_version, Opt_clear_cache,
299         Opt_user_subvol_rm_allowed, Opt_enospc_debug, Opt_subvolrootid,
300         Opt_defrag, Opt_inode_cache, Opt_no_space_cache, Opt_recovery,
301         Opt_skip_balance, Opt_check_integrity,
302         Opt_check_integrity_including_extent_data,
303         Opt_check_integrity_print_mask, Opt_fatal_errors, Opt_rescan_uuid_tree,
304         Opt_commit_interval, Opt_barrier, Opt_nodefrag, Opt_nodiscard,
305         Opt_noenospc_debug, Opt_noflushoncommit, Opt_acl, Opt_datacow,
306         Opt_datasum, Opt_treelog, Opt_noinode_cache,
307 #ifdef CONFIG_BTRFS_DEBUG
308         Opt_fragment_data, Opt_fragment_metadata, Opt_fragment_all,
309 #endif
310         Opt_err,
311 };
312
313 static match_table_t tokens = {
314         {Opt_degraded, "degraded"},
315         {Opt_subvol, "subvol=%s"},
316         {Opt_subvolid, "subvolid=%s"},
317         {Opt_device, "device=%s"},
318         {Opt_nodatasum, "nodatasum"},
319         {Opt_datasum, "datasum"},
320         {Opt_nodatacow, "nodatacow"},
321         {Opt_datacow, "datacow"},
322         {Opt_nobarrier, "nobarrier"},
323         {Opt_barrier, "barrier"},
324         {Opt_max_inline, "max_inline=%s"},
325         {Opt_alloc_start, "alloc_start=%s"},
326         {Opt_thread_pool, "thread_pool=%d"},
327         {Opt_compress, "compress"},
328         {Opt_compress_type, "compress=%s"},
329         {Opt_compress_force, "compress-force"},
330         {Opt_compress_force_type, "compress-force=%s"},
331         {Opt_ssd, "ssd"},
332         {Opt_ssd_spread, "ssd_spread"},
333         {Opt_nossd, "nossd"},
334         {Opt_acl, "acl"},
335         {Opt_noacl, "noacl"},
336         {Opt_notreelog, "notreelog"},
337         {Opt_treelog, "treelog"},
338         {Opt_flushoncommit, "flushoncommit"},
339         {Opt_noflushoncommit, "noflushoncommit"},
340         {Opt_ratio, "metadata_ratio=%d"},
341         {Opt_discard, "discard"},
342         {Opt_nodiscard, "nodiscard"},
343         {Opt_space_cache, "space_cache"},
344         {Opt_space_cache_version, "space_cache=%s"},
345         {Opt_clear_cache, "clear_cache"},
346         {Opt_user_subvol_rm_allowed, "user_subvol_rm_allowed"},
347         {Opt_enospc_debug, "enospc_debug"},
348         {Opt_noenospc_debug, "noenospc_debug"},
349         {Opt_subvolrootid, "subvolrootid=%d"},
350         {Opt_defrag, "autodefrag"},
351         {Opt_nodefrag, "noautodefrag"},
352         {Opt_inode_cache, "inode_cache"},
353         {Opt_noinode_cache, "noinode_cache"},
354         {Opt_no_space_cache, "nospace_cache"},
355         {Opt_recovery, "recovery"},
356         {Opt_skip_balance, "skip_balance"},
357         {Opt_check_integrity, "check_int"},
358         {Opt_check_integrity_including_extent_data, "check_int_data"},
359         {Opt_check_integrity_print_mask, "check_int_print_mask=%d"},
360         {Opt_rescan_uuid_tree, "rescan_uuid_tree"},
361         {Opt_fatal_errors, "fatal_errors=%s"},
362         {Opt_commit_interval, "commit=%d"},
363 #ifdef CONFIG_BTRFS_DEBUG
364         {Opt_fragment_data, "fragment=data"},
365         {Opt_fragment_metadata, "fragment=metadata"},
366         {Opt_fragment_all, "fragment=all"},
367 #endif
368         {Opt_err, NULL},
369 };
370
371 /*
372  * Regular mount options parser.  Everything that is needed only when
373  * reading in a new superblock is parsed here.
374  * XXX JDM: This needs to be cleaned up for remount.
375  */
376 int btrfs_parse_options(struct btrfs_root *root, char *options)
377 {
378         struct btrfs_fs_info *info = root->fs_info;
379         substring_t args[MAX_OPT_ARGS];
380         char *p, *num, *orig = NULL;
381         u64 cache_gen;
382         int intarg;
383         int ret = 0;
384         char *compress_type;
385         bool compress_force = false;
386
387         cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
388         if (btrfs_fs_compat_ro(root->fs_info, FREE_SPACE_TREE))
389                 btrfs_set_opt(info->mount_opt, FREE_SPACE_TREE);
390         else if (cache_gen)
391                 btrfs_set_opt(info->mount_opt, SPACE_CACHE);
392
393         if (!options)
394                 goto out;
395
396         /*
397          * strsep changes the string, duplicate it because parse_options
398          * gets called twice
399          */
400         options = kstrdup(options, GFP_NOFS);
401         if (!options)
402                 return -ENOMEM;
403
404         orig = options;
405
406         while ((p = strsep(&options, ",")) != NULL) {
407                 int token;
408                 if (!*p)
409                         continue;
410
411                 token = match_token(p, tokens, args);
412                 switch (token) {
413                 case Opt_degraded:
414                         btrfs_info(root->fs_info, "allowing degraded mounts");
415                         btrfs_set_opt(info->mount_opt, DEGRADED);
416                         break;
417                 case Opt_subvol:
418                 case Opt_subvolid:
419                 case Opt_subvolrootid:
420                 case Opt_device:
421                         /*
422                          * These are parsed by btrfs_parse_early_options
423                          * and can be happily ignored here.
424                          */
425                         break;
426                 case Opt_nodatasum:
427                         btrfs_set_and_info(root, NODATASUM,
428                                            "setting nodatasum");
429                         break;
430                 case Opt_datasum:
431                         if (btrfs_test_opt(root, NODATASUM)) {
432                                 if (btrfs_test_opt(root, NODATACOW))
433                                         btrfs_info(root->fs_info, "setting datasum, datacow enabled");
434                                 else
435                                         btrfs_info(root->fs_info, "setting datasum");
436                         }
437                         btrfs_clear_opt(info->mount_opt, NODATACOW);
438                         btrfs_clear_opt(info->mount_opt, NODATASUM);
439                         break;
440                 case Opt_nodatacow:
441                         if (!btrfs_test_opt(root, NODATACOW)) {
442                                 if (!btrfs_test_opt(root, COMPRESS) ||
443                                     !btrfs_test_opt(root, FORCE_COMPRESS)) {
444                                         btrfs_info(root->fs_info,
445                                                    "setting nodatacow, compression disabled");
446                                 } else {
447                                         btrfs_info(root->fs_info, "setting nodatacow");
448                                 }
449                         }
450                         btrfs_clear_opt(info->mount_opt, COMPRESS);
451                         btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
452                         btrfs_set_opt(info->mount_opt, NODATACOW);
453                         btrfs_set_opt(info->mount_opt, NODATASUM);
454                         break;
455                 case Opt_datacow:
456                         btrfs_clear_and_info(root, NODATACOW,
457                                              "setting datacow");
458                         break;
459                 case Opt_compress_force:
460                 case Opt_compress_force_type:
461                         compress_force = true;
462                         /* Fallthrough */
463                 case Opt_compress:
464                 case Opt_compress_type:
465                         if (token == Opt_compress ||
466                             token == Opt_compress_force ||
467                             strcmp(args[0].from, "zlib") == 0) {
468                                 compress_type = "zlib";
469                                 info->compress_type = BTRFS_COMPRESS_ZLIB;
470                                 btrfs_set_opt(info->mount_opt, COMPRESS);
471                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
472                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
473                         } else if (strcmp(args[0].from, "lzo") == 0) {
474                                 compress_type = "lzo";
475                                 info->compress_type = BTRFS_COMPRESS_LZO;
476                                 btrfs_set_opt(info->mount_opt, COMPRESS);
477                                 btrfs_clear_opt(info->mount_opt, NODATACOW);
478                                 btrfs_clear_opt(info->mount_opt, NODATASUM);
479                                 btrfs_set_fs_incompat(info, COMPRESS_LZO);
480                         } else if (strncmp(args[0].from, "no", 2) == 0) {
481                                 compress_type = "no";
482                                 btrfs_clear_opt(info->mount_opt, COMPRESS);
483                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
484                                 compress_force = false;
485                         } else {
486                                 ret = -EINVAL;
487                                 goto out;
488                         }
489
490                         if (compress_force) {
491                                 btrfs_set_and_info(root, FORCE_COMPRESS,
492                                                    "force %s compression",
493                                                    compress_type);
494                         } else {
495                                 if (!btrfs_test_opt(root, COMPRESS))
496                                         btrfs_info(root->fs_info,
497                                                    "btrfs: use %s compression",
498                                                    compress_type);
499                                 /*
500                                  * If we remount from compress-force=xxx to
501                                  * compress=xxx, we need clear FORCE_COMPRESS
502                                  * flag, otherwise, there is no way for users
503                                  * to disable forcible compression separately.
504                                  */
505                                 btrfs_clear_opt(info->mount_opt, FORCE_COMPRESS);
506                         }
507                         break;
508                 case Opt_ssd:
509                         btrfs_set_and_info(root, SSD,
510                                            "use ssd allocation scheme");
511                         break;
512                 case Opt_ssd_spread:
513                         btrfs_set_and_info(root, SSD_SPREAD,
514                                            "use spread ssd allocation scheme");
515                         btrfs_set_opt(info->mount_opt, SSD);
516                         break;
517                 case Opt_nossd:
518                         btrfs_set_and_info(root, NOSSD,
519                                              "not using ssd allocation scheme");
520                         btrfs_clear_opt(info->mount_opt, SSD);
521                         break;
522                 case Opt_barrier:
523                         btrfs_clear_and_info(root, NOBARRIER,
524                                              "turning on barriers");
525                         break;
526                 case Opt_nobarrier:
527                         btrfs_set_and_info(root, NOBARRIER,
528                                            "turning off barriers");
529                         break;
530                 case Opt_thread_pool:
531                         ret = match_int(&args[0], &intarg);
532                         if (ret) {
533                                 goto out;
534                         } else if (intarg > 0) {
535                                 info->thread_pool_size = intarg;
536                         } else {
537                                 ret = -EINVAL;
538                                 goto out;
539                         }
540                         break;
541                 case Opt_max_inline:
542                         num = match_strdup(&args[0]);
543                         if (num) {
544                                 info->max_inline = memparse(num, NULL);
545                                 kfree(num);
546
547                                 if (info->max_inline) {
548                                         info->max_inline = min_t(u64,
549                                                 info->max_inline,
550                                                 root->sectorsize);
551                                 }
552                                 btrfs_info(root->fs_info, "max_inline at %llu",
553                                         info->max_inline);
554                         } else {
555                                 ret = -ENOMEM;
556                                 goto out;
557                         }
558                         break;
559                 case Opt_alloc_start:
560                         num = match_strdup(&args[0]);
561                         if (num) {
562                                 mutex_lock(&info->chunk_mutex);
563                                 info->alloc_start = memparse(num, NULL);
564                                 mutex_unlock(&info->chunk_mutex);
565                                 kfree(num);
566                                 btrfs_info(root->fs_info, "allocations start at %llu",
567                                         info->alloc_start);
568                         } else {
569                                 ret = -ENOMEM;
570                                 goto out;
571                         }
572                         break;
573                 case Opt_acl:
574 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
575                         root->fs_info->sb->s_flags |= MS_POSIXACL;
576                         break;
577 #else
578                         btrfs_err(root->fs_info,
579                                 "support for ACL not compiled in!");
580                         ret = -EINVAL;
581                         goto out;
582 #endif
583                 case Opt_noacl:
584                         root->fs_info->sb->s_flags &= ~MS_POSIXACL;
585                         break;
586                 case Opt_notreelog:
587                         btrfs_set_and_info(root, NOTREELOG,
588                                            "disabling tree log");
589                         break;
590                 case Opt_treelog:
591                         btrfs_clear_and_info(root, NOTREELOG,
592                                              "enabling tree log");
593                         break;
594                 case Opt_flushoncommit:
595                         btrfs_set_and_info(root, FLUSHONCOMMIT,
596                                            "turning on flush-on-commit");
597                         break;
598                 case Opt_noflushoncommit:
599                         btrfs_clear_and_info(root, FLUSHONCOMMIT,
600                                              "turning off flush-on-commit");
601                         break;
602                 case Opt_ratio:
603                         ret = match_int(&args[0], &intarg);
604                         if (ret) {
605                                 goto out;
606                         } else if (intarg >= 0) {
607                                 info->metadata_ratio = intarg;
608                                 btrfs_info(root->fs_info, "metadata ratio %d",
609                                        info->metadata_ratio);
610                         } else {
611                                 ret = -EINVAL;
612                                 goto out;
613                         }
614                         break;
615                 case Opt_discard:
616                         btrfs_set_and_info(root, DISCARD,
617                                            "turning on discard");
618                         break;
619                 case Opt_nodiscard:
620                         btrfs_clear_and_info(root, DISCARD,
621                                              "turning off discard");
622                         break;
623                 case Opt_space_cache:
624                 case Opt_space_cache_version:
625                         if (token == Opt_space_cache ||
626                             strcmp(args[0].from, "v1") == 0) {
627                                 btrfs_clear_opt(root->fs_info->mount_opt,
628                                                 FREE_SPACE_TREE);
629                                 btrfs_set_and_info(root, SPACE_CACHE,
630                                                    "enabling disk space caching");
631                         } else if (strcmp(args[0].from, "v2") == 0) {
632                                 btrfs_clear_opt(root->fs_info->mount_opt,
633                                                 SPACE_CACHE);
634                                 btrfs_set_and_info(root, FREE_SPACE_TREE,
635                                                    "enabling free space tree");
636                         } else {
637                                 ret = -EINVAL;
638                                 goto out;
639                         }
640                         break;
641                 case Opt_rescan_uuid_tree:
642                         btrfs_set_opt(info->mount_opt, RESCAN_UUID_TREE);
643                         break;
644                 case Opt_no_space_cache:
645                         if (btrfs_test_opt(root, SPACE_CACHE)) {
646                                 btrfs_clear_and_info(root, SPACE_CACHE,
647                                                      "disabling disk space caching");
648                         }
649                         if (btrfs_test_opt(root, FREE_SPACE_TREE)) {
650                                 btrfs_clear_and_info(root, FREE_SPACE_TREE,
651                                                      "disabling free space tree");
652                         }
653                         break;
654                 case Opt_inode_cache:
655                         btrfs_set_pending_and_info(info, INODE_MAP_CACHE,
656                                            "enabling inode map caching");
657                         break;
658                 case Opt_noinode_cache:
659                         btrfs_clear_pending_and_info(info, INODE_MAP_CACHE,
660                                              "disabling inode map caching");
661                         break;
662                 case Opt_clear_cache:
663                         btrfs_set_and_info(root, CLEAR_CACHE,
664                                            "force clearing of disk cache");
665                         break;
666                 case Opt_user_subvol_rm_allowed:
667                         btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED);
668                         break;
669                 case Opt_enospc_debug:
670                         btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG);
671                         break;
672                 case Opt_noenospc_debug:
673                         btrfs_clear_opt(info->mount_opt, ENOSPC_DEBUG);
674                         break;
675                 case Opt_defrag:
676                         btrfs_set_and_info(root, AUTO_DEFRAG,
677                                            "enabling auto defrag");
678                         break;
679                 case Opt_nodefrag:
680                         btrfs_clear_and_info(root, AUTO_DEFRAG,
681                                              "disabling auto defrag");
682                         break;
683                 case Opt_recovery:
684                         btrfs_info(root->fs_info, "enabling auto recovery");
685                         btrfs_set_opt(info->mount_opt, RECOVERY);
686                         break;
687                 case Opt_skip_balance:
688                         btrfs_set_opt(info->mount_opt, SKIP_BALANCE);
689                         break;
690 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
691                 case Opt_check_integrity_including_extent_data:
692                         btrfs_info(root->fs_info,
693                                    "enabling check integrity including extent data");
694                         btrfs_set_opt(info->mount_opt,
695                                       CHECK_INTEGRITY_INCLUDING_EXTENT_DATA);
696                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
697                         break;
698                 case Opt_check_integrity:
699                         btrfs_info(root->fs_info, "enabling check integrity");
700                         btrfs_set_opt(info->mount_opt, CHECK_INTEGRITY);
701                         break;
702                 case Opt_check_integrity_print_mask:
703                         ret = match_int(&args[0], &intarg);
704                         if (ret) {
705                                 goto out;
706                         } else if (intarg >= 0) {
707                                 info->check_integrity_print_mask = intarg;
708                                 btrfs_info(root->fs_info, "check_integrity_print_mask 0x%x",
709                                        info->check_integrity_print_mask);
710                         } else {
711                                 ret = -EINVAL;
712                                 goto out;
713                         }
714                         break;
715 #else
716                 case Opt_check_integrity_including_extent_data:
717                 case Opt_check_integrity:
718                 case Opt_check_integrity_print_mask:
719                         btrfs_err(root->fs_info,
720                                 "support for check_integrity* not compiled in!");
721                         ret = -EINVAL;
722                         goto out;
723 #endif
724                 case Opt_fatal_errors:
725                         if (strcmp(args[0].from, "panic") == 0)
726                                 btrfs_set_opt(info->mount_opt,
727                                               PANIC_ON_FATAL_ERROR);
728                         else if (strcmp(args[0].from, "bug") == 0)
729                                 btrfs_clear_opt(info->mount_opt,
730                                               PANIC_ON_FATAL_ERROR);
731                         else {
732                                 ret = -EINVAL;
733                                 goto out;
734                         }
735                         break;
736                 case Opt_commit_interval:
737                         intarg = 0;
738                         ret = match_int(&args[0], &intarg);
739                         if (ret < 0) {
740                                 btrfs_err(root->fs_info, "invalid commit interval");
741                                 ret = -EINVAL;
742                                 goto out;
743                         }
744                         if (intarg > 0) {
745                                 if (intarg > 300) {
746                                         btrfs_warn(root->fs_info, "excessive commit interval %d",
747                                                         intarg);
748                                 }
749                                 info->commit_interval = intarg;
750                         } else {
751                                 btrfs_info(root->fs_info, "using default commit interval %ds",
752                                     BTRFS_DEFAULT_COMMIT_INTERVAL);
753                                 info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
754                         }
755                         break;
756 #ifdef CONFIG_BTRFS_DEBUG
757                 case Opt_fragment_all:
758                         btrfs_info(root->fs_info, "fragmenting all space");
759                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
760                         btrfs_set_opt(info->mount_opt, FRAGMENT_METADATA);
761                         break;
762                 case Opt_fragment_metadata:
763                         btrfs_info(root->fs_info, "fragmenting metadata");
764                         btrfs_set_opt(info->mount_opt,
765                                       FRAGMENT_METADATA);
766                         break;
767                 case Opt_fragment_data:
768                         btrfs_info(root->fs_info, "fragmenting data");
769                         btrfs_set_opt(info->mount_opt, FRAGMENT_DATA);
770                         break;
771 #endif
772                 case Opt_err:
773                         btrfs_info(root->fs_info, "unrecognized mount option '%s'", p);
774                         ret = -EINVAL;
775                         goto out;
776                 default:
777                         break;
778                 }
779         }
780 out:
781         if (btrfs_fs_compat_ro(root->fs_info, FREE_SPACE_TREE) &&
782             !btrfs_test_opt(root, FREE_SPACE_TREE) &&
783             !btrfs_test_opt(root, CLEAR_CACHE)) {
784                 btrfs_err(root->fs_info, "cannot disable free space tree");
785                 ret = -EINVAL;
786
787         }
788         if (!ret && btrfs_test_opt(root, SPACE_CACHE))
789                 btrfs_info(root->fs_info, "disk space caching is enabled");
790         if (!ret && btrfs_test_opt(root, FREE_SPACE_TREE))
791                 btrfs_info(root->fs_info, "using free space tree");
792         kfree(orig);
793         return ret;
794 }
795
796 /*
797  * Parse mount options that are required early in the mount process.
798  *
799  * All other options will be parsed on much later in the mount process and
800  * only when we need to allocate a new super block.
801  */
802 static int btrfs_parse_early_options(const char *options, fmode_t flags,
803                 void *holder, char **subvol_name, u64 *subvol_objectid,
804                 struct btrfs_fs_devices **fs_devices)
805 {
806         substring_t args[MAX_OPT_ARGS];
807         char *device_name, *opts, *orig, *p;
808         char *num = NULL;
809         int error = 0;
810
811         if (!options)
812                 return 0;
813
814         /*
815          * strsep changes the string, duplicate it because parse_options
816          * gets called twice
817          */
818         opts = kstrdup(options, GFP_KERNEL);
819         if (!opts)
820                 return -ENOMEM;
821         orig = opts;
822
823         while ((p = strsep(&opts, ",")) != NULL) {
824                 int token;
825                 if (!*p)
826                         continue;
827
828                 token = match_token(p, tokens, args);
829                 switch (token) {
830                 case Opt_subvol:
831                         kfree(*subvol_name);
832                         *subvol_name = match_strdup(&args[0]);
833                         if (!*subvol_name) {
834                                 error = -ENOMEM;
835                                 goto out;
836                         }
837                         break;
838                 case Opt_subvolid:
839                         num = match_strdup(&args[0]);
840                         if (num) {
841                                 *subvol_objectid = memparse(num, NULL);
842                                 kfree(num);
843                                 /* we want the original fs_tree */
844                                 if (!*subvol_objectid)
845                                         *subvol_objectid =
846                                                 BTRFS_FS_TREE_OBJECTID;
847                         } else {
848                                 error = -EINVAL;
849                                 goto out;
850                         }
851                         break;
852                 case Opt_subvolrootid:
853                         printk(KERN_WARNING
854                                 "BTRFS: 'subvolrootid' mount option is deprecated and has "
855                                 "no effect\n");
856                         break;
857                 case Opt_device:
858                         device_name = match_strdup(&args[0]);
859                         if (!device_name) {
860                                 error = -ENOMEM;
861                                 goto out;
862                         }
863                         error = btrfs_scan_one_device(device_name,
864                                         flags, holder, fs_devices);
865                         kfree(device_name);
866                         if (error)
867                                 goto out;
868                         break;
869                 default:
870                         break;
871                 }
872         }
873
874 out:
875         kfree(orig);
876         return error;
877 }
878
879 static char *get_subvol_name_from_objectid(struct btrfs_fs_info *fs_info,
880                                            u64 subvol_objectid)
881 {
882         struct btrfs_root *root = fs_info->tree_root;
883         struct btrfs_root *fs_root;
884         struct btrfs_root_ref *root_ref;
885         struct btrfs_inode_ref *inode_ref;
886         struct btrfs_key key;
887         struct btrfs_path *path = NULL;
888         char *name = NULL, *ptr;
889         u64 dirid;
890         int len;
891         int ret;
892
893         path = btrfs_alloc_path();
894         if (!path) {
895                 ret = -ENOMEM;
896                 goto err;
897         }
898         path->leave_spinning = 1;
899
900         name = kmalloc(PATH_MAX, GFP_NOFS);
901         if (!name) {
902                 ret = -ENOMEM;
903                 goto err;
904         }
905         ptr = name + PATH_MAX - 1;
906         ptr[0] = '\0';
907
908         /*
909          * Walk up the subvolume trees in the tree of tree roots by root
910          * backrefs until we hit the top-level subvolume.
911          */
912         while (subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
913                 key.objectid = subvol_objectid;
914                 key.type = BTRFS_ROOT_BACKREF_KEY;
915                 key.offset = (u64)-1;
916
917                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
918                 if (ret < 0) {
919                         goto err;
920                 } else if (ret > 0) {
921                         ret = btrfs_previous_item(root, path, subvol_objectid,
922                                                   BTRFS_ROOT_BACKREF_KEY);
923                         if (ret < 0) {
924                                 goto err;
925                         } else if (ret > 0) {
926                                 ret = -ENOENT;
927                                 goto err;
928                         }
929                 }
930
931                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
932                 subvol_objectid = key.offset;
933
934                 root_ref = btrfs_item_ptr(path->nodes[0], path->slots[0],
935                                           struct btrfs_root_ref);
936                 len = btrfs_root_ref_name_len(path->nodes[0], root_ref);
937                 ptr -= len + 1;
938                 if (ptr < name) {
939                         ret = -ENAMETOOLONG;
940                         goto err;
941                 }
942                 read_extent_buffer(path->nodes[0], ptr + 1,
943                                    (unsigned long)(root_ref + 1), len);
944                 ptr[0] = '/';
945                 dirid = btrfs_root_ref_dirid(path->nodes[0], root_ref);
946                 btrfs_release_path(path);
947
948                 key.objectid = subvol_objectid;
949                 key.type = BTRFS_ROOT_ITEM_KEY;
950                 key.offset = (u64)-1;
951                 fs_root = btrfs_read_fs_root_no_name(fs_info, &key);
952                 if (IS_ERR(fs_root)) {
953                         ret = PTR_ERR(fs_root);
954                         goto err;
955                 }
956
957                 /*
958                  * Walk up the filesystem tree by inode refs until we hit the
959                  * root directory.
960                  */
961                 while (dirid != BTRFS_FIRST_FREE_OBJECTID) {
962                         key.objectid = dirid;
963                         key.type = BTRFS_INODE_REF_KEY;
964                         key.offset = (u64)-1;
965
966                         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
967                         if (ret < 0) {
968                                 goto err;
969                         } else if (ret > 0) {
970                                 ret = btrfs_previous_item(fs_root, path, dirid,
971                                                           BTRFS_INODE_REF_KEY);
972                                 if (ret < 0) {
973                                         goto err;
974                                 } else if (ret > 0) {
975                                         ret = -ENOENT;
976                                         goto err;
977                                 }
978                         }
979
980                         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
981                         dirid = key.offset;
982
983                         inode_ref = btrfs_item_ptr(path->nodes[0],
984                                                    path->slots[0],
985                                                    struct btrfs_inode_ref);
986                         len = btrfs_inode_ref_name_len(path->nodes[0],
987                                                        inode_ref);
988                         ptr -= len + 1;
989                         if (ptr < name) {
990                                 ret = -ENAMETOOLONG;
991                                 goto err;
992                         }
993                         read_extent_buffer(path->nodes[0], ptr + 1,
994                                            (unsigned long)(inode_ref + 1), len);
995                         ptr[0] = '/';
996                         btrfs_release_path(path);
997                 }
998         }
999
1000         btrfs_free_path(path);
1001         if (ptr == name + PATH_MAX - 1) {
1002                 name[0] = '/';
1003                 name[1] = '\0';
1004         } else {
1005                 memmove(name, ptr, name + PATH_MAX - ptr);
1006         }
1007         return name;
1008
1009 err:
1010         btrfs_free_path(path);
1011         kfree(name);
1012         return ERR_PTR(ret);
1013 }
1014
1015 static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objectid)
1016 {
1017         struct btrfs_root *root = fs_info->tree_root;
1018         struct btrfs_dir_item *di;
1019         struct btrfs_path *path;
1020         struct btrfs_key location;
1021         u64 dir_id;
1022
1023         path = btrfs_alloc_path();
1024         if (!path)
1025                 return -ENOMEM;
1026         path->leave_spinning = 1;
1027
1028         /*
1029          * Find the "default" dir item which points to the root item that we
1030          * will mount by default if we haven't been given a specific subvolume
1031          * to mount.
1032          */
1033         dir_id = btrfs_super_root_dir(fs_info->super_copy);
1034         di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0);
1035         if (IS_ERR(di)) {
1036                 btrfs_free_path(path);
1037                 return PTR_ERR(di);
1038         }
1039         if (!di) {
1040                 /*
1041                  * Ok the default dir item isn't there.  This is weird since
1042                  * it's always been there, but don't freak out, just try and
1043                  * mount the top-level subvolume.
1044                  */
1045                 btrfs_free_path(path);
1046                 *objectid = BTRFS_FS_TREE_OBJECTID;
1047                 return 0;
1048         }
1049
1050         btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1051         btrfs_free_path(path);
1052         *objectid = location.objectid;
1053         return 0;
1054 }
1055
1056 static int btrfs_fill_super(struct super_block *sb,
1057                             struct btrfs_fs_devices *fs_devices,
1058                             void *data, int silent)
1059 {
1060         struct inode *inode;
1061         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1062         struct btrfs_key key;
1063         int err;
1064
1065         sb->s_maxbytes = MAX_LFS_FILESIZE;
1066         sb->s_magic = BTRFS_SUPER_MAGIC;
1067         sb->s_op = &btrfs_super_ops;
1068         sb->s_d_op = &btrfs_dentry_operations;
1069         sb->s_export_op = &btrfs_export_ops;
1070         sb->s_xattr = btrfs_xattr_handlers;
1071         sb->s_time_gran = 1;
1072 #ifdef CONFIG_BTRFS_FS_POSIX_ACL
1073         sb->s_flags |= MS_POSIXACL;
1074 #endif
1075         sb->s_flags |= MS_I_VERSION;
1076         sb->s_iflags |= SB_I_CGROUPWB;
1077         err = open_ctree(sb, fs_devices, (char *)data);
1078         if (err) {
1079                 printk(KERN_ERR "BTRFS: open_ctree failed\n");
1080                 return err;
1081         }
1082
1083         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1084         key.type = BTRFS_INODE_ITEM_KEY;
1085         key.offset = 0;
1086         inode = btrfs_iget(sb, &key, fs_info->fs_root, NULL);
1087         if (IS_ERR(inode)) {
1088                 err = PTR_ERR(inode);
1089                 goto fail_close;
1090         }
1091
1092         sb->s_root = d_make_root(inode);
1093         if (!sb->s_root) {
1094                 err = -ENOMEM;
1095                 goto fail_close;
1096         }
1097
1098         save_mount_options(sb, data);
1099         cleancache_init_fs(sb);
1100         sb->s_flags |= MS_ACTIVE;
1101         return 0;
1102
1103 fail_close:
1104         close_ctree(fs_info->tree_root);
1105         return err;
1106 }
1107
1108 int btrfs_sync_fs(struct super_block *sb, int wait)
1109 {
1110         struct btrfs_trans_handle *trans;
1111         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1112         struct btrfs_root *root = fs_info->tree_root;
1113
1114         trace_btrfs_sync_fs(wait);
1115
1116         if (!wait) {
1117                 filemap_flush(fs_info->btree_inode->i_mapping);
1118                 return 0;
1119         }
1120
1121         btrfs_wait_ordered_roots(fs_info, -1);
1122
1123         trans = btrfs_attach_transaction_barrier(root);
1124         if (IS_ERR(trans)) {
1125                 /* no transaction, don't bother */
1126                 if (PTR_ERR(trans) == -ENOENT) {
1127                         /*
1128                          * Exit unless we have some pending changes
1129                          * that need to go through commit
1130                          */
1131                         if (fs_info->pending_changes == 0)
1132                                 return 0;
1133                         /*
1134                          * A non-blocking test if the fs is frozen. We must not
1135                          * start a new transaction here otherwise a deadlock
1136                          * happens. The pending operations are delayed to the
1137                          * next commit after thawing.
1138                          */
1139                         if (__sb_start_write(sb, SB_FREEZE_WRITE, false))
1140                                 __sb_end_write(sb, SB_FREEZE_WRITE);
1141                         else
1142                                 return 0;
1143                         trans = btrfs_start_transaction(root, 0);
1144                 }
1145                 if (IS_ERR(trans))
1146                         return PTR_ERR(trans);
1147         }
1148         return btrfs_commit_transaction(trans, root);
1149 }
1150
1151 static int btrfs_show_options(struct seq_file *seq, struct dentry *dentry)
1152 {
1153         struct btrfs_fs_info *info = btrfs_sb(dentry->d_sb);
1154         struct btrfs_root *root = info->tree_root;
1155         char *compress_type;
1156
1157         if (btrfs_test_opt(root, DEGRADED))
1158                 seq_puts(seq, ",degraded");
1159         if (btrfs_test_opt(root, NODATASUM))
1160                 seq_puts(seq, ",nodatasum");
1161         if (btrfs_test_opt(root, NODATACOW))
1162                 seq_puts(seq, ",nodatacow");
1163         if (btrfs_test_opt(root, NOBARRIER))
1164                 seq_puts(seq, ",nobarrier");
1165         if (info->max_inline != BTRFS_DEFAULT_MAX_INLINE)
1166                 seq_printf(seq, ",max_inline=%llu", info->max_inline);
1167         if (info->alloc_start != 0)
1168                 seq_printf(seq, ",alloc_start=%llu", info->alloc_start);
1169         if (info->thread_pool_size !=  min_t(unsigned long,
1170                                              num_online_cpus() + 2, 8))
1171                 seq_printf(seq, ",thread_pool=%d", info->thread_pool_size);
1172         if (btrfs_test_opt(root, COMPRESS)) {
1173                 if (info->compress_type == BTRFS_COMPRESS_ZLIB)
1174                         compress_type = "zlib";
1175                 else
1176                         compress_type = "lzo";
1177                 if (btrfs_test_opt(root, FORCE_COMPRESS))
1178                         seq_printf(seq, ",compress-force=%s", compress_type);
1179                 else
1180                         seq_printf(seq, ",compress=%s", compress_type);
1181         }
1182         if (btrfs_test_opt(root, NOSSD))
1183                 seq_puts(seq, ",nossd");
1184         if (btrfs_test_opt(root, SSD_SPREAD))
1185                 seq_puts(seq, ",ssd_spread");
1186         else if (btrfs_test_opt(root, SSD))
1187                 seq_puts(seq, ",ssd");
1188         if (btrfs_test_opt(root, NOTREELOG))
1189                 seq_puts(seq, ",notreelog");
1190         if (btrfs_test_opt(root, FLUSHONCOMMIT))
1191                 seq_puts(seq, ",flushoncommit");
1192         if (btrfs_test_opt(root, DISCARD))
1193                 seq_puts(seq, ",discard");
1194         if (!(root->fs_info->sb->s_flags & MS_POSIXACL))
1195                 seq_puts(seq, ",noacl");
1196         if (btrfs_test_opt(root, SPACE_CACHE))
1197                 seq_puts(seq, ",space_cache");
1198         else if (btrfs_test_opt(root, FREE_SPACE_TREE))
1199                 seq_puts(seq, ",space_cache=v2");
1200         else
1201                 seq_puts(seq, ",nospace_cache");
1202         if (btrfs_test_opt(root, RESCAN_UUID_TREE))
1203                 seq_puts(seq, ",rescan_uuid_tree");
1204         if (btrfs_test_opt(root, CLEAR_CACHE))
1205                 seq_puts(seq, ",clear_cache");
1206         if (btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
1207                 seq_puts(seq, ",user_subvol_rm_allowed");
1208         if (btrfs_test_opt(root, ENOSPC_DEBUG))
1209                 seq_puts(seq, ",enospc_debug");
1210         if (btrfs_test_opt(root, AUTO_DEFRAG))
1211                 seq_puts(seq, ",autodefrag");
1212         if (btrfs_test_opt(root, INODE_MAP_CACHE))
1213                 seq_puts(seq, ",inode_cache");
1214         if (btrfs_test_opt(root, SKIP_BALANCE))
1215                 seq_puts(seq, ",skip_balance");
1216         if (btrfs_test_opt(root, RECOVERY))
1217                 seq_puts(seq, ",recovery");
1218 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
1219         if (btrfs_test_opt(root, CHECK_INTEGRITY_INCLUDING_EXTENT_DATA))
1220                 seq_puts(seq, ",check_int_data");
1221         else if (btrfs_test_opt(root, CHECK_INTEGRITY))
1222                 seq_puts(seq, ",check_int");
1223         if (info->check_integrity_print_mask)
1224                 seq_printf(seq, ",check_int_print_mask=%d",
1225                                 info->check_integrity_print_mask);
1226 #endif
1227         if (info->metadata_ratio)
1228                 seq_printf(seq, ",metadata_ratio=%d",
1229                                 info->metadata_ratio);
1230         if (btrfs_test_opt(root, PANIC_ON_FATAL_ERROR))
1231                 seq_puts(seq, ",fatal_errors=panic");
1232         if (info->commit_interval != BTRFS_DEFAULT_COMMIT_INTERVAL)
1233                 seq_printf(seq, ",commit=%d", info->commit_interval);
1234 #ifdef CONFIG_BTRFS_DEBUG
1235         if (btrfs_test_opt(root, FRAGMENT_DATA))
1236                 seq_puts(seq, ",fragment=data");
1237         if (btrfs_test_opt(root, FRAGMENT_METADATA))
1238                 seq_puts(seq, ",fragment=metadata");
1239 #endif
1240         seq_printf(seq, ",subvolid=%llu",
1241                   BTRFS_I(d_inode(dentry))->root->root_key.objectid);
1242         seq_puts(seq, ",subvol=");
1243         seq_dentry(seq, dentry, " \t\n\\");
1244         return 0;
1245 }
1246
1247 static int btrfs_test_super(struct super_block *s, void *data)
1248 {
1249         struct btrfs_fs_info *p = data;
1250         struct btrfs_fs_info *fs_info = btrfs_sb(s);
1251
1252         return fs_info->fs_devices == p->fs_devices;
1253 }
1254
1255 static int btrfs_set_super(struct super_block *s, void *data)
1256 {
1257         int err = set_anon_super(s, data);
1258         if (!err)
1259                 s->s_fs_info = data;
1260         return err;
1261 }
1262
1263 /*
1264  * subvolumes are identified by ino 256
1265  */
1266 static inline int is_subvolume_inode(struct inode *inode)
1267 {
1268         if (inode && inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
1269                 return 1;
1270         return 0;
1271 }
1272
1273 /*
1274  * This will add subvolid=0 to the argument string while removing any subvol=
1275  * and subvolid= arguments to make sure we get the top-level root for path
1276  * walking to the subvol we want.
1277  */
1278 static char *setup_root_args(char *args)
1279 {
1280         char *buf, *dst, *sep;
1281
1282         if (!args)
1283                 return kstrdup("subvolid=0", GFP_NOFS);
1284
1285         /* The worst case is that we add ",subvolid=0" to the end. */
1286         buf = dst = kmalloc(strlen(args) + strlen(",subvolid=0") + 1, GFP_NOFS);
1287         if (!buf)
1288                 return NULL;
1289
1290         while (1) {
1291                 sep = strchrnul(args, ',');
1292                 if (!strstarts(args, "subvol=") &&
1293                     !strstarts(args, "subvolid=")) {
1294                         memcpy(dst, args, sep - args);
1295                         dst += sep - args;
1296                         *dst++ = ',';
1297                 }
1298                 if (*sep)
1299                         args = sep + 1;
1300                 else
1301                         break;
1302         }
1303         strcpy(dst, "subvolid=0");
1304
1305         return buf;
1306 }
1307
1308 static struct dentry *mount_subvol(const char *subvol_name, u64 subvol_objectid,
1309                                    int flags, const char *device_name,
1310                                    char *data)
1311 {
1312         struct dentry *root;
1313         struct vfsmount *mnt = NULL;
1314         char *newargs;
1315         int ret;
1316
1317         newargs = setup_root_args(data);
1318         if (!newargs) {
1319                 root = ERR_PTR(-ENOMEM);
1320                 goto out;
1321         }
1322
1323         mnt = vfs_kern_mount(&btrfs_fs_type, flags, device_name, newargs);
1324         if (PTR_ERR_OR_ZERO(mnt) == -EBUSY) {
1325                 if (flags & MS_RDONLY) {
1326                         mnt = vfs_kern_mount(&btrfs_fs_type, flags & ~MS_RDONLY,
1327                                              device_name, newargs);
1328                 } else {
1329                         mnt = vfs_kern_mount(&btrfs_fs_type, flags | MS_RDONLY,
1330                                              device_name, newargs);
1331                         if (IS_ERR(mnt)) {
1332                                 root = ERR_CAST(mnt);
1333                                 mnt = NULL;
1334                                 goto out;
1335                         }
1336
1337                         down_write(&mnt->mnt_sb->s_umount);
1338                         ret = btrfs_remount(mnt->mnt_sb, &flags, NULL);
1339                         up_write(&mnt->mnt_sb->s_umount);
1340                         if (ret < 0) {
1341                                 root = ERR_PTR(ret);
1342                                 goto out;
1343                         }
1344                 }
1345         }
1346         if (IS_ERR(mnt)) {
1347                 root = ERR_CAST(mnt);
1348                 mnt = NULL;
1349                 goto out;
1350         }
1351
1352         if (!subvol_name) {
1353                 if (!subvol_objectid) {
1354                         ret = get_default_subvol_objectid(btrfs_sb(mnt->mnt_sb),
1355                                                           &subvol_objectid);
1356                         if (ret) {
1357                                 root = ERR_PTR(ret);
1358                                 goto out;
1359                         }
1360                 }
1361                 subvol_name = get_subvol_name_from_objectid(btrfs_sb(mnt->mnt_sb),
1362                                                             subvol_objectid);
1363                 if (IS_ERR(subvol_name)) {
1364                         root = ERR_CAST(subvol_name);
1365                         subvol_name = NULL;
1366                         goto out;
1367                 }
1368
1369         }
1370
1371         root = mount_subtree(mnt, subvol_name);
1372         /* mount_subtree() drops our reference on the vfsmount. */
1373         mnt = NULL;
1374
1375         if (!IS_ERR(root)) {
1376                 struct super_block *s = root->d_sb;
1377                 struct inode *root_inode = d_inode(root);
1378                 u64 root_objectid = BTRFS_I(root_inode)->root->root_key.objectid;
1379
1380                 ret = 0;
1381                 if (!is_subvolume_inode(root_inode)) {
1382                         pr_err("BTRFS: '%s' is not a valid subvolume\n",
1383                                subvol_name);
1384                         ret = -EINVAL;
1385                 }
1386                 if (subvol_objectid && root_objectid != subvol_objectid) {
1387                         /*
1388                          * This will also catch a race condition where a
1389                          * subvolume which was passed by ID is renamed and
1390                          * another subvolume is renamed over the old location.
1391                          */
1392                         pr_err("BTRFS: subvol '%s' does not match subvolid %llu\n",
1393                                subvol_name, subvol_objectid);
1394                         ret = -EINVAL;
1395                 }
1396                 if (ret) {
1397                         dput(root);
1398                         root = ERR_PTR(ret);
1399                         deactivate_locked_super(s);
1400                 }
1401         }
1402
1403 out:
1404         mntput(mnt);
1405         kfree(newargs);
1406         kfree(subvol_name);
1407         return root;
1408 }
1409
1410 static int parse_security_options(char *orig_opts,
1411                                   struct security_mnt_opts *sec_opts)
1412 {
1413         char *secdata = NULL;
1414         int ret = 0;
1415
1416         secdata = alloc_secdata();
1417         if (!secdata)
1418                 return -ENOMEM;
1419         ret = security_sb_copy_data(orig_opts, secdata);
1420         if (ret) {
1421                 free_secdata(secdata);
1422                 return ret;
1423         }
1424         ret = security_sb_parse_opts_str(secdata, sec_opts);
1425         free_secdata(secdata);
1426         return ret;
1427 }
1428
1429 static int setup_security_options(struct btrfs_fs_info *fs_info,
1430                                   struct super_block *sb,
1431                                   struct security_mnt_opts *sec_opts)
1432 {
1433         int ret = 0;
1434
1435         /*
1436          * Call security_sb_set_mnt_opts() to check whether new sec_opts
1437          * is valid.
1438          */
1439         ret = security_sb_set_mnt_opts(sb, sec_opts, 0, NULL);
1440         if (ret)
1441                 return ret;
1442
1443 #ifdef CONFIG_SECURITY
1444         if (!fs_info->security_opts.num_mnt_opts) {
1445                 /* first time security setup, copy sec_opts to fs_info */
1446                 memcpy(&fs_info->security_opts, sec_opts, sizeof(*sec_opts));
1447         } else {
1448                 /*
1449                  * Since SELinux(the only one supports security_mnt_opts) does
1450                  * NOT support changing context during remount/mount same sb,
1451                  * This must be the same or part of the same security options,
1452                  * just free it.
1453                  */
1454                 security_free_mnt_opts(sec_opts);
1455         }
1456 #endif
1457         return ret;
1458 }
1459
1460 /*
1461  * Find a superblock for the given device / mount point.
1462  *
1463  * Note:  This is based on get_sb_bdev from fs/super.c with a few additions
1464  *        for multiple device setup.  Make sure to keep it in sync.
1465  */
1466 static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags,
1467                 const char *device_name, void *data)
1468 {
1469         struct block_device *bdev = NULL;
1470         struct super_block *s;
1471         struct btrfs_fs_devices *fs_devices = NULL;
1472         struct btrfs_fs_info *fs_info = NULL;
1473         struct security_mnt_opts new_sec_opts;
1474         fmode_t mode = FMODE_READ;
1475         char *subvol_name = NULL;
1476         u64 subvol_objectid = 0;
1477         int error = 0;
1478
1479         if (!(flags & MS_RDONLY))
1480                 mode |= FMODE_WRITE;
1481
1482         error = btrfs_parse_early_options(data, mode, fs_type,
1483                                           &subvol_name, &subvol_objectid,
1484                                           &fs_devices);
1485         if (error) {
1486                 kfree(subvol_name);
1487                 return ERR_PTR(error);
1488         }
1489
1490         if (subvol_name || subvol_objectid != BTRFS_FS_TREE_OBJECTID) {
1491                 /* mount_subvol() will free subvol_name. */
1492                 return mount_subvol(subvol_name, subvol_objectid, flags,
1493                                     device_name, data);
1494         }
1495
1496         security_init_mnt_opts(&new_sec_opts);
1497         if (data) {
1498                 error = parse_security_options(data, &new_sec_opts);
1499                 if (error)
1500                         return ERR_PTR(error);
1501         }
1502
1503         error = btrfs_scan_one_device(device_name, mode, fs_type, &fs_devices);
1504         if (error)
1505                 goto error_sec_opts;
1506
1507         /*
1508          * Setup a dummy root and fs_info for test/set super.  This is because
1509          * we don't actually fill this stuff out until open_ctree, but we need
1510          * it for searching for existing supers, so this lets us do that and
1511          * then open_ctree will properly initialize everything later.
1512          */
1513         fs_info = kzalloc(sizeof(struct btrfs_fs_info), GFP_NOFS);
1514         if (!fs_info) {
1515                 error = -ENOMEM;
1516                 goto error_sec_opts;
1517         }
1518
1519         fs_info->fs_devices = fs_devices;
1520
1521         fs_info->super_copy = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_NOFS);
1522         fs_info->super_for_commit = kzalloc(BTRFS_SUPER_INFO_SIZE, GFP_NOFS);
1523         security_init_mnt_opts(&fs_info->security_opts);
1524         if (!fs_info->super_copy || !fs_info->super_for_commit) {
1525                 error = -ENOMEM;
1526                 goto error_fs_info;
1527         }
1528
1529         error = btrfs_open_devices(fs_devices, mode, fs_type);
1530         if (error)
1531                 goto error_fs_info;
1532
1533         if (!(flags & MS_RDONLY) && fs_devices->rw_devices == 0) {
1534                 error = -EACCES;
1535                 goto error_close_devices;
1536         }
1537
1538         bdev = fs_devices->latest_bdev;
1539         s = sget(fs_type, btrfs_test_super, btrfs_set_super, flags | MS_NOSEC,
1540                  fs_info);
1541         if (IS_ERR(s)) {
1542                 error = PTR_ERR(s);
1543                 goto error_close_devices;
1544         }
1545
1546         if (s->s_root) {
1547                 btrfs_close_devices(fs_devices);
1548                 free_fs_info(fs_info);
1549                 if ((flags ^ s->s_flags) & MS_RDONLY)
1550                         error = -EBUSY;
1551         } else {
1552                 char b[BDEVNAME_SIZE];
1553
1554                 strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id));
1555                 btrfs_sb(s)->bdev_holder = fs_type;
1556                 error = btrfs_fill_super(s, fs_devices, data,
1557                                          flags & MS_SILENT ? 1 : 0);
1558         }
1559         if (error) {
1560                 deactivate_locked_super(s);
1561                 goto error_sec_opts;
1562         }
1563
1564         fs_info = btrfs_sb(s);
1565         error = setup_security_options(fs_info, s, &new_sec_opts);
1566         if (error) {
1567                 deactivate_locked_super(s);
1568                 goto error_sec_opts;
1569         }
1570
1571         return dget(s->s_root);
1572
1573 error_close_devices:
1574         btrfs_close_devices(fs_devices);
1575 error_fs_info:
1576         free_fs_info(fs_info);
1577 error_sec_opts:
1578         security_free_mnt_opts(&new_sec_opts);
1579         return ERR_PTR(error);
1580 }
1581
1582 static void btrfs_resize_thread_pool(struct btrfs_fs_info *fs_info,
1583                                      int new_pool_size, int old_pool_size)
1584 {
1585         if (new_pool_size == old_pool_size)
1586                 return;
1587
1588         fs_info->thread_pool_size = new_pool_size;
1589
1590         btrfs_info(fs_info, "resize thread pool %d -> %d",
1591                old_pool_size, new_pool_size);
1592
1593         btrfs_workqueue_set_max(fs_info->workers, new_pool_size);
1594         btrfs_workqueue_set_max(fs_info->delalloc_workers, new_pool_size);
1595         btrfs_workqueue_set_max(fs_info->submit_workers, new_pool_size);
1596         btrfs_workqueue_set_max(fs_info->caching_workers, new_pool_size);
1597         btrfs_workqueue_set_max(fs_info->endio_workers, new_pool_size);
1598         btrfs_workqueue_set_max(fs_info->endio_meta_workers, new_pool_size);
1599         btrfs_workqueue_set_max(fs_info->endio_meta_write_workers,
1600                                 new_pool_size);
1601         btrfs_workqueue_set_max(fs_info->endio_write_workers, new_pool_size);
1602         btrfs_workqueue_set_max(fs_info->endio_freespace_worker, new_pool_size);
1603         btrfs_workqueue_set_max(fs_info->delayed_workers, new_pool_size);
1604         btrfs_workqueue_set_max(fs_info->readahead_workers, new_pool_size);
1605         btrfs_workqueue_set_max(fs_info->scrub_wr_completion_workers,
1606                                 new_pool_size);
1607 }
1608
1609 static inline void btrfs_remount_prepare(struct btrfs_fs_info *fs_info)
1610 {
1611         set_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1612 }
1613
1614 static inline void btrfs_remount_begin(struct btrfs_fs_info *fs_info,
1615                                        unsigned long old_opts, int flags)
1616 {
1617         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1618             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1619              (flags & MS_RDONLY))) {
1620                 /* wait for any defraggers to finish */
1621                 wait_event(fs_info->transaction_wait,
1622                            (atomic_read(&fs_info->defrag_running) == 0));
1623                 if (flags & MS_RDONLY)
1624                         sync_filesystem(fs_info->sb);
1625         }
1626 }
1627
1628 static inline void btrfs_remount_cleanup(struct btrfs_fs_info *fs_info,
1629                                          unsigned long old_opts)
1630 {
1631         /*
1632          * We need cleanup all defragable inodes if the autodefragment is
1633          * close or the fs is R/O.
1634          */
1635         if (btrfs_raw_test_opt(old_opts, AUTO_DEFRAG) &&
1636             (!btrfs_raw_test_opt(fs_info->mount_opt, AUTO_DEFRAG) ||
1637              (fs_info->sb->s_flags & MS_RDONLY))) {
1638                 btrfs_cleanup_defrag_inodes(fs_info);
1639         }
1640
1641         clear_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state);
1642 }
1643
1644 static int btrfs_remount(struct super_block *sb, int *flags, char *data)
1645 {
1646         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
1647         struct btrfs_root *root = fs_info->tree_root;
1648         unsigned old_flags = sb->s_flags;
1649         unsigned long old_opts = fs_info->mount_opt;
1650         unsigned long old_compress_type = fs_info->compress_type;
1651         u64 old_max_inline = fs_info->max_inline;
1652         u64 old_alloc_start = fs_info->alloc_start;
1653         int old_thread_pool_size = fs_info->thread_pool_size;
1654         unsigned int old_metadata_ratio = fs_info->metadata_ratio;
1655         int ret;
1656
1657         sync_filesystem(sb);
1658         btrfs_remount_prepare(fs_info);
1659
1660         if (data) {
1661                 struct security_mnt_opts new_sec_opts;
1662
1663                 security_init_mnt_opts(&new_sec_opts);
1664                 ret = parse_security_options(data, &new_sec_opts);
1665                 if (ret)
1666                         goto restore;
1667                 ret = setup_security_options(fs_info, sb,
1668                                              &new_sec_opts);
1669                 if (ret) {
1670                         security_free_mnt_opts(&new_sec_opts);
1671                         goto restore;
1672                 }
1673         }
1674
1675         ret = btrfs_parse_options(root, data);
1676         if (ret) {
1677                 ret = -EINVAL;
1678                 goto restore;
1679         }
1680
1681         btrfs_remount_begin(fs_info, old_opts, *flags);
1682         btrfs_resize_thread_pool(fs_info,
1683                 fs_info->thread_pool_size, old_thread_pool_size);
1684
1685         if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
1686                 goto out;
1687
1688         if (*flags & MS_RDONLY) {
1689                 /*
1690                  * this also happens on 'umount -rf' or on shutdown, when
1691                  * the filesystem is busy.
1692                  */
1693                 cancel_work_sync(&fs_info->async_reclaim_work);
1694
1695                 /* wait for the uuid_scan task to finish */
1696                 down(&fs_info->uuid_tree_rescan_sem);
1697                 /* avoid complains from lockdep et al. */
1698                 up(&fs_info->uuid_tree_rescan_sem);
1699
1700                 sb->s_flags |= MS_RDONLY;
1701
1702                 /*
1703                  * Setting MS_RDONLY will put the cleaner thread to
1704                  * sleep at the next loop if it's already active.
1705                  * If it's already asleep, we'll leave unused block
1706                  * groups on disk until we're mounted read-write again
1707                  * unless we clean them up here.
1708                  */
1709                 btrfs_delete_unused_bgs(fs_info);
1710
1711                 btrfs_dev_replace_suspend_for_unmount(fs_info);
1712                 btrfs_scrub_cancel(fs_info);
1713                 btrfs_pause_balance(fs_info);
1714
1715                 ret = btrfs_commit_super(root);
1716                 if (ret)
1717                         goto restore;
1718         } else {
1719                 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
1720                         btrfs_err(fs_info,
1721                                 "Remounting read-write after error is not allowed");
1722                         ret = -EINVAL;
1723                         goto restore;
1724                 }
1725                 if (fs_info->fs_devices->rw_devices == 0) {
1726                         ret = -EACCES;
1727                         goto restore;
1728                 }
1729
1730                 if (fs_info->fs_devices->missing_devices >
1731                      fs_info->num_tolerated_disk_barrier_failures &&
1732                     !(*flags & MS_RDONLY)) {
1733                         btrfs_warn(fs_info,
1734                                 "too many missing devices, writeable remount is not allowed");
1735                         ret = -EACCES;
1736                         goto restore;
1737                 }
1738
1739                 if (btrfs_super_log_root(fs_info->super_copy) != 0) {
1740                         ret = -EINVAL;
1741                         goto restore;
1742                 }
1743
1744                 ret = btrfs_cleanup_fs_roots(fs_info);
1745                 if (ret)
1746                         goto restore;
1747
1748                 /* recover relocation */
1749                 mutex_lock(&fs_info->cleaner_mutex);
1750                 ret = btrfs_recover_relocation(root);
1751                 mutex_unlock(&fs_info->cleaner_mutex);
1752                 if (ret)
1753                         goto restore;
1754
1755                 ret = btrfs_resume_balance_async(fs_info);
1756                 if (ret)
1757                         goto restore;
1758
1759                 ret = btrfs_resume_dev_replace_async(fs_info);
1760                 if (ret) {
1761                         btrfs_warn(fs_info, "failed to resume dev_replace");
1762                         goto restore;
1763                 }
1764
1765                 if (!fs_info->uuid_root) {
1766                         btrfs_info(fs_info, "creating UUID tree");
1767                         ret = btrfs_create_uuid_tree(fs_info);
1768                         if (ret) {
1769                                 btrfs_warn(fs_info, "failed to create the UUID tree %d", ret);
1770                                 goto restore;
1771                         }
1772                 }
1773                 sb->s_flags &= ~MS_RDONLY;
1774         }
1775 out:
1776         wake_up_process(fs_info->transaction_kthread);
1777         btrfs_remount_cleanup(fs_info, old_opts);
1778         return 0;
1779
1780 restore:
1781         /* We've hit an error - don't reset MS_RDONLY */
1782         if (sb->s_flags & MS_RDONLY)
1783                 old_flags |= MS_RDONLY;
1784         sb->s_flags = old_flags;
1785         fs_info->mount_opt = old_opts;
1786         fs_info->compress_type = old_compress_type;
1787         fs_info->max_inline = old_max_inline;
1788         mutex_lock(&fs_info->chunk_mutex);
1789         fs_info->alloc_start = old_alloc_start;
1790         mutex_unlock(&fs_info->chunk_mutex);
1791         btrfs_resize_thread_pool(fs_info,
1792                 old_thread_pool_size, fs_info->thread_pool_size);
1793         fs_info->metadata_ratio = old_metadata_ratio;
1794         btrfs_remount_cleanup(fs_info, old_opts);
1795         return ret;
1796 }
1797
1798 /* Used to sort the devices by max_avail(descending sort) */
1799 static int btrfs_cmp_device_free_bytes(const void *dev_info1,
1800                                        const void *dev_info2)
1801 {
1802         if (((struct btrfs_device_info *)dev_info1)->max_avail >
1803             ((struct btrfs_device_info *)dev_info2)->max_avail)
1804                 return -1;
1805         else if (((struct btrfs_device_info *)dev_info1)->max_avail <
1806                  ((struct btrfs_device_info *)dev_info2)->max_avail)
1807                 return 1;
1808         else
1809         return 0;
1810 }
1811
1812 /*
1813  * sort the devices by max_avail, in which max free extent size of each device
1814  * is stored.(Descending Sort)
1815  */
1816 static inline void btrfs_descending_sort_devices(
1817                                         struct btrfs_device_info *devices,
1818                                         size_t nr_devices)
1819 {
1820         sort(devices, nr_devices, sizeof(struct btrfs_device_info),
1821              btrfs_cmp_device_free_bytes, NULL);
1822 }
1823
1824 /*
1825  * The helper to calc the free space on the devices that can be used to store
1826  * file data.
1827  */
1828 static int btrfs_calc_avail_data_space(struct btrfs_root *root, u64 *free_bytes)
1829 {
1830         struct btrfs_fs_info *fs_info = root->fs_info;
1831         struct btrfs_device_info *devices_info;
1832         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1833         struct btrfs_device *device;
1834         u64 skip_space;
1835         u64 type;
1836         u64 avail_space;
1837         u64 used_space;
1838         u64 min_stripe_size;
1839         int min_stripes = 1, num_stripes = 1;
1840         int i = 0, nr_devices;
1841         int ret;
1842
1843         /*
1844          * We aren't under the device list lock, so this is racey-ish, but good
1845          * enough for our purposes.
1846          */
1847         nr_devices = fs_info->fs_devices->open_devices;
1848         if (!nr_devices) {
1849                 smp_mb();
1850                 nr_devices = fs_info->fs_devices->open_devices;
1851                 ASSERT(nr_devices);
1852                 if (!nr_devices) {
1853                         *free_bytes = 0;
1854                         return 0;
1855                 }
1856         }
1857
1858         devices_info = kmalloc_array(nr_devices, sizeof(*devices_info),
1859                                GFP_NOFS);
1860         if (!devices_info)
1861                 return -ENOMEM;
1862
1863         /* calc min stripe number for data space alloction */
1864         type = btrfs_get_alloc_profile(root, 1);
1865         if (type & BTRFS_BLOCK_GROUP_RAID0) {
1866                 min_stripes = 2;
1867                 num_stripes = nr_devices;
1868         } else if (type & BTRFS_BLOCK_GROUP_RAID1) {
1869                 min_stripes = 2;
1870                 num_stripes = 2;
1871         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
1872                 min_stripes = 4;
1873                 num_stripes = 4;
1874         }
1875
1876         if (type & BTRFS_BLOCK_GROUP_DUP)
1877                 min_stripe_size = 2 * BTRFS_STRIPE_LEN;
1878         else
1879                 min_stripe_size = BTRFS_STRIPE_LEN;
1880
1881         if (fs_info->alloc_start)
1882                 mutex_lock(&fs_devices->device_list_mutex);
1883         rcu_read_lock();
1884         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
1885                 if (!device->in_fs_metadata || !device->bdev ||
1886                     device->is_tgtdev_for_dev_replace)
1887                         continue;
1888
1889                 if (i >= nr_devices)
1890                         break;
1891
1892                 avail_space = device->total_bytes - device->bytes_used;
1893
1894                 /* align with stripe_len */
1895                 avail_space = div_u64(avail_space, BTRFS_STRIPE_LEN);
1896                 avail_space *= BTRFS_STRIPE_LEN;
1897
1898                 /*
1899                  * In order to avoid overwritting the superblock on the drive,
1900                  * btrfs starts at an offset of at least 1MB when doing chunk
1901                  * allocation.
1902                  */
1903                 skip_space = 1024 * 1024;
1904
1905                 /* user can set the offset in fs_info->alloc_start. */
1906                 if (fs_info->alloc_start &&
1907                     fs_info->alloc_start + BTRFS_STRIPE_LEN <=
1908                     device->total_bytes) {
1909                         rcu_read_unlock();
1910                         skip_space = max(fs_info->alloc_start, skip_space);
1911
1912                         /*
1913                          * btrfs can not use the free space in
1914                          * [0, skip_space - 1], we must subtract it from the
1915                          * total. In order to implement it, we account the used
1916                          * space in this range first.
1917                          */
1918                         ret = btrfs_account_dev_extents_size(device, 0,
1919                                                              skip_space - 1,
1920                                                              &used_space);
1921                         if (ret) {
1922                                 kfree(devices_info);
1923                                 mutex_unlock(&fs_devices->device_list_mutex);
1924                                 return ret;
1925                         }
1926
1927                         rcu_read_lock();
1928
1929                         /* calc the free space in [0, skip_space - 1] */
1930                         skip_space -= used_space;
1931                 }
1932
1933                 /*
1934                  * we can use the free space in [0, skip_space - 1], subtract
1935                  * it from the total.
1936                  */
1937                 if (avail_space && avail_space >= skip_space)
1938                         avail_space -= skip_space;
1939                 else
1940                         avail_space = 0;
1941
1942                 if (avail_space < min_stripe_size)
1943                         continue;
1944
1945                 devices_info[i].dev = device;
1946                 devices_info[i].max_avail = avail_space;
1947
1948                 i++;
1949         }
1950         rcu_read_unlock();
1951         if (fs_info->alloc_start)
1952                 mutex_unlock(&fs_devices->device_list_mutex);
1953
1954         nr_devices = i;
1955
1956         btrfs_descending_sort_devices(devices_info, nr_devices);
1957
1958         i = nr_devices - 1;
1959         avail_space = 0;
1960         while (nr_devices >= min_stripes) {
1961                 if (num_stripes > nr_devices)
1962                         num_stripes = nr_devices;
1963
1964                 if (devices_info[i].max_avail >= min_stripe_size) {
1965                         int j;
1966                         u64 alloc_size;
1967
1968                         avail_space += devices_info[i].max_avail * num_stripes;
1969                         alloc_size = devices_info[i].max_avail;
1970                         for (j = i + 1 - num_stripes; j <= i; j++)
1971                                 devices_info[j].max_avail -= alloc_size;
1972                 }
1973                 i--;
1974                 nr_devices--;
1975         }
1976
1977         kfree(devices_info);
1978         *free_bytes = avail_space;
1979         return 0;
1980 }
1981
1982 /*
1983  * Calculate numbers for 'df', pessimistic in case of mixed raid profiles.
1984  *
1985  * If there's a redundant raid level at DATA block groups, use the respective
1986  * multiplier to scale the sizes.
1987  *
1988  * Unused device space usage is based on simulating the chunk allocator
1989  * algorithm that respects the device sizes, order of allocations and the
1990  * 'alloc_start' value, this is a close approximation of the actual use but
1991  * there are other factors that may change the result (like a new metadata
1992  * chunk).
1993  *
1994  * FIXME: not accurate for mixed block groups, total and free/used are ok,
1995  * available appears slightly larger.
1996  */
1997 static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
1998 {
1999         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
2000         struct btrfs_super_block *disk_super = fs_info->super_copy;
2001         struct list_head *head = &fs_info->space_info;
2002         struct btrfs_space_info *found;
2003         u64 total_used = 0;
2004         u64 total_free_data = 0;
2005         int bits = dentry->d_sb->s_blocksize_bits;
2006         __be32 *fsid = (__be32 *)fs_info->fsid;
2007         unsigned factor = 1;
2008         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
2009         int ret;
2010
2011         /*
2012          * holding chunk_muext to avoid allocating new chunks, holding
2013          * device_list_mutex to avoid the device being removed
2014          */
2015         rcu_read_lock();
2016         list_for_each_entry_rcu(found, head, list) {
2017                 if (found->flags & BTRFS_BLOCK_GROUP_DATA) {
2018                         int i;
2019
2020                         total_free_data += found->disk_total - found->disk_used;
2021                         total_free_data -=
2022                                 btrfs_account_ro_block_groups_free_space(found);
2023
2024                         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2025                                 if (!list_empty(&found->block_groups[i])) {
2026                                         switch (i) {
2027                                         case BTRFS_RAID_DUP:
2028                                         case BTRFS_RAID_RAID1:
2029                                         case BTRFS_RAID_RAID10:
2030                                                 factor = 2;
2031                                         }
2032                                 }
2033                         }
2034                 }
2035
2036                 total_used += found->disk_used;
2037         }
2038
2039         rcu_read_unlock();
2040
2041         buf->f_blocks = div_u64(btrfs_super_total_bytes(disk_super), factor);
2042         buf->f_blocks >>= bits;
2043         buf->f_bfree = buf->f_blocks - (div_u64(total_used, factor) >> bits);
2044
2045         /* Account global block reserve as used, it's in logical size already */
2046         spin_lock(&block_rsv->lock);
2047         buf->f_bfree -= block_rsv->size >> bits;
2048         spin_unlock(&block_rsv->lock);
2049
2050         buf->f_bavail = div_u64(total_free_data, factor);
2051         ret = btrfs_calc_avail_data_space(fs_info->tree_root, &total_free_data);
2052         if (ret)
2053                 return ret;
2054         buf->f_bavail += div_u64(total_free_data, factor);
2055         buf->f_bavail = buf->f_bavail >> bits;
2056
2057         buf->f_type = BTRFS_SUPER_MAGIC;
2058         buf->f_bsize = dentry->d_sb->s_blocksize;
2059         buf->f_namelen = BTRFS_NAME_LEN;
2060
2061         /* We treat it as constant endianness (it doesn't matter _which_)
2062            because we want the fsid to come out the same whether mounted
2063            on a big-endian or little-endian host */
2064         buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]);
2065         buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]);
2066         /* Mask in the root object ID too, to disambiguate subvols */
2067         buf->f_fsid.val[0] ^= BTRFS_I(d_inode(dentry))->root->objectid >> 32;
2068         buf->f_fsid.val[1] ^= BTRFS_I(d_inode(dentry))->root->objectid;
2069
2070         return 0;
2071 }
2072
2073 static void btrfs_kill_super(struct super_block *sb)
2074 {
2075         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
2076         kill_anon_super(sb);
2077         free_fs_info(fs_info);
2078 }
2079
2080 static struct file_system_type btrfs_fs_type = {
2081         .owner          = THIS_MODULE,
2082         .name           = "btrfs",
2083         .mount          = btrfs_mount,
2084         .kill_sb        = btrfs_kill_super,
2085         .fs_flags       = FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA,
2086 };
2087 MODULE_ALIAS_FS("btrfs");
2088
2089 static int btrfs_control_open(struct inode *inode, struct file *file)
2090 {
2091         /*
2092          * The control file's private_data is used to hold the
2093          * transaction when it is started and is used to keep
2094          * track of whether a transaction is already in progress.
2095          */
2096         file->private_data = NULL;
2097         return 0;
2098 }
2099
2100 /*
2101  * used by btrfsctl to scan devices when no FS is mounted
2102  */
2103 static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
2104                                 unsigned long arg)
2105 {
2106         struct btrfs_ioctl_vol_args *vol;
2107         struct btrfs_fs_devices *fs_devices;
2108         int ret = -ENOTTY;
2109
2110         if (!capable(CAP_SYS_ADMIN))
2111                 return -EPERM;
2112
2113         vol = memdup_user((void __user *)arg, sizeof(*vol));
2114         if (IS_ERR(vol))
2115                 return PTR_ERR(vol);
2116
2117         switch (cmd) {
2118         case BTRFS_IOC_SCAN_DEV:
2119                 ret = btrfs_scan_one_device(vol->name, FMODE_READ,
2120                                             &btrfs_fs_type, &fs_devices);
2121                 break;
2122         case BTRFS_IOC_DEVICES_READY:
2123                 ret = btrfs_scan_one_device(vol->name, FMODE_READ,
2124                                             &btrfs_fs_type, &fs_devices);
2125                 if (ret)
2126                         break;
2127                 ret = !(fs_devices->num_devices == fs_devices->total_devices);
2128                 break;
2129         }
2130
2131         kfree(vol);
2132         return ret;
2133 }
2134
2135 static int btrfs_freeze(struct super_block *sb)
2136 {
2137         struct btrfs_trans_handle *trans;
2138         struct btrfs_root *root = btrfs_sb(sb)->tree_root;
2139
2140         trans = btrfs_attach_transaction_barrier(root);
2141         if (IS_ERR(trans)) {
2142                 /* no transaction, don't bother */
2143                 if (PTR_ERR(trans) == -ENOENT)
2144                         return 0;
2145                 return PTR_ERR(trans);
2146         }
2147         return btrfs_commit_transaction(trans, root);
2148 }
2149
2150 static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
2151 {
2152         struct btrfs_fs_info *fs_info = btrfs_sb(root->d_sb);
2153         struct btrfs_fs_devices *cur_devices;
2154         struct btrfs_device *dev, *first_dev = NULL;
2155         struct list_head *head;
2156         struct rcu_string *name;
2157
2158         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2159         cur_devices = fs_info->fs_devices;
2160         while (cur_devices) {
2161                 head = &cur_devices->devices;
2162                 list_for_each_entry(dev, head, dev_list) {
2163                         if (dev->missing)
2164                                 continue;
2165                         if (!dev->name)
2166                                 continue;
2167                         if (!first_dev || dev->devid < first_dev->devid)
2168                                 first_dev = dev;
2169                 }
2170                 cur_devices = cur_devices->seed;
2171         }
2172
2173         if (first_dev) {
2174                 rcu_read_lock();
2175                 name = rcu_dereference(first_dev->name);
2176                 seq_escape(m, name->str, " \t\n\\");
2177                 rcu_read_unlock();
2178         } else {
2179                 WARN_ON(1);
2180         }
2181         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2182         return 0;
2183 }
2184
2185 static const struct super_operations btrfs_super_ops = {
2186         .drop_inode     = btrfs_drop_inode,
2187         .evict_inode    = btrfs_evict_inode,
2188         .put_super      = btrfs_put_super,
2189         .sync_fs        = btrfs_sync_fs,
2190         .show_options   = btrfs_show_options,
2191         .show_devname   = btrfs_show_devname,
2192         .write_inode    = btrfs_write_inode,
2193         .alloc_inode    = btrfs_alloc_inode,
2194         .destroy_inode  = btrfs_destroy_inode,
2195         .statfs         = btrfs_statfs,
2196         .remount_fs     = btrfs_remount,
2197         .freeze_fs      = btrfs_freeze,
2198 };
2199
2200 static const struct file_operations btrfs_ctl_fops = {
2201         .open = btrfs_control_open,
2202         .unlocked_ioctl  = btrfs_control_ioctl,
2203         .compat_ioctl = btrfs_control_ioctl,
2204         .owner   = THIS_MODULE,
2205         .llseek = noop_llseek,
2206 };
2207
2208 static struct miscdevice btrfs_misc = {
2209         .minor          = BTRFS_MINOR,
2210         .name           = "btrfs-control",
2211         .fops           = &btrfs_ctl_fops
2212 };
2213
2214 MODULE_ALIAS_MISCDEV(BTRFS_MINOR);
2215 MODULE_ALIAS("devname:btrfs-control");
2216
2217 static int btrfs_interface_init(void)
2218 {
2219         return misc_register(&btrfs_misc);
2220 }
2221
2222 static void btrfs_interface_exit(void)
2223 {
2224         misc_deregister(&btrfs_misc);
2225 }
2226
2227 static void btrfs_print_info(void)
2228 {
2229         printk(KERN_INFO "Btrfs loaded"
2230 #ifdef CONFIG_BTRFS_DEBUG
2231                         ", debug=on"
2232 #endif
2233 #ifdef CONFIG_BTRFS_ASSERT
2234                         ", assert=on"
2235 #endif
2236 #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
2237                         ", integrity-checker=on"
2238 #endif
2239                         "\n");
2240 }
2241
2242 static int btrfs_run_sanity_tests(void)
2243 {
2244         int ret;
2245
2246         ret = btrfs_init_test_fs();
2247         if (ret)
2248                 return ret;
2249
2250         ret = btrfs_test_free_space_cache();
2251         if (ret)
2252                 goto out;
2253         ret = btrfs_test_extent_buffer_operations();
2254         if (ret)
2255                 goto out;
2256         ret = btrfs_test_extent_io();
2257         if (ret)
2258                 goto out;
2259         ret = btrfs_test_inodes();
2260         if (ret)
2261                 goto out;
2262         ret = btrfs_test_qgroups();
2263         if (ret)
2264                 goto out;
2265         ret = btrfs_test_free_space_tree();
2266 out:
2267         btrfs_destroy_test_fs();
2268         return ret;
2269 }
2270
2271 static int __init init_btrfs_fs(void)
2272 {
2273         int err;
2274
2275         err = btrfs_hash_init();
2276         if (err)
2277                 return err;
2278
2279         btrfs_props_init();
2280
2281         err = btrfs_init_sysfs();
2282         if (err)
2283                 goto free_hash;
2284
2285         btrfs_init_compress();
2286
2287         err = btrfs_init_cachep();
2288         if (err)
2289                 goto free_compress;
2290
2291         err = extent_io_init();
2292         if (err)
2293                 goto free_cachep;
2294
2295         err = extent_map_init();
2296         if (err)
2297                 goto free_extent_io;
2298
2299         err = ordered_data_init();
2300         if (err)
2301                 goto free_extent_map;
2302
2303         err = btrfs_delayed_inode_init();
2304         if (err)
2305                 goto free_ordered_data;
2306
2307         err = btrfs_auto_defrag_init();
2308         if (err)
2309                 goto free_delayed_inode;
2310
2311         err = btrfs_delayed_ref_init();
2312         if (err)
2313                 goto free_auto_defrag;
2314
2315         err = btrfs_prelim_ref_init();
2316         if (err)
2317                 goto free_delayed_ref;
2318
2319         err = btrfs_end_io_wq_init();
2320         if (err)
2321                 goto free_prelim_ref;
2322
2323         err = btrfs_interface_init();
2324         if (err)
2325                 goto free_end_io_wq;
2326
2327         btrfs_init_lockdep();
2328
2329         btrfs_print_info();
2330
2331         err = btrfs_run_sanity_tests();
2332         if (err)
2333                 goto unregister_ioctl;
2334
2335         err = register_filesystem(&btrfs_fs_type);
2336         if (err)
2337                 goto unregister_ioctl;
2338
2339         return 0;
2340
2341 unregister_ioctl:
2342         btrfs_interface_exit();
2343 free_end_io_wq:
2344         btrfs_end_io_wq_exit();
2345 free_prelim_ref:
2346         btrfs_prelim_ref_exit();
2347 free_delayed_ref:
2348         btrfs_delayed_ref_exit();
2349 free_auto_defrag:
2350         btrfs_auto_defrag_exit();
2351 free_delayed_inode:
2352         btrfs_delayed_inode_exit();
2353 free_ordered_data:
2354         ordered_data_exit();
2355 free_extent_map:
2356         extent_map_exit();
2357 free_extent_io:
2358         extent_io_exit();
2359 free_cachep:
2360         btrfs_destroy_cachep();
2361 free_compress:
2362         btrfs_exit_compress();
2363         btrfs_exit_sysfs();
2364 free_hash:
2365         btrfs_hash_exit();
2366         return err;
2367 }
2368
2369 static void __exit exit_btrfs_fs(void)
2370 {
2371         btrfs_destroy_cachep();
2372         btrfs_delayed_ref_exit();
2373         btrfs_auto_defrag_exit();
2374         btrfs_delayed_inode_exit();
2375         btrfs_prelim_ref_exit();
2376         ordered_data_exit();
2377         extent_map_exit();
2378         extent_io_exit();
2379         btrfs_interface_exit();
2380         btrfs_end_io_wq_exit();
2381         unregister_filesystem(&btrfs_fs_type);
2382         btrfs_exit_sysfs();
2383         btrfs_cleanup_fs_uuids();
2384         btrfs_exit_compress();
2385         btrfs_hash_exit();
2386 }
2387
2388 late_initcall(init_btrfs_fs);
2389 module_exit(exit_btrfs_fs)
2390
2391 MODULE_LICENSE("GPL");