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