btrfs-progs: Document logic of btrfs_read_dev_super
[platform/upstream/btrfs-progs.git] / cmds-fi-usage.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/ioctl.h>
22 #include <errno.h>
23 #include <stdarg.h>
24 #include <getopt.h>
25 #include <fcntl.h>
26
27 #include "utils.h"
28 #include "kerncompat.h"
29 #include "ctree.h"
30 #include "string-table.h"
31 #include "cmds-fi-usage.h"
32 #include "commands.h"
33 #include "disk-io.h"
34
35 #include "version.h"
36 #include "help.h"
37
38 /*
39  * Add the chunk info to the chunk_info list
40  */
41 static int add_info_to_list(struct chunk_info **info_ptr,
42                         int *info_count,
43                         struct btrfs_chunk *chunk)
44 {
45
46         u64 type = btrfs_stack_chunk_type(chunk);
47         u64 size = btrfs_stack_chunk_length(chunk);
48         int num_stripes = btrfs_stack_chunk_num_stripes(chunk);
49         int j;
50
51         for (j = 0 ; j < num_stripes ; j++) {
52                 int i;
53                 struct chunk_info *p = NULL;
54                 struct btrfs_stripe *stripe;
55                 u64    devid;
56
57                 stripe = btrfs_stripe_nr(chunk, j);
58                 devid = btrfs_stack_stripe_devid(stripe);
59
60                 for (i = 0 ; i < *info_count ; i++)
61                         if ((*info_ptr)[i].type == type &&
62                             (*info_ptr)[i].devid == devid &&
63                             (*info_ptr)[i].num_stripes == num_stripes ) {
64                                 p = (*info_ptr) + i;
65                                 break;
66                         }
67
68                 if (!p) {
69                         int tmp = sizeof(struct btrfs_chunk) * (*info_count + 1);
70                         struct chunk_info *res = realloc(*info_ptr, tmp);
71
72                         if (!res) {
73                                 free(*info_ptr);
74                                 error("not enough memory");
75                                 return -ENOMEM;
76                         }
77
78                         *info_ptr = res;
79                         p = res + *info_count;
80                         (*info_count)++;
81
82                         p->devid = devid;
83                         p->type = type;
84                         p->size = 0;
85                         p->num_stripes = num_stripes;
86                 }
87
88                 p->size += size;
89
90         }
91
92         return 0;
93
94 }
95
96 /*
97  *  Helper to sort the chunk type
98  */
99 static int cmp_chunk_block_group(u64 f1, u64 f2)
100 {
101
102         u64 mask;
103
104         if ((f1 & BTRFS_BLOCK_GROUP_TYPE_MASK) ==
105                 (f2 & BTRFS_BLOCK_GROUP_TYPE_MASK))
106                         mask = BTRFS_BLOCK_GROUP_PROFILE_MASK;
107         else if (f2 & BTRFS_BLOCK_GROUP_SYSTEM)
108                         return -1;
109         else if (f1 & BTRFS_BLOCK_GROUP_SYSTEM)
110                         return +1;
111         else
112                         mask = BTRFS_BLOCK_GROUP_TYPE_MASK;
113
114         if ((f1 & mask) > (f2 & mask))
115                 return +1;
116         else if ((f1 & mask) < (f2 & mask))
117                 return -1;
118         else
119                 return 0;
120 }
121
122 /*
123  * Helper to sort the chunk
124  */
125 static int cmp_chunk_info(const void *a, const void *b)
126 {
127         return cmp_chunk_block_group(
128                 ((struct chunk_info *)a)->type,
129                 ((struct chunk_info *)b)->type);
130 }
131
132 static int load_chunk_info(int fd, struct chunk_info **info_ptr, int *info_count)
133 {
134         int ret;
135         struct btrfs_ioctl_search_args args;
136         struct btrfs_ioctl_search_key *sk = &args.key;
137         struct btrfs_ioctl_search_header *sh;
138         unsigned long off = 0;
139         int i, e;
140
141         memset(&args, 0, sizeof(args));
142
143         /*
144          * there may be more than one ROOT_ITEM key if there are
145          * snapshots pending deletion, we have to loop through
146          * them.
147          */
148         sk->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
149
150         sk->min_objectid = 0;
151         sk->max_objectid = (u64)-1;
152         sk->max_type = 0;
153         sk->min_type = (u8)-1;
154         sk->min_offset = 0;
155         sk->max_offset = (u64)-1;
156         sk->min_transid = 0;
157         sk->max_transid = (u64)-1;
158         sk->nr_items = 4096;
159
160         while (1) {
161                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
162                 e = errno;
163                 if (e == EPERM)
164                         return -e;
165
166                 if (ret < 0) {
167                         error("cannot look up chunk tree info: %s",
168                                 strerror(e));
169                         return 1;
170                 }
171                 /* the ioctl returns the number of item it found in nr_items */
172
173                 if (sk->nr_items == 0)
174                         break;
175
176                 off = 0;
177                 for (i = 0; i < sk->nr_items; i++) {
178                         struct btrfs_chunk *item;
179                         sh = (struct btrfs_ioctl_search_header *)(args.buf +
180                                                                   off);
181
182                         off += sizeof(*sh);
183                         item = (struct btrfs_chunk *)(args.buf + off);
184
185                         ret = add_info_to_list(info_ptr, info_count, item);
186                         if (ret) {
187                                 *info_ptr = NULL;
188                                 return 1;
189                         }
190
191                         off += btrfs_search_header_len(sh);
192
193                         sk->min_objectid = btrfs_search_header_objectid(sh);
194                         sk->min_type = btrfs_search_header_type(sh);
195                         sk->min_offset = btrfs_search_header_offset(sh)+1;
196
197                 }
198                 if (!sk->min_offset)    /* overflow */
199                         sk->min_type++;
200                 else
201                         continue;
202
203                 if (!sk->min_type)
204                         sk->min_objectid++;
205                  else
206                         continue;
207
208                 if (!sk->min_objectid)
209                         break;
210         }
211
212         qsort(*info_ptr, *info_count, sizeof(struct chunk_info),
213                 cmp_chunk_info);
214
215         return 0;
216 }
217
218 /*
219  * Helper to sort the struct btrfs_ioctl_space_info
220  */
221 static int cmp_btrfs_ioctl_space_info(const void *a, const void *b)
222 {
223         return cmp_chunk_block_group(
224                 ((struct btrfs_ioctl_space_info *)a)->flags,
225                 ((struct btrfs_ioctl_space_info *)b)->flags);
226 }
227
228 /*
229  * This function load all the information about the space usage
230  */
231 static struct btrfs_ioctl_space_args *load_space_info(int fd, char *path)
232 {
233         struct btrfs_ioctl_space_args *sargs = NULL, *sargs_orig = NULL;
234         int ret, count;
235
236         sargs_orig = sargs = calloc(1, sizeof(struct btrfs_ioctl_space_args));
237         if (!sargs) {
238                 error("not enough memory");
239                 return NULL;
240         }
241
242         sargs->space_slots = 0;
243         sargs->total_spaces = 0;
244
245         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
246         if (ret < 0) {
247                 error("cannot get space info on '%s': %s", path,
248                         strerror(errno));
249                 free(sargs);
250                 return NULL;
251         }
252         if (!sargs->total_spaces) {
253                 free(sargs);
254                 printf("No chunks found\n");
255                 return NULL;
256         }
257
258         count = sargs->total_spaces;
259
260         sargs = realloc(sargs, sizeof(struct btrfs_ioctl_space_args) +
261                         (count * sizeof(struct btrfs_ioctl_space_info)));
262         if (!sargs) {
263                 free(sargs_orig);
264                 error("not enough memory");
265                 return NULL;
266         }
267
268         sargs->space_slots = count;
269         sargs->total_spaces = 0;
270
271         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
272         if (ret < 0) {
273                 error("cannot get space info with %u slots: %s",
274                         count, strerror(errno));
275                 free(sargs);
276                 return NULL;
277         }
278
279         qsort(&(sargs->spaces), count, sizeof(struct btrfs_ioctl_space_info),
280                 cmp_btrfs_ioctl_space_info);
281
282         return sargs;
283 }
284
285 /*
286  * This function computes the space occupied by a *single* RAID5/RAID6 chunk.
287  * The computation is performed on the basis of the number of stripes
288  * which compose the chunk, which could be different from the number of devices
289  * if a disk is added later.
290  */
291 static void get_raid56_used(struct chunk_info *chunks, int chunkcount,
292                 u64 *raid5_used, u64 *raid6_used)
293 {
294         struct chunk_info *info_ptr = chunks;
295         *raid5_used = 0;
296         *raid6_used = 0;
297
298         while (chunkcount-- > 0) {
299                 if (info_ptr->type & BTRFS_BLOCK_GROUP_RAID5)
300                         (*raid5_used) += info_ptr->size / (info_ptr->num_stripes - 1);
301                 if (info_ptr->type & BTRFS_BLOCK_GROUP_RAID6)
302                         (*raid6_used) += info_ptr->size / (info_ptr->num_stripes - 2);
303                 info_ptr++;
304         }
305 }
306
307 #define MIN_UNALOCATED_THRESH   SZ_16M
308 static int print_filesystem_usage_overall(int fd, struct chunk_info *chunkinfo,
309                 int chunkcount, struct device_info *devinfo, int devcount,
310                 char *path, unsigned unit_mode)
311 {
312         struct btrfs_ioctl_space_args *sargs = NULL;
313         int i;
314         int ret = 0;
315         int width = 10;         /* default 10 for human units */
316         /*
317          * r_* prefix is for raw data
318          * l_* is for logical
319          */
320         u64 r_total_size = 0;   /* filesystem size, sum of device sizes */
321         u64 r_total_chunks = 0; /* sum of chunks sizes on disk(s) */
322         u64 r_total_used = 0;
323         u64 r_total_unused = 0;
324         u64 r_total_missing = 0;        /* sum of missing devices size */
325         u64 r_data_used = 0;
326         u64 r_data_chunks = 0;
327         u64 l_data_chunks = 0;
328         u64 r_metadata_used = 0;
329         u64 r_metadata_chunks = 0;
330         u64 l_metadata_chunks = 0;
331         u64 r_system_used = 0;
332         u64 r_system_chunks = 0;
333         double data_ratio;
334         double metadata_ratio;
335         /* logical */
336         u64 raid5_used = 0;
337         u64 raid6_used = 0;
338         u64 l_global_reserve = 0;
339         u64 l_global_reserve_used = 0;
340         u64 free_estimated = 0;
341         u64 free_min = 0;
342         int max_data_ratio = 1;
343         int mixed = 0;
344
345         sargs = load_space_info(fd, path);
346         if (!sargs) {
347                 ret = 1;
348                 goto exit;
349         }
350
351         r_total_size = 0;
352         for (i = 0; i < devcount; i++) {
353                 r_total_size += devinfo[i].size;
354                 if (!devinfo[i].device_size)
355                         r_total_missing += devinfo[i].size;
356         }
357
358         if (r_total_size == 0) {
359                 error("cannot get space info on '%s': %s",
360                         path, strerror(errno));
361
362                 ret = 1;
363                 goto exit;
364         }
365         get_raid56_used(chunkinfo, chunkcount, &raid5_used, &raid6_used);
366
367         for (i = 0; i < sargs->total_spaces; i++) {
368                 int ratio;
369                 u64 flags = sargs->spaces[i].flags;
370
371                 /*
372                  * The raid5/raid6 ratio depends by the stripes number
373                  * used by every chunk. It is computed separately
374                  */
375                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
376                         ratio = 1;
377                 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
378                         ratio = 2;
379                 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
380                         ratio = 0;
381                 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
382                         ratio = 0;
383                 else if (flags & BTRFS_BLOCK_GROUP_DUP)
384                         ratio = 2;
385                 else if (flags & BTRFS_BLOCK_GROUP_RAID10)
386                         ratio = 2;
387                 else
388                         ratio = 1;
389
390                 if (!ratio)
391                         warning("RAID56 detected, not implemented");
392
393                 if (ratio > max_data_ratio)
394                         max_data_ratio = ratio;
395
396                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV) {
397                         l_global_reserve = sargs->spaces[i].total_bytes;
398                         l_global_reserve_used = sargs->spaces[i].used_bytes;
399                 }
400                 if ((flags & (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA))
401                     == (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA)) {
402                         mixed = 1;
403                 }
404                 if (flags & BTRFS_BLOCK_GROUP_DATA) {
405                         r_data_used += sargs->spaces[i].used_bytes * ratio;
406                         r_data_chunks += sargs->spaces[i].total_bytes * ratio;
407                         l_data_chunks += sargs->spaces[i].total_bytes;
408                 }
409                 if (flags & BTRFS_BLOCK_GROUP_METADATA) {
410                         r_metadata_used += sargs->spaces[i].used_bytes * ratio;
411                         r_metadata_chunks += sargs->spaces[i].total_bytes * ratio;
412                         l_metadata_chunks += sargs->spaces[i].total_bytes;
413                 }
414                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) {
415                         r_system_used += sargs->spaces[i].used_bytes * ratio;
416                         r_system_chunks += sargs->spaces[i].total_bytes * ratio;
417                 }
418         }
419
420         r_total_chunks = r_data_chunks + r_system_chunks;
421         r_total_used = r_data_used + r_system_used;
422         if (!mixed) {
423                 r_total_chunks += r_metadata_chunks;
424                 r_total_used += r_metadata_used;
425         }
426         r_total_unused = r_total_size - r_total_chunks;
427
428         /* Raw / Logical = raid factor, >= 1 */
429         data_ratio = (double)r_data_chunks / l_data_chunks;
430         if (mixed)
431                 metadata_ratio = data_ratio;
432         else
433                 metadata_ratio = (double)r_metadata_chunks / l_metadata_chunks;
434
435 #if 0
436         /* add the raid5/6 allocated space */
437         total_chunks += raid5_used + raid6_used;
438 #endif
439
440         /*
441          * We're able to fill at least DATA for the unused space
442          *
443          * With mixed raid levels, this gives a rough estimate but more
444          * accurate than just counting the logical free space
445          * (l_data_chunks - l_data_used)
446          *
447          * In non-mixed case there's no difference.
448          */
449         free_estimated = (r_data_chunks - r_data_used) / data_ratio;
450         /*
451          * For mixed-bg the metadata are left out in calculations thus global
452          * reserve would be lost. Part of it could be permanently allocated,
453          * we have to subtract the used bytes so we don't go under zero free.
454          */
455         if (mixed)
456                 free_estimated -= l_global_reserve - l_global_reserve_used;
457         free_min = free_estimated;
458
459         /* Chop unallocatable space */
460         /* FIXME: must be applied per device */
461         if (r_total_unused >= MIN_UNALOCATED_THRESH) {
462                 free_estimated += r_total_unused / data_ratio;
463                 /* Match the calculation of 'df', use the highest raid ratio */
464                 free_min += r_total_unused / max_data_ratio;
465         }
466
467         if (unit_mode != UNITS_HUMAN)
468                 width = 18;
469
470         printf("Overall:\n");
471
472         printf("    Device size:\t\t%*s\n", width,
473                 pretty_size_mode(r_total_size, unit_mode));
474         printf("    Device allocated:\t\t%*s\n", width,
475                 pretty_size_mode(r_total_chunks, unit_mode));
476         printf("    Device unallocated:\t\t%*s\n", width,
477                 pretty_size_mode(r_total_unused, unit_mode | UNITS_NEGATIVE));
478         printf("    Device missing:\t\t%*s\n", width,
479                 pretty_size_mode(r_total_missing, unit_mode));
480         printf("    Used:\t\t\t%*s\n", width,
481                 pretty_size_mode(r_total_used, unit_mode));
482         printf("    Free (estimated):\t\t%*s\t(",
483                 width,
484                 pretty_size_mode(free_estimated, unit_mode));
485         printf("min: %s)\n", pretty_size_mode(free_min, unit_mode));
486         printf("    Data ratio:\t\t\t%*.2f\n",
487                 width, data_ratio);
488         printf("    Metadata ratio:\t\t%*.2f\n",
489                 width, metadata_ratio);
490         printf("    Global reserve:\t\t%*s\t(used: %s)\n", width,
491                 pretty_size_mode(l_global_reserve, unit_mode),
492                 pretty_size_mode(l_global_reserve_used, unit_mode));
493
494 exit:
495
496         if (sargs)
497                 free(sargs);
498
499         return ret;
500 }
501
502 /*
503  *  Helper to sort the device_info structure
504  */
505 static int cmp_device_info(const void *a, const void *b)
506 {
507         return strcmp(((struct device_info *)a)->path,
508                         ((struct device_info *)b)->path);
509 }
510
511 int dev_to_fsid(const char *dev, u8 *fsid)
512 {
513         struct btrfs_super_block *disk_super;
514         char buf[BTRFS_SUPER_INFO_SIZE];
515         int ret;
516         int fd;
517
518         fd = open(dev, O_RDONLY);
519         if (fd < 0) {
520                 ret = -errno;
521                 return ret;
522         }
523
524         disk_super = (struct btrfs_super_block *)buf;
525         ret = btrfs_read_dev_super(fd, disk_super,
526                                    BTRFS_SUPER_INFO_OFFSET, SBREAD_DEFAULT);
527         if (ret)
528                 goto out;
529
530         memcpy(fsid, disk_super->fsid, BTRFS_FSID_SIZE);
531         ret = 0;
532
533 out:
534         close(fd);
535         return ret;
536 }
537
538 /*
539  *  This function loads the device_info structure and put them in an array
540  */
541 static int load_device_info(int fd, struct device_info **device_info_ptr,
542                            int *device_info_count)
543 {
544         int ret, i, ndevs;
545         struct btrfs_ioctl_fs_info_args fi_args;
546         struct btrfs_ioctl_dev_info_args dev_info;
547         struct device_info *info;
548         u8 fsid[BTRFS_UUID_SIZE];
549
550         *device_info_count = 0;
551         *device_info_ptr = NULL;
552
553         ret = ioctl(fd, BTRFS_IOC_FS_INFO, &fi_args);
554         if (ret < 0) {
555                 if (errno == EPERM)
556                         return -errno;
557                 error("cannot get filesystem info: %s",
558                                 strerror(errno));
559                 return 1;
560         }
561
562         info = calloc(fi_args.num_devices, sizeof(struct device_info));
563         if (!info) {
564                 error("not enough memory");
565                 return 1;
566         }
567
568         for (i = 0, ndevs = 0 ; i <= fi_args.max_id ; i++) {
569                 if (ndevs >= fi_args.num_devices) {
570                         error("unexpected number of devices: %d >= %llu", ndevs,
571                                 (unsigned long long)fi_args.num_devices);
572                         error(
573                 "if seed device is used, try running this command as root");
574                         goto out;
575                 }
576                 memset(&dev_info, 0, sizeof(dev_info));
577                 ret = get_device_info(fd, i, &dev_info);
578
579                 if (ret == -ENODEV)
580                         continue;
581                 if (ret) {
582                         error("cannot get info about device devid=%d", i);
583                         goto out;
584                 }
585
586                 /*
587                  * Skip seed device by checking device's fsid (requires root).
588                  * And we will skip only if dev_to_fsid is successful and dev
589                  * is a seed device.
590                  * Ignore any other error including -EACCES, which is seen when
591                  * a non-root process calls dev_to_fsid(path)->open(path).
592                  */
593                 ret = dev_to_fsid((const char *)dev_info.path, fsid);
594                 if (!ret && memcmp(fi_args.fsid, fsid, BTRFS_FSID_SIZE) != 0)
595                         continue;
596
597                 info[ndevs].devid = dev_info.devid;
598                 if (!dev_info.path[0]) {
599                         strcpy(info[ndevs].path, "missing");
600                 } else {
601                         strcpy(info[ndevs].path, (char *)dev_info.path);
602                         info[ndevs].device_size =
603                                 get_partition_size((char *)dev_info.path);
604                 }
605                 info[ndevs].size = dev_info.total_bytes;
606                 ++ndevs;
607         }
608
609         if (ndevs != fi_args.num_devices) {
610                 error("unexpected number of devices: %d != %llu", ndevs,
611                                 (unsigned long long)fi_args.num_devices);
612                 goto out;
613         }
614
615         qsort(info, fi_args.num_devices,
616                 sizeof(struct device_info), cmp_device_info);
617
618         *device_info_count = fi_args.num_devices;
619         *device_info_ptr = info;
620
621         return 0;
622
623 out:
624         free(info);
625         return ret;
626 }
627
628 int load_chunk_and_device_info(int fd, struct chunk_info **chunkinfo,
629                 int *chunkcount, struct device_info **devinfo, int *devcount)
630 {
631         int ret;
632
633         ret = load_chunk_info(fd, chunkinfo, chunkcount);
634         if (ret == -EPERM) {
635                 warning(
636 "cannot read detailed chunk info, RAID5/6 numbers will be incorrect, run as root");
637         } else if (ret) {
638                 return ret;
639         }
640
641         ret = load_device_info(fd, devinfo, devcount);
642         if (ret == -EPERM) {
643                 warning(
644                 "cannot get filesystem info from ioctl(FS_INFO), run as root");
645                 ret = 0;
646         }
647
648         return ret;
649 }
650
651 /*
652  *  This function computes the size of a chunk in a disk
653  */
654 static u64 calc_chunk_size(struct chunk_info *ci)
655 {
656         if (ci->type & BTRFS_BLOCK_GROUP_RAID0)
657                 return ci->size / ci->num_stripes;
658         else if (ci->type & BTRFS_BLOCK_GROUP_RAID1)
659                 return ci->size ;
660         else if (ci->type & BTRFS_BLOCK_GROUP_DUP)
661                 return ci->size ;
662         else if (ci->type & BTRFS_BLOCK_GROUP_RAID5)
663                 return ci->size / (ci->num_stripes -1);
664         else if (ci->type & BTRFS_BLOCK_GROUP_RAID6)
665                 return ci->size / (ci->num_stripes -2);
666         else if (ci->type & BTRFS_BLOCK_GROUP_RAID10)
667                 return ci->size / ci->num_stripes;
668         return ci->size;
669 }
670
671 /*
672  *  This function print the results of the command "btrfs fi usage"
673  *  in tabular format
674  */
675 static void _cmd_filesystem_usage_tabular(unsigned unit_mode,
676                                         struct btrfs_ioctl_space_args *sargs,
677                                         struct chunk_info *chunks_info_ptr,
678                                         int chunks_info_count,
679                                         struct device_info *device_info_ptr,
680                                         int device_info_count)
681 {
682         int i;
683         u64 total_unused = 0;
684         struct string_table *matrix = NULL;
685         int  ncols, nrows;
686         int col;
687         int unallocated_col;
688         int spaceinfos_col;
689         const int vhdr_skip = 3;        /* amount of vertical header space */
690
691         /* id, path, unallocated */
692         ncols = 3;
693         spaceinfos_col = 2;
694         /* Properly count the real space infos */
695         for (i = 0; i < sargs->total_spaces; i++) {
696                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
697                         continue;
698                 ncols++;
699         }
700
701         /* 2 for header, empty line, devices, ===, total, used */
702         nrows = vhdr_skip + device_info_count + 1 + 2;
703
704         matrix = table_create(ncols, nrows);
705         if (!matrix) {
706                 error("not enough memory");
707                 return;
708         }
709
710         /*
711          * We have to skip the global block reserve everywhere as it's an
712          * artificial blockgroup
713          */
714
715         /* header */
716         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
717                 u64 flags = sargs->spaces[i].flags;
718
719                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
720                         continue;
721
722                 table_printf(matrix, col, 0, "<%s",
723                                 btrfs_group_type_str(flags));
724                 table_printf(matrix, col, 1, "<%s",
725                                 btrfs_group_profile_str(flags));
726                 col++;
727         }
728         unallocated_col = col;
729
730         table_printf(matrix, 0, 1, "<Id");
731         table_printf(matrix, 1, 1, "<Path");
732         table_printf(matrix, unallocated_col, 1, "<Unallocated");
733
734         /* body */
735         for (i = 0; i < device_info_count; i++) {
736                 int k;
737                 char *p;
738
739                 u64  total_allocated = 0, unused;
740
741                 p = strrchr(device_info_ptr[i].path, '/');
742                 if (!p)
743                         p = device_info_ptr[i].path;
744                 else
745                         p++;
746
747                 table_printf(matrix, 0, vhdr_skip + i, ">%llu",
748                                 device_info_ptr[i].devid);
749                 table_printf(matrix, 1, vhdr_skip + i, "<%s",
750                                 device_info_ptr[i].path);
751
752                 for (col = spaceinfos_col, k = 0; k < sargs->total_spaces; k++) {
753                         u64     flags = sargs->spaces[k].flags;
754                         u64 devid = device_info_ptr[i].devid;
755                         int     j;
756                         u64 size = 0;
757
758                         if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
759                                 continue;
760
761                         for (j = 0 ; j < chunks_info_count ; j++) {
762                                 if (chunks_info_ptr[j].type != flags )
763                                                 continue;
764                                 if (chunks_info_ptr[j].devid != devid)
765                                                 continue;
766
767                                 size += calc_chunk_size(chunks_info_ptr+j);
768                         }
769
770                         if (size)
771                                 table_printf(matrix, col, vhdr_skip+ i,
772                                         ">%s", pretty_size_mode(size, unit_mode));
773                         else
774                                 table_printf(matrix, col, vhdr_skip + i, ">-");
775
776                         total_allocated += size;
777                         col++;
778                 }
779
780                 unused = get_partition_size(device_info_ptr[i].path)
781                                 - total_allocated;
782
783                 table_printf(matrix, unallocated_col, vhdr_skip + i, ">%s",
784                         pretty_size_mode(unused, unit_mode | UNITS_NEGATIVE));
785                 total_unused += unused;
786
787         }
788
789         for (i = 0; i < spaceinfos_col; i++) {
790                 table_printf(matrix, i, vhdr_skip - 1, "*-");
791                 table_printf(matrix, i, vhdr_skip + device_info_count, "*-");
792         }
793
794         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
795                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
796                         continue;
797
798                 table_printf(matrix, col, vhdr_skip - 1, "*-");
799                 table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
800                 col++;
801         }
802         /* One for Unallocated */
803         table_printf(matrix, col, vhdr_skip - 1, "*-");
804         table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
805
806         /* footer */
807         table_printf(matrix, 1, vhdr_skip + device_info_count + 1, "<Total");
808         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
809                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
810                         continue;
811
812                 table_printf(matrix, col++, vhdr_skip + device_info_count + 1,
813                         ">%s",
814                         pretty_size_mode(sargs->spaces[i].total_bytes, unit_mode));
815         }
816
817         table_printf(matrix, unallocated_col, vhdr_skip + device_info_count + 1,
818                 ">%s",
819                 pretty_size_mode(total_unused, unit_mode | UNITS_NEGATIVE));
820
821         table_printf(matrix, 1, vhdr_skip + device_info_count + 2, "<Used");
822         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
823                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
824                         continue;
825
826                 table_printf(matrix, col++, vhdr_skip + device_info_count + 2,
827                         ">%s",
828                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
829         }
830
831         table_dump(matrix);
832         table_free(matrix);
833 }
834
835 /*
836  *  This function prints the unused space per every disk
837  */
838 static void print_unused(struct chunk_info *info_ptr,
839                           int info_count,
840                           struct device_info *device_info_ptr,
841                           int device_info_count,
842                           unsigned unit_mode)
843 {
844         int i;
845         for (i = 0; i < device_info_count; i++) {
846                 int     j;
847                 u64     total = 0;
848
849                 for (j = 0; j < info_count; j++)
850                         if (info_ptr[j].devid == device_info_ptr[i].devid)
851                                 total += calc_chunk_size(info_ptr+j);
852
853                 printf("   %s\t%10s\n",
854                         device_info_ptr[i].path,
855                         pretty_size_mode(device_info_ptr[i].size - total,
856                                 unit_mode));
857         }
858 }
859
860 /*
861  *  This function prints the allocated chunk per every disk
862  */
863 static void print_chunk_device(u64 chunk_type,
864                                 struct chunk_info *chunks_info_ptr,
865                                 int chunks_info_count,
866                                 struct device_info *device_info_ptr,
867                                 int device_info_count,
868                                 unsigned unit_mode)
869 {
870         int i;
871
872         for (i = 0; i < device_info_count; i++) {
873                 int     j;
874                 u64     total = 0;
875
876                 for (j = 0; j < chunks_info_count; j++) {
877
878                         if (chunks_info_ptr[j].type != chunk_type)
879                                 continue;
880                         if (chunks_info_ptr[j].devid != device_info_ptr[i].devid)
881                                 continue;
882
883                         total += calc_chunk_size(&(chunks_info_ptr[j]));
884                         //total += chunks_info_ptr[j].size;
885                 }
886
887                 if (total > 0)
888                         printf("   %s\t%10s\n",
889                                 device_info_ptr[i].path,
890                                 pretty_size_mode(total, unit_mode));
891         }
892 }
893
894 /*
895  *  This function print the results of the command "btrfs fi usage"
896  *  in linear format
897  */
898 static void _cmd_filesystem_usage_linear(unsigned unit_mode,
899                                         struct btrfs_ioctl_space_args *sargs,
900                                         struct chunk_info *info_ptr,
901                                         int info_count,
902                                         struct device_info *device_info_ptr,
903                                         int device_info_count)
904 {
905         int i;
906
907         for (i = 0; i < sargs->total_spaces; i++) {
908                 const char *description;
909                 const char *r_mode;
910                 u64 flags = sargs->spaces[i].flags;
911
912                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
913                         continue;
914
915                 description = btrfs_group_type_str(flags);
916                 r_mode = btrfs_group_profile_str(flags);
917
918                 printf("%s,%s: Size:%s, ",
919                         description,
920                         r_mode,
921                         pretty_size_mode(sargs->spaces[i].total_bytes,
922                                 unit_mode));
923                 printf("Used:%s\n",
924                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
925                 print_chunk_device(flags, info_ptr, info_count,
926                                 device_info_ptr, device_info_count, unit_mode);
927                 printf("\n");
928         }
929
930         printf("Unallocated:\n");
931         print_unused(info_ptr, info_count, device_info_ptr, device_info_count,
932                         unit_mode | UNITS_NEGATIVE);
933 }
934
935 static int print_filesystem_usage_by_chunk(int fd,
936                 struct chunk_info *chunkinfo, int chunkcount,
937                 struct device_info *devinfo, int devcount,
938                 char *path, unsigned unit_mode, int tabular)
939 {
940         struct btrfs_ioctl_space_args *sargs;
941         int ret = 0;
942
943         if (!chunkinfo)
944                 return 0;
945
946         sargs = load_space_info(fd, path);
947         if (!sargs) {
948                 ret = 1;
949                 goto out;
950         }
951
952         if (tabular)
953                 _cmd_filesystem_usage_tabular(unit_mode, sargs, chunkinfo,
954                                 chunkcount, devinfo, devcount);
955         else
956                 _cmd_filesystem_usage_linear(unit_mode, sargs, chunkinfo,
957                                 chunkcount, devinfo, devcount);
958
959         free(sargs);
960 out:
961         return ret;
962 }
963
964 const char * const cmd_filesystem_usage_usage[] = {
965         "btrfs filesystem usage [options] <path> [<path>..]",
966         "Show detailed information about internal filesystem usage .",
967         HELPINFO_UNITS_SHORT_LONG,
968         "-T                 show data in tabular format",
969         NULL
970 };
971
972 int cmd_filesystem_usage(int argc, char **argv)
973 {
974         int ret = 0;
975         unsigned unit_mode;
976         int i;
977         int more_than_one = 0;
978         int tabular = 0;
979
980         unit_mode = get_unit_mode_from_arg(&argc, argv, 1);
981
982         while (1) {
983                 int c;
984
985                 c = getopt(argc, argv, "T");
986                 if (c < 0)
987                         break;
988
989                 switch (c) {
990                 case 'T':
991                         tabular = 1;
992                         break;
993                 default:
994                         usage(cmd_filesystem_usage_usage);
995                 }
996         }
997
998         if (check_argc_min(argc - optind, 1))
999                 usage(cmd_filesystem_usage_usage);
1000
1001         for (i = optind; i < argc; i++) {
1002                 int fd;
1003                 DIR *dirstream = NULL;
1004                 struct chunk_info *chunkinfo = NULL;
1005                 struct device_info *devinfo = NULL;
1006                 int chunkcount = 0;
1007                 int devcount = 0;
1008
1009                 fd = btrfs_open_dir(argv[i], &dirstream, 1);
1010                 if (fd < 0) {
1011                         ret = 1;
1012                         goto out;
1013                 }
1014                 if (more_than_one)
1015                         printf("\n");
1016
1017                 ret = load_chunk_and_device_info(fd, &chunkinfo, &chunkcount,
1018                                 &devinfo, &devcount);
1019                 if (ret)
1020                         goto cleanup;
1021
1022                 ret = print_filesystem_usage_overall(fd, chunkinfo, chunkcount,
1023                                 devinfo, devcount, argv[i], unit_mode);
1024                 if (ret)
1025                         goto cleanup;
1026                 printf("\n");
1027                 ret = print_filesystem_usage_by_chunk(fd, chunkinfo, chunkcount,
1028                                 devinfo, devcount, argv[i], unit_mode, tabular);
1029 cleanup:
1030                 close_file_or_dir(fd, dirstream);
1031                 free(chunkinfo);
1032                 free(devinfo);
1033
1034                 if (ret)
1035                         goto out;
1036                 more_than_one = 1;
1037         }
1038
1039 out:
1040         return !!ret;
1041 }
1042
1043 void print_device_chunks(struct device_info *devinfo,
1044                 struct chunk_info *chunks_info_ptr,
1045                 int chunks_info_count, unsigned unit_mode)
1046 {
1047         int i;
1048         u64 allocated = 0;
1049
1050         for (i = 0 ; i < chunks_info_count ; i++) {
1051                 const char *description;
1052                 const char *r_mode;
1053                 u64 flags;
1054                 u64 size;
1055
1056                 if (chunks_info_ptr[i].devid != devinfo->devid)
1057                         continue;
1058
1059                 flags = chunks_info_ptr[i].type;
1060
1061                 description = btrfs_group_type_str(flags);
1062                 r_mode = btrfs_group_profile_str(flags);
1063                 size = calc_chunk_size(chunks_info_ptr+i);
1064                 printf("   %s,%s:%*s%10s\n",
1065                         description,
1066                         r_mode,
1067                         (int)(20 - strlen(description) - strlen(r_mode)), "",
1068                         pretty_size_mode(size, unit_mode));
1069
1070                 allocated += size;
1071
1072         }
1073         printf("   Unallocated: %*s%10s\n",
1074                 (int)(20 - strlen("Unallocated")), "",
1075                 pretty_size_mode(devinfo->size - allocated,
1076                         unit_mode | UNITS_NEGATIVE));
1077 }
1078
1079 void print_device_sizes(struct device_info *devinfo, unsigned unit_mode)
1080 {
1081         printf("   Device size: %*s%10s\n",
1082                 (int)(20 - strlen("Device size")), "",
1083                 pretty_size_mode(devinfo->device_size, unit_mode));
1084         printf("   Device slack: %*s%10s\n",
1085                 (int)(20 - strlen("Device slack")), "",
1086                 pretty_size_mode(devinfo->device_size > 0 ?
1087                         devinfo->device_size - devinfo->size : 0,
1088                         unit_mode));
1089 }