]> git.sesse.net Git - bcachefs-tools-debian/blob - cmd_fusemount.c
Implement basic fuse mount tests.
[bcachefs-tools-debian] / cmd_fusemount.c
1 #include <errno.h>
2 #include <float.h>
3 #include <getopt.h>
4 #include <stdio.h>
5 #include <sys/statvfs.h>
6
7 #include <fuse_lowlevel.h>
8
9 #include "cmds.h"
10 #include "libbcachefs.h"
11 #include "tools-util.h"
12
13 #include "libbcachefs/bcachefs.h"
14 #include "libbcachefs/alloc_foreground.h"
15 #include "libbcachefs/btree_iter.h"
16 #include "libbcachefs/buckets.h"
17 #include "libbcachefs/dirent.h"
18 #include "libbcachefs/error.h"
19 #include "libbcachefs/fs-common.h"
20 #include "libbcachefs/inode.h"
21 #include "libbcachefs/io.h"
22 #include "libbcachefs/opts.h"
23 #include "libbcachefs/super.h"
24
25 /* mode_to_type(): */
26 #include "libbcachefs/fs.h"
27
28 #include <linux/dcache.h>
29
30 /* XXX cut and pasted from fsck.c */
31 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
32
33 static inline u64 map_root_ino(u64 ino)
34 {
35         return ino == 1 ? 4096 : ino;
36 }
37
38 static inline u64 unmap_root_ino(u64 ino)
39 {
40         return ino == 4096 ? 1 : ino;
41 }
42
43 static struct stat inode_to_stat(struct bch_fs *c,
44                                  struct bch_inode_unpacked *bi)
45 {
46         return (struct stat) {
47                 .st_ino         = unmap_root_ino(bi->bi_inum),
48                 .st_size        = bi->bi_size,
49                 .st_mode        = bi->bi_mode,
50                 .st_uid         = bi->bi_uid,
51                 .st_gid         = bi->bi_gid,
52                 .st_nlink       = bch2_inode_nlink_get(bi),
53                 .st_rdev        = bi->bi_dev,
54                 .st_blksize     = block_bytes(c),
55                 .st_blocks      = bi->bi_sectors,
56                 .st_atim        = bch2_time_to_timespec(c, bi->bi_atime),
57                 .st_mtim        = bch2_time_to_timespec(c, bi->bi_mtime),
58                 .st_ctim        = bch2_time_to_timespec(c, bi->bi_ctime),
59         };
60 }
61
62 static struct fuse_entry_param inode_to_entry(struct bch_fs *c,
63                                               struct bch_inode_unpacked *bi)
64 {
65         return (struct fuse_entry_param) {
66                 .ino            = unmap_root_ino(bi->bi_inum),
67                 .generation     = bi->bi_generation,
68                 .attr           = inode_to_stat(c, bi),
69                 .attr_timeout   = DBL_MAX,
70                 .entry_timeout  = DBL_MAX,
71         };
72 }
73
74 static void bcachefs_fuse_init(void *arg, struct fuse_conn_info *conn)
75 {
76         if (conn->capable & FUSE_CAP_WRITEBACK_CACHE) {
77                 fuse_log(FUSE_LOG_DEBUG, "fuse_init: activating writeback\n");
78                 conn->want |= FUSE_CAP_WRITEBACK_CACHE;
79         } else
80                 fuse_log(FUSE_LOG_DEBUG, "fuse_init: writeback not capable\n");
81
82         //conn->want |= FUSE_CAP_POSIX_ACL;
83 }
84
85 static void bcachefs_fuse_destroy(void *arg)
86 {
87         struct bch_fs *c = arg;
88
89         bch2_fs_stop(c);
90 }
91
92 static void bcachefs_fuse_lookup(fuse_req_t req, fuse_ino_t dir,
93                                  const char *name)
94 {
95         struct bch_fs *c = fuse_req_userdata(req);
96         struct bch_inode_unpacked bi;
97         struct qstr qstr = QSTR(name);
98         u64 inum;
99         int ret;
100
101         fuse_log(FUSE_LOG_DEBUG, "fuse_lookup(dir=%llu name=%s)\n",
102                  dir, name);
103
104         dir = map_root_ino(dir);
105
106         ret = bch2_inode_find_by_inum(c, dir, &bi);
107         if (ret) {
108                 fuse_reply_err(req, -ret);
109                 return;
110         }
111
112         struct bch_hash_info hash_info = bch2_hash_info_init(c, &bi);
113
114         inum = bch2_dirent_lookup(c, dir, &hash_info, &qstr);
115         if (!inum) {
116                 struct fuse_entry_param e = {
117                         .attr_timeout   = DBL_MAX,
118                         .entry_timeout  = DBL_MAX,
119                 };
120                 fuse_reply_entry(req, &e);
121                 return;
122         }
123
124         ret = bch2_inode_find_by_inum(c, inum, &bi);
125         if (ret)
126                 goto err;
127
128         fuse_log(FUSE_LOG_DEBUG, "fuse_lookup ret(inum=%llu)\n",
129                  bi.bi_inum);
130
131         struct fuse_entry_param e = inode_to_entry(c, &bi);
132         fuse_reply_entry(req, &e);
133         return;
134 err:
135         fuse_log(FUSE_LOG_DEBUG, "fuse_lookup error %i\n", ret);
136         fuse_reply_err(req, -ret);
137 }
138
139 static void bcachefs_fuse_getattr(fuse_req_t req, fuse_ino_t inum,
140                                   struct fuse_file_info *fi)
141 {
142         struct bch_fs *c = fuse_req_userdata(req);
143         struct bch_inode_unpacked bi;
144         struct stat attr;
145         int ret;
146
147         fuse_log(FUSE_LOG_DEBUG, "fuse_getattr(inum=%llu)\n",
148                  inum);
149
150         inum = map_root_ino(inum);
151
152         ret = bch2_inode_find_by_inum(c, inum, &bi);
153         if (ret) {
154                 fuse_log(FUSE_LOG_DEBUG, "fuse_getattr error %i\n", ret);
155                 fuse_reply_err(req, -ret);
156                 return;
157         }
158
159         fuse_log(FUSE_LOG_DEBUG, "fuse_getattr success\n");
160
161         attr = inode_to_stat(c, &bi);
162         fuse_reply_attr(req, &attr, DBL_MAX);
163 }
164
165 static void bcachefs_fuse_setattr(fuse_req_t req, fuse_ino_t inum,
166                                   struct stat *attr, int to_set,
167                                   struct fuse_file_info *fi)
168 {
169         struct bch_fs *c = fuse_req_userdata(req);
170         struct bch_inode_unpacked inode_u;
171         struct btree_trans trans;
172         struct btree_iter *iter;
173         u64 now;
174         int ret;
175
176         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_setattr(%llu, %x)\n",
177                  inum, to_set);
178
179         inum = map_root_ino(inum);
180
181         bch2_trans_init(&trans, c, 0, 0);
182 retry:
183         bch2_trans_begin(&trans);
184         now = bch2_current_time(c);
185
186         iter = bch2_inode_peek(&trans, &inode_u, inum, BTREE_ITER_INTENT);
187         ret = PTR_ERR_OR_ZERO(iter);
188         if (ret)
189                 goto err;
190
191         if (to_set & FUSE_SET_ATTR_MODE)
192                 inode_u.bi_mode = attr->st_mode;
193         if (to_set & FUSE_SET_ATTR_UID)
194                 inode_u.bi_uid  = attr->st_uid;
195         if (to_set & FUSE_SET_ATTR_GID)
196                 inode_u.bi_gid  = attr->st_gid;
197         if (to_set & FUSE_SET_ATTR_SIZE)
198                 inode_u.bi_size = attr->st_size;
199         if (to_set & FUSE_SET_ATTR_ATIME)
200                 inode_u.bi_atime = timespec_to_bch2_time(c, attr->st_atim);
201         if (to_set & FUSE_SET_ATTR_MTIME)
202                 inode_u.bi_mtime = timespec_to_bch2_time(c, attr->st_mtim);
203         if (to_set & FUSE_SET_ATTR_ATIME_NOW)
204                 inode_u.bi_atime = now;
205         if (to_set & FUSE_SET_ATTR_MTIME_NOW)
206                 inode_u.bi_mtime = now;
207         /* TODO: CTIME? */
208
209         ret   = bch2_inode_write(&trans, iter, &inode_u) ?:
210                 bch2_trans_commit(&trans, NULL, NULL,
211                                   BTREE_INSERT_ATOMIC|
212                                   BTREE_INSERT_NOFAIL);
213 err:
214         if (ret == -EINTR)
215                 goto retry;
216
217         bch2_trans_exit(&trans);
218
219         if (!ret) {
220                 *attr = inode_to_stat(c, &inode_u);
221                 fuse_reply_attr(req, attr, DBL_MAX);
222         } else {
223                 fuse_reply_err(req, -ret);
224         }
225 }
226
227 static int do_create(struct bch_fs *c, u64 dir,
228                      const char *name, mode_t mode, dev_t rdev,
229                      struct bch_inode_unpacked *new_inode)
230 {
231         struct qstr qstr = QSTR(name);
232         struct bch_inode_unpacked dir_u;
233
234         dir = map_root_ino(dir);
235
236         bch2_inode_init_early(c, new_inode);
237
238         return bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC,
239                         bch2_create_trans(&trans,
240                                 dir, &dir_u,
241                                 new_inode, &qstr,
242                                 0, 0, mode, rdev, NULL, NULL));
243 }
244
245 static void bcachefs_fuse_mknod(fuse_req_t req, fuse_ino_t dir,
246                                 const char *name, mode_t mode,
247                                 dev_t rdev)
248 {
249         struct bch_fs *c = fuse_req_userdata(req);
250         struct bch_inode_unpacked new_inode;
251         int ret;
252
253         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_mknod(%llu, %s, %x, %x)\n",
254                  dir, name, mode, rdev);
255         ret = do_create(c, dir, name, mode, rdev, &new_inode);
256         if (ret)
257                 goto err;
258
259         struct fuse_entry_param e = inode_to_entry(c, &new_inode);
260         fuse_reply_entry(req, &e);
261         return;
262 err:
263         fuse_reply_err(req, -ret);
264 }
265
266 static void bcachefs_fuse_mkdir(fuse_req_t req, fuse_ino_t dir,
267                                 const char *name, mode_t mode)
268 {
269         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_mkdir(%llu, %s, %x)\n",
270                  dir, name, mode);
271
272         BUG_ON(mode & S_IFMT);
273
274         mode |= S_IFDIR;
275         bcachefs_fuse_mknod(req, dir, name, mode, 0);
276 }
277
278 static void bcachefs_fuse_unlink(fuse_req_t req, fuse_ino_t dir,
279                                  const char *name)
280 {
281         struct bch_fs *c = fuse_req_userdata(req);
282         struct bch_inode_unpacked dir_u, inode_u;
283         struct qstr qstr = QSTR(name);
284         int ret;
285
286         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_unlink(%llu, %s)\n", dir, name);
287
288         dir = map_root_ino(dir);
289
290         ret = bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC|BTREE_INSERT_NOFAIL,
291                             bch2_unlink_trans(&trans, dir, &dir_u,
292                                               &inode_u, &qstr));
293
294         fuse_reply_err(req, -ret);
295 }
296
297 static void bcachefs_fuse_rmdir(fuse_req_t req, fuse_ino_t dir,
298                                 const char *name)
299 {
300         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_rmdir(%llu, %s)\n", dir, name);
301
302         dir = map_root_ino(dir);
303
304         bcachefs_fuse_unlink(req, dir, name);
305 }
306
307 static void bcachefs_fuse_rename(fuse_req_t req,
308                                  fuse_ino_t src_dir, const char *srcname,
309                                  fuse_ino_t dst_dir, const char *dstname,
310                                  unsigned flags)
311 {
312         struct bch_fs *c = fuse_req_userdata(req);
313         struct bch_inode_unpacked dst_dir_u, src_dir_u;
314         struct bch_inode_unpacked src_inode_u, dst_inode_u;
315         struct qstr dst_name = QSTR(srcname);
316         struct qstr src_name = QSTR(dstname);
317         int ret;
318
319         fuse_log(FUSE_LOG_DEBUG,
320                  "bcachefs_fuse_rename(%llu, %s, %llu, %s, %x)\n",
321                  src_dir, srcname, dst_dir, dstname, flags);
322
323         src_dir = map_root_ino(src_dir);
324         dst_dir = map_root_ino(dst_dir);
325
326         /* XXX handle overwrites */
327         ret = bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC,
328                 bch2_rename_trans(&trans,
329                                   src_dir, &src_dir_u,
330                                   dst_dir, &dst_dir_u,
331                                   &src_inode_u, &dst_inode_u,
332                                   &src_name, &dst_name,
333                                   BCH_RENAME));
334
335         fuse_reply_err(req, -ret);
336 }
337
338 static void bcachefs_fuse_link(fuse_req_t req, fuse_ino_t inum,
339                                fuse_ino_t newparent, const char *newname)
340 {
341         struct bch_fs *c = fuse_req_userdata(req);
342         struct bch_inode_unpacked inode_u;
343         struct qstr qstr = QSTR(newname);
344         int ret;
345
346         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_link(%llu, %llu, %s)\n",
347                  inum, newparent, newname);
348
349         newparent = map_root_ino(newparent);
350
351         ret = bch2_trans_do(c, NULL, BTREE_INSERT_ATOMIC,
352                             bch2_link_trans(&trans, newparent,
353                                             inum, &inode_u, &qstr));
354
355         if (!ret) {
356                 struct fuse_entry_param e = inode_to_entry(c, &inode_u);
357                 fuse_reply_entry(req, &e);
358         } else {
359                 fuse_reply_err(req, -ret);
360         }
361 }
362
363 static void bcachefs_fuse_open(fuse_req_t req, fuse_ino_t inum,
364                                struct fuse_file_info *fi)
365 {
366         fi->direct_io           = false;
367         fi->keep_cache          = true;
368         fi->cache_readdir       = true;
369
370         fuse_reply_open(req, fi);
371 }
372
373 static void userbio_init(struct bio *bio, struct bio_vec *bv,
374                          void *buf, size_t size)
375 {
376         bio_init(bio, bv, 1);
377         bio->bi_iter.bi_size    = size;
378         bv->bv_page             = buf;
379         bv->bv_len              = size;
380         bv->bv_offset           = 0;
381 }
382
383 static int get_inode_io_opts(struct bch_fs *c, u64 inum,
384                              struct bch_io_opts *opts)
385 {
386         struct bch_inode_unpacked inode;
387         if (bch2_inode_find_by_inum(c, inum, &inode))
388                 return -EINVAL;
389
390         *opts = bch2_opts_to_inode_opts(c->opts);
391         bch2_io_opts_apply(opts, bch2_inode_opts_get(&inode));
392         return 0;
393 }
394
395 static void bcachefs_fuse_read_endio(struct bio *bio)
396 {
397         closure_put(bio->bi_private);
398 }
399
400 struct fuse_align_io {
401         off_t           start;
402         size_t          pad_start;
403         off_t           end;
404         size_t          pad_end;
405         size_t          size;
406 };
407
408 /* Handle unaligned start and end */
409 /* TODO: align to block_bytes, sector size, or page size? */
410 static struct fuse_align_io align_io(const struct bch_fs *c, size_t size,
411                                      off_t offset)
412 {
413         struct fuse_align_io align;
414
415         BUG_ON(offset < 0);
416
417         align.start = round_down(offset, block_bytes(c));
418         align.pad_start = offset - align.start;
419
420         off_t end = offset + size;
421         align.end = round_up(end, block_bytes(c));
422         align.pad_end = align.end - end;
423
424         align.size = align.end - align.start;
425
426         return align;
427 }
428
429 /*
430  * Given an aligned number of bytes transferred, figure out how many unaligned
431  * bytes were transferred.
432  */
433 static size_t align_fix_up_bytes(const struct fuse_align_io *align,
434                                  size_t align_bytes)
435 {
436         size_t bytes = 0;
437
438         if (align_bytes > align->pad_start) {
439                 bytes = align_bytes - align->pad_start;
440                 bytes = bytes > align->pad_end ? bytes - align->pad_end : 0;
441         }
442
443         return bytes;
444 }
445
446 /*
447  * Read aligned data.
448  */
449 static int read_aligned(struct bch_fs *c, fuse_ino_t inum, size_t aligned_size,
450                         off_t aligned_offset, void *buf)
451 {
452         BUG_ON(aligned_size & (block_bytes(c) - 1));
453         BUG_ON(aligned_offset & (block_bytes(c) - 1));
454
455         struct bch_io_opts io_opts;
456         if (get_inode_io_opts(c, inum, &io_opts))
457                 return -ENOENT;
458
459         struct bch_read_bio rbio;
460         struct bio_vec bv;
461         userbio_init(&rbio.bio, &bv, buf, aligned_size);
462         bio_set_op_attrs(&rbio.bio, REQ_OP_READ, REQ_SYNC);
463         rbio.bio.bi_iter.bi_sector      = aligned_offset >> 9;
464
465         struct closure cl;
466         closure_init_stack(&cl);
467
468         closure_get(&cl);
469         rbio.bio.bi_end_io              = bcachefs_fuse_read_endio;
470         rbio.bio.bi_private             = &cl;
471
472         bch2_read(c, rbio_init(&rbio.bio, io_opts), inum);
473
474         closure_sync(&cl);
475
476         return -blk_status_to_errno(rbio.bio.bi_status);
477 }
478
479 static void bcachefs_fuse_read(fuse_req_t req, fuse_ino_t inum,
480                                size_t size, off_t offset,
481                                struct fuse_file_info *fi)
482 {
483         struct bch_fs *c = fuse_req_userdata(req);
484
485         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_read(%llu, %zd, %lld)\n",
486                  inum, size, offset);
487
488         /* Check inode size. */
489         struct bch_inode_unpacked bi;
490         int ret = bch2_inode_find_by_inum(c, inum, &bi);
491         if (ret) {
492                 fuse_reply_err(req, -ret);
493                 return;
494         }
495
496         off_t end = min_t(u64, bi.bi_size, offset + size);
497         if (end <= offset) {
498                 fuse_reply_buf(req, NULL, 0);
499                 return;
500         }
501         size = end - offset;
502
503         struct fuse_align_io align = align_io(c, size, offset);
504
505         void *buf = aligned_alloc(PAGE_SIZE, align.size);
506         if (!buf) {
507                 fuse_reply_err(req, ENOMEM);
508                 return;
509         }
510
511         ret = read_aligned(c, inum, align.size, align.start, buf);
512
513         if (likely(!ret))
514                 fuse_reply_buf(req, buf + align.pad_start, size);
515         else
516                 fuse_reply_err(req, -ret);
517
518         free(buf);
519 }
520
521 static int inode_update_times(struct bch_fs *c, fuse_ino_t inum)
522 {
523         struct btree_trans trans;
524         struct btree_iter *iter;
525         struct bch_inode_unpacked inode_u;
526         int ret = 0;
527         u64 now;
528
529         bch2_trans_init(&trans, c, 0, 0);
530 retry:
531         bch2_trans_begin(&trans);
532         now = bch2_current_time(c);
533
534         iter = bch2_inode_peek(&trans, &inode_u, inum, BTREE_ITER_INTENT);
535         ret = PTR_ERR_OR_ZERO(iter);
536         if (ret)
537                 goto err;
538
539         inode_u.bi_mtime = now;
540         inode_u.bi_ctime = now;
541
542         ret = bch2_inode_write(&trans, iter, &inode_u);
543         if (ret)
544                 goto err;
545
546         ret = bch2_trans_commit(&trans, NULL, NULL,
547                                 BTREE_INSERT_ATOMIC|BTREE_INSERT_NOFAIL);
548
549 err:
550         if (ret == -EINTR)
551                 goto retry;
552
553         bch2_trans_exit(&trans);
554         return ret;
555 }
556
557 static int write_aligned(struct bch_fs *c, fuse_ino_t inum,
558                          struct bch_io_opts io_opts, void *buf,
559                          size_t aligned_size, off_t aligned_offset,
560                          off_t new_i_size, size_t *written_out)
561 {
562         struct bch_write_op     op = { 0 };
563         struct bio_vec          bv;
564         struct closure          cl;
565
566         BUG_ON(aligned_size & (block_bytes(c) - 1));
567         BUG_ON(aligned_offset & (block_bytes(c) - 1));
568
569         *written_out = 0;
570
571         closure_init_stack(&cl);
572
573         bch2_write_op_init(&op, c, io_opts); /* XXX reads from op?! */
574         op.write_point  = writepoint_hashed(0);
575         op.nr_replicas  = io_opts.data_replicas;
576         op.target       = io_opts.foreground_target;
577         op.pos          = POS(inum, aligned_offset >> 9);
578         op.new_i_size   = new_i_size;
579
580         userbio_init(&op.wbio.bio, &bv, buf, aligned_size);
581         bio_set_op_attrs(&op.wbio.bio, REQ_OP_WRITE, REQ_SYNC);
582
583         if (bch2_disk_reservation_get(c, &op.res, aligned_size >> 9,
584                                       op.nr_replicas, 0)) {
585                 /* XXX: use check_range_allocated like dio write path */
586                 return -ENOSPC;
587         }
588
589         closure_call(&op.cl, bch2_write, NULL, &cl);
590         closure_sync(&cl);
591
592         if (!op.error)
593                 *written_out = op.written << 9;
594
595         return op.error;
596 }
597
598 static void bcachefs_fuse_write(fuse_req_t req, fuse_ino_t inum,
599                                 const char *buf, size_t size,
600                                 off_t offset,
601                                 struct fuse_file_info *fi)
602 {
603         struct bch_fs *c        = fuse_req_userdata(req);
604         struct bch_io_opts      io_opts;
605         size_t                  aligned_written;
606         int                     ret = 0;
607
608         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_write(%llu, %zd, %lld)\n",
609                  inum, size, offset);
610
611         struct fuse_align_io align = align_io(c, size, offset);
612         void *aligned_buf = aligned_alloc(PAGE_SIZE, align.size);
613         BUG_ON(!aligned_buf);
614
615         if (get_inode_io_opts(c, inum, &io_opts)) {
616                 ret = -ENOENT;
617                 goto err;
618         }
619
620         /* Realign the data and read in start and end, if needed */
621
622         /* Read partial start data. */
623         if (align.pad_start) {
624                 memset(aligned_buf, 0, block_bytes(c));
625
626                 ret = read_aligned(c, inum, block_bytes(c), align.start,
627                                    aligned_buf);
628                 if (ret)
629                         goto err;
630         }
631
632         /*
633          * Read partial end data. If the whole write fits in one block, the
634          * start data and the end data are the same so this isn't needed.
635          */
636         if (align.pad_end &&
637             !(align.pad_start && align.size == block_bytes(c))) {
638                 off_t partial_end_start = align.end - block_bytes(c);
639                 size_t buf_offset = align.size - block_bytes(c);
640
641                 memset(aligned_buf + buf_offset, 0, block_bytes(c));
642
643                 ret = read_aligned(c, inum, block_bytes(c), partial_end_start,
644                                    aligned_buf + buf_offset);
645                 if (ret)
646                         goto err;
647         }
648
649         /* Overlay what we want to write. */
650         memcpy(aligned_buf + align.pad_start, buf, size);
651
652         /* Actually write. */
653         ret = write_aligned(c, inum, io_opts, aligned_buf,
654                             align.size, align.start,
655                             offset + size, &aligned_written);
656
657         /* Figure out how many unaligned bytes were written. */
658         size_t written = align_fix_up_bytes(&align, aligned_written);
659         BUG_ON(written > size);
660
661         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_write: wrote %zd bytes\n",
662                  written);
663
664         if (written > 0)
665                 ret = 0;
666
667         /*
668          * Update inode times.
669          * TODO: Integrate with bch2_extent_update()
670          */
671         if (!ret)
672                 ret = inode_update_times(c, inum);
673
674         if (!ret) {
675                 BUG_ON(written == 0);
676                 fuse_reply_write(req, written);
677                 free(aligned_buf);
678                 return;
679         }
680
681 err:
682         fuse_reply_err(req, -ret);
683         free(aligned_buf);
684 }
685
686 static void bcachefs_fuse_symlink(fuse_req_t req, const char *link,
687                                   fuse_ino_t dir, const char *name)
688 {
689         struct bch_fs *c = fuse_req_userdata(req);
690         struct bch_inode_unpacked new_inode;
691         size_t link_len = strlen(link);
692         int ret;
693
694         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_symlink(%s, %llu, %s)\n",
695                  link, dir, name);
696
697         dir = map_root_ino(dir);
698
699         ret = do_create(c, dir, name, S_IFLNK|S_IRWXUGO, 0, &new_inode);
700         if (ret)
701                 goto err;
702
703         struct bch_io_opts io_opts;
704         ret = get_inode_io_opts(c, new_inode.bi_inum, &io_opts);
705         if (ret)
706                 goto err;
707
708         struct fuse_align_io align = align_io(c, link_len + 1, 0);
709
710         void *aligned_buf = aligned_alloc(PAGE_SIZE, align.size);
711         BUG_ON(!aligned_buf);
712
713         memset(aligned_buf, 0, align.size);
714         memcpy(aligned_buf, link, link_len); /* already terminated */
715
716         size_t aligned_written;
717         ret = write_aligned(c, new_inode.bi_inum, io_opts, aligned_buf,
718                             align.size, align.start, link_len + 1,
719                             &aligned_written);
720         free(aligned_buf);
721
722         if (ret)
723                 goto err;
724
725         size_t written = align_fix_up_bytes(&align, aligned_written);
726         BUG_ON(written != link_len + 1); // TODO: handle short
727
728         ret = inode_update_times(c, new_inode.bi_inum);
729         if (ret)
730                 goto err;
731
732         new_inode.bi_size = written;
733
734         struct fuse_entry_param e = inode_to_entry(c, &new_inode);
735         fuse_reply_entry(req, &e);
736         return;
737
738 err:
739         fuse_reply_err(req, -ret);
740 }
741
742 static void bcachefs_fuse_readlink(fuse_req_t req, fuse_ino_t inum)
743 {
744         struct bch_fs *c = fuse_req_userdata(req);
745         char *buf = NULL;
746
747         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_readlink(%llu)\n", inum);
748
749         struct bch_inode_unpacked bi;
750         int ret = bch2_inode_find_by_inum(c, inum, &bi);
751         if (ret)
752                 goto err;
753
754         struct fuse_align_io align = align_io(c, bi.bi_size, 0);
755
756         ret = -ENOMEM;
757         buf = aligned_alloc(PAGE_SIZE, align.size);
758         if (!buf)
759                 goto err;
760
761         ret = read_aligned(c, inum, align.size, align.start, buf);
762         if (ret)
763                 goto err;
764
765         BUG_ON(buf[align.size - 1] != 0);
766
767         fuse_reply_readlink(req, buf);
768
769 err:
770         if (ret)
771                 fuse_reply_err(req, -ret);
772
773         free(buf);
774 }
775
776 #if 0
777 /*
778  * FUSE flush is essentially the close() call, however it is not guaranteed
779  * that one flush happens per open/create.
780  *
781  * It doesn't have to do anything, and is mostly relevant for NFS-style
782  * filesystems where close has some relationship to caching.
783  */
784 static void bcachefs_fuse_flush(fuse_req_t req, fuse_ino_t inum,
785                                 struct fuse_file_info *fi)
786 {
787         struct bch_fs *c = fuse_req_userdata(req);
788 }
789
790 static void bcachefs_fuse_release(fuse_req_t req, fuse_ino_t inum,
791                                   struct fuse_file_info *fi)
792 {
793         struct bch_fs *c = fuse_req_userdata(req);
794 }
795
796 static void bcachefs_fuse_fsync(fuse_req_t req, fuse_ino_t inum, int datasync,
797                                 struct fuse_file_info *fi)
798 {
799         struct bch_fs *c = fuse_req_userdata(req);
800 }
801
802 static void bcachefs_fuse_opendir(fuse_req_t req, fuse_ino_t inum,
803                                   struct fuse_file_info *fi)
804 {
805         struct bch_fs *c = fuse_req_userdata(req);
806 }
807 #endif
808
809 struct fuse_dir_context {
810         struct dir_context      ctx;
811         fuse_req_t              req;
812         char                    *buf;
813         size_t                  bufsize;
814 };
815
816 struct fuse_dirent {
817         uint64_t        ino;
818         uint64_t        off;
819         uint32_t        namelen;
820         uint32_t        type;
821         char name[];
822 };
823
824 #define FUSE_NAME_OFFSET offsetof(struct fuse_dirent, name)
825 #define FUSE_DIRENT_ALIGN(x) \
826         (((x) + sizeof(uint64_t) - 1) & ~(sizeof(uint64_t) - 1))
827
828 static size_t fuse_add_direntry2(char *buf, size_t bufsize,
829                                  const char *name, int namelen,
830                                  const struct stat *stbuf, off_t off)
831 {
832         size_t entlen           = FUSE_NAME_OFFSET + namelen;
833         size_t entlen_padded    = FUSE_DIRENT_ALIGN(entlen);
834         struct fuse_dirent *dirent = (struct fuse_dirent *) buf;
835
836         if ((buf == NULL) || (entlen_padded > bufsize))
837                 return entlen_padded;
838
839         dirent->ino = stbuf->st_ino;
840         dirent->off = off;
841         dirent->namelen = namelen;
842         dirent->type = (stbuf->st_mode & S_IFMT) >> 12;
843         memcpy(dirent->name, name, namelen);
844         memset(dirent->name + namelen, 0, entlen_padded - entlen);
845
846         return entlen_padded;
847 }
848
849 static int fuse_filldir(struct dir_context *_ctx,
850                         const char *name, int namelen,
851                         loff_t pos, u64 ino, unsigned type)
852 {
853         struct fuse_dir_context *ctx =
854                 container_of(_ctx, struct fuse_dir_context, ctx);
855
856         struct stat statbuf = {
857                 .st_ino         = unmap_root_ino(ino),
858                 .st_mode        = type << 12,
859         };
860
861         fuse_log(FUSE_LOG_DEBUG, "fuse_filldir(name=%s inum=%llu pos=%llu)\n",
862                  name, statbuf.st_ino, pos);
863
864         size_t len = fuse_add_direntry2(ctx->buf,
865                                         ctx->bufsize,
866                                         name,
867                                         namelen,
868                                         &statbuf,
869                                         pos + 1);
870
871         if (len > ctx->bufsize)
872                 return -1;
873
874         ctx->buf        += len;
875         ctx->bufsize    -= len;
876
877         return 0;
878 }
879
880 static bool handle_dots(struct fuse_dir_context *ctx, fuse_ino_t dir)
881 {
882         if (ctx->ctx.pos == 0) {
883                 if (fuse_filldir(&ctx->ctx, ".", 1, ctx->ctx.pos,
884                                  dir, DT_DIR) < 0)
885                         return false;
886                 ctx->ctx.pos = 1;
887         }
888
889         if (ctx->ctx.pos == 1) {
890                 if (fuse_filldir(&ctx->ctx, "..", 2, ctx->ctx.pos,
891                                  /*TODO: parent*/ 1, DT_DIR) < 0)
892                         return false;
893                 ctx->ctx.pos = 2;
894         }
895
896         return true;
897 }
898
899 static void bcachefs_fuse_readdir(fuse_req_t req, fuse_ino_t dir,
900                                   size_t size, off_t off,
901                                   struct fuse_file_info *fi)
902 {
903         struct bch_fs *c = fuse_req_userdata(req);
904         struct bch_inode_unpacked bi;
905         char *buf = calloc(size, 1);
906         struct fuse_dir_context ctx = {
907                 .ctx.actor      = fuse_filldir,
908                 .ctx.pos        = off,
909                 .req            = req,
910                 .buf            = buf,
911                 .bufsize        = size,
912         };
913         int ret = 0;
914
915         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_readdir(dir=%llu, size=%zu, "
916                  "off=%lld)\n", dir, size, off);
917
918         dir = map_root_ino(dir);
919
920         ret = bch2_inode_find_by_inum(c, dir, &bi);
921         if (ret)
922                 goto reply;
923
924         if (!S_ISDIR(bi.bi_mode)) {
925                 ret = -ENOTDIR;
926                 goto reply;
927         }
928
929         if (!handle_dots(&ctx, dir))
930                 goto reply;
931
932         ret = bch2_readdir(c, dir, &ctx.ctx);
933 reply:
934         if (!ret) {
935                 fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_readdir reply %zd\n",
936                                         ctx.buf - buf);
937                 fuse_reply_buf(req, buf, ctx.buf - buf);
938         } else {
939                 fuse_reply_err(req, -ret);
940         }
941
942         free(buf);
943 }
944
945 #if 0
946 static void bcachefs_fuse_readdirplus(fuse_req_t req, fuse_ino_t dir,
947                                       size_t size, off_t off,
948                                       struct fuse_file_info *fi)
949 {
950
951 }
952
953 static void bcachefs_fuse_releasedir(fuse_req_t req, fuse_ino_t inum,
954                                      struct fuse_file_info *fi)
955 {
956         struct bch_fs *c = fuse_req_userdata(req);
957 }
958
959 static void bcachefs_fuse_fsyncdir(fuse_req_t req, fuse_ino_t inum, int datasync,
960                                    struct fuse_file_info *fi)
961 {
962         struct bch_fs *c = fuse_req_userdata(req);
963 }
964 #endif
965
966 static void bcachefs_fuse_statfs(fuse_req_t req, fuse_ino_t inum)
967 {
968         struct bch_fs *c = fuse_req_userdata(req);
969         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
970         unsigned shift = c->block_bits;
971         struct statvfs statbuf = {
972                 .f_bsize        = block_bytes(c),
973                 .f_frsize       = block_bytes(c),
974                 .f_blocks       = usage.capacity >> shift,
975                 .f_bfree        = (usage.capacity - usage.used) >> shift,
976                 //.f_bavail     = statbuf.f_bfree,
977                 .f_files        = usage.nr_inodes,
978                 .f_ffree        = U64_MAX,
979                 .f_namemax      = BCH_NAME_MAX,
980         };
981
982         fuse_reply_statfs(req, &statbuf);
983 }
984
985 #if 0
986 static void bcachefs_fuse_setxattr(fuse_req_t req, fuse_ino_t inum,
987                                    const char *name, const char *value,
988                                    size_t size, int flags)
989 {
990         struct bch_fs *c = fuse_req_userdata(req);
991 }
992
993 static void bcachefs_fuse_getxattr(fuse_req_t req, fuse_ino_t inum,
994                                    const char *name, size_t size)
995 {
996         struct bch_fs *c = fuse_req_userdata(req);
997
998         fuse_reply_xattr(req, );
999 }
1000
1001 static void bcachefs_fuse_listxattr(fuse_req_t req, fuse_ino_t inum, size_t size)
1002 {
1003         struct bch_fs *c = fuse_req_userdata(req);
1004 }
1005
1006 static void bcachefs_fuse_removexattr(fuse_req_t req, fuse_ino_t inum,
1007                                       const char *name)
1008 {
1009         struct bch_fs *c = fuse_req_userdata(req);
1010 }
1011 #endif
1012
1013 static void bcachefs_fuse_create(fuse_req_t req, fuse_ino_t dir,
1014                                  const char *name, mode_t mode,
1015                                  struct fuse_file_info *fi)
1016 {
1017         struct bch_fs *c = fuse_req_userdata(req);
1018         struct bch_inode_unpacked new_inode;
1019         int ret;
1020
1021         fuse_log(FUSE_LOG_DEBUG, "bcachefs_fuse_create(%llu, %s, %x)\n",
1022                  dir, name, mode);
1023
1024         ret = do_create(c, dir, name, mode, 0, &new_inode);
1025         if (ret)
1026                 goto err;
1027
1028         struct fuse_entry_param e = inode_to_entry(c, &new_inode);
1029         fuse_reply_create(req, &e, fi);
1030         return;
1031 err:
1032         fuse_reply_err(req, -ret);
1033
1034 }
1035
1036 #if 0
1037 static void bcachefs_fuse_write_buf(fuse_req_t req, fuse_ino_t inum,
1038                                     struct fuse_bufvec *bufv, off_t off,
1039                                     struct fuse_file_info *fi)
1040 {
1041         struct bch_fs *c = fuse_req_userdata(req);
1042 }
1043
1044 static void bcachefs_fuse_fallocate(fuse_req_t req, fuse_ino_t inum, int mode,
1045                                     off_t offset, off_t length,
1046                                     struct fuse_file_info *fi)
1047 {
1048         struct bch_fs *c = fuse_req_userdata(req);
1049 }
1050 #endif
1051
1052 static const struct fuse_lowlevel_ops bcachefs_fuse_ops = {
1053         .init           = bcachefs_fuse_init,
1054         .destroy        = bcachefs_fuse_destroy,
1055         .lookup         = bcachefs_fuse_lookup,
1056         .getattr        = bcachefs_fuse_getattr,
1057         .setattr        = bcachefs_fuse_setattr,
1058         .readlink       = bcachefs_fuse_readlink,
1059         .mknod          = bcachefs_fuse_mknod,
1060         .mkdir          = bcachefs_fuse_mkdir,
1061         .unlink         = bcachefs_fuse_unlink,
1062         .rmdir          = bcachefs_fuse_rmdir,
1063         .symlink        = bcachefs_fuse_symlink,
1064         .rename         = bcachefs_fuse_rename,
1065         .link           = bcachefs_fuse_link,
1066         .open           = bcachefs_fuse_open,
1067         .read           = bcachefs_fuse_read,
1068         .write          = bcachefs_fuse_write,
1069         //.flush        = bcachefs_fuse_flush,
1070         //.release      = bcachefs_fuse_release,
1071         //.fsync        = bcachefs_fuse_fsync,
1072         //.opendir      = bcachefs_fuse_opendir,
1073         .readdir        = bcachefs_fuse_readdir,
1074         //.readdirplus  = bcachefs_fuse_readdirplus,
1075         //.releasedir   = bcachefs_fuse_releasedir,
1076         //.fsyncdir     = bcachefs_fuse_fsyncdir,
1077         .statfs         = bcachefs_fuse_statfs,
1078         //.setxattr     = bcachefs_fuse_setxattr,
1079         //.getxattr     = bcachefs_fuse_getxattr,
1080         //.listxattr    = bcachefs_fuse_listxattr,
1081         //.removexattr  = bcachefs_fuse_removexattr,
1082         .create         = bcachefs_fuse_create,
1083
1084         /* posix locks: */
1085 #if 0
1086         .getlk          = bcachefs_fuse_getlk,
1087         .setlk          = bcachefs_fuse_setlk,
1088 #endif
1089         //.write_buf    = bcachefs_fuse_write_buf,
1090         //.fallocate    = bcachefs_fuse_fallocate,
1091
1092 };
1093
1094 /*
1095  * Setup and command parsing.
1096  */
1097
1098 struct bf_context {
1099         char            *devices_str;
1100         char            **devices;
1101         int             nr_devices;
1102 };
1103
1104 static void bf_context_free(struct bf_context *ctx)
1105 {
1106         int i;
1107
1108         free(ctx->devices_str);
1109         for (i = 0; i < ctx->nr_devices; ++i)
1110                 free(ctx->devices[i]);
1111         free(ctx->devices);
1112 }
1113
1114 static struct fuse_opt bf_opts[] = {
1115         FUSE_OPT_END
1116 };
1117
1118 /*
1119  * Fuse option parsing helper -- returning 0 means we consumed the argument, 1
1120  * means we did not.
1121  */
1122 static int bf_opt_proc(void *data, const char *arg, int key,
1123     struct fuse_args *outargs)
1124 {
1125         struct bf_context *ctx = data;
1126
1127         switch (key) {
1128         case FUSE_OPT_KEY_NONOPT:
1129                 /* Just extract the first non-option string. */
1130                 if (!ctx->devices_str) {
1131                         ctx->devices_str = strdup(arg);
1132                         return 0;
1133                 }
1134                 return 1;
1135         }
1136
1137         return 1;
1138 }
1139
1140 /*
1141  * dev1:dev2 -> [ dev1, dev2 ]
1142  * dev       -> [ dev ]
1143  */
1144 static void tokenize_devices(struct bf_context *ctx)
1145 {
1146         char *devices_str = strdup(ctx->devices_str);
1147         char *devices_tmp = devices_str;
1148         char **devices = NULL;
1149         int nr = 0;
1150         char *dev = NULL;
1151
1152         while ((dev = strsep(&devices_tmp, ":"))) {
1153                 if (strlen(dev) > 0) {
1154                         devices = realloc(devices, (nr + 1) * sizeof *devices);
1155                         devices[nr] = strdup(dev);
1156                         nr++;
1157                 }
1158         }
1159
1160         if (!devices) {
1161                 devices = malloc(sizeof *devices);
1162                 devices[0] = strdup(ctx->devices_str);
1163                 nr = 1;
1164         }
1165
1166         ctx->devices = devices;
1167         ctx->nr_devices = nr;
1168
1169         free(devices_str);
1170 }
1171
1172 static void usage(char *argv[])
1173 {
1174         printf("Usage: %s fusemount [options] <dev>[:dev2:...] <mountpoint>\n",
1175                argv[0]);
1176         printf("\n");
1177 }
1178
1179 int cmd_fusemount(int argc, char *argv[])
1180 {
1181         struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
1182         struct bch_opts bch_opts = bch2_opts_empty();
1183         struct bf_context ctx = { 0 };
1184         struct bch_fs *c = NULL;
1185         int ret = 0, i;
1186
1187         /* Parse arguments. */
1188         if (fuse_opt_parse(&args, &ctx, bf_opts, bf_opt_proc) < 0)
1189                 die("fuse_opt_parse err: %m");
1190
1191         struct fuse_cmdline_opts fuse_opts;
1192         if (fuse_parse_cmdline(&args, &fuse_opts) < 0)
1193                 die("fuse_parse_cmdline err: %m");
1194
1195         if (fuse_opts.show_help) {
1196                 usage(argv);
1197                 fuse_cmdline_help();
1198                 fuse_lowlevel_help();
1199                 ret = 0;
1200                 goto out;
1201         }
1202         if (fuse_opts.show_version) {
1203                 /* TODO: Show bcachefs version. */
1204                 printf("FUSE library version %s\n", fuse_pkgversion());
1205                 fuse_lowlevel_version();
1206                 ret = 0;
1207                 goto out;
1208         }
1209         if (!fuse_opts.mountpoint) {
1210                 usage(argv);
1211                 printf("Please supply a mountpoint.\n");
1212                 ret = 1;
1213                 goto out;
1214         }
1215         if (!ctx.devices_str) {
1216                 usage(argv);
1217                 printf("Please specify a device or device1:device2:...\n");
1218                 ret = 1;
1219                 goto out;
1220         }
1221         tokenize_devices(&ctx);
1222
1223         /* Open bch */
1224         printf("Opening bcachefs filesystem on:\n");
1225         for (i = 0; i < ctx.nr_devices; ++i)
1226                 printf("\t%s\n", ctx.devices[i]);
1227
1228         c = bch2_fs_open(ctx.devices, ctx.nr_devices, bch_opts);
1229         if (IS_ERR(c))
1230                 die("error opening %s: %s", ctx.devices_str,
1231                     strerror(-PTR_ERR(c)));
1232
1233         /* Fuse */
1234         struct fuse_session *se =
1235                 fuse_session_new(&args, &bcachefs_fuse_ops,
1236                                  sizeof(bcachefs_fuse_ops), c);
1237         if (!se)
1238                 die("fuse_lowlevel_new err: %m");
1239
1240         if (fuse_set_signal_handlers(se) < 0)
1241                 die("fuse_set_signal_handlers err: %m");
1242
1243         if (fuse_session_mount(se, fuse_opts.mountpoint))
1244                 die("fuse_mount err: %m");
1245
1246         /* This print statement is a trigger for tests. */
1247         printf("Fuse mount initialized.\n");
1248
1249         fuse_daemonize(fuse_opts.foreground);
1250
1251         ret = fuse_session_loop(se);
1252
1253         /* Cleanup */
1254         fuse_session_unmount(se);
1255         fuse_remove_signal_handlers(se);
1256         fuse_session_destroy(se);
1257
1258 out:
1259         free(fuse_opts.mountpoint);
1260         fuse_opt_free_args(&args);
1261         bf_context_free(&ctx);
1262
1263         return ret ? 1 : 0;
1264 }