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