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