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