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