xref: /spdk/lib/blobfs/blobfs.c (revision 9889ab2dc80e40dae92dcef361d53dcba722043d)
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 	__wake_caller(args, fserrno);
1100 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.create.name);
1101 }
1102 
1103 static void
1104 __fs_create_file(void *arg)
1105 {
1106 	struct spdk_fs_request *req = arg;
1107 	struct spdk_fs_cb_args *args = &req->args;
1108 
1109 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.create.name);
1110 	spdk_fs_create_file_async(args->fs, args->op.create.name, __fs_create_file_done, req);
1111 }
1112 
1113 int
1114 spdk_fs_create_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx, const char *name)
1115 {
1116 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1117 	struct spdk_fs_request *req;
1118 	struct spdk_fs_cb_args *args;
1119 	int rc;
1120 
1121 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1122 
1123 	req = alloc_fs_request(channel);
1124 	if (req == NULL) {
1125 		SPDK_ERRLOG("Cannot allocate req to create file=%s\n", name);
1126 		return -ENOMEM;
1127 	}
1128 
1129 	args = &req->args;
1130 	args->fs = fs;
1131 	args->op.create.name = name;
1132 	args->sem = &channel->sem;
1133 	fs->send_request(__fs_create_file, req);
1134 	sem_wait(&channel->sem);
1135 	rc = args->rc;
1136 	free_fs_request(req);
1137 
1138 	return rc;
1139 }
1140 
1141 static void
1142 fs_open_blob_done(void *ctx, struct spdk_blob *blob, int bserrno)
1143 {
1144 	struct spdk_fs_request *req = ctx;
1145 	struct spdk_fs_cb_args *args = &req->args;
1146 	struct spdk_file *f = args->file;
1147 
1148 	f->blob = blob;
1149 	while (!TAILQ_EMPTY(&f->open_requests)) {
1150 		req = TAILQ_FIRST(&f->open_requests);
1151 		args = &req->args;
1152 		TAILQ_REMOVE(&f->open_requests, req, args.op.open.tailq);
1153 		spdk_trace_record(TRACE_BLOBFS_OPEN, 0, 0, 0, f->trace_arg_name);
1154 		args->fn.file_op_with_handle(args->arg, f, bserrno);
1155 		free_fs_request(req);
1156 	}
1157 }
1158 
1159 static void
1160 fs_open_blob_create_cb(void *ctx, int bserrno)
1161 {
1162 	struct spdk_fs_request *req = ctx;
1163 	struct spdk_fs_cb_args *args = &req->args;
1164 	struct spdk_file *file = args->file;
1165 	struct spdk_filesystem *fs = args->fs;
1166 
1167 	if (file == NULL) {
1168 		/*
1169 		 * This is from an open with CREATE flag - the file
1170 		 *  is now created so look it up in the file list for this
1171 		 *  filesystem.
1172 		 */
1173 		file = fs_find_file(fs, args->op.open.name);
1174 		assert(file != NULL);
1175 		args->file = file;
1176 	}
1177 
1178 	file->ref_count++;
1179 	TAILQ_INSERT_TAIL(&file->open_requests, req, args.op.open.tailq);
1180 	if (file->ref_count == 1) {
1181 		assert(file->blob == NULL);
1182 		spdk_bs_open_blob(fs->bs, file->blobid, fs_open_blob_done, req);
1183 	} else if (file->blob != NULL) {
1184 		fs_open_blob_done(req, file->blob, 0);
1185 	} else {
1186 		/*
1187 		 * The blob open for this file is in progress due to a previous
1188 		 *  open request.  When that open completes, it will invoke the
1189 		 *  open callback for this request.
1190 		 */
1191 	}
1192 }
1193 
1194 void
1195 spdk_fs_open_file_async(struct spdk_filesystem *fs, const char *name, uint32_t flags,
1196 			spdk_file_op_with_handle_complete cb_fn, void *cb_arg)
1197 {
1198 	struct spdk_file *f = NULL;
1199 	struct spdk_fs_request *req;
1200 	struct spdk_fs_cb_args *args;
1201 
1202 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1203 		cb_fn(cb_arg, NULL, -ENAMETOOLONG);
1204 		return;
1205 	}
1206 
1207 	f = fs_find_file(fs, name);
1208 	if (f == NULL && !(flags & SPDK_BLOBFS_OPEN_CREATE)) {
1209 		cb_fn(cb_arg, NULL, -ENOENT);
1210 		return;
1211 	}
1212 
1213 	if (f != NULL && f->is_deleted == true) {
1214 		cb_fn(cb_arg, NULL, -ENOENT);
1215 		return;
1216 	}
1217 
1218 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1219 	if (req == NULL) {
1220 		SPDK_ERRLOG("Cannot allocate async open req for file=%s\n", name);
1221 		cb_fn(cb_arg, NULL, -ENOMEM);
1222 		return;
1223 	}
1224 
1225 	args = &req->args;
1226 	args->fn.file_op_with_handle = cb_fn;
1227 	args->arg = cb_arg;
1228 	args->file = f;
1229 	args->fs = fs;
1230 	args->op.open.name = name;
1231 
1232 	if (f == NULL) {
1233 		spdk_fs_create_file_async(fs, name, fs_open_blob_create_cb, req);
1234 	} else {
1235 		fs_open_blob_create_cb(req, 0);
1236 	}
1237 }
1238 
1239 static void
1240 __fs_open_file_done(void *arg, struct spdk_file *file, int bserrno)
1241 {
1242 	struct spdk_fs_request *req = arg;
1243 	struct spdk_fs_cb_args *args = &req->args;
1244 
1245 	args->file = file;
1246 	__wake_caller(args, bserrno);
1247 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.open.name);
1248 }
1249 
1250 static void
1251 __fs_open_file(void *arg)
1252 {
1253 	struct spdk_fs_request *req = arg;
1254 	struct spdk_fs_cb_args *args = &req->args;
1255 
1256 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", args->op.open.name);
1257 	spdk_fs_open_file_async(args->fs, args->op.open.name, args->op.open.flags,
1258 				__fs_open_file_done, req);
1259 }
1260 
1261 int
1262 spdk_fs_open_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1263 		  const char *name, uint32_t flags, struct spdk_file **file)
1264 {
1265 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1266 	struct spdk_fs_request *req;
1267 	struct spdk_fs_cb_args *args;
1268 	int rc;
1269 
1270 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1271 
1272 	req = alloc_fs_request(channel);
1273 	if (req == NULL) {
1274 		SPDK_ERRLOG("Cannot allocate req for opening file=%s\n", name);
1275 		return -ENOMEM;
1276 	}
1277 
1278 	args = &req->args;
1279 	args->fs = fs;
1280 	args->op.open.name = name;
1281 	args->op.open.flags = flags;
1282 	args->sem = &channel->sem;
1283 	fs->send_request(__fs_open_file, req);
1284 	sem_wait(&channel->sem);
1285 	rc = args->rc;
1286 	if (rc == 0) {
1287 		*file = args->file;
1288 	} else {
1289 		*file = NULL;
1290 	}
1291 	free_fs_request(req);
1292 
1293 	return rc;
1294 }
1295 
1296 static void
1297 fs_rename_blob_close_cb(void *ctx, int bserrno)
1298 {
1299 	struct spdk_fs_request *req = ctx;
1300 	struct spdk_fs_cb_args *args = &req->args;
1301 
1302 	args->fn.fs_op(args->arg, bserrno);
1303 	free_fs_request(req);
1304 }
1305 
1306 static void
1307 fs_rename_blob_open_cb(void *ctx, struct spdk_blob *blob, int bserrno)
1308 {
1309 	struct spdk_fs_request *req = ctx;
1310 	struct spdk_fs_cb_args *args = &req->args;
1311 	const char *new_name = args->op.rename.new_name;
1312 
1313 	spdk_blob_set_xattr(blob, "name", new_name, strlen(new_name) + 1);
1314 	spdk_blob_close(blob, fs_rename_blob_close_cb, req);
1315 }
1316 
1317 static void
1318 __spdk_fs_md_rename_file(struct spdk_fs_request *req)
1319 {
1320 	struct spdk_fs_cb_args *args = &req->args;
1321 	struct spdk_file *f;
1322 
1323 	f = fs_find_file(args->fs, args->op.rename.old_name);
1324 	if (f == NULL) {
1325 		args->fn.fs_op(args->arg, -ENOENT);
1326 		free_fs_request(req);
1327 		return;
1328 	}
1329 
1330 	free(f->name);
1331 	f->name = strdup(args->op.rename.new_name);
1332 	_file_build_trace_arg_name(f);
1333 	args->file = f;
1334 	spdk_bs_open_blob(args->fs->bs, f->blobid, fs_rename_blob_open_cb, req);
1335 }
1336 
1337 static void
1338 fs_rename_delete_done(void *arg, int fserrno)
1339 {
1340 	__spdk_fs_md_rename_file(arg);
1341 }
1342 
1343 void
1344 spdk_fs_rename_file_async(struct spdk_filesystem *fs,
1345 			  const char *old_name, const char *new_name,
1346 			  spdk_file_op_complete cb_fn, void *cb_arg)
1347 {
1348 	struct spdk_file *f;
1349 	struct spdk_fs_request *req;
1350 	struct spdk_fs_cb_args *args;
1351 
1352 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "old=%s new=%s\n", old_name, new_name);
1353 	if (strnlen(new_name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1354 		cb_fn(cb_arg, -ENAMETOOLONG);
1355 		return;
1356 	}
1357 
1358 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1359 	if (req == NULL) {
1360 		SPDK_ERRLOG("Cannot allocate rename async req for renaming file from %s to %s\n", old_name,
1361 			    new_name);
1362 		cb_fn(cb_arg, -ENOMEM);
1363 		return;
1364 	}
1365 
1366 	args = &req->args;
1367 	args->fn.fs_op = cb_fn;
1368 	args->fs = fs;
1369 	args->arg = cb_arg;
1370 	args->op.rename.old_name = old_name;
1371 	args->op.rename.new_name = new_name;
1372 
1373 	f = fs_find_file(fs, new_name);
1374 	if (f == NULL) {
1375 		__spdk_fs_md_rename_file(req);
1376 		return;
1377 	}
1378 
1379 	/*
1380 	 * The rename overwrites an existing file.  So delete the existing file, then
1381 	 *  do the actual rename.
1382 	 */
1383 	spdk_fs_delete_file_async(fs, new_name, fs_rename_delete_done, req);
1384 }
1385 
1386 static void
1387 __fs_rename_file_done(void *arg, int fserrno)
1388 {
1389 	struct spdk_fs_request *req = arg;
1390 	struct spdk_fs_cb_args *args = &req->args;
1391 
1392 	__wake_caller(args, fserrno);
1393 }
1394 
1395 static void
1396 __fs_rename_file(void *arg)
1397 {
1398 	struct spdk_fs_request *req = arg;
1399 	struct spdk_fs_cb_args *args = &req->args;
1400 
1401 	spdk_fs_rename_file_async(args->fs, args->op.rename.old_name, args->op.rename.new_name,
1402 				  __fs_rename_file_done, req);
1403 }
1404 
1405 int
1406 spdk_fs_rename_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1407 		    const char *old_name, const char *new_name)
1408 {
1409 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1410 	struct spdk_fs_request *req;
1411 	struct spdk_fs_cb_args *args;
1412 	int rc;
1413 
1414 	req = alloc_fs_request(channel);
1415 	if (req == NULL) {
1416 		SPDK_ERRLOG("Cannot allocate rename req for file=%s\n", old_name);
1417 		return -ENOMEM;
1418 	}
1419 
1420 	args = &req->args;
1421 
1422 	args->fs = fs;
1423 	args->op.rename.old_name = old_name;
1424 	args->op.rename.new_name = new_name;
1425 	args->sem = &channel->sem;
1426 	fs->send_request(__fs_rename_file, req);
1427 	sem_wait(&channel->sem);
1428 	rc = args->rc;
1429 	free_fs_request(req);
1430 	return rc;
1431 }
1432 
1433 static void
1434 blob_delete_cb(void *ctx, int bserrno)
1435 {
1436 	struct spdk_fs_request *req = ctx;
1437 	struct spdk_fs_cb_args *args = &req->args;
1438 
1439 	args->fn.file_op(args->arg, bserrno);
1440 	free_fs_request(req);
1441 }
1442 
1443 void
1444 spdk_fs_delete_file_async(struct spdk_filesystem *fs, const char *name,
1445 			  spdk_file_op_complete cb_fn, void *cb_arg)
1446 {
1447 	struct spdk_file *f;
1448 	spdk_blob_id blobid;
1449 	struct spdk_fs_request *req;
1450 	struct spdk_fs_cb_args *args;
1451 
1452 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s\n", name);
1453 
1454 	if (strnlen(name, SPDK_FILE_NAME_MAX + 1) == SPDK_FILE_NAME_MAX + 1) {
1455 		cb_fn(cb_arg, -ENAMETOOLONG);
1456 		return;
1457 	}
1458 
1459 	f = fs_find_file(fs, name);
1460 	if (f == NULL) {
1461 		SPDK_ERRLOG("Cannot find the file=%s to deleted\n", name);
1462 		cb_fn(cb_arg, -ENOENT);
1463 		return;
1464 	}
1465 
1466 	req = alloc_fs_request(fs->md_target.md_fs_channel);
1467 	if (req == NULL) {
1468 		SPDK_ERRLOG("Cannot allocate the req for the file=%s to deleted\n", name);
1469 		cb_fn(cb_arg, -ENOMEM);
1470 		return;
1471 	}
1472 
1473 	args = &req->args;
1474 	args->fn.file_op = cb_fn;
1475 	args->arg = cb_arg;
1476 
1477 	if (f->ref_count > 0) {
1478 		/* If the ref > 0, we mark the file as deleted and delete it when we close it. */
1479 		f->is_deleted = true;
1480 		spdk_blob_set_xattr(f->blob, "is_deleted", &f->is_deleted, sizeof(bool));
1481 		spdk_blob_sync_md(f->blob, blob_delete_cb, req);
1482 		return;
1483 	}
1484 
1485 	TAILQ_REMOVE(&fs->files, f, tailq);
1486 
1487 	cache_free_buffers(f);
1488 
1489 	blobid = f->blobid;
1490 
1491 	free(f->name);
1492 	free(f->tree);
1493 	free(f);
1494 
1495 	spdk_bs_delete_blob(fs->bs, blobid, blob_delete_cb, req);
1496 }
1497 
1498 static uint64_t
1499 fs_name_to_uint64(const char *name)
1500 {
1501 	uint64_t result = 0;
1502 	memcpy(&result, name, spdk_min(sizeof(result), strlen(name)));
1503 	return result;
1504 }
1505 
1506 static void
1507 __fs_delete_file_done(void *arg, int fserrno)
1508 {
1509 	struct spdk_fs_request *req = arg;
1510 	struct spdk_fs_cb_args *args = &req->args;
1511 
1512 	spdk_trace_record(TRACE_BLOBFS_DELETE_DONE, 0, 0, 0, fs_name_to_uint64(args->op.delete.name));
1513 	__wake_caller(args, fserrno);
1514 }
1515 
1516 static void
1517 __fs_delete_file(void *arg)
1518 {
1519 	struct spdk_fs_request *req = arg;
1520 	struct spdk_fs_cb_args *args = &req->args;
1521 
1522 	spdk_trace_record(TRACE_BLOBFS_DELETE_START, 0, 0, 0, fs_name_to_uint64(args->op.delete.name));
1523 	spdk_fs_delete_file_async(args->fs, args->op.delete.name, __fs_delete_file_done, req);
1524 }
1525 
1526 int
1527 spdk_fs_delete_file(struct spdk_filesystem *fs, struct spdk_fs_thread_ctx *ctx,
1528 		    const char *name)
1529 {
1530 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1531 	struct spdk_fs_request *req;
1532 	struct spdk_fs_cb_args *args;
1533 	int rc;
1534 
1535 	req = alloc_fs_request(channel);
1536 	if (req == NULL) {
1537 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "Cannot allocate req to delete file=%s\n", name);
1538 		return -ENOMEM;
1539 	}
1540 
1541 	args = &req->args;
1542 	args->fs = fs;
1543 	args->op.delete.name = name;
1544 	args->sem = &channel->sem;
1545 	fs->send_request(__fs_delete_file, req);
1546 	sem_wait(&channel->sem);
1547 	rc = args->rc;
1548 	free_fs_request(req);
1549 
1550 	return rc;
1551 }
1552 
1553 spdk_fs_iter
1554 spdk_fs_iter_first(struct spdk_filesystem *fs)
1555 {
1556 	struct spdk_file *f;
1557 
1558 	f = TAILQ_FIRST(&fs->files);
1559 	return f;
1560 }
1561 
1562 spdk_fs_iter
1563 spdk_fs_iter_next(spdk_fs_iter iter)
1564 {
1565 	struct spdk_file *f = iter;
1566 
1567 	if (f == NULL) {
1568 		return NULL;
1569 	}
1570 
1571 	f = TAILQ_NEXT(f, tailq);
1572 	return f;
1573 }
1574 
1575 const char *
1576 spdk_file_get_name(struct spdk_file *file)
1577 {
1578 	return file->name;
1579 }
1580 
1581 uint64_t
1582 spdk_file_get_length(struct spdk_file *file)
1583 {
1584 	uint64_t length;
1585 
1586 	assert(file != NULL);
1587 
1588 	length = file->append_pos >= file->length ? file->append_pos : file->length;
1589 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s length=0x%jx\n", file->name, length);
1590 	return length;
1591 }
1592 
1593 static void
1594 fs_truncate_complete_cb(void *ctx, int bserrno)
1595 {
1596 	struct spdk_fs_request *req = ctx;
1597 	struct spdk_fs_cb_args *args = &req->args;
1598 
1599 	args->fn.file_op(args->arg, bserrno);
1600 	free_fs_request(req);
1601 }
1602 
1603 static void
1604 fs_truncate_resize_cb(void *ctx, int bserrno)
1605 {
1606 	struct spdk_fs_request *req = ctx;
1607 	struct spdk_fs_cb_args *args = &req->args;
1608 	struct spdk_file *file = args->file;
1609 	uint64_t *length = &args->op.truncate.length;
1610 
1611 	if (bserrno) {
1612 		args->fn.file_op(args->arg, bserrno);
1613 		free_fs_request(req);
1614 		return;
1615 	}
1616 
1617 	spdk_blob_set_xattr(file->blob, "length", length, sizeof(*length));
1618 
1619 	file->length = *length;
1620 	if (file->append_pos > file->length) {
1621 		file->append_pos = file->length;
1622 	}
1623 
1624 	spdk_blob_sync_md(file->blob, fs_truncate_complete_cb, req);
1625 }
1626 
1627 static uint64_t
1628 __bytes_to_clusters(uint64_t length, uint64_t cluster_sz)
1629 {
1630 	return (length + cluster_sz - 1) / cluster_sz;
1631 }
1632 
1633 void
1634 spdk_file_truncate_async(struct spdk_file *file, uint64_t length,
1635 			 spdk_file_op_complete cb_fn, void *cb_arg)
1636 {
1637 	struct spdk_filesystem *fs;
1638 	size_t num_clusters;
1639 	struct spdk_fs_request *req;
1640 	struct spdk_fs_cb_args *args;
1641 
1642 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s old=0x%jx new=0x%jx\n", file->name, file->length, length);
1643 	if (length == file->length) {
1644 		cb_fn(cb_arg, 0);
1645 		return;
1646 	}
1647 
1648 	req = alloc_fs_request(file->fs->md_target.md_fs_channel);
1649 	if (req == NULL) {
1650 		cb_fn(cb_arg, -ENOMEM);
1651 		return;
1652 	}
1653 
1654 	args = &req->args;
1655 	args->fn.file_op = cb_fn;
1656 	args->arg = cb_arg;
1657 	args->file = file;
1658 	args->op.truncate.length = length;
1659 	fs = file->fs;
1660 
1661 	num_clusters = __bytes_to_clusters(length, fs->bs_opts.cluster_sz);
1662 
1663 	spdk_blob_resize(file->blob, num_clusters, fs_truncate_resize_cb, req);
1664 }
1665 
1666 static void
1667 __truncate(void *arg)
1668 {
1669 	struct spdk_fs_request *req = arg;
1670 	struct spdk_fs_cb_args *args = &req->args;
1671 
1672 	spdk_file_truncate_async(args->file, args->op.truncate.length,
1673 				 args->fn.file_op, args);
1674 }
1675 
1676 int
1677 spdk_file_truncate(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
1678 		   uint64_t length)
1679 {
1680 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
1681 	struct spdk_fs_request *req;
1682 	struct spdk_fs_cb_args *args;
1683 	int rc;
1684 
1685 	req = alloc_fs_request(channel);
1686 	if (req == NULL) {
1687 		return -ENOMEM;
1688 	}
1689 
1690 	args = &req->args;
1691 
1692 	args->file = file;
1693 	args->op.truncate.length = length;
1694 	args->fn.file_op = __wake_caller;
1695 	args->sem = &channel->sem;
1696 
1697 	channel->send_request(__truncate, req);
1698 	sem_wait(&channel->sem);
1699 	rc = args->rc;
1700 	free_fs_request(req);
1701 
1702 	return rc;
1703 }
1704 
1705 static void
1706 __rw_done(void *ctx, int bserrno)
1707 {
1708 	struct spdk_fs_request *req = ctx;
1709 	struct spdk_fs_cb_args *args = &req->args;
1710 
1711 	spdk_free(args->op.rw.pin_buf);
1712 	args->fn.file_op(args->arg, bserrno);
1713 	free_fs_request(req);
1714 }
1715 
1716 static void
1717 _copy_iovs_to_buf(void *buf, size_t buf_len, struct iovec *iovs, int iovcnt)
1718 {
1719 	int i;
1720 	size_t len;
1721 
1722 	for (i = 0; i < iovcnt; i++) {
1723 		len = spdk_min(iovs[i].iov_len, buf_len);
1724 		memcpy(buf, iovs[i].iov_base, len);
1725 		buf += len;
1726 		assert(buf_len >= len);
1727 		buf_len -= len;
1728 	}
1729 }
1730 
1731 static void
1732 _copy_buf_to_iovs(struct iovec *iovs, int iovcnt, void *buf, size_t buf_len)
1733 {
1734 	int i;
1735 	size_t len;
1736 
1737 	for (i = 0; i < iovcnt; i++) {
1738 		len = spdk_min(iovs[i].iov_len, buf_len);
1739 		memcpy(iovs[i].iov_base, buf, len);
1740 		buf += len;
1741 		assert(buf_len >= len);
1742 		buf_len -= len;
1743 	}
1744 }
1745 
1746 static void
1747 __read_done(void *ctx, int bserrno)
1748 {
1749 	struct spdk_fs_request *req = ctx;
1750 	struct spdk_fs_cb_args *args = &req->args;
1751 	void *buf;
1752 
1753 	assert(req != NULL);
1754 	buf = (void *)((uintptr_t)args->op.rw.pin_buf + (args->op.rw.offset & (args->op.rw.blocklen - 1)));
1755 	if (args->op.rw.is_read) {
1756 		_copy_buf_to_iovs(args->iovs, args->iovcnt, buf, args->op.rw.length);
1757 		__rw_done(req, 0);
1758 	} else {
1759 		_copy_iovs_to_buf(buf, args->op.rw.length, args->iovs, args->iovcnt);
1760 		spdk_blob_io_write(args->file->blob, args->op.rw.channel,
1761 				   args->op.rw.pin_buf,
1762 				   args->op.rw.start_lba, args->op.rw.num_lba,
1763 				   __rw_done, req);
1764 	}
1765 }
1766 
1767 static void
1768 __do_blob_read(void *ctx, int fserrno)
1769 {
1770 	struct spdk_fs_request *req = ctx;
1771 	struct spdk_fs_cb_args *args = &req->args;
1772 
1773 	if (fserrno) {
1774 		__rw_done(req, fserrno);
1775 		return;
1776 	}
1777 	spdk_blob_io_read(args->file->blob, args->op.rw.channel,
1778 			  args->op.rw.pin_buf,
1779 			  args->op.rw.start_lba, args->op.rw.num_lba,
1780 			  __read_done, req);
1781 }
1782 
1783 static void
1784 __get_page_parameters(struct spdk_file *file, uint64_t offset, uint64_t length,
1785 		      uint64_t *start_lba, uint32_t *lba_size, uint64_t *num_lba)
1786 {
1787 	uint64_t end_lba;
1788 
1789 	*lba_size = spdk_bs_get_io_unit_size(file->fs->bs);
1790 	*start_lba = offset / *lba_size;
1791 	end_lba = (offset + length - 1) / *lba_size;
1792 	*num_lba = (end_lba - *start_lba + 1);
1793 }
1794 
1795 static void
1796 _fs_request_setup_iovs(struct spdk_fs_request *req, struct iovec *iovs, uint32_t iovcnt)
1797 {
1798 	uint32_t i;
1799 
1800 	for (i = 0; i < iovcnt; i++) {
1801 		req->args.iovs[i].iov_base = iovs[i].iov_base;
1802 		req->args.iovs[i].iov_len = iovs[i].iov_len;
1803 	}
1804 }
1805 
1806 static void
1807 __readvwritev(struct spdk_file *file, struct spdk_io_channel *_channel,
1808 	      struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1809 	      spdk_file_op_complete cb_fn, void *cb_arg, int is_read)
1810 {
1811 	struct spdk_fs_request *req;
1812 	struct spdk_fs_cb_args *args;
1813 	struct spdk_fs_channel *channel = spdk_io_channel_get_ctx(_channel);
1814 	uint64_t start_lba, num_lba, pin_buf_length;
1815 	uint32_t lba_size;
1816 
1817 	if (is_read && offset + length > file->length) {
1818 		cb_fn(cb_arg, -EINVAL);
1819 		return;
1820 	}
1821 
1822 	req = alloc_fs_request_with_iov(channel, iovcnt);
1823 	if (req == NULL) {
1824 		cb_fn(cb_arg, -ENOMEM);
1825 		return;
1826 	}
1827 
1828 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
1829 
1830 	args = &req->args;
1831 	args->fn.file_op = cb_fn;
1832 	args->arg = cb_arg;
1833 	args->file = file;
1834 	args->op.rw.channel = channel->bs_channel;
1835 	_fs_request_setup_iovs(req, iovs, iovcnt);
1836 	args->op.rw.is_read = is_read;
1837 	args->op.rw.offset = offset;
1838 	args->op.rw.blocklen = lba_size;
1839 
1840 	pin_buf_length = num_lba * lba_size;
1841 	args->op.rw.length = pin_buf_length;
1842 	args->op.rw.pin_buf = spdk_malloc(pin_buf_length, lba_size, NULL,
1843 					  SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
1844 	if (args->op.rw.pin_buf == NULL) {
1845 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "Failed to allocate buf for: file=%s offset=%jx length=%jx\n",
1846 			      file->name, offset, length);
1847 		free_fs_request(req);
1848 		cb_fn(cb_arg, -ENOMEM);
1849 		return;
1850 	}
1851 
1852 	args->op.rw.start_lba = start_lba;
1853 	args->op.rw.num_lba = num_lba;
1854 
1855 	if (!is_read && file->length < offset + length) {
1856 		spdk_file_truncate_async(file, offset + length, __do_blob_read, req);
1857 	} else {
1858 		__do_blob_read(req, 0);
1859 	}
1860 }
1861 
1862 static void
1863 __readwrite(struct spdk_file *file, struct spdk_io_channel *channel,
1864 	    void *payload, uint64_t offset, uint64_t length,
1865 	    spdk_file_op_complete cb_fn, void *cb_arg, int is_read)
1866 {
1867 	struct iovec iov;
1868 
1869 	iov.iov_base = payload;
1870 	iov.iov_len = (size_t)length;
1871 
1872 	__readvwritev(file, channel, &iov, 1, offset, length, cb_fn, cb_arg, is_read);
1873 }
1874 
1875 void
1876 spdk_file_write_async(struct spdk_file *file, struct spdk_io_channel *channel,
1877 		      void *payload, uint64_t offset, uint64_t length,
1878 		      spdk_file_op_complete cb_fn, void *cb_arg)
1879 {
1880 	__readwrite(file, channel, payload, offset, length, cb_fn, cb_arg, 0);
1881 }
1882 
1883 void
1884 spdk_file_writev_async(struct spdk_file *file, struct spdk_io_channel *channel,
1885 		       struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1886 		       spdk_file_op_complete cb_fn, void *cb_arg)
1887 {
1888 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1889 		      file->name, offset, length);
1890 
1891 	__readvwritev(file, channel, iovs, iovcnt, offset, length, cb_fn, cb_arg, 0);
1892 }
1893 
1894 void
1895 spdk_file_read_async(struct spdk_file *file, struct spdk_io_channel *channel,
1896 		     void *payload, uint64_t offset, uint64_t length,
1897 		     spdk_file_op_complete cb_fn, void *cb_arg)
1898 {
1899 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1900 		      file->name, offset, length);
1901 	__readwrite(file, channel, payload, offset, length, cb_fn, cb_arg, 1);
1902 }
1903 
1904 void
1905 spdk_file_readv_async(struct spdk_file *file, struct spdk_io_channel *channel,
1906 		      struct iovec *iovs, uint32_t iovcnt, uint64_t offset, uint64_t length,
1907 		      spdk_file_op_complete cb_fn, void *cb_arg)
1908 {
1909 	SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "file=%s offset=%jx length=%jx\n",
1910 		      file->name, offset, length);
1911 
1912 	__readvwritev(file, channel, iovs, iovcnt, offset, length, cb_fn, cb_arg, 1);
1913 }
1914 
1915 struct spdk_io_channel *
1916 spdk_fs_alloc_io_channel(struct spdk_filesystem *fs)
1917 {
1918 	struct spdk_io_channel *io_channel;
1919 	struct spdk_fs_channel *fs_channel;
1920 
1921 	io_channel = spdk_get_io_channel(&fs->io_target);
1922 	fs_channel = spdk_io_channel_get_ctx(io_channel);
1923 	fs_channel->bs_channel = spdk_bs_alloc_io_channel(fs->bs);
1924 	fs_channel->send_request = __send_request_direct;
1925 
1926 	return io_channel;
1927 }
1928 
1929 void
1930 spdk_fs_free_io_channel(struct spdk_io_channel *channel)
1931 {
1932 	spdk_put_io_channel(channel);
1933 }
1934 
1935 struct spdk_fs_thread_ctx *
1936 spdk_fs_alloc_thread_ctx(struct spdk_filesystem *fs)
1937 {
1938 	struct spdk_fs_thread_ctx *ctx;
1939 
1940 	ctx = calloc(1, sizeof(*ctx));
1941 	if (!ctx) {
1942 		return NULL;
1943 	}
1944 
1945 	_spdk_fs_channel_create(fs, &ctx->ch, 512);
1946 
1947 	ctx->ch.send_request = fs->send_request;
1948 	ctx->ch.sync = 1;
1949 	pthread_spin_init(&ctx->ch.lock, 0);
1950 
1951 	return ctx;
1952 }
1953 
1954 
1955 void
1956 spdk_fs_free_thread_ctx(struct spdk_fs_thread_ctx *ctx)
1957 {
1958 	assert(ctx->ch.sync == 1);
1959 
1960 	while (true) {
1961 		pthread_spin_lock(&ctx->ch.lock);
1962 		if (ctx->ch.outstanding_reqs == 0) {
1963 			pthread_spin_unlock(&ctx->ch.lock);
1964 			break;
1965 		}
1966 		pthread_spin_unlock(&ctx->ch.lock);
1967 		usleep(1000);
1968 	}
1969 
1970 	_spdk_fs_channel_destroy(NULL, &ctx->ch);
1971 	free(ctx);
1972 }
1973 
1974 void
1975 spdk_fs_set_cache_size(uint64_t size_in_mb)
1976 {
1977 	g_fs_cache_size = size_in_mb * 1024 * 1024;
1978 }
1979 
1980 uint64_t
1981 spdk_fs_get_cache_size(void)
1982 {
1983 	return g_fs_cache_size / (1024 * 1024);
1984 }
1985 
1986 static void __file_flush(void *ctx);
1987 
1988 static void *
1989 alloc_cache_memory_buffer(struct spdk_file *context)
1990 {
1991 	struct spdk_file *file;
1992 	void *buf;
1993 
1994 	buf = spdk_mempool_get(g_cache_pool);
1995 	if (buf != NULL) {
1996 		return buf;
1997 	}
1998 
1999 	pthread_spin_lock(&g_caches_lock);
2000 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2001 		if (!file->open_for_writing &&
2002 		    file->priority == SPDK_FILE_PRIORITY_LOW &&
2003 		    file != context) {
2004 			break;
2005 		}
2006 	}
2007 	pthread_spin_unlock(&g_caches_lock);
2008 	if (file != NULL) {
2009 		cache_free_buffers(file);
2010 		buf = spdk_mempool_get(g_cache_pool);
2011 		if (buf != NULL) {
2012 			return buf;
2013 		}
2014 	}
2015 
2016 	pthread_spin_lock(&g_caches_lock);
2017 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2018 		if (!file->open_for_writing && file != context) {
2019 			break;
2020 		}
2021 	}
2022 	pthread_spin_unlock(&g_caches_lock);
2023 	if (file != NULL) {
2024 		cache_free_buffers(file);
2025 		buf = spdk_mempool_get(g_cache_pool);
2026 		if (buf != NULL) {
2027 			return buf;
2028 		}
2029 	}
2030 
2031 	pthread_spin_lock(&g_caches_lock);
2032 	TAILQ_FOREACH(file, &g_caches, cache_tailq) {
2033 		if (file != context) {
2034 			break;
2035 		}
2036 	}
2037 	pthread_spin_unlock(&g_caches_lock);
2038 	if (file != NULL) {
2039 		cache_free_buffers(file);
2040 		buf = spdk_mempool_get(g_cache_pool);
2041 		if (buf != NULL) {
2042 			return buf;
2043 		}
2044 	}
2045 
2046 	return NULL;
2047 }
2048 
2049 static struct cache_buffer *
2050 cache_insert_buffer(struct spdk_file *file, uint64_t offset)
2051 {
2052 	struct cache_buffer *buf;
2053 	int count = 0;
2054 
2055 	buf = calloc(1, sizeof(*buf));
2056 	if (buf == NULL) {
2057 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "calloc failed\n");
2058 		return NULL;
2059 	}
2060 
2061 	buf->buf = alloc_cache_memory_buffer(file);
2062 	while (buf->buf == NULL) {
2063 		/*
2064 		 * TODO: alloc_cache_memory_buffer() should eventually free
2065 		 *  some buffers.  Need a more sophisticated check here, instead
2066 		 *  of just bailing if 100 tries does not result in getting a
2067 		 *  free buffer.  This will involve using the sync channel's
2068 		 *  semaphore to block until a buffer becomes available.
2069 		 */
2070 		if (count++ == 100) {
2071 			SPDK_ERRLOG("Could not allocate cache buffer for file=%p on offset=%jx\n",
2072 				    file, offset);
2073 			free(buf);
2074 			return NULL;
2075 		}
2076 		buf->buf = alloc_cache_memory_buffer(file);
2077 	}
2078 
2079 	buf->buf_size = CACHE_BUFFER_SIZE;
2080 	buf->offset = offset;
2081 
2082 	pthread_spin_lock(&g_caches_lock);
2083 	if (file->tree->present_mask == 0) {
2084 		TAILQ_INSERT_TAIL(&g_caches, file, cache_tailq);
2085 	}
2086 	file->tree = spdk_tree_insert_buffer(file->tree, buf);
2087 	pthread_spin_unlock(&g_caches_lock);
2088 
2089 	return buf;
2090 }
2091 
2092 static struct cache_buffer *
2093 cache_append_buffer(struct spdk_file *file)
2094 {
2095 	struct cache_buffer *last;
2096 
2097 	assert(file->last == NULL || file->last->bytes_filled == file->last->buf_size);
2098 	assert((file->append_pos % CACHE_BUFFER_SIZE) == 0);
2099 
2100 	last = cache_insert_buffer(file, file->append_pos);
2101 	if (last == NULL) {
2102 		SPDK_DEBUGLOG(SPDK_LOG_BLOBFS, "cache_insert_buffer failed\n");
2103 		return NULL;
2104 	}
2105 
2106 	file->last = last;
2107 
2108 	return last;
2109 }
2110 
2111 static void __check_sync_reqs(struct spdk_file *file);
2112 
2113 static void
2114 __file_cache_finish_sync(void *ctx, int bserrno)
2115 {
2116 	struct spdk_file *file;
2117 	struct spdk_fs_request *sync_req = ctx;
2118 	struct spdk_fs_cb_args *sync_args;
2119 
2120 	sync_args = &sync_req->args;
2121 	file = sync_args->file;
2122 	pthread_spin_lock(&file->lock);
2123 	file->length_xattr = sync_args->op.sync.length;
2124 	assert(sync_args->op.sync.offset <= file->length_flushed);
2125 	spdk_trace_record(TRACE_BLOBFS_XATTR_END, 0, sync_args->op.sync.offset,
2126 			  0, file->trace_arg_name);
2127 	BLOBFS_TRACE(file, "sync done offset=%jx\n", sync_args->op.sync.offset);
2128 	TAILQ_REMOVE(&file->sync_requests, sync_req, args.op.sync.tailq);
2129 	pthread_spin_unlock(&file->lock);
2130 
2131 	sync_args->fn.file_op(sync_args->arg, bserrno);
2132 	pthread_spin_lock(&file->lock);
2133 	free_fs_request(sync_req);
2134 	pthread_spin_unlock(&file->lock);
2135 
2136 	__check_sync_reqs(file);
2137 }
2138 
2139 static void
2140 __check_sync_reqs(struct spdk_file *file)
2141 {
2142 	struct spdk_fs_request *sync_req;
2143 
2144 	pthread_spin_lock(&file->lock);
2145 
2146 	TAILQ_FOREACH(sync_req, &file->sync_requests, args.op.sync.tailq) {
2147 		if (sync_req->args.op.sync.offset <= file->length_flushed) {
2148 			break;
2149 		}
2150 	}
2151 
2152 	if (sync_req != NULL && !sync_req->args.op.sync.xattr_in_progress) {
2153 		BLOBFS_TRACE(file, "set xattr length 0x%jx\n", file->length_flushed);
2154 		sync_req->args.op.sync.xattr_in_progress = true;
2155 		sync_req->args.op.sync.length = file->length_flushed;
2156 		spdk_blob_set_xattr(file->blob, "length", &file->length_flushed,
2157 				    sizeof(file->length_flushed));
2158 
2159 		pthread_spin_unlock(&file->lock);
2160 		spdk_trace_record(TRACE_BLOBFS_XATTR_START, 0, file->length_flushed,
2161 				  0, file->trace_arg_name);
2162 		spdk_blob_sync_md(file->blob, __file_cache_finish_sync, sync_req);
2163 	} else {
2164 		pthread_spin_unlock(&file->lock);
2165 	}
2166 }
2167 
2168 static void
2169 __file_flush_done(void *ctx, int bserrno)
2170 {
2171 	struct spdk_fs_request *req = ctx;
2172 	struct spdk_fs_cb_args *args = &req->args;
2173 	struct spdk_file *file = args->file;
2174 	struct cache_buffer *next = args->op.flush.cache_buffer;
2175 
2176 	BLOBFS_TRACE(file, "length=%jx\n", args->op.flush.length);
2177 
2178 	pthread_spin_lock(&file->lock);
2179 	next->in_progress = false;
2180 	next->bytes_flushed += args->op.flush.length;
2181 	file->length_flushed += args->op.flush.length;
2182 	if (file->length_flushed > file->length) {
2183 		file->length = file->length_flushed;
2184 	}
2185 	if (next->bytes_flushed == next->buf_size) {
2186 		BLOBFS_TRACE(file, "write buffer fully flushed 0x%jx\n", file->length_flushed);
2187 		next = spdk_tree_find_buffer(file->tree, file->length_flushed);
2188 	}
2189 
2190 	/*
2191 	 * Assert that there is no cached data that extends past the end of the underlying
2192 	 *  blob.
2193 	 */
2194 	assert(next == NULL || next->offset < __file_get_blob_size(file) ||
2195 	       next->bytes_filled == 0);
2196 
2197 	pthread_spin_unlock(&file->lock);
2198 
2199 	__check_sync_reqs(file);
2200 
2201 	__file_flush(req);
2202 }
2203 
2204 static void
2205 __file_flush(void *ctx)
2206 {
2207 	struct spdk_fs_request *req = ctx;
2208 	struct spdk_fs_cb_args *args = &req->args;
2209 	struct spdk_file *file = args->file;
2210 	struct cache_buffer *next;
2211 	uint64_t offset, length, start_lba, num_lba;
2212 	uint32_t lba_size;
2213 
2214 	pthread_spin_lock(&file->lock);
2215 	next = spdk_tree_find_buffer(file->tree, file->length_flushed);
2216 	if (next == NULL || next->in_progress ||
2217 	    ((next->bytes_filled < next->buf_size) && TAILQ_EMPTY(&file->sync_requests))) {
2218 		/*
2219 		 * There is either no data to flush, a flush I/O is already in
2220 		 *  progress, or the next buffer is partially filled but there's no
2221 		 *  outstanding request to sync it.
2222 		 * So return immediately - if a flush I/O is in progress we will flush
2223 		 *  more data after that is completed, or a partial buffer will get flushed
2224 		 *  when it is either filled or the file is synced.
2225 		 */
2226 		free_fs_request(req);
2227 		if (next == NULL) {
2228 			/*
2229 			 * For cases where a file's cache was evicted, and then the
2230 			 *  file was later appended, we will write the data directly
2231 			 *  to disk and bypass cache.  So just update length_flushed
2232 			 *  here to reflect that all data was already written to disk.
2233 			 */
2234 			file->length_flushed = file->append_pos;
2235 		}
2236 		pthread_spin_unlock(&file->lock);
2237 		if (next == NULL) {
2238 			/*
2239 			 * There is no data to flush, but we still need to check for any
2240 			 *  outstanding sync requests to make sure metadata gets updated.
2241 			 */
2242 			__check_sync_reqs(file);
2243 		}
2244 		return;
2245 	}
2246 
2247 	offset = next->offset + next->bytes_flushed;
2248 	length = next->bytes_filled - next->bytes_flushed;
2249 	if (length == 0) {
2250 		free_fs_request(req);
2251 		pthread_spin_unlock(&file->lock);
2252 		/*
2253 		 * There is no data to flush, but we still need to check for any
2254 		 *  outstanding sync requests to make sure metadata gets updated.
2255 		 */
2256 		__check_sync_reqs(file);
2257 		return;
2258 	}
2259 	args->op.flush.length = length;
2260 	args->op.flush.cache_buffer = next;
2261 
2262 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
2263 
2264 	next->in_progress = true;
2265 	BLOBFS_TRACE(file, "offset=%jx length=%jx page start=%jx num=%jx\n",
2266 		     offset, length, start_lba, num_lba);
2267 	pthread_spin_unlock(&file->lock);
2268 	spdk_blob_io_write(file->blob, file->fs->sync_target.sync_fs_channel->bs_channel,
2269 			   next->buf + (start_lba * lba_size) - next->offset,
2270 			   start_lba, num_lba, __file_flush_done, req);
2271 }
2272 
2273 static void
2274 __file_extend_done(void *arg, int bserrno)
2275 {
2276 	struct spdk_fs_cb_args *args = arg;
2277 
2278 	__wake_caller(args, bserrno);
2279 }
2280 
2281 static void
2282 __file_extend_resize_cb(void *_args, int bserrno)
2283 {
2284 	struct spdk_fs_cb_args *args = _args;
2285 	struct spdk_file *file = args->file;
2286 
2287 	if (bserrno) {
2288 		__wake_caller(args, bserrno);
2289 		return;
2290 	}
2291 
2292 	spdk_blob_sync_md(file->blob, __file_extend_done, args);
2293 }
2294 
2295 static void
2296 __file_extend_blob(void *_args)
2297 {
2298 	struct spdk_fs_cb_args *args = _args;
2299 	struct spdk_file *file = args->file;
2300 
2301 	spdk_blob_resize(file->blob, args->op.resize.num_clusters, __file_extend_resize_cb, args);
2302 }
2303 
2304 static void
2305 __rw_from_file_done(void *ctx, int bserrno)
2306 {
2307 	struct spdk_fs_request *req = ctx;
2308 
2309 	__wake_caller(&req->args, bserrno);
2310 	free_fs_request(req);
2311 }
2312 
2313 static void
2314 __rw_from_file(void *ctx)
2315 {
2316 	struct spdk_fs_request *req = ctx;
2317 	struct spdk_fs_cb_args *args = &req->args;
2318 	struct spdk_file *file = args->file;
2319 
2320 	if (args->op.rw.is_read) {
2321 		spdk_file_read_async(file, file->fs->sync_target.sync_io_channel, args->iovs[0].iov_base,
2322 				     args->op.rw.offset, (uint64_t)args->iovs[0].iov_len,
2323 				     __rw_from_file_done, req);
2324 	} else {
2325 		spdk_file_write_async(file, file->fs->sync_target.sync_io_channel, args->iovs[0].iov_base,
2326 				      args->op.rw.offset, (uint64_t)args->iovs[0].iov_len,
2327 				      __rw_from_file_done, req);
2328 	}
2329 }
2330 
2331 static int
2332 __send_rw_from_file(struct spdk_file *file, void *payload,
2333 		    uint64_t offset, uint64_t length, bool is_read,
2334 		    struct spdk_fs_channel *channel)
2335 {
2336 	struct spdk_fs_request *req;
2337 	struct spdk_fs_cb_args *args;
2338 
2339 	req = alloc_fs_request_with_iov(channel, 1);
2340 	if (req == NULL) {
2341 		sem_post(&channel->sem);
2342 		return -ENOMEM;
2343 	}
2344 
2345 	args = &req->args;
2346 	args->file = file;
2347 	args->sem = &channel->sem;
2348 	args->iovs[0].iov_base = payload;
2349 	args->iovs[0].iov_len = (size_t)length;
2350 	args->op.rw.offset = offset;
2351 	args->op.rw.is_read = is_read;
2352 	file->fs->send_request(__rw_from_file, req);
2353 	return 0;
2354 }
2355 
2356 int
2357 spdk_file_write(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
2358 		void *payload, uint64_t offset, uint64_t length)
2359 {
2360 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2361 	struct spdk_fs_request *flush_req;
2362 	uint64_t rem_length, copy, blob_size, cluster_sz;
2363 	uint32_t cache_buffers_filled = 0;
2364 	uint8_t *cur_payload;
2365 	struct cache_buffer *last;
2366 
2367 	BLOBFS_TRACE_RW(file, "offset=%jx length=%jx\n", offset, length);
2368 
2369 	if (length == 0) {
2370 		return 0;
2371 	}
2372 
2373 	if (offset != file->append_pos) {
2374 		BLOBFS_TRACE(file, " error offset=%jx append_pos=%jx\n", offset, file->append_pos);
2375 		return -EINVAL;
2376 	}
2377 
2378 	pthread_spin_lock(&file->lock);
2379 	file->open_for_writing = true;
2380 
2381 	if ((file->last == NULL) && (file->append_pos % CACHE_BUFFER_SIZE == 0)) {
2382 		cache_append_buffer(file);
2383 	}
2384 
2385 	if (file->last == NULL) {
2386 		int rc;
2387 
2388 		file->append_pos += length;
2389 		pthread_spin_unlock(&file->lock);
2390 		rc = __send_rw_from_file(file, payload, offset, length, false, channel);
2391 		sem_wait(&channel->sem);
2392 		return rc;
2393 	}
2394 
2395 	blob_size = __file_get_blob_size(file);
2396 
2397 	if ((offset + length) > blob_size) {
2398 		struct spdk_fs_cb_args extend_args = {};
2399 
2400 		cluster_sz = file->fs->bs_opts.cluster_sz;
2401 		extend_args.sem = &channel->sem;
2402 		extend_args.op.resize.num_clusters = __bytes_to_clusters((offset + length), cluster_sz);
2403 		extend_args.file = file;
2404 		BLOBFS_TRACE(file, "start resize to %u clusters\n", extend_args.op.resize.num_clusters);
2405 		pthread_spin_unlock(&file->lock);
2406 		file->fs->send_request(__file_extend_blob, &extend_args);
2407 		sem_wait(&channel->sem);
2408 		if (extend_args.rc) {
2409 			return extend_args.rc;
2410 		}
2411 	}
2412 
2413 	flush_req = alloc_fs_request(channel);
2414 	if (flush_req == NULL) {
2415 		pthread_spin_unlock(&file->lock);
2416 		return -ENOMEM;
2417 	}
2418 
2419 	last = file->last;
2420 	rem_length = length;
2421 	cur_payload = payload;
2422 	while (rem_length > 0) {
2423 		copy = last->buf_size - last->bytes_filled;
2424 		if (copy > rem_length) {
2425 			copy = rem_length;
2426 		}
2427 		BLOBFS_TRACE_RW(file, "  fill offset=%jx length=%jx\n", file->append_pos, copy);
2428 		memcpy(&last->buf[last->bytes_filled], cur_payload, copy);
2429 		file->append_pos += copy;
2430 		if (file->length < file->append_pos) {
2431 			file->length = file->append_pos;
2432 		}
2433 		cur_payload += copy;
2434 		last->bytes_filled += copy;
2435 		rem_length -= copy;
2436 		if (last->bytes_filled == last->buf_size) {
2437 			cache_buffers_filled++;
2438 			last = cache_append_buffer(file);
2439 			if (last == NULL) {
2440 				BLOBFS_TRACE(file, "nomem\n");
2441 				free_fs_request(flush_req);
2442 				pthread_spin_unlock(&file->lock);
2443 				return -ENOMEM;
2444 			}
2445 		}
2446 	}
2447 
2448 	pthread_spin_unlock(&file->lock);
2449 
2450 	if (cache_buffers_filled == 0) {
2451 		free_fs_request(flush_req);
2452 		return 0;
2453 	}
2454 
2455 	flush_req->args.file = file;
2456 	file->fs->send_request(__file_flush, flush_req);
2457 	return 0;
2458 }
2459 
2460 static void
2461 __readahead_done(void *ctx, int bserrno)
2462 {
2463 	struct spdk_fs_request *req = ctx;
2464 	struct spdk_fs_cb_args *args = &req->args;
2465 	struct cache_buffer *cache_buffer = args->op.readahead.cache_buffer;
2466 	struct spdk_file *file = args->file;
2467 
2468 	BLOBFS_TRACE(file, "offset=%jx\n", cache_buffer->offset);
2469 
2470 	pthread_spin_lock(&file->lock);
2471 	cache_buffer->bytes_filled = args->op.readahead.length;
2472 	cache_buffer->bytes_flushed = args->op.readahead.length;
2473 	cache_buffer->in_progress = false;
2474 	pthread_spin_unlock(&file->lock);
2475 
2476 	free_fs_request(req);
2477 }
2478 
2479 static void
2480 __readahead(void *ctx)
2481 {
2482 	struct spdk_fs_request *req = ctx;
2483 	struct spdk_fs_cb_args *args = &req->args;
2484 	struct spdk_file *file = args->file;
2485 	uint64_t offset, length, start_lba, num_lba;
2486 	uint32_t lba_size;
2487 
2488 	offset = args->op.readahead.offset;
2489 	length = args->op.readahead.length;
2490 	assert(length > 0);
2491 
2492 	__get_page_parameters(file, offset, length, &start_lba, &lba_size, &num_lba);
2493 
2494 	BLOBFS_TRACE(file, "offset=%jx length=%jx page start=%jx num=%jx\n",
2495 		     offset, length, start_lba, num_lba);
2496 	spdk_blob_io_read(file->blob, file->fs->sync_target.sync_fs_channel->bs_channel,
2497 			  args->op.readahead.cache_buffer->buf,
2498 			  start_lba, num_lba, __readahead_done, req);
2499 }
2500 
2501 static uint64_t
2502 __next_cache_buffer_offset(uint64_t offset)
2503 {
2504 	return (offset + CACHE_BUFFER_SIZE) & ~(CACHE_TREE_LEVEL_MASK(0));
2505 }
2506 
2507 static void
2508 check_readahead(struct spdk_file *file, uint64_t offset,
2509 		struct spdk_fs_channel *channel)
2510 {
2511 	struct spdk_fs_request *req;
2512 	struct spdk_fs_cb_args *args;
2513 
2514 	offset = __next_cache_buffer_offset(offset);
2515 	if (spdk_tree_find_buffer(file->tree, offset) != NULL || file->length <= offset) {
2516 		return;
2517 	}
2518 
2519 	req = alloc_fs_request(channel);
2520 	if (req == NULL) {
2521 		return;
2522 	}
2523 	args = &req->args;
2524 
2525 	BLOBFS_TRACE(file, "offset=%jx\n", offset);
2526 
2527 	args->file = file;
2528 	args->op.readahead.offset = offset;
2529 	args->op.readahead.cache_buffer = cache_insert_buffer(file, offset);
2530 	if (!args->op.readahead.cache_buffer) {
2531 		BLOBFS_TRACE(file, "Cannot allocate buf for offset=%jx\n", offset);
2532 		free_fs_request(req);
2533 		return;
2534 	}
2535 
2536 	args->op.readahead.cache_buffer->in_progress = true;
2537 	if (file->length < (offset + CACHE_BUFFER_SIZE)) {
2538 		args->op.readahead.length = file->length & (CACHE_BUFFER_SIZE - 1);
2539 	} else {
2540 		args->op.readahead.length = CACHE_BUFFER_SIZE;
2541 	}
2542 	file->fs->send_request(__readahead, req);
2543 }
2544 
2545 static int
2546 __file_read(struct spdk_file *file, void *payload, uint64_t offset, uint64_t length,
2547 	    struct spdk_fs_channel *channel)
2548 {
2549 	struct cache_buffer *buf;
2550 	int rc;
2551 
2552 	buf = spdk_tree_find_filled_buffer(file->tree, offset);
2553 	if (buf == NULL) {
2554 		pthread_spin_unlock(&file->lock);
2555 		rc = __send_rw_from_file(file, payload, offset, length, true, channel);
2556 		pthread_spin_lock(&file->lock);
2557 		return rc;
2558 	}
2559 
2560 	if ((offset + length) > (buf->offset + buf->bytes_filled)) {
2561 		length = buf->offset + buf->bytes_filled - offset;
2562 	}
2563 	BLOBFS_TRACE(file, "read %p offset=%ju length=%ju\n", payload, offset, length);
2564 	memcpy(payload, &buf->buf[offset - buf->offset], length);
2565 	if ((offset + length) % CACHE_BUFFER_SIZE == 0) {
2566 		pthread_spin_lock(&g_caches_lock);
2567 		spdk_tree_remove_buffer(file->tree, buf);
2568 		if (file->tree->present_mask == 0) {
2569 			TAILQ_REMOVE(&g_caches, file, cache_tailq);
2570 		}
2571 		pthread_spin_unlock(&g_caches_lock);
2572 	}
2573 
2574 	sem_post(&channel->sem);
2575 	return 0;
2576 }
2577 
2578 int64_t
2579 spdk_file_read(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx,
2580 	       void *payload, uint64_t offset, uint64_t length)
2581 {
2582 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2583 	uint64_t final_offset, final_length;
2584 	uint32_t sub_reads = 0;
2585 	int rc = 0;
2586 
2587 	pthread_spin_lock(&file->lock);
2588 
2589 	BLOBFS_TRACE_RW(file, "offset=%ju length=%ju\n", offset, length);
2590 
2591 	file->open_for_writing = false;
2592 
2593 	if (length == 0 || offset >= file->append_pos) {
2594 		pthread_spin_unlock(&file->lock);
2595 		return 0;
2596 	}
2597 
2598 	if (offset + length > file->append_pos) {
2599 		length = file->append_pos - offset;
2600 	}
2601 
2602 	if (offset != file->next_seq_offset) {
2603 		file->seq_byte_count = 0;
2604 	}
2605 	file->seq_byte_count += length;
2606 	file->next_seq_offset = offset + length;
2607 	if (file->seq_byte_count >= CACHE_READAHEAD_THRESHOLD) {
2608 		check_readahead(file, offset, channel);
2609 		check_readahead(file, offset + CACHE_BUFFER_SIZE, channel);
2610 	}
2611 
2612 	final_length = 0;
2613 	final_offset = offset + length;
2614 	while (offset < final_offset) {
2615 		length = NEXT_CACHE_BUFFER_OFFSET(offset) - offset;
2616 		if (length > (final_offset - offset)) {
2617 			length = final_offset - offset;
2618 		}
2619 
2620 		sub_reads++;
2621 		rc = __file_read(file, payload, offset, length, channel);
2622 		if (rc == 0) {
2623 			final_length += length;
2624 		} else {
2625 			break;
2626 		}
2627 		payload += length;
2628 		offset += length;
2629 	}
2630 	pthread_spin_unlock(&file->lock);
2631 	while (sub_reads-- > 0) {
2632 		sem_wait(&channel->sem);
2633 	}
2634 	if (rc == 0) {
2635 		return final_length;
2636 	} else {
2637 		return rc;
2638 	}
2639 }
2640 
2641 static void
2642 _file_sync(struct spdk_file *file, struct spdk_fs_channel *channel,
2643 	   spdk_file_op_complete cb_fn, void *cb_arg)
2644 {
2645 	struct spdk_fs_request *sync_req;
2646 	struct spdk_fs_request *flush_req;
2647 	struct spdk_fs_cb_args *sync_args;
2648 	struct spdk_fs_cb_args *flush_args;
2649 
2650 	BLOBFS_TRACE(file, "offset=%jx\n", file->append_pos);
2651 
2652 	pthread_spin_lock(&file->lock);
2653 	if (file->append_pos <= file->length_xattr) {
2654 		BLOBFS_TRACE(file, "done - file already synced\n");
2655 		pthread_spin_unlock(&file->lock);
2656 		cb_fn(cb_arg, 0);
2657 		return;
2658 	}
2659 
2660 	sync_req = alloc_fs_request(channel);
2661 	if (!sync_req) {
2662 		SPDK_ERRLOG("Cannot allocate sync req for file=%s\n", file->name);
2663 		pthread_spin_unlock(&file->lock);
2664 		cb_fn(cb_arg, -ENOMEM);
2665 		return;
2666 	}
2667 	sync_args = &sync_req->args;
2668 
2669 	flush_req = alloc_fs_request(channel);
2670 	if (!flush_req) {
2671 		SPDK_ERRLOG("Cannot allocate flush req for file=%s\n", file->name);
2672 		free_fs_request(sync_req);
2673 		pthread_spin_unlock(&file->lock);
2674 		cb_fn(cb_arg, -ENOMEM);
2675 		return;
2676 	}
2677 	flush_args = &flush_req->args;
2678 
2679 	sync_args->file = file;
2680 	sync_args->fn.file_op = cb_fn;
2681 	sync_args->arg = cb_arg;
2682 	sync_args->op.sync.offset = file->append_pos;
2683 	sync_args->op.sync.xattr_in_progress = false;
2684 	TAILQ_INSERT_TAIL(&file->sync_requests, sync_req, args.op.sync.tailq);
2685 	pthread_spin_unlock(&file->lock);
2686 
2687 	flush_args->file = file;
2688 	channel->send_request(__file_flush, flush_req);
2689 }
2690 
2691 int
2692 spdk_file_sync(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx)
2693 {
2694 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2695 	struct spdk_fs_cb_args args = {};
2696 
2697 	args.sem = &channel->sem;
2698 	_file_sync(file, channel, __wake_caller, &args);
2699 	sem_wait(&channel->sem);
2700 
2701 	return args.rc;
2702 }
2703 
2704 void
2705 spdk_file_sync_async(struct spdk_file *file, struct spdk_io_channel *_channel,
2706 		     spdk_file_op_complete cb_fn, void *cb_arg)
2707 {
2708 	struct spdk_fs_channel *channel = spdk_io_channel_get_ctx(_channel);
2709 
2710 	_file_sync(file, channel, cb_fn, cb_arg);
2711 }
2712 
2713 void
2714 spdk_file_set_priority(struct spdk_file *file, uint32_t priority)
2715 {
2716 	BLOBFS_TRACE(file, "priority=%u\n", priority);
2717 	file->priority = priority;
2718 
2719 }
2720 
2721 /*
2722  * Close routines
2723  */
2724 
2725 static void
2726 __file_close_async_done(void *ctx, int bserrno)
2727 {
2728 	struct spdk_fs_request *req = ctx;
2729 	struct spdk_fs_cb_args *args = &req->args;
2730 	struct spdk_file *file = args->file;
2731 
2732 	spdk_trace_record(TRACE_BLOBFS_CLOSE, 0, 0, 0, file->trace_arg_name);
2733 
2734 	if (file->is_deleted) {
2735 		spdk_fs_delete_file_async(file->fs, file->name, blob_delete_cb, ctx);
2736 		return;
2737 	}
2738 
2739 	args->fn.file_op(args->arg, bserrno);
2740 	free_fs_request(req);
2741 }
2742 
2743 static void
2744 __file_close_async(struct spdk_file *file, struct spdk_fs_request *req)
2745 {
2746 	struct spdk_blob *blob;
2747 
2748 	pthread_spin_lock(&file->lock);
2749 	if (file->ref_count == 0) {
2750 		pthread_spin_unlock(&file->lock);
2751 		__file_close_async_done(req, -EBADF);
2752 		return;
2753 	}
2754 
2755 	file->ref_count--;
2756 	if (file->ref_count > 0) {
2757 		pthread_spin_unlock(&file->lock);
2758 		req->args.fn.file_op(req->args.arg, 0);
2759 		free_fs_request(req);
2760 		return;
2761 	}
2762 
2763 	pthread_spin_unlock(&file->lock);
2764 
2765 	blob = file->blob;
2766 	file->blob = NULL;
2767 	spdk_blob_close(blob, __file_close_async_done, req);
2768 }
2769 
2770 static void
2771 __file_close_async__sync_done(void *arg, int fserrno)
2772 {
2773 	struct spdk_fs_request *req = arg;
2774 	struct spdk_fs_cb_args *args = &req->args;
2775 
2776 	__file_close_async(args->file, req);
2777 }
2778 
2779 void
2780 spdk_file_close_async(struct spdk_file *file, spdk_file_op_complete cb_fn, void *cb_arg)
2781 {
2782 	struct spdk_fs_request *req;
2783 	struct spdk_fs_cb_args *args;
2784 
2785 	req = alloc_fs_request(file->fs->md_target.md_fs_channel);
2786 	if (req == NULL) {
2787 		SPDK_ERRLOG("Cannot allocate close async req for file=%s\n", file->name);
2788 		cb_fn(cb_arg, -ENOMEM);
2789 		return;
2790 	}
2791 
2792 	args = &req->args;
2793 	args->file = file;
2794 	args->fn.file_op = cb_fn;
2795 	args->arg = cb_arg;
2796 
2797 	spdk_file_sync_async(file, file->fs->md_target.md_io_channel, __file_close_async__sync_done, req);
2798 }
2799 
2800 static void
2801 __file_close(void *arg)
2802 {
2803 	struct spdk_fs_request *req = arg;
2804 	struct spdk_fs_cb_args *args = &req->args;
2805 	struct spdk_file *file = args->file;
2806 
2807 	__file_close_async(file, req);
2808 }
2809 
2810 int
2811 spdk_file_close(struct spdk_file *file, struct spdk_fs_thread_ctx *ctx)
2812 {
2813 	struct spdk_fs_channel *channel = (struct spdk_fs_channel *)ctx;
2814 	struct spdk_fs_request *req;
2815 	struct spdk_fs_cb_args *args;
2816 
2817 	req = alloc_fs_request(channel);
2818 	if (req == NULL) {
2819 		SPDK_ERRLOG("Cannot allocate close req for file=%s\n", file->name);
2820 		return -ENOMEM;
2821 	}
2822 
2823 	args = &req->args;
2824 
2825 	spdk_file_sync(file, ctx);
2826 	BLOBFS_TRACE(file, "name=%s\n", file->name);
2827 	args->file = file;
2828 	args->sem = &channel->sem;
2829 	args->fn.file_op = __wake_caller;
2830 	args->arg = args;
2831 	channel->send_request(__file_close, req);
2832 	sem_wait(&channel->sem);
2833 
2834 	return args->rc;
2835 }
2836 
2837 int
2838 spdk_file_get_id(struct spdk_file *file, void *id, size_t size)
2839 {
2840 	if (size < sizeof(spdk_blob_id)) {
2841 		return -EINVAL;
2842 	}
2843 
2844 	memcpy(id, &file->blobid, sizeof(spdk_blob_id));
2845 
2846 	return sizeof(spdk_blob_id);
2847 }
2848 
2849 static void
2850 cache_free_buffers(struct spdk_file *file)
2851 {
2852 	BLOBFS_TRACE(file, "free=%s\n", file->name);
2853 	pthread_spin_lock(&file->lock);
2854 	pthread_spin_lock(&g_caches_lock);
2855 	if (file->tree->present_mask == 0) {
2856 		pthread_spin_unlock(&g_caches_lock);
2857 		pthread_spin_unlock(&file->lock);
2858 		return;
2859 	}
2860 	spdk_tree_free_buffers(file->tree);
2861 
2862 	TAILQ_REMOVE(&g_caches, file, cache_tailq);
2863 	/* If not freed, put it in the end of the queue */
2864 	if (file->tree->present_mask != 0) {
2865 		TAILQ_INSERT_TAIL(&g_caches, file, cache_tailq);
2866 	}
2867 	file->last = NULL;
2868 	pthread_spin_unlock(&g_caches_lock);
2869 	pthread_spin_unlock(&file->lock);
2870 }
2871 
2872 SPDK_LOG_REGISTER_COMPONENT("blobfs", SPDK_LOG_BLOBFS)
2873 SPDK_LOG_REGISTER_COMPONENT("blobfs_rw", SPDK_LOG_BLOBFS_RW)
2874