xref: /spdk/lib/blobfs/blobfs.c (revision 5adac19ad07b8f1b2714583df586534b8f5738b6)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "spdk/blobfs.h"
37 #include "spdk/conf.h"
38 #include "tree.h"
39 
40 #include "spdk/queue.h"
41 #include "spdk/thread.h"
42 #include "spdk/assert.h"
43 #include "spdk/env.h"
44 #include "spdk/util.h"
45 #include "spdk_internal/log.h"
46 #include "spdk/trace.h"
47 
48 #define BLOBFS_TRACE(file, str, args...) \
49 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s " str, file->name, ##args)
50 
51 #define BLOBFS_TRACE_RW(file, str, args...) \
52 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS_RW, "file=%s " str, file->name, ##args)
53 
54 #define BLOBFS_DEFAULT_CACHE_SIZE (4ULL * 1024 * 1024 * 1024)
55 #define SPDK_BLOBFS_DEFAULT_OPTS_CLUSTER_SZ (1024 * 1024)
56 
57 #define SPDK_BLOBFS_SIGNATURE	"BLOBFS"
58 
59 static uint64_t g_fs_cache_size = BLOBFS_DEFAULT_CACHE_SIZE;
60 static struct spdk_mempool *g_cache_pool;
61 static TAILQ_HEAD(, spdk_file) g_caches;
62 static int g_fs_count = 0;
63 static pthread_mutex_t g_cache_init_lock = PTHREAD_MUTEX_INITIALIZER;
64 static pthread_spinlock_t g_caches_lock;
65 
66 #define TRACE_GROUP_BLOBFS	0x7
67 #define TRACE_BLOBFS_XATTR_START	SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x0)
68 #define TRACE_BLOBFS_XATTR_END		SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x1)
69 #define TRACE_BLOBFS_OPEN		SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x2)
70 #define TRACE_BLOBFS_CLOSE		SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x3)
71 #define TRACE_BLOBFS_DELETE_START	SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x4)
72 #define TRACE_BLOBFS_DELETE_DONE	SPDK_TPOINT_ID(TRACE_GROUP_BLOBFS, 0x5)
73 
74 SPDK_TRACE_REGISTER_FN(blobfs_trace, "blobfs", TRACE_GROUP_BLOBFS)
75 {
76 	spdk_trace_register_description("BLOBFS_XATTR_START",
77 					TRACE_BLOBFS_XATTR_START,
78 					OWNER_NONE, OBJECT_NONE, 0,
79 					SPDK_TRACE_ARG_TYPE_STR,
80 					"file:    ");
81 	spdk_trace_register_description("BLOBFS_XATTR_END",
82 					TRACE_BLOBFS_XATTR_END,
83 					OWNER_NONE, OBJECT_NONE, 0,
84 					SPDK_TRACE_ARG_TYPE_STR,
85 					"file:    ");
86 	spdk_trace_register_description("BLOBFS_OPEN",
87 					TRACE_BLOBFS_OPEN,
88 					OWNER_NONE, OBJECT_NONE, 0,
89 					SPDK_TRACE_ARG_TYPE_STR,
90 					"file:    ");
91 	spdk_trace_register_description("BLOBFS_CLOSE",
92 					TRACE_BLOBFS_CLOSE,
93 					OWNER_NONE, OBJECT_NONE, 0,
94 					SPDK_TRACE_ARG_TYPE_STR,
95 					"file:    ");
96 	spdk_trace_register_description("BLOBFS_DELETE_START",
97 					TRACE_BLOBFS_DELETE_START,
98 					OWNER_NONE, OBJECT_NONE, 0,
99 					SPDK_TRACE_ARG_TYPE_STR,
100 					"file:    ");
101 	spdk_trace_register_description("BLOBFS_DELETE_DONE",
102 					TRACE_BLOBFS_DELETE_DONE,
103 					OWNER_NONE, OBJECT_NONE, 0,
104 					SPDK_TRACE_ARG_TYPE_STR,
105 					"file:    ");
106 }
107 
108 void
109 spdk_cache_buffer_free(struct cache_buffer *cache_buffer)
110 {
111 	spdk_mempool_put(g_cache_pool, cache_buffer->buf);
112 	free(cache_buffer);
113 }
114 
115 #define CACHE_READAHEAD_THRESHOLD	(128 * 1024)
116 
117 struct spdk_file {
118 	struct spdk_filesystem	*fs;
119 	struct spdk_blob	*blob;
120 	char			*name;
121 	uint64_t		trace_arg_name;
122 	uint64_t		length;
123 	bool                    is_deleted;
124 	bool			open_for_writing;
125 	uint64_t		length_flushed;
126 	uint64_t		length_xattr;
127 	uint64_t		append_pos;
128 	uint64_t		seq_byte_count;
129 	uint64_t		next_seq_offset;
130 	uint32_t		priority;
131 	TAILQ_ENTRY(spdk_file)	tailq;
132 	spdk_blob_id		blobid;
133 	uint32_t		ref_count;
134 	pthread_spinlock_t	lock;
135 	struct cache_buffer	*last;
136 	struct cache_tree	*tree;
137 	TAILQ_HEAD(open_requests_head, spdk_fs_request) open_requests;
138 	TAILQ_HEAD(sync_requests_head, spdk_fs_request) sync_requests;
139 	TAILQ_ENTRY(spdk_file)	cache_tailq;
140 };
141 
142 struct spdk_deleted_file {
143 	spdk_blob_id	id;
144 	TAILQ_ENTRY(spdk_deleted_file)	tailq;
145 };
146 
147 struct spdk_filesystem {
148 	struct spdk_blob_store	*bs;
149 	TAILQ_HEAD(, spdk_file)	files;
150 	struct spdk_bs_opts	bs_opts;
151 	struct spdk_bs_dev	*bdev;
152 	fs_send_request_fn	send_request;
153 
154 	struct {
155 		uint32_t		max_ops;
156 		struct spdk_io_channel	*sync_io_channel;
157 		struct spdk_fs_channel	*sync_fs_channel;
158 	} sync_target;
159 
160 	struct {
161 		uint32_t		max_ops;
162 		struct spdk_io_channel	*md_io_channel;
163 		struct spdk_fs_channel	*md_fs_channel;
164 	} md_target;
165 
166 	struct {
167 		uint32_t		max_ops;
168 	} io_target;
169 };
170 
171 struct spdk_fs_cb_args {
172 	union {
173 		spdk_fs_op_with_handle_complete		fs_op_with_handle;
174 		spdk_fs_op_complete			fs_op;
175 		spdk_file_op_with_handle_complete	file_op_with_handle;
176 		spdk_file_op_complete			file_op;
177 		spdk_file_stat_op_complete		stat_op;
178 	} fn;
179 	void *arg;
180 	sem_t *sem;
181 	struct spdk_filesystem *fs;
182 	struct spdk_file *file;
183 	int rc;
184 	struct iovec *iovs;
185 	uint32_t iovcnt;
186 	struct iovec iov;
187 	union {
188 		struct {
189 			TAILQ_HEAD(, spdk_deleted_file)	deleted_files;
190 		} fs_load;
191 		struct {
192 			uint64_t	length;
193 		} truncate;
194 		struct {
195 			struct spdk_io_channel	*channel;
196 			void		*pin_buf;
197 			int		is_read;
198 			off_t		offset;
199 			size_t		length;
200 			uint64_t	start_lba;
201 			uint64_t	num_lba;
202 			uint32_t	blocklen;
203 		} rw;
204 		struct {
205 			const char	*old_name;
206 			const char	*new_name;
207 		} rename;
208 		struct {
209 			struct cache_buffer	*cache_buffer;
210 			uint64_t		length;
211 		} flush;
212 		struct {
213 			struct cache_buffer	*cache_buffer;
214 			uint64_t		length;
215 			uint64_t		offset;
216 		} readahead;
217 		struct {
218 			/* offset of the file when the sync request was made */
219 			uint64_t			offset;
220 			TAILQ_ENTRY(spdk_fs_request)	tailq;
221 			bool				xattr_in_progress;
222 			/* length written to the xattr for this file - this should
223 			 * always be the same as the offset if only one thread is
224 			 * writing to the file, but could differ if multiple threads
225 			 * are appending
226 			 */
227 			uint64_t			length;
228 		} sync;
229 		struct {
230 			uint32_t			num_clusters;
231 		} resize;
232 		struct {
233 			const char	*name;
234 			uint32_t	flags;
235 			TAILQ_ENTRY(spdk_fs_request)	tailq;
236 		} open;
237 		struct {
238 			const char		*name;
239 			struct spdk_blob	*blob;
240 		} create;
241 		struct {
242 			const char	*name;
243 		} delete;
244 		struct {
245 			const char	*name;
246 		} stat;
247 	} op;
248 };
249 
250 static void cache_free_buffers(struct spdk_file *file);
251 static void spdk_fs_io_device_unregister(struct spdk_filesystem *fs);
252 static void spdk_fs_free_io_channels(struct spdk_filesystem *fs);
253 
254 void
255 spdk_fs_opts_init(struct spdk_blobfs_opts *opts)
256 {
257 	opts->cluster_sz = SPDK_BLOBFS_DEFAULT_OPTS_CLUSTER_SZ;
258 }
259 
260 static void
261 __initialize_cache(void)
262 {
263 	assert(g_cache_pool == NULL);
264 
265 	g_cache_pool = spdk_mempool_create("spdk_fs_cache",
266 					   g_fs_cache_size / CACHE_BUFFER_SIZE,
267 					   CACHE_BUFFER_SIZE,
268 					   SPDK_MEMPOOL_DEFAULT_CACHE_SIZE,
269 					   SPDK_ENV_SOCKET_ID_ANY);
270 	if (!g_cache_pool) {
271 		SPDK_ERRLOG("Create mempool failed, you may "
272 			    "increase the memory and try again\n");
273 		assert(false);
274 	}
275 	TAILQ_INIT(&g_caches);
276 	pthread_spin_init(&g_caches_lock, 0);
277 }
278 
279 static void
280 __free_cache(void)
281 {
282 	assert(g_cache_pool != NULL);
283 
284 	spdk_mempool_free(g_cache_pool);
285 	g_cache_pool = NULL;
286 }
287 
288 static uint64_t
289 __file_get_blob_size(struct spdk_file *file)
290 {
291 	uint64_t cluster_sz;
292 
293 	cluster_sz = file->fs->bs_opts.cluster_sz;
294 	return cluster_sz * spdk_blob_get_num_clusters(file->blob);
295 }
296 
297 struct spdk_fs_request {
298 	struct spdk_fs_cb_args		args;
299 	TAILQ_ENTRY(spdk_fs_request)	link;
300 	struct spdk_fs_channel		*channel;
301 };
302 
303 struct spdk_fs_channel {
304 	struct spdk_fs_request		*req_mem;
305 	TAILQ_HEAD(, spdk_fs_request)	reqs;
306 	sem_t				sem;
307 	struct spdk_filesystem		*fs;
308 	struct spdk_io_channel		*bs_channel;
309 	fs_send_request_fn		send_request;
310 	bool				sync;
311 	uint32_t			outstanding_reqs;
312 	pthread_spinlock_t		lock;
313 };
314 
315 /* For now, this is effectively an alias. But eventually we'll shift
316  * some data members over. */
317 struct spdk_fs_thread_ctx {
318 	struct spdk_fs_channel	ch;
319 };
320 
321 static struct spdk_fs_request *
322 alloc_fs_request_with_iov(struct spdk_fs_channel *channel, uint32_t iovcnt)
323 {
324 	struct spdk_fs_request *req;
325 	struct iovec *iovs = NULL;
326 
327 	if (iovcnt > 1) {
328 		iovs = calloc(iovcnt, sizeof(struct iovec));
329 		if (!iovs) {
330 			return NULL;
331 		}
332 	}
333 
334 	if (channel->sync) {
335 		pthread_spin_lock(&channel->lock);
336 	}
337 
338 	req = TAILQ_FIRST(&channel->reqs);
339 	if (req) {
340 		channel->outstanding_reqs++;
341 		TAILQ_REMOVE(&channel->reqs, req, link);
342 	}
343 
344 	if (channel->sync) {
345 		pthread_spin_unlock(&channel->lock);
346 	}
347 
348 	if (req == NULL) {
349 		SPDK_ERRLOG("Cannot allocate req on spdk_fs_channel =%p\n", channel);
350 		free(iovs);
351 		return NULL;
352 	}
353 	memset(req, 0, sizeof(*req));
354 	req->channel = channel;
355 	if (iovcnt > 1) {
356 		req->args.iovs = iovs;
357 	} else {
358 		req->args.iovs = &req->args.iov;
359 	}
360 	req->args.iovcnt = iovcnt;
361 
362 	return req;
363 }
364 
365 static struct spdk_fs_request *
366 alloc_fs_request(struct spdk_fs_channel *channel)
367 {
368 	return alloc_fs_request_with_iov(channel, 0);
369 }
370 
371 static void
372 free_fs_request(struct spdk_fs_request *req)
373 {
374 	struct spdk_fs_channel *channel = req->channel;
375 
376 	if (req->args.iovcnt > 1) {
377 		free(req->args.iovs);
378 	}
379 
380 	if (channel->sync) {
381 		pthread_spin_lock(&channel->lock);
382 	}
383 
384 	TAILQ_INSERT_HEAD(&req->channel->reqs, req, link);
385 	channel->outstanding_reqs--;
386 
387 	if (channel->sync) {
388 		pthread_spin_unlock(&channel->lock);
389 	}
390 }
391 
392 static int
393 _spdk_fs_channel_create(struct spdk_filesystem *fs, struct spdk_fs_channel *channel,
394 			uint32_t max_ops)
395 {
396 	uint32_t i;
397 
398 	channel->req_mem = calloc(max_ops, sizeof(struct spdk_fs_request));
399 	if (!channel->req_mem) {
400 		return -1;
401 	}
402 
403 	channel->outstanding_reqs = 0;
404 	TAILQ_INIT(&channel->reqs);
405 	sem_init(&channel->sem, 0, 0);
406 
407 	for (i = 0; i < max_ops; i++) {
408 		TAILQ_INSERT_TAIL(&channel->reqs, &channel->req_mem[i], link);
409 	}
410 
411 	channel->fs = fs;
412 
413 	return 0;
414 }
415 
416 static int
417 _spdk_fs_md_channel_create(void *io_device, void *ctx_buf)
418 {
419 	struct spdk_filesystem		*fs;
420 	struct spdk_fs_channel		*channel = ctx_buf;
421 
422 	fs = SPDK_CONTAINEROF(io_device, struct spdk_filesystem, md_target);
423 
424 	return _spdk_fs_channel_create(fs, channel, fs->md_target.max_ops);
425 }
426 
427 static int
428 _spdk_fs_sync_channel_create(void *io_device, void *ctx_buf)
429 {
430 	struct spdk_filesystem		*fs;
431 	struct spdk_fs_channel		*channel = ctx_buf;
432 
433 	fs = SPDK_CONTAINEROF(io_device, struct spdk_filesystem, sync_target);
434 
435 	return _spdk_fs_channel_create(fs, channel, fs->sync_target.max_ops);
436 }
437 
438 static int
439 _spdk_fs_io_channel_create(void *io_device, void *ctx_buf)
440 {
441 	struct spdk_filesystem		*fs;
442 	struct spdk_fs_channel		*channel = ctx_buf;
443 
444 	fs = SPDK_CONTAINEROF(io_device, struct spdk_filesystem, io_target);
445 
446 	return _spdk_fs_channel_create(fs, channel, fs->io_target.max_ops);
447 }
448 
449 static void
450 _spdk_fs_channel_destroy(void *io_device, void *ctx_buf)
451 {
452 	struct spdk_fs_channel *channel = ctx_buf;
453 
454 	if (channel->outstanding_reqs > 0) {
455 		SPDK_ERRLOG("channel freed with %" PRIu32 " outstanding requests!\n",
456 			    channel->outstanding_reqs);
457 	}
458 
459 	free(channel->req_mem);
460 	if (channel->bs_channel != NULL) {
461 		spdk_bs_free_io_channel(channel->bs_channel);
462 	}
463 }
464 
465 static void
466 __send_request_direct(fs_request_fn fn, void *arg)
467 {
468 	fn(arg);
469 }
470 
471 static void
472 common_fs_bs_init(struct spdk_filesystem *fs, struct spdk_blob_store *bs)
473 {
474 	fs->bs = bs;
475 	fs->bs_opts.cluster_sz = spdk_bs_get_cluster_size(bs);
476 	fs->md_target.md_fs_channel->bs_channel = spdk_bs_alloc_io_channel(fs->bs);
477 	fs->md_target.md_fs_channel->send_request = __send_request_direct;
478 	fs->sync_target.sync_fs_channel->bs_channel = spdk_bs_alloc_io_channel(fs->bs);
479 	fs->sync_target.sync_fs_channel->send_request = __send_request_direct;
480 
481 	pthread_mutex_lock(&g_cache_init_lock);
482 	if (g_fs_count == 0) {
483 		__initialize_cache();
484 	}
485 	g_fs_count++;
486 	pthread_mutex_unlock(&g_cache_init_lock);
487 }
488 
489 static void
490 init_cb(void *ctx, struct spdk_blob_store *bs, int bserrno)
491 {
492 	struct spdk_fs_request *req = ctx;
493 	struct spdk_fs_cb_args *args = &req->args;
494 	struct spdk_filesystem *fs = args->fs;
495 
496 	if (bserrno == 0) {
497 		common_fs_bs_init(fs, bs);
498 	} else {
499 		free(fs);
500 		fs = NULL;
501 	}
502 
503 	args->fn.fs_op_with_handle(args->arg, fs, bserrno);
504 	free_fs_request(req);
505 }
506 
507 static void
508 fs_conf_parse(void)
509 {
510 	struct spdk_conf_section *sp;
511 
512 	sp = spdk_conf_find_section(NULL, "Blobfs");
513 	if (sp == NULL) {
514 		g_fs_cache_buffer_shift = CACHE_BUFFER_SHIFT_DEFAULT;
515 		return;
516 	}
517 
518 	g_fs_cache_buffer_shift = spdk_conf_section_get_intval(sp, "CacheBufferShift");
519 	if (g_fs_cache_buffer_shift <= 0) {
520 		g_fs_cache_buffer_shift = CACHE_BUFFER_SHIFT_DEFAULT;
521 	}
522 }
523 
524 static struct spdk_filesystem *
525 fs_alloc(struct spdk_bs_dev *dev, fs_send_request_fn send_request_fn)
526 {
527 	struct spdk_filesystem *fs;
528 
529 	fs = calloc(1, sizeof(*fs));
530 	if (fs == NULL) {
531 		return NULL;
532 	}
533 
534 	fs->bdev = dev;
535 	fs->send_request = send_request_fn;
536 	TAILQ_INIT(&fs->files);
537 
538 	fs->md_target.max_ops = 512;
539 	spdk_io_device_register(&fs->md_target, _spdk_fs_md_channel_create, _spdk_fs_channel_destroy,
540 				sizeof(struct spdk_fs_channel), "blobfs_md");
541 	fs->md_target.md_io_channel = spdk_get_io_channel(&fs->md_target);
542 	fs->md_target.md_fs_channel = spdk_io_channel_get_ctx(fs->md_target.md_io_channel);
543 
544 	fs->sync_target.max_ops = 512;
545 	spdk_io_device_register(&fs->sync_target, _spdk_fs_sync_channel_create, _spdk_fs_channel_destroy,
546 				sizeof(struct spdk_fs_channel), "blobfs_sync");
547 	fs->sync_target.sync_io_channel = spdk_get_io_channel(&fs->sync_target);
548 	fs->sync_target.sync_fs_channel = spdk_io_channel_get_ctx(fs->sync_target.sync_io_channel);
549 
550 	fs->io_target.max_ops = 512;
551 	spdk_io_device_register(&fs->io_target, _spdk_fs_io_channel_create, _spdk_fs_channel_destroy,
552 				sizeof(struct spdk_fs_channel), "blobfs_io");
553 
554 	return fs;
555 }
556 
557 static void
558 __wake_caller(void *arg, int fserrno)
559 {
560 	struct spdk_fs_cb_args *args = arg;
561 
562 	args->rc = fserrno;
563 	sem_post(args->sem);
564 }
565 
566 void
567 spdk_fs_init(struct spdk_bs_dev *dev, struct spdk_blobfs_opts *opt,
568 	     fs_send_request_fn send_request_fn,
569 	     spdk_fs_op_with_handle_complete cb_fn, void *cb_arg)
570 {
571 	struct spdk_filesystem *fs;
572 	struct spdk_fs_request *req;
573 	struct spdk_fs_cb_args *args;
574 	struct spdk_bs_opts opts = {};
575 
576 	fs = fs_alloc(dev, send_request_fn);
577 	if (fs == NULL) {
578 		cb_fn(cb_arg, NULL, -ENOMEM);
579 		return;
580 	}
581 
582 	fs_conf_parse();
583 
584 	req = alloc_fs_request(fs->md_target.md_fs_channel);
585 	if (req == NULL) {
586 		spdk_fs_free_io_channels(fs);
587 		spdk_fs_io_device_unregister(fs);
588 		cb_fn(cb_arg, NULL, -ENOMEM);
589 		return;
590 	}
591 
592 	args = &req->args;
593 	args->fn.fs_op_with_handle = cb_fn;
594 	args->arg = cb_arg;
595 	args->fs = fs;
596 
597 	spdk_bs_opts_init(&opts);
598 	snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), SPDK_BLOBFS_SIGNATURE);
599 	if (opt) {
600 		opts.cluster_sz = opt->cluster_sz;
601 	}
602 	spdk_bs_init(dev, &opts, init_cb, req);
603 }
604 
605 static struct spdk_file *
606 file_alloc(struct spdk_filesystem *fs)
607 {
608 	struct spdk_file *file;
609 
610 	file = calloc(1, sizeof(*file));
611 	if (file == NULL) {
612 		return NULL;
613 	}
614 
615 	file->tree = calloc(1, sizeof(*file->tree));
616 	if (file->tree == NULL) {
617 		free(file);
618 		return NULL;
619 	}
620 
621 	file->fs = fs;
622 	TAILQ_INIT(&file->open_requests);
623 	TAILQ_INIT(&file->sync_requests);
624 	pthread_spin_init(&file->lock, 0);
625 	TAILQ_INSERT_TAIL(&fs->files, file, tailq);
626 	file->priority = SPDK_FILE_PRIORITY_LOW;
627 	return file;
628 }
629 
630 static void fs_load_done(void *ctx, int bserrno);
631 
632 static int
633 _handle_deleted_files(struct spdk_fs_request *req)
634 {
635 	struct spdk_fs_cb_args *args = &req->args;
636 	struct spdk_filesystem *fs = args->fs;
637 
638 	if (!TAILQ_EMPTY(&args->op.fs_load.deleted_files)) {
639 		struct spdk_deleted_file *deleted_file;
640 
641 		deleted_file = TAILQ_FIRST(&args->op.fs_load.deleted_files);
642 		TAILQ_REMOVE(&args->op.fs_load.deleted_files, deleted_file, tailq);
643 		spdk_bs_delete_blob(fs->bs, deleted_file->id, fs_load_done, req);
644 		free(deleted_file);
645 		return 0;
646 	}
647 
648 	return 1;
649 }
650 
651 static void
652 fs_load_done(void *ctx, int bserrno)
653 {
654 	struct spdk_fs_request *req = ctx;
655 	struct spdk_fs_cb_args *args = &req->args;
656 	struct spdk_filesystem *fs = args->fs;
657 
658 	/* The filesystem has been loaded.  Now check if there are any files that
659 	 *  were marked for deletion before last unload.  Do not complete the
660 	 *  fs_load callback until all of them have been deleted on disk.
661 	 */
662 	if (_handle_deleted_files(req) == 0) {
663 		/* We found a file that's been marked for deleting but not actually
664 		 *  deleted yet.  This function will get called again once the delete
665 		 *  operation is completed.
666 		 */
667 		return;
668 	}
669 
670 	args->fn.fs_op_with_handle(args->arg, fs, 0);
671 	free_fs_request(req);
672 
673 }
674 
675 static void
676 _file_build_trace_arg_name(struct spdk_file *f)
677 {
678 	f->trace_arg_name = 0;
679 	memcpy(&f->trace_arg_name, f->name,
680 	       spdk_min(sizeof(f->trace_arg_name), strlen(f->name)));
681 }
682 
683 static void
684 iter_cb(void *ctx, struct spdk_blob *blob, int rc)
685 {
686 	struct spdk_fs_request *req = ctx;
687 	struct spdk_fs_cb_args *args = &req->args;
688 	struct spdk_filesystem *fs = args->fs;
689 	uint64_t *length;
690 	const char *name;
691 	uint32_t *is_deleted;
692 	size_t value_len;
693 
694 	if (rc < 0) {
695 		args->fn.fs_op_with_handle(args->arg, fs, rc);
696 		free_fs_request(req);
697 		return;
698 	}
699 
700 	rc = spdk_blob_get_xattr_value(blob, "name", (const void **)&name, &value_len);
701 	if (rc < 0) {
702 		args->fn.fs_op_with_handle(args->arg, fs, rc);
703 		free_fs_request(req);
704 		return;
705 	}
706 
707 	rc = spdk_blob_get_xattr_value(blob, "length", (const void **)&length, &value_len);
708 	if (rc < 0) {
709 		args->fn.fs_op_with_handle(args->arg, fs, rc);
710 		free_fs_request(req);
711 		return;
712 	}
713 
714 	assert(value_len == 8);
715 
716 	/* This file could be deleted last time without close it, then app crashed, so we delete it now */
717 	rc = spdk_blob_get_xattr_value(blob, "is_deleted", (const void **)&is_deleted, &value_len);
718 	if (rc < 0) {
719 		struct spdk_file *f;
720 
721 		f = file_alloc(fs);
722 		if (f == NULL) {
723 			SPDK_ERRLOG("Cannot allocate file to handle deleted file on disk\n");
724 			args->fn.fs_op_with_handle(args->arg, fs, -ENOMEM);
725 			free_fs_request(req);
726 			return;
727 		}
728 
729 		f->name = strdup(name);
730 		_file_build_trace_arg_name(f);
731 		f->blobid = spdk_blob_get_id(blob);
732 		f->length = *length;
733 		f->length_flushed = *length;
734 		f->length_xattr = *length;
735 		f->append_pos = *length;
736 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "added file %s length=%ju\n", f->name, f->length);
737 	} else {
738 		struct spdk_deleted_file *deleted_file;
739 
740 		deleted_file = calloc(1, sizeof(*deleted_file));
741 		if (deleted_file == NULL) {
742 			args->fn.fs_op_with_handle(args->arg, fs, -ENOMEM);
743 			free_fs_request(req);
744 			return;
745 		}
746 		deleted_file->id = spdk_blob_get_id(blob);
747 		TAILQ_INSERT_TAIL(&args->op.fs_load.deleted_files, deleted_file, tailq);
748 	}
749 }
750 
751 static void
752 load_cb(void *ctx, struct spdk_blob_store *bs, int bserrno)
753 {
754 	struct spdk_fs_request *req = ctx;
755 	struct spdk_fs_cb_args *args = &req->args;
756 	struct spdk_filesystem *fs = args->fs;
757 	struct spdk_bs_type bstype;
758 	static const struct spdk_bs_type blobfs_type = {SPDK_BLOBFS_SIGNATURE};
759 	static const struct spdk_bs_type zeros;
760 
761 	if (bserrno != 0) {
762 		args->fn.fs_op_with_handle(args->arg, NULL, bserrno);
763 		free_fs_request(req);
764 		spdk_fs_free_io_channels(fs);
765 		spdk_fs_io_device_unregister(fs);
766 		return;
767 	}
768 
769 	bstype = spdk_bs_get_bstype(bs);
770 
771 	if (!memcmp(&bstype, &zeros, sizeof(bstype))) {
772 		SPDK_DEBUGLOG(SPDK_LOG_BLOB, "assigning bstype\n");
773 		spdk_bs_set_bstype(bs, blobfs_type);
774 	} else if (memcmp(&bstype, &blobfs_type, sizeof(bstype))) {
775 		SPDK_ERRLOG("not blobfs\n");
776 		SPDK_LOGDUMP(SPDK_LOG_BLOB, "bstype", &bstype, sizeof(bstype));
777 		args->fn.fs_op_with_handle(args->arg, NULL, -EINVAL);
778 		free_fs_request(req);
779 		spdk_fs_free_io_channels(fs);
780 		spdk_fs_io_device_unregister(fs);
781 		return;
782 	}
783 
784 	common_fs_bs_init(fs, bs);
785 	fs_load_done(req, 0);
786 }
787 
788 static void
789 spdk_fs_io_device_unregister(struct spdk_filesystem *fs)
790 {
791 	assert(fs != NULL);
792 	spdk_io_device_unregister(&fs->md_target, NULL);
793 	spdk_io_device_unregister(&fs->sync_target, NULL);
794 	spdk_io_device_unregister(&fs->io_target, NULL);
795 	free(fs);
796 }
797 
798 static void
799 spdk_fs_free_io_channels(struct spdk_filesystem *fs)
800 {
801 	assert(fs != NULL);
802 	spdk_fs_free_io_channel(fs->md_target.md_io_channel);
803 	spdk_fs_free_io_channel(fs->sync_target.sync_io_channel);
804 }
805 
806 void
807 spdk_fs_load(struct spdk_bs_dev *dev, fs_send_request_fn send_request_fn,
808 	     spdk_fs_op_with_handle_complete cb_fn, void *cb_arg)
809 {
810 	struct spdk_filesystem *fs;
811 	struct spdk_fs_cb_args *args;
812 	struct spdk_fs_request *req;
813 	struct spdk_bs_opts	bs_opts;
814 
815 	fs = fs_alloc(dev, send_request_fn);
816 	if (fs == NULL) {
817 		cb_fn(cb_arg, NULL, -ENOMEM);
818 		return;
819 	}
820 
821 	fs_conf_parse();
822 
823 	req = alloc_fs_request(fs->md_target.md_fs_channel);
824 	if (req == NULL) {
825 		spdk_fs_free_io_channels(fs);
826 		spdk_fs_io_device_unregister(fs);
827 		cb_fn(cb_arg, NULL, -ENOMEM);
828 		return;
829 	}
830 
831 	args = &req->args;
832 	args->fn.fs_op_with_handle = cb_fn;
833 	args->arg = cb_arg;
834 	args->fs = fs;
835 	TAILQ_INIT(&args->op.fs_load.deleted_files);
836 	spdk_bs_opts_init(&bs_opts);
837 	bs_opts.iter_cb_fn = iter_cb;
838 	bs_opts.iter_cb_arg = req;
839 	spdk_bs_load(dev, &bs_opts, load_cb, req);
840 }
841 
842 static void
843 unload_cb(void *ctx, int bserrno)
844 {
845 	struct spdk_fs_request *req = ctx;
846 	struct spdk_fs_cb_args *args = &req->args;
847 	struct spdk_filesystem *fs = args->fs;
848 	struct spdk_file *file, *tmp;
849 
850 	TAILQ_FOREACH_SAFE(file, &fs->files, tailq, tmp) {
851 		TAILQ_REMOVE(&fs->files, file, tailq);
852 		cache_free_buffers(file);
853 		free(file->name);
854 		free(file->tree);
855 		free(file);
856 	}
857 
858 	pthread_mutex_lock(&g_cache_init_lock);
859 	g_fs_count--;
860 	if (g_fs_count == 0) {
861 		__free_cache();
862 	}
863 	pthread_mutex_unlock(&g_cache_init_lock);
864 
865 	args->fn.fs_op(args->arg, bserrno);
866 	free(req);
867 
868 	spdk_fs_io_device_unregister(fs);
869 }
870 
871 void
872 spdk_fs_unload(struct spdk_filesystem *fs, spdk_fs_op_complete cb_fn, void *cb_arg)
873 {
874 	struct spdk_fs_request *req;
875 	struct spdk_fs_cb_args *args;
876 
877 	/*
878 	 * We must free the md_channel before unloading the blobstore, so just
879 	 *  allocate this request from the general heap.
880 	 */
881 	req = calloc(1, sizeof(*req));
882 	if (req == NULL) {
883 		cb_fn(cb_arg, -ENOMEM);
884 		return;
885 	}
886 
887 	args = &req->args;
888 	args->fn.fs_op = cb_fn;
889 	args->arg = cb_arg;
890 	args->fs = fs;
891 
892 	spdk_fs_free_io_channels(fs);
893 	spdk_bs_unload(fs->bs, unload_cb, req);
894 }
895 
896 static struct spdk_file *
897 fs_find_file(struct spdk_filesystem *fs, const char *name)
898 {
899 	struct spdk_file *file;
900 
901 	TAILQ_FOREACH(file, &fs->files, tailq) {
902 		if (!strncmp(name, file->name, SPDK_FILE_NAME_MAX)) {
903 			return file;
904 		}
905 	}
906 
907 	return NULL;
908 }
909 
910 void
911 spdk_fs_file_stat_async(struct spdk_filesystem *fs, const char *name,
912 			spdk_file_stat_op_complete cb_fn, void *cb_arg)
913 {
914 	struct spdk_file_stat stat;
915 	struct spdk_file *f = NULL;
916 
917 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
918 		cb_fn(cb_arg, NULL, -ENAMETOOLONG);
919 		return;
920 	}
921 
922 	f = fs_find_file(fs, name);
923 	if (f != NULL) {
924 		stat.blobid = f->blobid;
925 		stat.size = f->append_pos >= f->length ? f->append_pos : f->length;
926 		cb_fn(cb_arg, &stat, 0);
927 		return;
928 	}
929 
930 	cb_fn(cb_arg, NULL, -ENOENT);
931 }
932 
933 static void
934 __copy_stat(void *arg, struct spdk_file_stat *stat, int fserrno)
935 {
936 	struct spdk_fs_request *req = arg;
937 	struct spdk_fs_cb_args *args = &req->args;
938 
939 	args->rc = fserrno;
940 	if (fserrno == 0) {
941 		memcpy(args->arg, stat, sizeof(*stat));
942 	}
943 	sem_post(args->sem);
944 }
945 
946 static void
947 __file_stat(void *arg)
948 {
949 	struct spdk_fs_request *req = arg;
950 	struct spdk_fs_cb_args *args = &req->args;
951 
952 	spdk_fs_file_stat_async(args->fs, args->op.stat.name,
953 				args->fn.stat_op, req);
954 }
955 
956 int
957 spdk_fs_file_stat(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
958 		  const char *name, struct spdk_file_stat *stat)
959 {
960 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
961 	struct spdk_fs_request *req;
962 	int rc;
963 
964 	req = alloc_fs_request(channel);
965 	if (req == NULL) {
966 		SPDK_ERRLOG("Cannot allocate stat req on file=%s\n", name);
967 		return -ENOMEM;
968 	}
969 
970 	req->args.fs = fs;
971 	req->args.op.stat.name = name;
972 	req->args.fn.stat_op = __copy_stat;
973 	req->args.arg = stat;
974 	req->args.sem = &channel->sem;
975 	channel->send_request(__file_stat, req);
976 	sem_wait(&channel->sem);
977 
978 	rc = req->args.rc;
979 	free_fs_request(req);
980 
981 	return rc;
982 }
983 
984 static void
985 fs_create_blob_close_cb(void *ctx, int bserrno)
986 {
987 	int rc;
988 	struct spdk_fs_request *req = ctx;
989 	struct spdk_fs_cb_args *args = &req->args;
990 
991 	rc = args->rc ? args->rc : bserrno;
992 	args->fn.file_op(args->arg, rc);
993 	free_fs_request(req);
994 }
995 
996 static void
997 fs_create_blob_resize_cb(void *ctx, int bserrno)
998 {
999 	struct spdk_fs_request *req = ctx;
1000 	struct spdk_fs_cb_args *args = &req->args;
1001 	struct spdk_file *f = args->file;
1002 	struct spdk_blob *blob = args->op.create.blob;
1003 	uint64_t length = 0;
1004 
1005 	args->rc = bserrno;
1006 	if (bserrno) {
1007 		spdk_blob_close(blob, fs_create_blob_close_cb, args);
1008 		return;
1009 	}
1010 
1011 	spdk_blob_set_xattr(blob, "name", f->name, strlen(f->name) + 1);
1012 	spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
1013 
1014 	spdk_blob_close(blob, fs_create_blob_close_cb, args);
1015 }
1016 
1017 static void
1018 fs_create_blob_open_cb(void *ctx, struct spdk_blob *blob, int bserrno)
1019 {
1020 	struct spdk_fs_request *req = ctx;
1021 	struct spdk_fs_cb_args *args = &req->args;
1022 
1023 	if (bserrno) {
1024 		args->fn.file_op(args->arg, bserrno);
1025 		free_fs_request(req);
1026 		return;
1027 	}
1028 
1029 	args->op.create.blob = blob;
1030 	spdk_blob_resize(blob, 1, fs_create_blob_resize_cb, req);
1031 }
1032 
1033 static void
1034 fs_create_blob_create_cb(void *ctx, spdk_blob_id blobid, int bserrno)
1035 {
1036 	struct spdk_fs_request *req = ctx;
1037 	struct spdk_fs_cb_args *args = &req->args;
1038 	struct spdk_file *f = args->file;
1039 
1040 	if (bserrno) {
1041 		args->fn.file_op(args->arg, bserrno);
1042 		free_fs_request(req);
1043 		return;
1044 	}
1045 
1046 	f->blobid = blobid;
1047 	spdk_bs_open_blob(f->fs->bs, blobid, fs_create_blob_open_cb, req);
1048 }
1049 
1050 void
1051 spdk_fs_create_file_async(struct spdk_filesystem *fs, const char *name,
1052 			  spdk_file_op_complete cb_fn, void *cb_arg)
1053 {
1054 	struct spdk_file *file;
1055 	struct spdk_fs_request *req;
1056 	struct spdk_fs_cb_args *args;
1057 
1058 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1059 		cb_fn(cb_arg, -ENAMETOOLONG);
1060 		return;
1061 	}
1062 
1063 	file = fs_find_file(fs, name);
1064 	if (file != NULL) {
1065 		cb_fn(cb_arg, -EEXIST);
1066 		return;
1067 	}
1068 
1069 	file = file_alloc(fs);
1070 	if (file == NULL) {
1071 		SPDK_ERRLOG("Cannot allocate new file for creation\n");
1072 		cb_fn(cb_arg, -ENOMEM);
1073 		return;
1074 	}
1075 
1076 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1077 	if (req == NULL) {
1078 		SPDK_ERRLOG("Cannot allocate create async req for file=%s\n", name);
1079 		cb_fn(cb_arg, -ENOMEM);
1080 		return;
1081 	}
1082 
1083 	args = &req->args;
1084 	args->file = file;
1085 	args->fn.file_op = cb_fn;
1086 	args->arg = cb_arg;
1087 
1088 	file->name = strdup(name);
1089 	_file_build_trace_arg_name(file);
1090 	spdk_bs_create_blob(fs->bs, fs_create_blob_create_cb, args);
1091 }
1092 
1093 static void
1094 __fs_create_file_done(void *arg, int fserrno)
1095 {
1096 	struct spdk_fs_request *req = arg;
1097 	struct spdk_fs_cb_args *args = &req->args;
1098 
1099 	args->rc = fserrno;
1100 	sem_post(args->sem);
1101 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.create.name);
1102 }
1103 
1104 static void
1105 __fs_create_file(void *arg)
1106 {
1107 	struct spdk_fs_request *req = arg;
1108 	struct spdk_fs_cb_args *args = &req->args;
1109 
1110 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.create.name);
1111 	spdk_fs_create_file_async(args->fs, args->op.create.name, __fs_create_file_done, req);
1112 }
1113 
1114 int
1115 spdk_fs_create_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx, const char *name)
1116 {
1117 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1118 	struct spdk_fs_request *req;
1119 	struct spdk_fs_cb_args *args;
1120 	int rc;
1121 
1122 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1123 
1124 	req = alloc_fs_request(channel);
1125 	if (req == NULL) {
1126 		SPDK_ERRLOG("Cannot allocate req to create file=%s\n", name);
1127 		return -ENOMEM;
1128 	}
1129 
1130 	args = &req->args;
1131 	args->fs = fs;
1132 	args->op.create.name = name;
1133 	args->sem = &channel->sem;
1134 	fs->send_request(__fs_create_file, req);
1135 	sem_wait(&channel->sem);
1136 	rc = args->rc;
1137 	free_fs_request(req);
1138 
1139 	return rc;
1140 }
1141 
1142 static void
1143 fs_open_blob_done(void *ctx, struct spdk_blob *blob, int bserrno)
1144 {
1145 	struct spdk_fs_request *req = ctx;
1146 	struct spdk_fs_cb_args *args = &req->args;
1147 	struct spdk_file *f = args->file;
1148 
1149 	f->blob = blob;
1150 	while (!TAILQ_EMPTY(&f->open_requests)) {
1151 		req = TAILQ_FIRST(&f->open_requests);
1152 		args = &req->args;
1153 		TAILQ_REMOVE(&f->open_requests, req, args.op.open.tailq);
1154 		spdk_trace_record(TRACE_BLOBFS_OPEN, 0, 0, 0, f->trace_arg_name);
1155 		args->fn.file_op_with_handle(args->arg, f, bserrno);
1156 		free_fs_request(req);
1157 	}
1158 }
1159 
1160 static void
1161 fs_open_blob_create_cb(void *ctx, int bserrno)
1162 {
1163 	struct spdk_fs_request *req = ctx;
1164 	struct spdk_fs_cb_args *args = &req->args;
1165 	struct spdk_file *file = args->file;
1166 	struct spdk_filesystem *fs = args->fs;
1167 
1168 	if (file == NULL) {
1169 		/*
1170 		 * This is from an open with CREATE flag - the file
1171 		 *  is now created so look it up in the file list for this
1172 		 *  filesystem.
1173 		 */
1174 		file = fs_find_file(fs, args->op.open.name);
1175 		assert(file != NULL);
1176 		args->file = file;
1177 	}
1178 
1179 	file->ref_count++;
1180 	TAILQ_INSERT_TAIL(&file->open_requests, req, args.op.open.tailq);
1181 	if (file->ref_count == 1) {
1182 		assert(file->blob == NULL);
1183 		spdk_bs_open_blob(fs->bs, file->blobid, fs_open_blob_done, req);
1184 	} else if (file->blob != NULL) {
1185 		fs_open_blob_done(req, file->blob, 0);
1186 	} else {
1187 		/*
1188 		 * The blob open for this file is in progress due to a previous
1189 		 *  open request.  When that open completes, it will invoke the
1190 		 *  open callback for this request.
1191 		 */
1192 	}
1193 }
1194 
1195 void
1196 spdk_fs_open_file_async(struct spdk_filesystem *fs, const char *name, uint32_t flags,
1197 			spdk_file_op_with_handle_complete cb_fn, void *cb_arg)
1198 {
1199 	struct spdk_file *f = NULL;
1200 	struct spdk_fs_request *req;
1201 	struct spdk_fs_cb_args *args;
1202 
1203 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1204 		cb_fn(cb_arg, NULL, -ENAMETOOLONG);
1205 		return;
1206 	}
1207 
1208 	f = fs_find_file(fs, name);
1209 	if (f == NULL && !(flags & SPDK_BLOBFS_OPEN_CREATE)) {
1210 		cb_fn(cb_arg, NULL, -ENOENT);
1211 		return;
1212 	}
1213 
1214 	if (f != NULL && f->is_deleted == true) {
1215 		cb_fn(cb_arg, NULL, -ENOENT);
1216 		return;
1217 	}
1218 
1219 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1220 	if (req == NULL) {
1221 		SPDK_ERRLOG("Cannot allocate async open req for file=%s\n", name);
1222 		cb_fn(cb_arg, NULL, -ENOMEM);
1223 		return;
1224 	}
1225 
1226 	args = &req->args;
1227 	args->fn.file_op_with_handle = cb_fn;
1228 	args->arg = cb_arg;
1229 	args->file = f;
1230 	args->fs = fs;
1231 	args->op.open.name = name;
1232 
1233 	if (f == NULL) {
1234 		spdk_fs_create_file_async(fs, name, fs_open_blob_create_cb, req);
1235 	} else {
1236 		fs_open_blob_create_cb(req, 0);
1237 	}
1238 }
1239 
1240 static void
1241 __fs_open_file_done(void *arg, struct spdk_file *file, int bserrno)
1242 {
1243 	struct spdk_fs_request *req = arg;
1244 	struct spdk_fs_cb_args *args = &req->args;
1245 
1246 	args->file = file;
1247 	__wake_caller(args, bserrno);
1248 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.open.name);
1249 }
1250 
1251 static void
1252 __fs_open_file(void *arg)
1253 {
1254 	struct spdk_fs_request *req = arg;
1255 	struct spdk_fs_cb_args *args = &req->args;
1256 
1257 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.open.name);
1258 	spdk_fs_open_file_async(args->fs, args->op.open.name, args->op.open.flags,
1259 				__fs_open_file_done, req);
1260 }
1261 
1262 int
1263 spdk_fs_open_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1264 		  const char *name, uint32_t flags, struct spdk_file **file)
1265 {
1266 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1267 	struct spdk_fs_request *req;
1268 	struct spdk_fs_cb_args *args;
1269 	int rc;
1270 
1271 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1272 
1273 	req = alloc_fs_request(channel);
1274 	if (req == NULL) {
1275 		SPDK_ERRLOG("Cannot allocate req for opening file=%s\n", name);
1276 		return -ENOMEM;
1277 	}
1278 
1279 	args = &req->args;
1280 	args->fs = fs;
1281 	args->op.open.name = name;
1282 	args->op.open.flags = flags;
1283 	args->sem = &channel->sem;
1284 	fs->send_request(__fs_open_file, req);
1285 	sem_wait(&channel->sem);
1286 	rc = args->rc;
1287 	if (rc == 0) {
1288 		*file = args->file;
1289 	} else {
1290 		*file = NULL;
1291 	}
1292 	free_fs_request(req);
1293 
1294 	return rc;
1295 }
1296 
1297 static void
1298 fs_rename_blob_close_cb(void *ctx, int bserrno)
1299 {
1300 	struct spdk_fs_request *req = ctx;
1301 	struct spdk_fs_cb_args *args = &req->args;
1302 
1303 	args->fn.fs_op(args->arg, bserrno);
1304 	free_fs_request(req);
1305 }
1306 
1307 static void
1308 fs_rename_blob_open_cb(void *ctx, struct spdk_blob *blob, int bserrno)
1309 {
1310 	struct spdk_fs_request *req = ctx;
1311 	struct spdk_fs_cb_args *args = &req->args;
1312 	const char *new_name = args->op.rename.new_name;
1313 
1314 	spdk_blob_set_xattr(blob, "name", new_name, strlen(new_name) + 1);
1315 	spdk_blob_close(blob, fs_rename_blob_close_cb, req);
1316 }
1317 
1318 static void
1319 __spdk_fs_md_rename_file(struct spdk_fs_request *req)
1320 {
1321 	struct spdk_fs_cb_args *args = &req->args;
1322 	struct spdk_file *f;
1323 
1324 	f = fs_find_file(args->fs, args->op.rename.old_name);
1325 	if (f == NULL) {
1326 		args->fn.fs_op(args->arg, -ENOENT);
1327 		free_fs_request(req);
1328 		return;
1329 	}
1330 
1331 	free(f->name);
1332 	f->name = strdup(args->op.rename.new_name);
1333 	_file_build_trace_arg_name(f);
1334 	args->file = f;
1335 	spdk_bs_open_blob(args->fs->bs, f->blobid, fs_rename_blob_open_cb, req);
1336 }
1337 
1338 static void
1339 fs_rename_delete_done(void *arg, int fserrno)
1340 {
1341 	__spdk_fs_md_rename_file(arg);
1342 }
1343 
1344 void
1345 spdk_fs_rename_file_async(struct spdk_filesystem *fs,
1346 			  const char *old_name, const char *new_name,
1347 			  spdk_file_op_complete cb_fn, void *cb_arg)
1348 {
1349 	struct spdk_file *f;
1350 	struct spdk_fs_request *req;
1351 	struct spdk_fs_cb_args *args;
1352 
1353 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "old=%s new=%s\n", old_name, new_name);
1354 	if (strnlen(new_name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1355 		cb_fn(cb_arg, -ENAMETOOLONG);
1356 		return;
1357 	}
1358 
1359 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1360 	if (req == NULL) {
1361 		SPDK_ERRLOG("Cannot allocate rename async req for renaming file from %s to %s\n", old_name,
1362 			    new_name);
1363 		cb_fn(cb_arg, -ENOMEM);
1364 		return;
1365 	}
1366 
1367 	args = &req->args;
1368 	args->fn.fs_op = cb_fn;
1369 	args->fs = fs;
1370 	args->arg = cb_arg;
1371 	args->op.rename.old_name = old_name;
1372 	args->op.rename.new_name = new_name;
1373 
1374 	f = fs_find_file(fs, new_name);
1375 	if (f == NULL) {
1376 		__spdk_fs_md_rename_file(req);
1377 		return;
1378 	}
1379 
1380 	/*
1381 	 * The rename overwrites an existing file.  So delete the existing file, then
1382 	 *  do the actual rename.
1383 	 */
1384 	spdk_fs_delete_file_async(fs, new_name, fs_rename_delete_done, req);
1385 }
1386 
1387 static void
1388 __fs_rename_file_done(void *arg, int fserrno)
1389 {
1390 	struct spdk_fs_request *req = arg;
1391 	struct spdk_fs_cb_args *args = &req->args;
1392 
1393 	__wake_caller(args, fserrno);
1394 }
1395 
1396 static void
1397 __fs_rename_file(void *arg)
1398 {
1399 	struct spdk_fs_request *req = arg;
1400 	struct spdk_fs_cb_args *args = &req->args;
1401 
1402 	spdk_fs_rename_file_async(args->fs, args->op.rename.old_name, args->op.rename.new_name,
1403 				  __fs_rename_file_done, req);
1404 }
1405 
1406 int
1407 spdk_fs_rename_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1408 		    const char *old_name, const char *new_name)
1409 {
1410 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1411 	struct spdk_fs_request *req;
1412 	struct spdk_fs_cb_args *args;
1413 	int rc;
1414 
1415 	req = alloc_fs_request(channel);
1416 	if (req == NULL) {
1417 		SPDK_ERRLOG("Cannot allocate rename req for file=%s\n", old_name);
1418 		return -ENOMEM;
1419 	}
1420 
1421 	args = &req->args;
1422 
1423 	args->fs = fs;
1424 	args->op.rename.old_name = old_name;
1425 	args->op.rename.new_name = new_name;
1426 	args->sem = &channel->sem;
1427 	fs->send_request(__fs_rename_file, req);
1428 	sem_wait(&channel->sem);
1429 	rc = args->rc;
1430 	free_fs_request(req);
1431 	return rc;
1432 }
1433 
1434 static void
1435 blob_delete_cb(void *ctx, int bserrno)
1436 {
1437 	struct spdk_fs_request *req = ctx;
1438 	struct spdk_fs_cb_args *args = &req->args;
1439 
1440 	args->fn.file_op(args->arg, bserrno);
1441 	free_fs_request(req);
1442 }
1443 
1444 void
1445 spdk_fs_delete_file_async(struct spdk_filesystem *fs, const char *name,
1446 			  spdk_file_op_complete cb_fn, void *cb_arg)
1447 {
1448 	struct spdk_file *f;
1449 	spdk_blob_id blobid;
1450 	struct spdk_fs_request *req;
1451 	struct spdk_fs_cb_args *args;
1452 
1453 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1454 
1455 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1456 		cb_fn(cb_arg, -ENAMETOOLONG);
1457 		return;
1458 	}
1459 
1460 	f = fs_find_file(fs, name);
1461 	if (f == NULL) {
1462 		SPDK_ERRLOG("Cannot find the file=%s to deleted\n", name);
1463 		cb_fn(cb_arg, -ENOENT);
1464 		return;
1465 	}
1466 
1467 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1468 	if (req == NULL) {
1469 		SPDK_ERRLOG("Cannot allocate the req for the file=%s to deleted\n", name);
1470 		cb_fn(cb_arg, -ENOMEM);
1471 		return;
1472 	}
1473 
1474 	args = &req->args;
1475 	args->fn.file_op = cb_fn;
1476 	args->arg = cb_arg;
1477 
1478 	if (f->ref_count > 0) {
1479 		/* If the ref > 0, we mark the file as deleted and delete it when we close it. */
1480 		f->is_deleted = true;
1481 		spdk_blob_set_xattr(f->blob, "is_deleted", &f->is_deleted, sizeof(bool));
1482 		spdk_blob_sync_md(f->blob, blob_delete_cb, req);
1483 		return;
1484 	}
1485 
1486 	TAILQ_REMOVE(&fs->files, f, tailq);
1487 
1488 	cache_free_buffers(f);
1489 
1490 	blobid = f->blobid;
1491 
1492 	free(f->name);
1493 	free(f->tree);
1494 	free(f);
1495 
1496 	spdk_bs_delete_blob(fs->bs, blobid, blob_delete_cb, req);
1497 }
1498 
1499 static uint64_t
1500 fs_name_to_uint64(const char *name)
1501 {
1502 	uint64_t result = 0;
1503 	memcpy(&result, name, spdk_min(sizeof(result), strlen(name)));
1504 	return result;
1505 }
1506 
1507 static void
1508 __fs_delete_file_done(void *arg, int fserrno)
1509 {
1510 	struct spdk_fs_request *req = arg;
1511 	struct spdk_fs_cb_args *args = &req->args;
1512 
1513 	spdk_trace_record(TRACE_BLOBFS_DELETE_DONE, 0, 0, 0, fs_name_to_uint64(args->op.delete.name));
1514 	__wake_caller(args, fserrno);
1515 }
1516 
1517 static void
1518 __fs_delete_file(void *arg)
1519 {
1520 	struct spdk_fs_request *req = arg;
1521 	struct spdk_fs_cb_args *args = &req->args;
1522 
1523 	spdk_trace_record(TRACE_BLOBFS_DELETE_START, 0, 0, 0, fs_name_to_uint64(args->op.delete.name));
1524 	spdk_fs_delete_file_async(args->fs, args->op.delete.name, __fs_delete_file_done, req);
1525 }
1526 
1527 int
1528 spdk_fs_delete_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1529 		    const char *name)
1530 {
1531 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1532 	struct spdk_fs_request *req;
1533 	struct spdk_fs_cb_args *args;
1534 	int rc;
1535 
1536 	req = alloc_fs_request(channel);
1537 	if (req == NULL) {
1538 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "Cannot allocate req to delete file=%s\n", name);
1539 		return -ENOMEM;
1540 	}
1541 
1542 	args = &req->args;
1543 	args->fs = fs;
1544 	args->op.delete.name = name;
1545 	args->sem = &channel->sem;
1546 	fs->send_request(__fs_delete_file, req);
1547 	sem_wait(&channel->sem);
1548 	rc = args->rc;
1549 	free_fs_request(req);
1550 
1551 	return rc;
1552 }
1553 
1554 spdk_fs_iter
1555 spdk_fs_iter_first(struct spdk_filesystem *fs)
1556 {
1557 	struct spdk_file *f;
1558 
1559 	f = TAILQ_FIRST(&fs->files);
1560 	return f;
1561 }
1562 
1563 spdk_fs_iter
1564 spdk_fs_iter_next(spdk_fs_iter iter)
1565 {
1566 	struct spdk_file *f = iter;
1567 
1568 	if (f == NULL) {
1569 		return NULL;
1570 	}
1571 
1572 	f = TAILQ_NEXT(f, tailq);
1573 	return f;
1574 }
1575 
1576 const char *
1577 spdk_file_get_name(struct spdk_file *file)
1578 {
1579 	return file->name;
1580 }
1581 
1582 uint64_t
1583 spdk_file_get_length(struct spdk_file *file)
1584 {
1585 	uint64_t length;
1586 
1587 	assert(file != NULL);
1588 
1589 	length = file->append_pos >= file->length ? file->append_pos : file->length;
1590 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s length=0x%jx\n", file->name, length);
1591 	return length;
1592 }
1593 
1594 static void
1595 fs_truncate_complete_cb(void *ctx, int bserrno)
1596 {
1597 	struct spdk_fs_request *req = ctx;
1598 	struct spdk_fs_cb_args *args = &req->args;
1599 
1600 	args->fn.file_op(args->arg, bserrno);
1601 	free_fs_request(req);
1602 }
1603 
1604 static void
1605 fs_truncate_resize_cb(void *ctx, int bserrno)
1606 {
1607 	struct spdk_fs_request *req = ctx;
1608 	struct spdk_fs_cb_args *args = &req->args;
1609 	struct spdk_file *file = args->file;
1610 	uint64_t *length = &args->op.truncate.length;
1611 
1612 	if (bserrno) {
1613 		args->fn.file_op(args->arg, bserrno);
1614 		free_fs_request(req);
1615 		return;
1616 	}
1617 
1618 	spdk_blob_set_xattr(file->blob, "length", length, sizeof(*length));
1619 
1620 	file->length = *length;
1621 	if (file->append_pos > file->length) {
1622 		file->append_pos = file->length;
1623 	}
1624 
1625 	spdk_blob_sync_md(file->blob, fs_truncate_complete_cb, req);
1626 }
1627 
1628 static uint64_t
1629 __bytes_to_clusters(uint64_t length, uint64_t cluster_sz)
1630 {
1631 	return (length + cluster_sz - 1) / cluster_sz;
1632 }
1633 
1634 void
1635 spdk_file_truncate_async(struct spdk_file *file, uint64_t length,
1636 			 spdk_file_op_complete cb_fn, void *cb_arg)
1637 {
1638 	struct spdk_filesystem *fs;
1639 	size_t num_clusters;
1640 	struct spdk_fs_request *req;
1641 	struct spdk_fs_cb_args *args;
1642 
1643 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s old=0x%jx new=0x%jx\n", file->name, file->length, length);
1644 	if (length == file->length) {
1645 		cb_fn(cb_arg, 0);
1646 		return;
1647 	}
1648 
1649 	req = alloc_fs_request(file->fs->md_target.md_fs_channel);
1650 	if (req == NULL) {
1651 		cb_fn(cb_arg, -ENOMEM);
1652 		return;
1653 	}
1654 
1655 	args = &req->args;
1656 	args->fn.file_op = cb_fn;
1657 	args->arg = cb_arg;
1658 	args->file = file;
1659 	args->op.truncate.length = length;
1660 	fs = file->fs;
1661 
1662 	num_clusters = __bytes_to_clusters(length, fs->bs_opts.cluster_sz);
1663 
1664 	spdk_blob_resize(file->blob, num_clusters, fs_truncate_resize_cb, req);
1665 }
1666 
1667 static void
1668 __truncate(void *arg)
1669 {
1670 	struct spdk_fs_request *req = arg;
1671 	struct spdk_fs_cb_args *args = &req->args;
1672 
1673 	spdk_file_truncate_async(args->file, args->op.truncate.length,
1674 				 args->fn.file_op, args);
1675 }
1676 
1677 int
1678 spdk_file_truncate(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
1679 		   uint64_t length)
1680 {
1681 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1682 	struct spdk_fs_request *req;
1683 	struct spdk_fs_cb_args *args;
1684 	int rc;
1685 
1686 	req = alloc_fs_request(channel);
1687 	if (req == NULL) {
1688 		return -ENOMEM;
1689 	}
1690 
1691 	args = &req->args;
1692 
1693 	args->file = file;
1694 	args->op.truncate.length = length;
1695 	args->fn.file_op = __wake_caller;
1696 	args->sem = &channel->sem;
1697 
1698 	channel->send_request(__truncate, req);
1699 	sem_wait(&channel->sem);
1700 	rc = args->rc;
1701 	free_fs_request(req);
1702 
1703 	return rc;
1704 }
1705 
1706 static void
1707 __rw_done(void *ctx, int bserrno)
1708 {
1709 	struct spdk_fs_request *req = ctx;
1710 	struct spdk_fs_cb_args *args = &req->args;
1711 
1712 	spdk_free(args->op.rw.pin_buf);
1713 	args->fn.file_op(args->arg, bserrno);
1714 	free_fs_request(req);
1715 }
1716 
1717 static void
1718 _copy_iovs_to_buf(void *buf, size_t buf_len, struct iovec *iovs, int iovcnt)
1719 {
1720 	int i;
1721 	size_t len;
1722 
1723 	for (i = 0; i < iovcnt; i++) {
1724 		len = spdk_min(iovs[i].iov_len, buf_len);
1725 		memcpy(buf, iovs[i].iov_base, len);
1726 		buf += len;
1727 		assert(buf_len >= len);
1728 		buf_len -= len;
1729 	}
1730 }
1731 
1732 static void
1733 _copy_buf_to_iovs(struct iovec *iovs, int iovcnt, void *buf, size_t buf_len)
1734 {
1735 	int i;
1736 	size_t len;
1737 
1738 	for (i = 0; i < iovcnt; i++) {
1739 		len = spdk_min(iovs[i].iov_len, buf_len);
1740 		memcpy(iovs[i].iov_base, buf, len);
1741 		buf += len;
1742 		assert(buf_len >= len);
1743 		buf_len -= len;
1744 	}
1745 }
1746 
1747 static void
1748 __read_done(void *ctx, int bserrno)
1749 {
1750 	struct spdk_fs_request *req = ctx;
1751 	struct spdk_fs_cb_args *args = &req->args;
1752 	void *buf;
1753 
1754 	assert(req != NULL);
1755 	buf = (void *)((uintptr_t)args->op.rw.pin_buf + (args->op.rw.offset & (args->op.rw.blocklen - 1)));
1756 	if (args->op.rw.is_read) {
1757 		_copy_buf_to_iovs(args->iovs, args->iovcnt, buf, args->op.rw.length);
1758 		__rw_done(req, 0);
1759 	} else {
1760 		_copy_iovs_to_buf(buf, args->op.rw.length, args->iovs, args->iovcnt);
1761 		spdk_blob_io_write(args->file->blob, args->op.rw.channel,
1762 				   args->op.rw.pin_buf,
1763 				   args->op.rw.start_lba, args->op.rw.num_lba,
1764 				   __rw_done, req);
1765 	}
1766 }
1767 
1768 static void
1769 __do_blob_read(void *ctx, int fserrno)
1770 {
1771 	struct spdk_fs_request *req = ctx;
1772 	struct spdk_fs_cb_args *args = &req->args;
1773 
1774 	if (fserrno) {
1775 		__rw_done(req, fserrno);
1776 		return;
1777 	}
1778 	spdk_blob_io_read(args->file->blob, args->op.rw.channel,
1779 			  args->op.rw.pin_buf,
1780 			  args->op.rw.start_lba, args->op.rw.num_lba,
1781 			  __read_done, req);
1782 }
1783 
1784 static void
1785 __get_page_parameters(struct spdk_file *file, uint64_t offset, uint64_t length,
1786 		      uint64_t *start_lba, uint32_t *lba_size, uint64_t *num_lba)
1787 {
1788 	uint64_t end_lba;
1789 
1790 	*lba_size = spdk_bs_get_io_unit_size(file->fs->bs);
1791 	*start_lba = offset / *lba_size;
1792 	end_lba = (offset + length - 1) / *lba_size;
1793 	*num_lba = (end_lba - *start_lba + 1);
1794 }
1795 
1796 static void
1797 _fs_request_setup_iovs(struct spdk_fs_request *req, struct iovec *iovs, uint32_t iovcnt)
1798 {
1799 	uint32_t i;
1800 
1801 	for (i = 0; i < iovcnt; i++) {
1802 		req->args.iovs[i].iov_base = iovs[i].iov_base;
1803 		req->args.iovs[i].iov_len = iovs[i].iov_len;
1804 	}
1805 }
1806 
1807 static void
1808 __readvwritev(struct spdk_file *file, struct spdk_io_channel *_channel,
1809 	      struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1810 	      spdk_file_op_complete cb_fn, void *cb_arg, int is_read)
1811 {
1812 	struct spdk_fs_request *req;
1813 	struct spdk_fs_cb_args *args;
1814 	struct spdk_fs_channel *channel = spdk_io_channel_get_ctx(_channel);
1815 	uint64_t start_lba, num_lba, pin_buf_length;
1816 	uint32_t lba_size;
1817 
1818 	if (is_read && offset + length > file->length) {
1819 		cb_fn(cb_arg, -EINVAL);
1820 		return;
1821 	}
1822 
1823 	req = alloc_fs_request_with_iov(channel, iovcnt);
1824 	if (req == NULL) {
1825 		cb_fn(cb_arg, -ENOMEM);
1826 		return;
1827 	}
1828 
1829 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
1830 
1831 	args = &req->args;
1832 	args->fn.file_op = cb_fn;
1833 	args->arg = cb_arg;
1834 	args->file = file;
1835 	args->op.rw.channel = channel->bs_channel;
1836 	_fs_request_setup_iovs(req, iovs, iovcnt);
1837 	args->op.rw.is_read = is_read;
1838 	args->op.rw.offset = offset;
1839 	args->op.rw.blocklen = lba_size;
1840 
1841 	pin_buf_length = num_lba * lba_size;
1842 	args->op.rw.length = pin_buf_length;
1843 	args->op.rw.pin_buf = spdk_malloc(pin_buf_length, lba_size, NULL,
1844 					  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1845 	if (args->op.rw.pin_buf == NULL) {
1846 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "Failed to allocate buf for: file=%s offset=%jx length=%jx\n",
1847 			      file->name, offset, length);
1848 		free_fs_request(req);
1849 		cb_fn(cb_arg, -ENOMEM);
1850 		return;
1851 	}
1852 
1853 	args->op.rw.start_lba = start_lba;
1854 	args->op.rw.num_lba = num_lba;
1855 
1856 	if (!is_read && file->length < offset + length) {
1857 		spdk_file_truncate_async(file, offset + length, __do_blob_read, req);
1858 	} else {
1859 		__do_blob_read(req, 0);
1860 	}
1861 }
1862 
1863 static void
1864 __readwrite(struct spdk_file *file, struct spdk_io_channel *channel,
1865 	    void *payload, uint64_t offset, uint64_t length,
1866 	    spdk_file_op_complete cb_fn, void *cb_arg, int is_read)
1867 {
1868 	struct iovec iov;
1869 
1870 	iov.iov_base = payload;
1871 	iov.iov_len = (size_t)length;
1872 
1873 	__readvwritev(file, channel, &iov, 1, offset, length, cb_fn, cb_arg, is_read);
1874 }
1875 
1876 void
1877 spdk_file_write_async(struct spdk_file *file, struct spdk_io_channel *channel,
1878 		      void *payload, uint64_t offset, uint64_t length,
1879 		      spdk_file_op_complete cb_fn, void *cb_arg)
1880 {
1881 	__readwrite(file, channel, payload, offset, length, cb_fn, cb_arg, 0);
1882 }
1883 
1884 void
1885 spdk_file_writev_async(struct spdk_file *file, struct spdk_io_channel *channel,
1886 		       struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1887 		       spdk_file_op_complete cb_fn, void *cb_arg)
1888 {
1889 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1890 		      file->name, offset, length);
1891 
1892 	__readvwritev(file, channel, iovs, iovcnt, offset, length, cb_fn, cb_arg, 0);
1893 }
1894 
1895 void
1896 spdk_file_read_async(struct spdk_file *file, struct spdk_io_channel *channel,
1897 		     void *payload, uint64_t offset, uint64_t length,
1898 		     spdk_file_op_complete cb_fn, void *cb_arg)
1899 {
1900 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1901 		      file->name, offset, length);
1902 	__readwrite(file, channel, payload, offset, length, cb_fn, cb_arg, 1);
1903 }
1904 
1905 void
1906 spdk_file_readv_async(struct spdk_file *file, struct spdk_io_channel *channel,
1907 		      struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1908 		      spdk_file_op_complete cb_fn, void *cb_arg)
1909 {
1910 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1911 		      file->name, offset, length);
1912 
1913 	__readvwritev(file, channel, iovs, iovcnt, offset, length, cb_fn, cb_arg, 1);
1914 }
1915 
1916 struct spdk_io_channel *
1917 spdk_fs_alloc_io_channel(struct spdk_filesystem *fs)
1918 {
1919 	struct spdk_io_channel *io_channel;
1920 	struct spdk_fs_channel *fs_channel;
1921 
1922 	io_channel = spdk_get_io_channel(&fs->io_target);
1923 	fs_channel = spdk_io_channel_get_ctx(io_channel);
1924 	fs_channel->bs_channel = spdk_bs_alloc_io_channel(fs->bs);
1925 	fs_channel->send_request = __send_request_direct;
1926 
1927 	return io_channel;
1928 }
1929 
1930 void
1931 spdk_fs_free_io_channel(struct spdk_io_channel *channel)
1932 {
1933 	spdk_put_io_channel(channel);
1934 }
1935 
1936 struct spdk_fs_thread_ctx *
1937 spdk_fs_alloc_thread_ctx(struct spdk_filesystem *fs)
1938 {
1939 	struct spdk_fs_thread_ctx *ctx;
1940 
1941 	ctx = calloc(1, sizeof(*ctx));
1942 	if (!ctx) {
1943 		return NULL;
1944 	}
1945 
1946 	_spdk_fs_channel_create(fs, &ctx->ch, 512);
1947 
1948 	ctx->ch.send_request = fs->send_request;
1949 	ctx->ch.sync = 1;
1950 	pthread_spin_init(&ctx->ch.lock, 0);
1951 
1952 	return ctx;
1953 }
1954 
1955 
1956 void
1957 spdk_fs_free_thread_ctx(struct spdk_fs_thread_ctx *ctx)
1958 {
1959 	assert(ctx->ch.sync == 1);
1960 
1961 	while (true) {
1962 		pthread_spin_lock(&ctx->ch.lock);
1963 		if (ctx->ch.outstanding_reqs == 0) {
1964 			pthread_spin_unlock(&ctx->ch.lock);
1965 			break;
1966 		}
1967 		pthread_spin_unlock(&ctx->ch.lock);
1968 		usleep(1000);
1969 	}
1970 
1971 	_spdk_fs_channel_destroy(NULL, &ctx->ch);
1972 	free(ctx);
1973 }
1974 
1975 void
1976 spdk_fs_set_cache_size(uint64_t size_in_mb)
1977 {
1978 	g_fs_cache_size = size_in_mb * 1024 * 1024;
1979 }
1980 
1981 uint64_t
1982 spdk_fs_get_cache_size(void)
1983 {
1984 	return g_fs_cache_size / (1024 * 1024);
1985 }
1986 
1987 static void __file_flush(void *ctx);
1988 
1989 static void *
1990 alloc_cache_memory_buffer(struct spdk_file *context)
1991 {
1992 	struct spdk_file *file;
1993 	void *buf;
1994 
1995 	buf = spdk_mempool_get(g_cache_pool);
1996 	if (buf != NULL) {
1997 		return buf;
1998 	}
1999 
2000 	pthread_spin_lock(&g_caches_lock);
2001 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2002 		if (!file->open_for_writing &&
2003 		    file->priority == SPDK_FILE_PRIORITY_LOW &&
2004 		    file != context) {
2005 			break;
2006 		}
2007 	}
2008 	pthread_spin_unlock(&g_caches_lock);
2009 	if (file != NULL) {
2010 		cache_free_buffers(file);
2011 		buf = spdk_mempool_get(g_cache_pool);
2012 		if (buf != NULL) {
2013 			return buf;
2014 		}
2015 	}
2016 
2017 	pthread_spin_lock(&g_caches_lock);
2018 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2019 		if (!file->open_for_writing && file != context) {
2020 			break;
2021 		}
2022 	}
2023 	pthread_spin_unlock(&g_caches_lock);
2024 	if (file != NULL) {
2025 		cache_free_buffers(file);
2026 		buf = spdk_mempool_get(g_cache_pool);
2027 		if (buf != NULL) {
2028 			return buf;
2029 		}
2030 	}
2031 
2032 	pthread_spin_lock(&g_caches_lock);
2033 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2034 		if (file != context) {
2035 			break;
2036 		}
2037 	}
2038 	pthread_spin_unlock(&g_caches_lock);
2039 	if (file != NULL) {
2040 		cache_free_buffers(file);
2041 		buf = spdk_mempool_get(g_cache_pool);
2042 		if (buf != NULL) {
2043 			return buf;
2044 		}
2045 	}
2046 
2047 	return NULL;
2048 }
2049 
2050 static struct cache_buffer *
2051 cache_insert_buffer(struct spdk_file *file, uint64_t offset)
2052 {
2053 	struct cache_buffer *buf;
2054 	int count = 0;
2055 
2056 	buf = calloc(1, sizeof(*buf));
2057 	if (buf == NULL) {
2058 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "calloc failed\n");
2059 		return NULL;
2060 	}
2061 
2062 	buf->buf = alloc_cache_memory_buffer(file);
2063 	while (buf->buf == NULL) {
2064 		/*
2065 		 * TODO: alloc_cache_memory_buffer() should eventually free
2066 		 *  some buffers.  Need a more sophisticated check here, instead
2067 		 *  of just bailing if 100 tries does not result in getting a
2068 		 *  free buffer.  This will involve using the sync channel's
2069 		 *  semaphore to block until a buffer becomes available.
2070 		 */
2071 		if (count++ == 100) {
2072 			SPDK_ERRLOG("Could not allocate cache buffer for file=%p on offset=%jx\n",
2073 				    file, offset);
2074 			free(buf);
2075 			return NULL;
2076 		}
2077 		buf->buf = alloc_cache_memory_buffer(file);
2078 	}
2079 
2080 	buf->buf_size = CACHE_BUFFER_SIZE;
2081 	buf->offset = offset;
2082 
2083 	pthread_spin_lock(&g_caches_lock);
2084 	if (file->tree->present_mask == 0) {
2085 		TAILQ_INSERT_TAIL(&g_caches, file, cache_tailq);
2086 	}
2087 	file->tree = spdk_tree_insert_buffer(file->tree, buf);
2088 	pthread_spin_unlock(&g_caches_lock);
2089 
2090 	return buf;
2091 }
2092 
2093 static struct cache_buffer *
2094 cache_append_buffer(struct spdk_file *file)
2095 {
2096 	struct cache_buffer *last;
2097 
2098 	assert(file->last == NULL || file->last->bytes_filled == file->last->buf_size);
2099 	assert((file->append_pos % CACHE_BUFFER_SIZE) == 0);
2100 
2101 	last = cache_insert_buffer(file, file->append_pos);
2102 	if (last == NULL) {
2103 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "cache_insert_buffer failed\n");
2104 		return NULL;
2105 	}
2106 
2107 	file->last = last;
2108 
2109 	return last;
2110 }
2111 
2112 static void __check_sync_reqs(struct spdk_file *file);
2113 
2114 static void
2115 __file_cache_finish_sync(void *ctx, int bserrno)
2116 {
2117 	struct spdk_file *file;
2118 	struct spdk_fs_request *sync_req = ctx;
2119 	struct spdk_fs_cb_args *sync_args;
2120 
2121 	sync_args = &sync_req->args;
2122 	file = sync_args->file;
2123 	pthread_spin_lock(&file->lock);
2124 	file->length_xattr = sync_args->op.sync.length;
2125 	assert(sync_args->op.sync.offset <= file->length_flushed);
2126 	spdk_trace_record(TRACE_BLOBFS_XATTR_END, 0, sync_args->op.sync.offset,
2127 			  0, file->trace_arg_name);
2128 	BLOBFS_TRACE(file, "sync done offset=%jx\n", sync_args->op.sync.offset);
2129 	TAILQ_REMOVE(&file->sync_requests, sync_req, args.op.sync.tailq);
2130 	pthread_spin_unlock(&file->lock);
2131 
2132 	sync_args->fn.file_op(sync_args->arg, bserrno);
2133 	pthread_spin_lock(&file->lock);
2134 	free_fs_request(sync_req);
2135 	pthread_spin_unlock(&file->lock);
2136 
2137 	__check_sync_reqs(file);
2138 }
2139 
2140 static void
2141 __check_sync_reqs(struct spdk_file *file)
2142 {
2143 	struct spdk_fs_request *sync_req;
2144 
2145 	pthread_spin_lock(&file->lock);
2146 
2147 	TAILQ_FOREACH(sync_req, &file->sync_requests, args.op.sync.tailq) {
2148 		if (sync_req->args.op.sync.offset <= file->length_flushed) {
2149 			break;
2150 		}
2151 	}
2152 
2153 	if (sync_req != NULL && !sync_req->args.op.sync.xattr_in_progress) {
2154 		BLOBFS_TRACE(file, "set xattr length 0x%jx\n", file->length_flushed);
2155 		sync_req->args.op.sync.xattr_in_progress = true;
2156 		sync_req->args.op.sync.length = file->length_flushed;
2157 		spdk_blob_set_xattr(file->blob, "length", &file->length_flushed,
2158 				    sizeof(file->length_flushed));
2159 
2160 		pthread_spin_unlock(&file->lock);
2161 		spdk_trace_record(TRACE_BLOBFS_XATTR_START, 0, file->length_flushed,
2162 				  0, file->trace_arg_name);
2163 		spdk_blob_sync_md(file->blob, __file_cache_finish_sync, sync_req);
2164 	} else {
2165 		pthread_spin_unlock(&file->lock);
2166 	}
2167 }
2168 
2169 static void
2170 __file_flush_done(void *ctx, int bserrno)
2171 {
2172 	struct spdk_fs_request *req = ctx;
2173 	struct spdk_fs_cb_args *args = &req->args;
2174 	struct spdk_file *file = args->file;
2175 	struct cache_buffer *next = args->op.flush.cache_buffer;
2176 
2177 	BLOBFS_TRACE(file, "length=%jx\n", args->op.flush.length);
2178 
2179 	pthread_spin_lock(&file->lock);
2180 	next->in_progress = false;
2181 	next->bytes_flushed += args->op.flush.length;
2182 	file->length_flushed += args->op.flush.length;
2183 	if (file->length_flushed > file->length) {
2184 		file->length = file->length_flushed;
2185 	}
2186 	if (next->bytes_flushed == next->buf_size) {
2187 		BLOBFS_TRACE(file, "write buffer fully flushed 0x%jx\n", file->length_flushed);
2188 		next = spdk_tree_find_buffer(file->tree, file->length_flushed);
2189 	}
2190 
2191 	/*
2192 	 * Assert that there is no cached data that extends past the end of the underlying
2193 	 *  blob.
2194 	 */
2195 	assert(next == NULL || next->offset < __file_get_blob_size(file) ||
2196 	       next->bytes_filled == 0);
2197 
2198 	pthread_spin_unlock(&file->lock);
2199 
2200 	__check_sync_reqs(file);
2201 
2202 	__file_flush(req);
2203 }
2204 
2205 static void
2206 __file_flush(void *ctx)
2207 {
2208 	struct spdk_fs_request *req = ctx;
2209 	struct spdk_fs_cb_args *args = &req->args;
2210 	struct spdk_file *file = args->file;
2211 	struct cache_buffer *next;
2212 	uint64_t offset, length, start_lba, num_lba;
2213 	uint32_t lba_size;
2214 
2215 	pthread_spin_lock(&file->lock);
2216 	next = spdk_tree_find_buffer(file->tree, file->length_flushed);
2217 	if (next == NULL || next->in_progress ||
2218 	    ((next->bytes_filled < next->buf_size) && TAILQ_EMPTY(&file->sync_requests))) {
2219 		/*
2220 		 * There is either no data to flush, a flush I/O is already in
2221 		 *  progress, or the next buffer is partially filled but there's no
2222 		 *  outstanding request to sync it.
2223 		 * So return immediately - if a flush I/O is in progress we will flush
2224 		 *  more data after that is completed, or a partial buffer will get flushed
2225 		 *  when it is either filled or the file is synced.
2226 		 */
2227 		free_fs_request(req);
2228 		if (next == NULL) {
2229 			/*
2230 			 * For cases where a file's cache was evicted, and then the
2231 			 *  file was later appended, we will write the data directly
2232 			 *  to disk and bypass cache.  So just update length_flushed
2233 			 *  here to reflect that all data was already written to disk.
2234 			 */
2235 			file->length_flushed = file->append_pos;
2236 		}
2237 		pthread_spin_unlock(&file->lock);
2238 		if (next == NULL) {
2239 			/*
2240 			 * There is no data to flush, but we still need to check for any
2241 			 *  outstanding sync requests to make sure metadata gets updated.
2242 			 */
2243 			__check_sync_reqs(file);
2244 		}
2245 		return;
2246 	}
2247 
2248 	offset = next->offset + next->bytes_flushed;
2249 	length = next->bytes_filled - next->bytes_flushed;
2250 	if (length == 0) {
2251 		free_fs_request(req);
2252 		pthread_spin_unlock(&file->lock);
2253 		/*
2254 		 * There is no data to flush, but we still need to check for any
2255 		 *  outstanding sync requests to make sure metadata gets updated.
2256 		 */
2257 		__check_sync_reqs(file);
2258 		return;
2259 	}
2260 	args->op.flush.length = length;
2261 	args->op.flush.cache_buffer = next;
2262 
2263 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
2264 
2265 	next->in_progress = true;
2266 	BLOBFS_TRACE(file, "offset=%jx length=%jx page start=%jx num=%jx\n",
2267 		     offset, length, start_lba, num_lba);
2268 	pthread_spin_unlock(&file->lock);
2269 	spdk_blob_io_write(file->blob, file->fs->sync_target.sync_fs_channel->bs_channel,
2270 			   next->buf + (start_lba * lba_size) - next->offset,
2271 			   start_lba, num_lba, __file_flush_done, req);
2272 }
2273 
2274 static void
2275 __file_extend_done(void *arg, int bserrno)
2276 {
2277 	struct spdk_fs_cb_args *args = arg;
2278 
2279 	__wake_caller(args, bserrno);
2280 }
2281 
2282 static void
2283 __file_extend_resize_cb(void *_args, int bserrno)
2284 {
2285 	struct spdk_fs_cb_args *args = _args;
2286 	struct spdk_file *file = args->file;
2287 
2288 	if (bserrno) {
2289 		__wake_caller(args, bserrno);
2290 		return;
2291 	}
2292 
2293 	spdk_blob_sync_md(file->blob, __file_extend_done, args);
2294 }
2295 
2296 static void
2297 __file_extend_blob(void *_args)
2298 {
2299 	struct spdk_fs_cb_args *args = _args;
2300 	struct spdk_file *file = args->file;
2301 
2302 	spdk_blob_resize(file->blob, args->op.resize.num_clusters, __file_extend_resize_cb, args);
2303 }
2304 
2305 static void
2306 __rw_from_file_done(void *ctx, int bserrno)
2307 {
2308 	struct spdk_fs_request *req = ctx;
2309 
2310 	__wake_caller(&req->args, bserrno);
2311 	free_fs_request(req);
2312 }
2313 
2314 static void
2315 __rw_from_file(void *ctx)
2316 {
2317 	struct spdk_fs_request *req = ctx;
2318 	struct spdk_fs_cb_args *args = &req->args;
2319 	struct spdk_file *file = args->file;
2320 
2321 	if (args->op.rw.is_read) {
2322 		spdk_file_read_async(file, file->fs->sync_target.sync_io_channel, args->iovs[0].iov_base,
2323 				     args->op.rw.offset, (uint64_t)args->iovs[0].iov_len,
2324 				     __rw_from_file_done, req);
2325 	} else {
2326 		spdk_file_write_async(file, file->fs->sync_target.sync_io_channel, args->iovs[0].iov_base,
2327 				      args->op.rw.offset, (uint64_t)args->iovs[0].iov_len,
2328 				      __rw_from_file_done, req);
2329 	}
2330 }
2331 
2332 static int
2333 __send_rw_from_file(struct spdk_file *file, void *payload,
2334 		    uint64_t offset, uint64_t length, bool is_read,
2335 		    struct spdk_fs_channel *channel)
2336 {
2337 	struct spdk_fs_request *req;
2338 	struct spdk_fs_cb_args *args;
2339 
2340 	req = alloc_fs_request_with_iov(channel, 1);
2341 	if (req == NULL) {
2342 		sem_post(&channel->sem);
2343 		return -ENOMEM;
2344 	}
2345 
2346 	args = &req->args;
2347 	args->file = file;
2348 	args->sem = &channel->sem;
2349 	args->iovs[0].iov_base = payload;
2350 	args->iovs[0].iov_len = (size_t)length;
2351 	args->op.rw.offset = offset;
2352 	args->op.rw.is_read = is_read;
2353 	file->fs->send_request(__rw_from_file, req);
2354 	return 0;
2355 }
2356 
2357 int
2358 spdk_file_write(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
2359 		void *payload, uint64_t offset, uint64_t length)
2360 {
2361 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2362 	struct spdk_fs_request *flush_req;
2363 	uint64_t rem_length, copy, blob_size, cluster_sz;
2364 	uint32_t cache_buffers_filled = 0;
2365 	uint8_t *cur_payload;
2366 	struct cache_buffer *last;
2367 
2368 	BLOBFS_TRACE_RW(file, "offset=%jx length=%jx\n", offset, length);
2369 
2370 	if (length == 0) {
2371 		return 0;
2372 	}
2373 
2374 	if (offset != file->append_pos) {
2375 		BLOBFS_TRACE(file, " error offset=%jx append_pos=%jx\n", offset, file->append_pos);
2376 		return -EINVAL;
2377 	}
2378 
2379 	pthread_spin_lock(&file->lock);
2380 	file->open_for_writing = true;
2381 
2382 	if ((file->last == NULL) && (file->append_pos % CACHE_BUFFER_SIZE == 0)) {
2383 		cache_append_buffer(file);
2384 	}
2385 
2386 	if (file->last == NULL) {
2387 		int rc;
2388 
2389 		file->append_pos += length;
2390 		pthread_spin_unlock(&file->lock);
2391 		rc = __send_rw_from_file(file, payload, offset, length, false, channel);
2392 		sem_wait(&channel->sem);
2393 		return rc;
2394 	}
2395 
2396 	blob_size = __file_get_blob_size(file);
2397 
2398 	if ((offset + length) > blob_size) {
2399 		struct spdk_fs_cb_args extend_args = {};
2400 
2401 		cluster_sz = file->fs->bs_opts.cluster_sz;
2402 		extend_args.sem = &channel->sem;
2403 		extend_args.op.resize.num_clusters = __bytes_to_clusters((offset + length), cluster_sz);
2404 		extend_args.file = file;
2405 		BLOBFS_TRACE(file, "start resize to %u clusters\n", extend_args.op.resize.num_clusters);
2406 		pthread_spin_unlock(&file->lock);
2407 		file->fs->send_request(__file_extend_blob, &extend_args);
2408 		sem_wait(&channel->sem);
2409 		if (extend_args.rc) {
2410 			return extend_args.rc;
2411 		}
2412 	}
2413 
2414 	flush_req = alloc_fs_request(channel);
2415 	if (flush_req == NULL) {
2416 		pthread_spin_unlock(&file->lock);
2417 		return -ENOMEM;
2418 	}
2419 
2420 	last = file->last;
2421 	rem_length = length;
2422 	cur_payload = payload;
2423 	while (rem_length > 0) {
2424 		copy = last->buf_size - last->bytes_filled;
2425 		if (copy > rem_length) {
2426 			copy = rem_length;
2427 		}
2428 		BLOBFS_TRACE_RW(file, "  fill offset=%jx length=%jx\n", file->append_pos, copy);
2429 		memcpy(&last->buf[last->bytes_filled], cur_payload, copy);
2430 		file->append_pos += copy;
2431 		if (file->length < file->append_pos) {
2432 			file->length = file->append_pos;
2433 		}
2434 		cur_payload += copy;
2435 		last->bytes_filled += copy;
2436 		rem_length -= copy;
2437 		if (last->bytes_filled == last->buf_size) {
2438 			cache_buffers_filled++;
2439 			last = cache_append_buffer(file);
2440 			if (last == NULL) {
2441 				BLOBFS_TRACE(file, "nomem\n");
2442 				free_fs_request(flush_req);
2443 				pthread_spin_unlock(&file->lock);
2444 				return -ENOMEM;
2445 			}
2446 		}
2447 	}
2448 
2449 	pthread_spin_unlock(&file->lock);
2450 
2451 	if (cache_buffers_filled == 0) {
2452 		free_fs_request(flush_req);
2453 		return 0;
2454 	}
2455 
2456 	flush_req->args.file = file;
2457 	file->fs->send_request(__file_flush, flush_req);
2458 	return 0;
2459 }
2460 
2461 static void
2462 __readahead_done(void *ctx, int bserrno)
2463 {
2464 	struct spdk_fs_request *req = ctx;
2465 	struct spdk_fs_cb_args *args = &req->args;
2466 	struct cache_buffer *cache_buffer = args->op.readahead.cache_buffer;
2467 	struct spdk_file *file = args->file;
2468 
2469 	BLOBFS_TRACE(file, "offset=%jx\n", cache_buffer->offset);
2470 
2471 	pthread_spin_lock(&file->lock);
2472 	cache_buffer->bytes_filled = args->op.readahead.length;
2473 	cache_buffer->bytes_flushed = args->op.readahead.length;
2474 	cache_buffer->in_progress = false;
2475 	pthread_spin_unlock(&file->lock);
2476 
2477 	free_fs_request(req);
2478 }
2479 
2480 static void
2481 __readahead(void *ctx)
2482 {
2483 	struct spdk_fs_request *req = ctx;
2484 	struct spdk_fs_cb_args *args = &req->args;
2485 	struct spdk_file *file = args->file;
2486 	uint64_t offset, length, start_lba, num_lba;
2487 	uint32_t lba_size;
2488 
2489 	offset = args->op.readahead.offset;
2490 	length = args->op.readahead.length;
2491 	assert(length > 0);
2492 
2493 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
2494 
2495 	BLOBFS_TRACE(file, "offset=%jx length=%jx page start=%jx num=%jx\n",
2496 		     offset, length, start_lba, num_lba);
2497 	spdk_blob_io_read(file->blob, file->fs->sync_target.sync_fs_channel->bs_channel,
2498 			  args->op.readahead.cache_buffer->buf,
2499 			  start_lba, num_lba, __readahead_done, req);
2500 }
2501 
2502 static uint64_t
2503 __next_cache_buffer_offset(uint64_t offset)
2504 {
2505 	return (offset + CACHE_BUFFER_SIZE) & ~(CACHE_TREE_LEVEL_MASK(0));
2506 }
2507 
2508 static void
2509 check_readahead(struct spdk_file *file, uint64_t offset,
2510 		struct spdk_fs_channel *channel)
2511 {
2512 	struct spdk_fs_request *req;
2513 	struct spdk_fs_cb_args *args;
2514 
2515 	offset = __next_cache_buffer_offset(offset);
2516 	if (spdk_tree_find_buffer(file->tree, offset) != NULL || file->length <= offset) {
2517 		return;
2518 	}
2519 
2520 	req = alloc_fs_request(channel);
2521 	if (req == NULL) {
2522 		return;
2523 	}
2524 	args = &req->args;
2525 
2526 	BLOBFS_TRACE(file, "offset=%jx\n", offset);
2527 
2528 	args->file = file;
2529 	args->op.readahead.offset = offset;
2530 	args->op.readahead.cache_buffer = cache_insert_buffer(file, offset);
2531 	if (!args->op.readahead.cache_buffer) {
2532 		BLOBFS_TRACE(file, "Cannot allocate buf for offset=%jx\n", offset);
2533 		free_fs_request(req);
2534 		return;
2535 	}
2536 
2537 	args->op.readahead.cache_buffer->in_progress = true;
2538 	if (file->length < (offset + CACHE_BUFFER_SIZE)) {
2539 		args->op.readahead.length = file->length & (CACHE_BUFFER_SIZE - 1);
2540 	} else {
2541 		args->op.readahead.length = CACHE_BUFFER_SIZE;
2542 	}
2543 	file->fs->send_request(__readahead, req);
2544 }
2545 
2546 static int
2547 __file_read(struct spdk_file *file, void *payload, uint64_t offset, uint64_t length,
2548 	    struct spdk_fs_channel *channel)
2549 {
2550 	struct cache_buffer *buf;
2551 	int rc;
2552 
2553 	buf = spdk_tree_find_filled_buffer(file->tree, offset);
2554 	if (buf == NULL) {
2555 		pthread_spin_unlock(&file->lock);
2556 		rc = __send_rw_from_file(file, payload, offset, length, true, channel);
2557 		pthread_spin_lock(&file->lock);
2558 		return rc;
2559 	}
2560 
2561 	if ((offset + length) > (buf->offset + buf->bytes_filled)) {
2562 		length = buf->offset + buf->bytes_filled - offset;
2563 	}
2564 	BLOBFS_TRACE(file, "read %p offset=%ju length=%ju\n", payload, offset, length);
2565 	memcpy(payload, &buf->buf[offset - buf->offset], length);
2566 	if ((offset + length) % CACHE_BUFFER_SIZE == 0) {
2567 		pthread_spin_lock(&g_caches_lock);
2568 		spdk_tree_remove_buffer(file->tree, buf);
2569 		if (file->tree->present_mask == 0) {
2570 			TAILQ_REMOVE(&g_caches, file, cache_tailq);
2571 		}
2572 		pthread_spin_unlock(&g_caches_lock);
2573 	}
2574 
2575 	sem_post(&channel->sem);
2576 	return 0;
2577 }
2578 
2579 int64_t
2580 spdk_file_read(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
2581 	       void *payload, uint64_t offset, uint64_t length)
2582 {
2583 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2584 	uint64_t final_offset, final_length;
2585 	uint32_t sub_reads = 0;
2586 	int rc = 0;
2587 
2588 	pthread_spin_lock(&file->lock);
2589 
2590 	BLOBFS_TRACE_RW(file, "offset=%ju length=%ju\n", offset, length);
2591 
2592 	file->open_for_writing = false;
2593 
2594 	if (length == 0 || offset >= file->append_pos) {
2595 		pthread_spin_unlock(&file->lock);
2596 		return 0;
2597 	}
2598 
2599 	if (offset + length > file->append_pos) {
2600 		length = file->append_pos - offset;
2601 	}
2602 
2603 	if (offset != file->next_seq_offset) {
2604 		file->seq_byte_count = 0;
2605 	}
2606 	file->seq_byte_count += length;
2607 	file->next_seq_offset = offset + length;
2608 	if (file->seq_byte_count >= CACHE_READAHEAD_THRESHOLD) {
2609 		check_readahead(file, offset, channel);
2610 		check_readahead(file, offset + CACHE_BUFFER_SIZE, channel);
2611 	}
2612 
2613 	final_length = 0;
2614 	final_offset = offset + length;
2615 	while (offset < final_offset) {
2616 		length = NEXT_CACHE_BUFFER_OFFSET(offset) - offset;
2617 		if (length > (final_offset - offset)) {
2618 			length = final_offset - offset;
2619 		}
2620 
2621 		sub_reads++;
2622 		rc = __file_read(file, payload, offset, length, channel);
2623 		if (rc == 0) {
2624 			final_length += length;
2625 		} else {
2626 			break;
2627 		}
2628 		payload += length;
2629 		offset += length;
2630 	}
2631 	pthread_spin_unlock(&file->lock);
2632 	while (sub_reads-- > 0) {
2633 		sem_wait(&channel->sem);
2634 	}
2635 	if (rc == 0) {
2636 		return final_length;
2637 	} else {
2638 		return rc;
2639 	}
2640 }
2641 
2642 static void
2643 _file_sync(struct spdk_file *file, struct spdk_fs_channel *channel,
2644 	   spdk_file_op_complete cb_fn, void *cb_arg)
2645 {
2646 	struct spdk_fs_request *sync_req;
2647 	struct spdk_fs_request *flush_req;
2648 	struct spdk_fs_cb_args *sync_args;
2649 	struct spdk_fs_cb_args *flush_args;
2650 
2651 	BLOBFS_TRACE(file, "offset=%jx\n", file->append_pos);
2652 
2653 	pthread_spin_lock(&file->lock);
2654 	if (file->append_pos <= file->length_xattr) {
2655 		BLOBFS_TRACE(file, "done - file already synced\n");
2656 		pthread_spin_unlock(&file->lock);
2657 		cb_fn(cb_arg, 0);
2658 		return;
2659 	}
2660 
2661 	sync_req = alloc_fs_request(channel);
2662 	if (!sync_req) {
2663 		SPDK_ERRLOG("Cannot allocate sync req for file=%s\n", file->name);
2664 		pthread_spin_unlock(&file->lock);
2665 		cb_fn(cb_arg, -ENOMEM);
2666 		return;
2667 	}
2668 	sync_args = &sync_req->args;
2669 
2670 	flush_req = alloc_fs_request(channel);
2671 	if (!flush_req) {
2672 		SPDK_ERRLOG("Cannot allocate flush req for file=%s\n", file->name);
2673 		free_fs_request(sync_req);
2674 		pthread_spin_unlock(&file->lock);
2675 		cb_fn(cb_arg, -ENOMEM);
2676 		return;
2677 	}
2678 	flush_args = &flush_req->args;
2679 
2680 	sync_args->file = file;
2681 	sync_args->fn.file_op = cb_fn;
2682 	sync_args->arg = cb_arg;
2683 	sync_args->op.sync.offset = file->append_pos;
2684 	sync_args->op.sync.xattr_in_progress = false;
2685 	TAILQ_INSERT_TAIL(&file->sync_requests, sync_req, args.op.sync.tailq);
2686 	pthread_spin_unlock(&file->lock);
2687 
2688 	flush_args->file = file;
2689 	channel->send_request(__file_flush, flush_req);
2690 }
2691 
2692 int
2693 spdk_file_sync(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx)
2694 {
2695 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2696 	struct spdk_fs_cb_args args = {};
2697 
2698 	args.sem = &channel->sem;
2699 	_file_sync(file, channel, __wake_caller, &args);
2700 	sem_wait(&channel->sem);
2701 
2702 	return args.rc;
2703 }
2704 
2705 void
2706 spdk_file_sync_async(struct spdk_file *file, struct spdk_io_channel *_channel,
2707 		     spdk_file_op_complete cb_fn, void *cb_arg)
2708 {
2709 	struct spdk_fs_channel *channel = spdk_io_channel_get_ctx(_channel);
2710 
2711 	_file_sync(file, channel, cb_fn, cb_arg);
2712 }
2713 
2714 void
2715 spdk_file_set_priority(struct spdk_file *file, uint32_t priority)
2716 {
2717 	BLOBFS_TRACE(file, "priority=%u\n", priority);
2718 	file->priority = priority;
2719 
2720 }
2721 
2722 /*
2723  * Close routines
2724  */
2725 
2726 static void
2727 __file_close_async_done(void *ctx, int bserrno)
2728 {
2729 	struct spdk_fs_request *req = ctx;
2730 	struct spdk_fs_cb_args *args = &req->args;
2731 	struct spdk_file *file = args->file;
2732 
2733 	spdk_trace_record(TRACE_BLOBFS_CLOSE, 0, 0, 0, file->trace_arg_name);
2734 
2735 	if (file->is_deleted) {
2736 		spdk_fs_delete_file_async(file->fs, file->name, blob_delete_cb, ctx);
2737 		return;
2738 	}
2739 
2740 	args->fn.file_op(args->arg, bserrno);
2741 	free_fs_request(req);
2742 }
2743 
2744 static void
2745 __file_close_async(struct spdk_file *file, struct spdk_fs_request *req)
2746 {
2747 	struct spdk_blob *blob;
2748 
2749 	pthread_spin_lock(&file->lock);
2750 	if (file->ref_count == 0) {
2751 		pthread_spin_unlock(&file->lock);
2752 		__file_close_async_done(req, -EBADF);
2753 		return;
2754 	}
2755 
2756 	file->ref_count--;
2757 	if (file->ref_count > 0) {
2758 		pthread_spin_unlock(&file->lock);
2759 		req->args.fn.file_op(req->args.arg, 0);
2760 		free_fs_request(req);
2761 		return;
2762 	}
2763 
2764 	pthread_spin_unlock(&file->lock);
2765 
2766 	blob = file->blob;
2767 	file->blob = NULL;
2768 	spdk_blob_close(blob, __file_close_async_done, req);
2769 }
2770 
2771 static void
2772 __file_close_async__sync_done(void *arg, int fserrno)
2773 {
2774 	struct spdk_fs_request *req = arg;
2775 	struct spdk_fs_cb_args *args = &req->args;
2776 
2777 	__file_close_async(args->file, req);
2778 }
2779 
2780 void
2781 spdk_file_close_async(struct spdk_file *file, spdk_file_op_complete cb_fn, void *cb_arg)
2782 {
2783 	struct spdk_fs_request *req;
2784 	struct spdk_fs_cb_args *args;
2785 
2786 	req = alloc_fs_request(file->fs->md_target.md_fs_channel);
2787 	if (req == NULL) {
2788 		SPDK_ERRLOG("Cannot allocate close async req for file=%s\n", file->name);
2789 		cb_fn(cb_arg, -ENOMEM);
2790 		return;
2791 	}
2792 
2793 	args = &req->args;
2794 	args->file = file;
2795 	args->fn.file_op = cb_fn;
2796 	args->arg = cb_arg;
2797 
2798 	spdk_file_sync_async(file, file->fs->md_target.md_io_channel, __file_close_async__sync_done, req);
2799 }
2800 
2801 static void
2802 __file_close(void *arg)
2803 {
2804 	struct spdk_fs_request *req = arg;
2805 	struct spdk_fs_cb_args *args = &req->args;
2806 	struct spdk_file *file = args->file;
2807 
2808 	__file_close_async(file, req);
2809 }
2810 
2811 int
2812 spdk_file_close(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx)
2813 {
2814 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2815 	struct spdk_fs_request *req;
2816 	struct spdk_fs_cb_args *args;
2817 
2818 	req = alloc_fs_request(channel);
2819 	if (req == NULL) {
2820 		SPDK_ERRLOG("Cannot allocate close req for file=%s\n", file->name);
2821 		return -ENOMEM;
2822 	}
2823 
2824 	args = &req->args;
2825 
2826 	spdk_file_sync(file, ctx);
2827 	BLOBFS_TRACE(file, "name=%s\n", file->name);
2828 	args->file = file;
2829 	args->sem = &channel->sem;
2830 	args->fn.file_op = __wake_caller;
2831 	args->arg = args;
2832 	channel->send_request(__file_close, req);
2833 	sem_wait(&channel->sem);
2834 
2835 	return args->rc;
2836 }
2837 
2838 int
2839 spdk_file_get_id(struct spdk_file *file, void *id, size_t size)
2840 {
2841 	if (size < sizeof(spdk_blob_id)) {
2842 		return -EINVAL;
2843 	}
2844 
2845 	memcpy(id, &file->blobid, sizeof(spdk_blob_id));
2846 
2847 	return sizeof(spdk_blob_id);
2848 }
2849 
2850 static void
2851 cache_free_buffers(struct spdk_file *file)
2852 {
2853 	BLOBFS_TRACE(file, "free=%s\n", file->name);
2854 	pthread_spin_lock(&file->lock);
2855 	pthread_spin_lock(&g_caches_lock);
2856 	if (file->tree->present_mask == 0) {
2857 		pthread_spin_unlock(&g_caches_lock);
2858 		pthread_spin_unlock(&file->lock);
2859 		return;
2860 	}
2861 	spdk_tree_free_buffers(file->tree);
2862 
2863 	TAILQ_REMOVE(&g_caches, file, cache_tailq);
2864 	/* If not freed, put it in the end of the queue */
2865 	if (file->tree->present_mask != 0) {
2866 		TAILQ_INSERT_TAIL(&g_caches, file, cache_tailq);
2867 	}
2868 	file->last = NULL;
2869 	pthread_spin_unlock(&g_caches_lock);
2870 	pthread_spin_unlock(&file->lock);
2871 }
2872 
2873 SPDK_LOG_REGISTER_COMPONENT("blobfs", SPDK_LOG_BLOBFS)
2874 SPDK_LOG_REGISTER_COMPONENT("blobfs_rw", SPDK_LOG_BLOBFS_RW)
2875