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