xref: /spdk/lib/reduce/reduce.c (revision 63e0c25dad5f2793fdb9ff9b1e6ce516673dc6aa)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2018 Intel Corporation.
3  *   All rights reserved.
4  *   Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "queue_internal.h"
10 
11 #include "spdk/reduce.h"
12 #include "spdk/env.h"
13 #include "spdk/string.h"
14 #include "spdk/bit_array.h"
15 #include "spdk/util.h"
16 #include "spdk/log.h"
17 #include "spdk/memory.h"
18 #include "spdk/tree.h"
19 
20 #include "libpmem.h"
21 
22 /* Always round up the size of the PM region to the nearest cacheline. */
23 #define REDUCE_PM_SIZE_ALIGNMENT	64
24 
25 /* Offset into the backing device where the persistent memory file's path is stored. */
26 #define REDUCE_BACKING_DEV_PATH_OFFSET	4096
27 
28 #define REDUCE_EMPTY_MAP_ENTRY	-1ULL
29 
30 #define REDUCE_NUM_VOL_REQUESTS	256
31 
32 /* Structure written to offset 0 of both the pm file and the backing device. */
33 struct spdk_reduce_vol_superblock {
34 	uint8_t				signature[8];
35 	struct spdk_reduce_vol_params	params;
36 	uint8_t				reserved[4040];
37 };
38 SPDK_STATIC_ASSERT(sizeof(struct spdk_reduce_vol_superblock) == 4096, "size incorrect");
39 
40 #define SPDK_REDUCE_SIGNATURE "SPDKREDU"
41 /* null terminator counts one */
42 SPDK_STATIC_ASSERT(sizeof(SPDK_REDUCE_SIGNATURE) - 1 ==
43 		   SPDK_SIZEOF_MEMBER(struct spdk_reduce_vol_superblock, signature), "size incorrect");
44 
45 #define REDUCE_PATH_MAX 4096
46 
47 #define REDUCE_ZERO_BUF_SIZE 0x100000
48 
49 /**
50  * Describes a persistent memory file used to hold metadata associated with a
51  *  compressed volume.
52  */
53 struct spdk_reduce_pm_file {
54 	char			path[REDUCE_PATH_MAX];
55 	void			*pm_buf;
56 	int			pm_is_pmem;
57 	uint64_t		size;
58 };
59 
60 #define REDUCE_IO_READV		1
61 #define REDUCE_IO_WRITEV	2
62 
63 struct spdk_reduce_chunk_map {
64 	uint32_t		compressed_size;
65 	uint32_t		reserved;
66 	uint64_t		io_unit_index[0];
67 };
68 
69 struct spdk_reduce_vol_request {
70 	/**
71 	 *  Scratch buffer used for uncompressed chunk.  This is used for:
72 	 *   1) source buffer for compression operations
73 	 *   2) destination buffer for decompression operations
74 	 *   3) data buffer when writing uncompressed chunk to disk
75 	 *   4) data buffer when reading uncompressed chunk from disk
76 	 */
77 	uint8_t					*decomp_buf;
78 	struct iovec				*decomp_buf_iov;
79 
80 	/**
81 	 * These are used to construct the iovecs that are sent to
82 	 *  the decomp engine, they point to a mix of the scratch buffer
83 	 *  and user buffer
84 	 */
85 	struct iovec				decomp_iov[REDUCE_MAX_IOVECS + 2];
86 	int					decomp_iovcnt;
87 
88 	/**
89 	 *  Scratch buffer used for compressed chunk.  This is used for:
90 	 *   1) destination buffer for compression operations
91 	 *   2) source buffer for decompression operations
92 	 *   3) data buffer when writing compressed chunk to disk
93 	 *   4) data buffer when reading compressed chunk from disk
94 	 */
95 	uint8_t					*comp_buf;
96 	struct iovec				*comp_buf_iov;
97 	struct iovec				*iov;
98 	bool					rmw;
99 	struct spdk_reduce_vol			*vol;
100 	int					type;
101 	int					reduce_errno;
102 	int					iovcnt;
103 	int					num_backing_ops;
104 	uint32_t				num_io_units;
105 	struct spdk_reduce_backing_io           *backing_io;
106 	bool					chunk_is_compressed;
107 	bool					copy_after_decompress;
108 	uint64_t				offset;
109 	uint64_t				logical_map_index;
110 	uint64_t				length;
111 	uint64_t				chunk_map_index;
112 	struct spdk_reduce_chunk_map		*chunk;
113 	spdk_reduce_vol_op_complete		cb_fn;
114 	void					*cb_arg;
115 	TAILQ_ENTRY(spdk_reduce_vol_request)	tailq;
116 	RB_ENTRY(spdk_reduce_vol_request)	rbnode;
117 	struct spdk_reduce_vol_cb_args		backing_cb_args;
118 };
119 
120 struct spdk_reduce_vol {
121 	struct spdk_reduce_vol_params		params;
122 	uint32_t				backing_io_units_per_chunk;
123 	uint32_t				backing_lba_per_io_unit;
124 	uint32_t				logical_blocks_per_chunk;
125 	struct spdk_reduce_pm_file		pm_file;
126 	struct spdk_reduce_backing_dev		*backing_dev;
127 	struct spdk_reduce_vol_superblock	*backing_super;
128 	struct spdk_reduce_vol_superblock	*pm_super;
129 	uint64_t				*pm_logical_map;
130 	uint64_t				*pm_chunk_maps;
131 
132 	struct spdk_bit_array			*allocated_chunk_maps;
133 	/* The starting position when looking for a block from allocated_chunk_maps */
134 	uint64_t				find_chunk_offset;
135 	/* Cache free chunks to speed up lookup of free chunk. */
136 	struct reduce_queue			free_chunks_queue;
137 	struct spdk_bit_array			*allocated_backing_io_units;
138 	/* The starting position when looking for a block from allocated_backing_io_units */
139 	uint64_t				find_block_offset;
140 	/* Cache free blocks for backing bdev to speed up lookup of free backing blocks. */
141 	struct reduce_queue			free_backing_blocks_queue;
142 
143 	struct spdk_reduce_vol_request		*request_mem;
144 	TAILQ_HEAD(, spdk_reduce_vol_request)	free_requests;
145 	RB_HEAD(executing_req_tree, spdk_reduce_vol_request) executing_requests;
146 	TAILQ_HEAD(, spdk_reduce_vol_request)	queued_requests;
147 
148 	/* Single contiguous buffer used for all request buffers for this volume. */
149 	uint8_t					*buf_mem;
150 	struct iovec				*buf_iov_mem;
151 	/* Single contiguous buffer used for backing io buffers for this volume. */
152 	uint8_t					*buf_backing_io_mem;
153 };
154 
155 static void _start_readv_request(struct spdk_reduce_vol_request *req);
156 static void _start_writev_request(struct spdk_reduce_vol_request *req);
157 static uint8_t *g_zero_buf;
158 static int g_vol_count = 0;
159 
160 /*
161  * Allocate extra metadata chunks and corresponding backing io units to account for
162  *  outstanding IO in worst case scenario where logical map is completely allocated
163  *  and no data can be compressed.  We need extra chunks in this case to handle
164  *  in-flight writes since reduce never writes data in place.
165  */
166 #define REDUCE_NUM_EXTRA_CHUNKS 128
167 
168 static void
169 _reduce_persist(struct spdk_reduce_vol *vol, const void *addr, size_t len)
170 {
171 	if (vol->pm_file.pm_is_pmem) {
172 		pmem_persist(addr, len);
173 	} else {
174 		pmem_msync(addr, len);
175 	}
176 }
177 
178 static uint64_t
179 _get_pm_logical_map_size(uint64_t vol_size, uint64_t chunk_size)
180 {
181 	uint64_t chunks_in_logical_map, logical_map_size;
182 
183 	chunks_in_logical_map = vol_size / chunk_size;
184 	logical_map_size = chunks_in_logical_map * sizeof(uint64_t);
185 
186 	/* Round up to next cacheline. */
187 	return spdk_divide_round_up(logical_map_size, REDUCE_PM_SIZE_ALIGNMENT) *
188 	       REDUCE_PM_SIZE_ALIGNMENT;
189 }
190 
191 static uint64_t
192 _get_total_chunks(uint64_t vol_size, uint64_t chunk_size)
193 {
194 	uint64_t num_chunks;
195 
196 	num_chunks = vol_size / chunk_size;
197 	num_chunks += REDUCE_NUM_EXTRA_CHUNKS;
198 
199 	return num_chunks;
200 }
201 
202 static inline uint32_t
203 _reduce_vol_get_chunk_struct_size(uint64_t backing_io_units_per_chunk)
204 {
205 	return sizeof(struct spdk_reduce_chunk_map) + sizeof(uint64_t) * backing_io_units_per_chunk;
206 }
207 
208 static uint64_t
209 _get_pm_total_chunks_size(uint64_t vol_size, uint64_t chunk_size, uint64_t backing_io_unit_size)
210 {
211 	uint64_t io_units_per_chunk, num_chunks, total_chunks_size;
212 
213 	num_chunks = _get_total_chunks(vol_size, chunk_size);
214 	io_units_per_chunk = chunk_size / backing_io_unit_size;
215 
216 	total_chunks_size = num_chunks * _reduce_vol_get_chunk_struct_size(io_units_per_chunk);
217 
218 	return spdk_divide_round_up(total_chunks_size, REDUCE_PM_SIZE_ALIGNMENT) *
219 	       REDUCE_PM_SIZE_ALIGNMENT;
220 }
221 
222 static struct spdk_reduce_chunk_map *
223 _reduce_vol_get_chunk_map(struct spdk_reduce_vol *vol, uint64_t chunk_map_index)
224 {
225 	uintptr_t chunk_map_addr;
226 
227 	assert(chunk_map_index < _get_total_chunks(vol->params.vol_size, vol->params.chunk_size));
228 
229 	chunk_map_addr = (uintptr_t)vol->pm_chunk_maps;
230 	chunk_map_addr += chunk_map_index *
231 			  _reduce_vol_get_chunk_struct_size(vol->backing_io_units_per_chunk);
232 
233 	return (struct spdk_reduce_chunk_map *)chunk_map_addr;
234 }
235 
236 static int
237 _validate_vol_params(struct spdk_reduce_vol_params *params)
238 {
239 	if (params->vol_size > 0) {
240 		/**
241 		 * User does not pass in the vol size - it gets calculated by libreduce from
242 		 *  values in this structure plus the size of the backing device.
243 		 */
244 		return -EINVAL;
245 	}
246 
247 	if (params->chunk_size == 0 || params->backing_io_unit_size == 0 ||
248 	    params->logical_block_size == 0) {
249 		return -EINVAL;
250 	}
251 
252 	/* Chunk size must be an even multiple of the backing io unit size. */
253 	if ((params->chunk_size % params->backing_io_unit_size) != 0) {
254 		return -EINVAL;
255 	}
256 
257 	/* Chunk size must be an even multiple of the logical block size. */
258 	if ((params->chunk_size % params->logical_block_size) != 0) {
259 		return -1;
260 	}
261 
262 	return 0;
263 }
264 
265 static uint64_t
266 _get_vol_size(uint64_t chunk_size, uint64_t backing_dev_size)
267 {
268 	uint64_t num_chunks;
269 
270 	num_chunks = backing_dev_size / chunk_size;
271 	if (num_chunks <= REDUCE_NUM_EXTRA_CHUNKS) {
272 		return 0;
273 	}
274 
275 	num_chunks -= REDUCE_NUM_EXTRA_CHUNKS;
276 	return num_chunks * chunk_size;
277 }
278 
279 static uint64_t
280 _get_pm_file_size(struct spdk_reduce_vol_params *params)
281 {
282 	uint64_t total_pm_size;
283 
284 	total_pm_size = sizeof(struct spdk_reduce_vol_superblock);
285 	total_pm_size += _get_pm_logical_map_size(params->vol_size, params->chunk_size);
286 	total_pm_size += _get_pm_total_chunks_size(params->vol_size, params->chunk_size,
287 			 params->backing_io_unit_size);
288 	return total_pm_size;
289 }
290 
291 const struct spdk_uuid *
292 spdk_reduce_vol_get_uuid(struct spdk_reduce_vol *vol)
293 {
294 	return &vol->params.uuid;
295 }
296 
297 static void
298 _initialize_vol_pm_pointers(struct spdk_reduce_vol *vol)
299 {
300 	uint64_t logical_map_size;
301 
302 	/* Superblock is at the beginning of the pm file. */
303 	vol->pm_super = (struct spdk_reduce_vol_superblock *)vol->pm_file.pm_buf;
304 
305 	/* Logical map immediately follows the super block. */
306 	vol->pm_logical_map = (uint64_t *)(vol->pm_super + 1);
307 
308 	/* Chunks maps follow the logical map. */
309 	logical_map_size = _get_pm_logical_map_size(vol->params.vol_size, vol->params.chunk_size);
310 	vol->pm_chunk_maps = (uint64_t *)((uint8_t *)vol->pm_logical_map + logical_map_size);
311 }
312 
313 /* We need 2 iovs during load - one for the superblock, another for the path */
314 #define LOAD_IOV_COUNT	2
315 
316 struct reduce_init_load_ctx {
317 	struct spdk_reduce_vol			*vol;
318 	struct spdk_reduce_vol_cb_args		backing_cb_args;
319 	spdk_reduce_vol_op_with_handle_complete	cb_fn;
320 	void					*cb_arg;
321 	struct iovec				iov[LOAD_IOV_COUNT];
322 	void					*path;
323 	struct spdk_reduce_backing_io           *backing_io;
324 };
325 
326 static inline bool
327 _addr_crosses_huge_page(const void *addr, size_t *size)
328 {
329 	size_t _size;
330 	uint64_t rc;
331 
332 	assert(size);
333 
334 	_size = *size;
335 	rc = spdk_vtophys(addr, size);
336 
337 	return rc == SPDK_VTOPHYS_ERROR || _size != *size;
338 }
339 
340 static inline int
341 _set_buffer(uint8_t **vol_buffer, uint8_t **_addr, uint8_t *addr_range, size_t buffer_size)
342 {
343 	uint8_t *addr;
344 	size_t size_tmp = buffer_size;
345 
346 	addr = *_addr;
347 
348 	/* Verify that addr + buffer_size doesn't cross huge page boundary */
349 	if (_addr_crosses_huge_page(addr, &size_tmp)) {
350 		/* Memory start is aligned on 2MiB, so buffer should be located at the end of the page.
351 		 * Skip remaining bytes and continue from the beginning of the next page */
352 		addr += size_tmp;
353 	}
354 
355 	if (addr + buffer_size > addr_range) {
356 		SPDK_ERRLOG("Vol buffer %p out of range %p\n", addr, addr_range);
357 		return -ERANGE;
358 	}
359 
360 	*vol_buffer = addr;
361 	*_addr = addr + buffer_size;
362 
363 	return 0;
364 }
365 
366 static int
367 _allocate_vol_requests(struct spdk_reduce_vol *vol)
368 {
369 	struct spdk_reduce_vol_request *req;
370 	struct spdk_reduce_backing_dev *backing_dev = vol->backing_dev;
371 	uint32_t reqs_in_2mb_page, huge_pages_needed;
372 	uint8_t *buffer, *buffer_end;
373 	int i = 0;
374 	int rc = 0;
375 
376 	/* It is needed to allocate comp and decomp buffers so that they do not cross physical
377 	* page boundaries. Assume that the system uses default 2MiB pages and chunk_size is not
378 	* necessarily power of 2
379 	* Allocate 2x since we need buffers for both read/write and compress/decompress
380 	* intermediate buffers. */
381 	reqs_in_2mb_page = VALUE_2MB / (vol->params.chunk_size * 2);
382 	if (!reqs_in_2mb_page) {
383 		return -EINVAL;
384 	}
385 	huge_pages_needed = SPDK_CEIL_DIV(REDUCE_NUM_VOL_REQUESTS, reqs_in_2mb_page);
386 
387 	vol->buf_mem = spdk_dma_malloc(VALUE_2MB * huge_pages_needed, VALUE_2MB, NULL);
388 	if (vol->buf_mem == NULL) {
389 		return -ENOMEM;
390 	}
391 
392 	vol->request_mem = calloc(REDUCE_NUM_VOL_REQUESTS, sizeof(*req));
393 	if (vol->request_mem == NULL) {
394 		spdk_free(vol->buf_mem);
395 		vol->buf_mem = NULL;
396 		return -ENOMEM;
397 	}
398 
399 	/* Allocate 2x since we need iovs for both read/write and compress/decompress intermediate
400 	 *  buffers.
401 	 */
402 	vol->buf_iov_mem = calloc(REDUCE_NUM_VOL_REQUESTS,
403 				  2 * sizeof(struct iovec) * vol->backing_io_units_per_chunk);
404 	if (vol->buf_iov_mem == NULL) {
405 		free(vol->request_mem);
406 		spdk_free(vol->buf_mem);
407 		vol->request_mem = NULL;
408 		vol->buf_mem = NULL;
409 		return -ENOMEM;
410 	}
411 
412 	vol->buf_backing_io_mem = calloc(REDUCE_NUM_VOL_REQUESTS, (sizeof(struct spdk_reduce_backing_io) +
413 					 backing_dev->user_ctx_size) * vol->backing_io_units_per_chunk);
414 	if (vol->buf_backing_io_mem == NULL) {
415 		free(vol->request_mem);
416 		free(vol->buf_iov_mem);
417 		spdk_free(vol->buf_mem);
418 		vol->request_mem = NULL;
419 		vol->buf_iov_mem = NULL;
420 		vol->buf_mem = NULL;
421 		return -ENOMEM;
422 	}
423 
424 	buffer = vol->buf_mem;
425 	buffer_end = buffer + VALUE_2MB * huge_pages_needed;
426 
427 	for (i = 0; i < REDUCE_NUM_VOL_REQUESTS; i++) {
428 		req = &vol->request_mem[i];
429 		TAILQ_INSERT_HEAD(&vol->free_requests, req, tailq);
430 		req->backing_io = (struct spdk_reduce_backing_io *)(vol->buf_backing_io_mem + i *
431 				  (sizeof(struct spdk_reduce_backing_io) + backing_dev->user_ctx_size) *
432 				  vol->backing_io_units_per_chunk);
433 
434 		req->decomp_buf_iov = &vol->buf_iov_mem[(2 * i) * vol->backing_io_units_per_chunk];
435 		req->comp_buf_iov = &vol->buf_iov_mem[(2 * i + 1) * vol->backing_io_units_per_chunk];
436 
437 		rc = _set_buffer(&req->comp_buf, &buffer, buffer_end, vol->params.chunk_size);
438 		if (rc) {
439 			SPDK_ERRLOG("Failed to set comp buffer for req idx %u, addr %p, start %p, end %p\n", i, buffer,
440 				    vol->buf_mem, buffer_end);
441 			break;
442 		}
443 		rc = _set_buffer(&req->decomp_buf, &buffer, buffer_end, vol->params.chunk_size);
444 		if (rc) {
445 			SPDK_ERRLOG("Failed to set decomp buffer for req idx %u, addr %p, start %p, end %p\n", i, buffer,
446 				    vol->buf_mem, buffer_end);
447 			break;
448 		}
449 	}
450 
451 	if (rc) {
452 		free(vol->buf_backing_io_mem);
453 		free(vol->buf_iov_mem);
454 		free(vol->request_mem);
455 		spdk_free(vol->buf_mem);
456 		vol->buf_mem = NULL;
457 		vol->buf_backing_io_mem = NULL;
458 		vol->buf_iov_mem = NULL;
459 		vol->request_mem = NULL;
460 	}
461 
462 	return rc;
463 }
464 
465 static void
466 _init_load_cleanup(struct spdk_reduce_vol *vol, struct reduce_init_load_ctx *ctx)
467 {
468 	if (ctx != NULL) {
469 		spdk_free(ctx->path);
470 		free(ctx->backing_io);
471 		free(ctx);
472 	}
473 
474 	if (vol != NULL) {
475 		if (vol->pm_file.pm_buf != NULL) {
476 			pmem_unmap(vol->pm_file.pm_buf, vol->pm_file.size);
477 		}
478 
479 		spdk_free(vol->backing_super);
480 		spdk_bit_array_free(&vol->allocated_chunk_maps);
481 		spdk_bit_array_free(&vol->allocated_backing_io_units);
482 		free(vol->request_mem);
483 		free(vol->buf_backing_io_mem);
484 		free(vol->buf_iov_mem);
485 		spdk_free(vol->buf_mem);
486 		free(vol);
487 	}
488 }
489 
490 static int
491 _alloc_zero_buff(void)
492 {
493 	int rc = 0;
494 
495 	/* The zero buffer is shared between all volumes and just used
496 	 * for reads so allocate one global instance here if not already
497 	 * allocated when another vol init'd or loaded.
498 	 */
499 	if (g_vol_count++ == 0) {
500 		g_zero_buf = spdk_zmalloc(REDUCE_ZERO_BUF_SIZE,
501 					  64, NULL, SPDK_ENV_LCORE_ID_ANY,
502 					  SPDK_MALLOC_DMA);
503 		if (g_zero_buf == NULL) {
504 			g_vol_count--;
505 			rc = -ENOMEM;
506 		}
507 	}
508 	return rc;
509 }
510 
511 static void
512 _init_write_super_cpl(void *cb_arg, int reduce_errno)
513 {
514 	struct reduce_init_load_ctx *init_ctx = cb_arg;
515 	int rc;
516 
517 	rc = _allocate_vol_requests(init_ctx->vol);
518 	if (rc != 0) {
519 		init_ctx->cb_fn(init_ctx->cb_arg, NULL, rc);
520 		_init_load_cleanup(init_ctx->vol, init_ctx);
521 		return;
522 	}
523 
524 	rc = _alloc_zero_buff();
525 	if (rc != 0) {
526 		init_ctx->cb_fn(init_ctx->cb_arg, NULL, rc);
527 		_init_load_cleanup(init_ctx->vol, init_ctx);
528 		return;
529 	}
530 
531 	init_ctx->cb_fn(init_ctx->cb_arg, init_ctx->vol, reduce_errno);
532 	/* Only clean up the ctx - the vol has been passed to the application
533 	 *  for use now that initialization was successful.
534 	 */
535 	_init_load_cleanup(NULL, init_ctx);
536 }
537 
538 static void
539 _init_write_path_cpl(void *cb_arg, int reduce_errno)
540 {
541 	struct reduce_init_load_ctx *init_ctx = cb_arg;
542 	struct spdk_reduce_vol *vol = init_ctx->vol;
543 	struct spdk_reduce_backing_io *backing_io = init_ctx->backing_io;
544 
545 	init_ctx->iov[0].iov_base = vol->backing_super;
546 	init_ctx->iov[0].iov_len = sizeof(*vol->backing_super);
547 	init_ctx->backing_cb_args.cb_fn = _init_write_super_cpl;
548 	init_ctx->backing_cb_args.cb_arg = init_ctx;
549 
550 	backing_io->dev = vol->backing_dev;
551 	backing_io->iov = init_ctx->iov;
552 	backing_io->iovcnt = 1;
553 	backing_io->lba = 0;
554 	backing_io->lba_count = sizeof(*vol->backing_super) / vol->backing_dev->blocklen;
555 	backing_io->backing_cb_args = &init_ctx->backing_cb_args;
556 	backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_WRITE;
557 
558 	vol->backing_dev->submit_backing_io(backing_io);
559 }
560 
561 static int
562 _allocate_bit_arrays(struct spdk_reduce_vol *vol)
563 {
564 	uint64_t total_chunks, total_backing_io_units;
565 	uint32_t i, num_metadata_io_units;
566 
567 	total_chunks = _get_total_chunks(vol->params.vol_size, vol->params.chunk_size);
568 	vol->allocated_chunk_maps = spdk_bit_array_create(total_chunks);
569 	vol->find_chunk_offset = 0;
570 	total_backing_io_units = total_chunks * (vol->params.chunk_size / vol->params.backing_io_unit_size);
571 	vol->allocated_backing_io_units = spdk_bit_array_create(total_backing_io_units);
572 	vol->find_block_offset = 0;
573 
574 	if (vol->allocated_chunk_maps == NULL || vol->allocated_backing_io_units == NULL) {
575 		return -ENOMEM;
576 	}
577 
578 	/* Set backing io unit bits associated with metadata. */
579 	num_metadata_io_units = (sizeof(*vol->backing_super) + REDUCE_PATH_MAX) /
580 				vol->params.backing_io_unit_size;
581 	for (i = 0; i < num_metadata_io_units; i++) {
582 		spdk_bit_array_set(vol->allocated_backing_io_units, i);
583 	}
584 
585 	return 0;
586 }
587 
588 static int
589 overlap_cmp(struct spdk_reduce_vol_request *req1, struct spdk_reduce_vol_request *req2)
590 {
591 	return (req1->logical_map_index < req2->logical_map_index ? -1 : req1->logical_map_index >
592 		req2->logical_map_index);
593 }
594 RB_GENERATE_STATIC(executing_req_tree, spdk_reduce_vol_request, rbnode, overlap_cmp);
595 
596 
597 void
598 spdk_reduce_vol_init(struct spdk_reduce_vol_params *params,
599 		     struct spdk_reduce_backing_dev *backing_dev,
600 		     const char *pm_file_dir,
601 		     spdk_reduce_vol_op_with_handle_complete cb_fn, void *cb_arg)
602 {
603 	struct spdk_reduce_vol *vol;
604 	struct reduce_init_load_ctx *init_ctx;
605 	struct spdk_reduce_backing_io *backing_io;
606 	uint64_t backing_dev_size;
607 	size_t mapped_len;
608 	int dir_len, max_dir_len, rc;
609 
610 	/* We need to append a path separator and the UUID to the supplied
611 	 * path.
612 	 */
613 	max_dir_len = REDUCE_PATH_MAX - SPDK_UUID_STRING_LEN - 1;
614 	dir_len = strnlen(pm_file_dir, max_dir_len);
615 	/* Strip trailing slash if the user provided one - we will add it back
616 	 * later when appending the filename.
617 	 */
618 	if (pm_file_dir[dir_len - 1] == '/') {
619 		dir_len--;
620 	}
621 	if (dir_len == max_dir_len) {
622 		SPDK_ERRLOG("pm_file_dir (%s) too long\n", pm_file_dir);
623 		cb_fn(cb_arg, NULL, -EINVAL);
624 		return;
625 	}
626 
627 	rc = _validate_vol_params(params);
628 	if (rc != 0) {
629 		SPDK_ERRLOG("invalid vol params\n");
630 		cb_fn(cb_arg, NULL, rc);
631 		return;
632 	}
633 
634 	backing_dev_size = backing_dev->blockcnt * backing_dev->blocklen;
635 	params->vol_size = _get_vol_size(params->chunk_size, backing_dev_size);
636 	if (params->vol_size == 0) {
637 		SPDK_ERRLOG("backing device is too small\n");
638 		cb_fn(cb_arg, NULL, -EINVAL);
639 		return;
640 	}
641 
642 	if (backing_dev->submit_backing_io == NULL) {
643 		SPDK_ERRLOG("backing_dev function pointer not specified\n");
644 		cb_fn(cb_arg, NULL, -EINVAL);
645 		return;
646 	}
647 
648 	vol = calloc(1, sizeof(*vol));
649 	if (vol == NULL) {
650 		cb_fn(cb_arg, NULL, -ENOMEM);
651 		return;
652 	}
653 
654 	TAILQ_INIT(&vol->free_requests);
655 	RB_INIT(&vol->executing_requests);
656 	TAILQ_INIT(&vol->queued_requests);
657 	queue_init(&vol->free_chunks_queue);
658 	queue_init(&vol->free_backing_blocks_queue);
659 
660 	vol->backing_super = spdk_zmalloc(sizeof(*vol->backing_super), 0, NULL,
661 					  SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
662 	if (vol->backing_super == NULL) {
663 		cb_fn(cb_arg, NULL, -ENOMEM);
664 		_init_load_cleanup(vol, NULL);
665 		return;
666 	}
667 
668 	init_ctx = calloc(1, sizeof(*init_ctx));
669 	if (init_ctx == NULL) {
670 		cb_fn(cb_arg, NULL, -ENOMEM);
671 		_init_load_cleanup(vol, NULL);
672 		return;
673 	}
674 
675 	backing_io = calloc(1, sizeof(*backing_io) + backing_dev->user_ctx_size);
676 	if (backing_io == NULL) {
677 		cb_fn(cb_arg, NULL, -ENOMEM);
678 		_init_load_cleanup(vol, init_ctx);
679 		return;
680 	}
681 	init_ctx->backing_io = backing_io;
682 
683 	init_ctx->path = spdk_zmalloc(REDUCE_PATH_MAX, 0, NULL,
684 				      SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
685 	if (init_ctx->path == NULL) {
686 		cb_fn(cb_arg, NULL, -ENOMEM);
687 		_init_load_cleanup(vol, init_ctx);
688 		return;
689 	}
690 
691 	if (spdk_uuid_is_null(&params->uuid)) {
692 		spdk_uuid_generate(&params->uuid);
693 	}
694 
695 	memcpy(vol->pm_file.path, pm_file_dir, dir_len);
696 	vol->pm_file.path[dir_len] = '/';
697 	spdk_uuid_fmt_lower(&vol->pm_file.path[dir_len + 1], SPDK_UUID_STRING_LEN,
698 			    &params->uuid);
699 	vol->pm_file.size = _get_pm_file_size(params);
700 	vol->pm_file.pm_buf = pmem_map_file(vol->pm_file.path, vol->pm_file.size,
701 					    PMEM_FILE_CREATE | PMEM_FILE_EXCL, 0600,
702 					    &mapped_len, &vol->pm_file.pm_is_pmem);
703 	if (vol->pm_file.pm_buf == NULL) {
704 		SPDK_ERRLOG("could not pmem_map_file(%s): %s\n",
705 			    vol->pm_file.path, strerror(errno));
706 		cb_fn(cb_arg, NULL, -errno);
707 		_init_load_cleanup(vol, init_ctx);
708 		return;
709 	}
710 
711 	if (vol->pm_file.size != mapped_len) {
712 		SPDK_ERRLOG("could not map entire pmem file (size=%" PRIu64 " mapped=%" PRIu64 ")\n",
713 			    vol->pm_file.size, mapped_len);
714 		cb_fn(cb_arg, NULL, -ENOMEM);
715 		_init_load_cleanup(vol, init_ctx);
716 		return;
717 	}
718 
719 	vol->backing_io_units_per_chunk = params->chunk_size / params->backing_io_unit_size;
720 	vol->logical_blocks_per_chunk = params->chunk_size / params->logical_block_size;
721 	vol->backing_lba_per_io_unit = params->backing_io_unit_size / backing_dev->blocklen;
722 	memcpy(&vol->params, params, sizeof(*params));
723 
724 	vol->backing_dev = backing_dev;
725 
726 	rc = _allocate_bit_arrays(vol);
727 	if (rc != 0) {
728 		cb_fn(cb_arg, NULL, rc);
729 		_init_load_cleanup(vol, init_ctx);
730 		return;
731 	}
732 
733 	memcpy(vol->backing_super->signature, SPDK_REDUCE_SIGNATURE,
734 	       sizeof(vol->backing_super->signature));
735 	memcpy(&vol->backing_super->params, params, sizeof(*params));
736 
737 	_initialize_vol_pm_pointers(vol);
738 
739 	memcpy(vol->pm_super, vol->backing_super, sizeof(*vol->backing_super));
740 	/* Writing 0xFF's is equivalent of filling it all with SPDK_EMPTY_MAP_ENTRY.
741 	 * Note that this writes 0xFF to not just the logical map but the chunk maps as well.
742 	 */
743 	memset(vol->pm_logical_map, 0xFF, vol->pm_file.size - sizeof(*vol->backing_super));
744 	_reduce_persist(vol, vol->pm_file.pm_buf, vol->pm_file.size);
745 
746 	init_ctx->vol = vol;
747 	init_ctx->cb_fn = cb_fn;
748 	init_ctx->cb_arg = cb_arg;
749 
750 	memcpy(init_ctx->path, vol->pm_file.path, REDUCE_PATH_MAX);
751 	init_ctx->iov[0].iov_base = init_ctx->path;
752 	init_ctx->iov[0].iov_len = REDUCE_PATH_MAX;
753 	init_ctx->backing_cb_args.cb_fn = _init_write_path_cpl;
754 	init_ctx->backing_cb_args.cb_arg = init_ctx;
755 	/* Write path to offset 4K on backing device - just after where the super
756 	 *  block will be written.  We wait until this is committed before writing the
757 	 *  super block to guarantee we don't get the super block written without the
758 	 *  the path if the system crashed in the middle of a write operation.
759 	 */
760 	backing_io->dev = vol->backing_dev;
761 	backing_io->iov = init_ctx->iov;
762 	backing_io->iovcnt = 1;
763 	backing_io->lba = REDUCE_BACKING_DEV_PATH_OFFSET / vol->backing_dev->blocklen;
764 	backing_io->lba_count = REDUCE_PATH_MAX / vol->backing_dev->blocklen;
765 	backing_io->backing_cb_args = &init_ctx->backing_cb_args;
766 	backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_WRITE;
767 
768 	vol->backing_dev->submit_backing_io(backing_io);
769 }
770 
771 static void destroy_load_cb(void *cb_arg, struct spdk_reduce_vol *vol, int reduce_errno);
772 
773 static void
774 _load_read_super_and_path_cpl(void *cb_arg, int reduce_errno)
775 {
776 	struct reduce_init_load_ctx *load_ctx = cb_arg;
777 	struct spdk_reduce_vol *vol = load_ctx->vol;
778 	uint64_t backing_dev_size;
779 	uint64_t i, num_chunks, logical_map_index;
780 	struct spdk_reduce_chunk_map *chunk;
781 	size_t mapped_len;
782 	uint32_t j;
783 	int rc;
784 
785 	rc = _alloc_zero_buff();
786 	if (rc) {
787 		goto error;
788 	}
789 
790 	if (memcmp(vol->backing_super->signature,
791 		   SPDK_REDUCE_SIGNATURE,
792 		   sizeof(vol->backing_super->signature)) != 0) {
793 		/* This backing device isn't a libreduce backing device. */
794 		rc = -EILSEQ;
795 		goto error;
796 	}
797 
798 	/* If the cb_fn is destroy_load_cb, it means we are wanting to destroy this compress bdev.
799 	 *  So don't bother getting the volume ready to use - invoke the callback immediately
800 	 *  so destroy_load_cb can delete the metadata off of the block device and delete the
801 	 *  persistent memory file if it exists.
802 	 */
803 	memcpy(vol->pm_file.path, load_ctx->path, sizeof(vol->pm_file.path));
804 	if (load_ctx->cb_fn == (*destroy_load_cb)) {
805 		load_ctx->cb_fn(load_ctx->cb_arg, vol, 0);
806 		_init_load_cleanup(NULL, load_ctx);
807 		return;
808 	}
809 
810 	memcpy(&vol->params, &vol->backing_super->params, sizeof(vol->params));
811 	vol->backing_io_units_per_chunk = vol->params.chunk_size / vol->params.backing_io_unit_size;
812 	vol->logical_blocks_per_chunk = vol->params.chunk_size / vol->params.logical_block_size;
813 	vol->backing_lba_per_io_unit = vol->params.backing_io_unit_size / vol->backing_dev->blocklen;
814 
815 	rc = _allocate_bit_arrays(vol);
816 	if (rc != 0) {
817 		goto error;
818 	}
819 
820 	backing_dev_size = vol->backing_dev->blockcnt * vol->backing_dev->blocklen;
821 	if (_get_vol_size(vol->params.chunk_size, backing_dev_size) < vol->params.vol_size) {
822 		SPDK_ERRLOG("backing device size %" PRIi64 " smaller than expected\n",
823 			    backing_dev_size);
824 		rc = -EILSEQ;
825 		goto error;
826 	}
827 
828 	vol->pm_file.size = _get_pm_file_size(&vol->params);
829 	vol->pm_file.pm_buf = pmem_map_file(vol->pm_file.path, 0, 0, 0, &mapped_len,
830 					    &vol->pm_file.pm_is_pmem);
831 	if (vol->pm_file.pm_buf == NULL) {
832 		SPDK_ERRLOG("could not pmem_map_file(%s): %s\n", vol->pm_file.path, strerror(errno));
833 		rc = -errno;
834 		goto error;
835 	}
836 
837 	if (vol->pm_file.size != mapped_len) {
838 		SPDK_ERRLOG("could not map entire pmem file (size=%" PRIu64 " mapped=%" PRIu64 ")\n",
839 			    vol->pm_file.size, mapped_len);
840 		rc = -ENOMEM;
841 		goto error;
842 	}
843 
844 	rc = _allocate_vol_requests(vol);
845 	if (rc != 0) {
846 		goto error;
847 	}
848 
849 	_initialize_vol_pm_pointers(vol);
850 
851 	num_chunks = vol->params.vol_size / vol->params.chunk_size;
852 	for (i = 0; i < num_chunks; i++) {
853 		logical_map_index = vol->pm_logical_map[i];
854 		if (logical_map_index == REDUCE_EMPTY_MAP_ENTRY) {
855 			continue;
856 		}
857 		spdk_bit_array_set(vol->allocated_chunk_maps, logical_map_index);
858 		chunk = _reduce_vol_get_chunk_map(vol, logical_map_index);
859 		for (j = 0; j < vol->backing_io_units_per_chunk; j++) {
860 			if (chunk->io_unit_index[j] != REDUCE_EMPTY_MAP_ENTRY) {
861 				spdk_bit_array_set(vol->allocated_backing_io_units, chunk->io_unit_index[j]);
862 			}
863 		}
864 	}
865 
866 	load_ctx->cb_fn(load_ctx->cb_arg, vol, 0);
867 	/* Only clean up the ctx - the vol has been passed to the application
868 	 *  for use now that volume load was successful.
869 	 */
870 	_init_load_cleanup(NULL, load_ctx);
871 	return;
872 
873 error:
874 	load_ctx->cb_fn(load_ctx->cb_arg, NULL, rc);
875 	_init_load_cleanup(vol, load_ctx);
876 }
877 
878 void
879 spdk_reduce_vol_load(struct spdk_reduce_backing_dev *backing_dev,
880 		     spdk_reduce_vol_op_with_handle_complete cb_fn, void *cb_arg)
881 {
882 	struct spdk_reduce_vol *vol;
883 	struct reduce_init_load_ctx *load_ctx;
884 	struct spdk_reduce_backing_io *backing_io;
885 
886 	if (backing_dev->submit_backing_io == NULL) {
887 		SPDK_ERRLOG("backing_dev function pointer not specified\n");
888 		cb_fn(cb_arg, NULL, -EINVAL);
889 		return;
890 	}
891 
892 	vol = calloc(1, sizeof(*vol));
893 	if (vol == NULL) {
894 		cb_fn(cb_arg, NULL, -ENOMEM);
895 		return;
896 	}
897 
898 	TAILQ_INIT(&vol->free_requests);
899 	RB_INIT(&vol->executing_requests);
900 	TAILQ_INIT(&vol->queued_requests);
901 	queue_init(&vol->free_chunks_queue);
902 	queue_init(&vol->free_backing_blocks_queue);
903 
904 	vol->backing_super = spdk_zmalloc(sizeof(*vol->backing_super), 64, NULL,
905 					  SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
906 	if (vol->backing_super == NULL) {
907 		_init_load_cleanup(vol, NULL);
908 		cb_fn(cb_arg, NULL, -ENOMEM);
909 		return;
910 	}
911 
912 	vol->backing_dev = backing_dev;
913 
914 	load_ctx = calloc(1, sizeof(*load_ctx));
915 	if (load_ctx == NULL) {
916 		_init_load_cleanup(vol, NULL);
917 		cb_fn(cb_arg, NULL, -ENOMEM);
918 		return;
919 	}
920 
921 	backing_io = calloc(1, sizeof(*backing_io) + backing_dev->user_ctx_size);
922 	if (backing_io == NULL) {
923 		_init_load_cleanup(vol, load_ctx);
924 		cb_fn(cb_arg, NULL, -ENOMEM);
925 		return;
926 	}
927 
928 	load_ctx->backing_io = backing_io;
929 
930 	load_ctx->path = spdk_zmalloc(REDUCE_PATH_MAX, 64, NULL,
931 				      SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
932 	if (load_ctx->path == NULL) {
933 		_init_load_cleanup(vol, load_ctx);
934 		cb_fn(cb_arg, NULL, -ENOMEM);
935 		return;
936 	}
937 
938 	load_ctx->vol = vol;
939 	load_ctx->cb_fn = cb_fn;
940 	load_ctx->cb_arg = cb_arg;
941 
942 	load_ctx->iov[0].iov_base = vol->backing_super;
943 	load_ctx->iov[0].iov_len = sizeof(*vol->backing_super);
944 	load_ctx->iov[1].iov_base = load_ctx->path;
945 	load_ctx->iov[1].iov_len = REDUCE_PATH_MAX;
946 	backing_io->dev = vol->backing_dev;
947 	backing_io->iov = load_ctx->iov;
948 	backing_io->iovcnt = LOAD_IOV_COUNT;
949 	backing_io->lba = 0;
950 	backing_io->lba_count = (sizeof(*vol->backing_super) + REDUCE_PATH_MAX) /
951 				vol->backing_dev->blocklen;
952 	backing_io->backing_cb_args = &load_ctx->backing_cb_args;
953 	backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_READ;
954 
955 	load_ctx->backing_cb_args.cb_fn = _load_read_super_and_path_cpl;
956 	load_ctx->backing_cb_args.cb_arg = load_ctx;
957 	vol->backing_dev->submit_backing_io(backing_io);
958 }
959 
960 void
961 spdk_reduce_vol_unload(struct spdk_reduce_vol *vol,
962 		       spdk_reduce_vol_op_complete cb_fn, void *cb_arg)
963 {
964 	if (vol == NULL) {
965 		/* This indicates a programming error. */
966 		assert(false);
967 		cb_fn(cb_arg, -EINVAL);
968 		return;
969 	}
970 
971 	if (--g_vol_count == 0) {
972 		spdk_free(g_zero_buf);
973 	}
974 	assert(g_vol_count >= 0);
975 	_init_load_cleanup(vol, NULL);
976 	cb_fn(cb_arg, 0);
977 }
978 
979 struct reduce_destroy_ctx {
980 	spdk_reduce_vol_op_complete		cb_fn;
981 	void					*cb_arg;
982 	struct spdk_reduce_vol			*vol;
983 	struct spdk_reduce_vol_superblock	*super;
984 	struct iovec				iov;
985 	struct spdk_reduce_vol_cb_args		backing_cb_args;
986 	int					reduce_errno;
987 	char					pm_path[REDUCE_PATH_MAX];
988 	struct spdk_reduce_backing_io           *backing_io;
989 };
990 
991 static void
992 destroy_unload_cpl(void *cb_arg, int reduce_errno)
993 {
994 	struct reduce_destroy_ctx *destroy_ctx = cb_arg;
995 
996 	if (destroy_ctx->reduce_errno == 0) {
997 		if (unlink(destroy_ctx->pm_path)) {
998 			SPDK_ERRLOG("%s could not be unlinked: %s\n",
999 				    destroy_ctx->pm_path, strerror(errno));
1000 		}
1001 	}
1002 
1003 	/* Even if the unload somehow failed, we still pass the destroy_ctx
1004 	 * reduce_errno since that indicates whether or not the volume was
1005 	 * actually destroyed.
1006 	 */
1007 	destroy_ctx->cb_fn(destroy_ctx->cb_arg, destroy_ctx->reduce_errno);
1008 	spdk_free(destroy_ctx->super);
1009 	free(destroy_ctx->backing_io);
1010 	free(destroy_ctx);
1011 }
1012 
1013 static void
1014 _destroy_zero_super_cpl(void *cb_arg, int reduce_errno)
1015 {
1016 	struct reduce_destroy_ctx *destroy_ctx = cb_arg;
1017 	struct spdk_reduce_vol *vol = destroy_ctx->vol;
1018 
1019 	destroy_ctx->reduce_errno = reduce_errno;
1020 	spdk_reduce_vol_unload(vol, destroy_unload_cpl, destroy_ctx);
1021 }
1022 
1023 static void
1024 destroy_load_cb(void *cb_arg, struct spdk_reduce_vol *vol, int reduce_errno)
1025 {
1026 	struct reduce_destroy_ctx *destroy_ctx = cb_arg;
1027 	struct spdk_reduce_backing_io *backing_io = destroy_ctx->backing_io;
1028 
1029 	if (reduce_errno != 0) {
1030 		destroy_ctx->cb_fn(destroy_ctx->cb_arg, reduce_errno);
1031 		spdk_free(destroy_ctx->super);
1032 		free(destroy_ctx);
1033 		return;
1034 	}
1035 
1036 	destroy_ctx->vol = vol;
1037 	memcpy(destroy_ctx->pm_path, vol->pm_file.path, sizeof(destroy_ctx->pm_path));
1038 	destroy_ctx->iov.iov_base = destroy_ctx->super;
1039 	destroy_ctx->iov.iov_len = sizeof(*destroy_ctx->super);
1040 	destroy_ctx->backing_cb_args.cb_fn = _destroy_zero_super_cpl;
1041 	destroy_ctx->backing_cb_args.cb_arg = destroy_ctx;
1042 
1043 	backing_io->dev = vol->backing_dev;
1044 	backing_io->iov = &destroy_ctx->iov;
1045 	backing_io->iovcnt = 1;
1046 	backing_io->lba = 0;
1047 	backing_io->lba_count = sizeof(*destroy_ctx->super) / vol->backing_dev->blocklen;
1048 	backing_io->backing_cb_args = &destroy_ctx->backing_cb_args;
1049 	backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_WRITE;
1050 
1051 	vol->backing_dev->submit_backing_io(backing_io);
1052 }
1053 
1054 void
1055 spdk_reduce_vol_destroy(struct spdk_reduce_backing_dev *backing_dev,
1056 			spdk_reduce_vol_op_complete cb_fn, void *cb_arg)
1057 {
1058 	struct reduce_destroy_ctx *destroy_ctx;
1059 	struct spdk_reduce_backing_io *backing_io;
1060 
1061 	destroy_ctx = calloc(1, sizeof(*destroy_ctx));
1062 	if (destroy_ctx == NULL) {
1063 		cb_fn(cb_arg, -ENOMEM);
1064 		return;
1065 	}
1066 
1067 	backing_io = calloc(1, sizeof(*backing_io) + backing_dev->user_ctx_size);
1068 	if (backing_io == NULL) {
1069 		free(destroy_ctx);
1070 		cb_fn(cb_arg, -ENOMEM);
1071 		return;
1072 	}
1073 
1074 	destroy_ctx->backing_io = backing_io;
1075 
1076 	destroy_ctx->super = spdk_zmalloc(sizeof(*destroy_ctx->super), 64, NULL,
1077 					  SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1078 	if (destroy_ctx->super == NULL) {
1079 		free(destroy_ctx);
1080 		free(backing_io);
1081 		cb_fn(cb_arg, -ENOMEM);
1082 		return;
1083 	}
1084 	destroy_ctx->cb_fn = cb_fn;
1085 	destroy_ctx->cb_arg = cb_arg;
1086 	spdk_reduce_vol_load(backing_dev, destroy_load_cb, destroy_ctx);
1087 }
1088 
1089 static bool
1090 _request_spans_chunk_boundary(struct spdk_reduce_vol *vol, uint64_t offset, uint64_t length)
1091 {
1092 	uint64_t start_chunk, end_chunk;
1093 
1094 	start_chunk = offset / vol->logical_blocks_per_chunk;
1095 	end_chunk = (offset + length - 1) / vol->logical_blocks_per_chunk;
1096 
1097 	return (start_chunk != end_chunk);
1098 }
1099 
1100 typedef void (*reduce_request_fn)(void *_req, int reduce_errno);
1101 
1102 static void
1103 _reduce_vol_complete_req(struct spdk_reduce_vol_request *req, int reduce_errno)
1104 {
1105 	struct spdk_reduce_vol_request *next_req;
1106 	struct spdk_reduce_vol *vol = req->vol;
1107 
1108 	req->cb_fn(req->cb_arg, reduce_errno);
1109 	RB_REMOVE(executing_req_tree, &vol->executing_requests, req);
1110 
1111 	TAILQ_FOREACH(next_req, &vol->queued_requests, tailq) {
1112 		if (next_req->logical_map_index == req->logical_map_index) {
1113 			TAILQ_REMOVE(&vol->queued_requests, next_req, tailq);
1114 			if (next_req->type == REDUCE_IO_READV) {
1115 				_start_readv_request(next_req);
1116 			} else {
1117 				assert(next_req->type == REDUCE_IO_WRITEV);
1118 				_start_writev_request(next_req);
1119 			}
1120 			break;
1121 		}
1122 	}
1123 
1124 	TAILQ_INSERT_HEAD(&vol->free_requests, req, tailq);
1125 }
1126 
1127 static void
1128 _reduce_vol_reset_chunk(struct spdk_reduce_vol *vol, uint64_t chunk_map_index)
1129 {
1130 	struct spdk_reduce_chunk_map *chunk;
1131 	uint64_t index;
1132 	bool success;
1133 	uint32_t i;
1134 
1135 	chunk = _reduce_vol_get_chunk_map(vol, chunk_map_index);
1136 	for (i = 0; i < vol->backing_io_units_per_chunk; i++) {
1137 		index = chunk->io_unit_index[i];
1138 		if (index == REDUCE_EMPTY_MAP_ENTRY) {
1139 			break;
1140 		}
1141 		assert(spdk_bit_array_get(vol->allocated_backing_io_units,
1142 					  index) == true);
1143 		spdk_bit_array_clear(vol->allocated_backing_io_units, index);
1144 		success = queue_enqueue(&vol->free_backing_blocks_queue, index);
1145 		if (!success && index < vol->find_block_offset) {
1146 			vol->find_block_offset = index;
1147 		}
1148 		chunk->io_unit_index[i] = REDUCE_EMPTY_MAP_ENTRY;
1149 	}
1150 	success = queue_enqueue(&vol->free_chunks_queue, chunk_map_index);
1151 	if (!success && chunk_map_index < vol->find_chunk_offset) {
1152 		vol->find_chunk_offset = chunk_map_index;
1153 	}
1154 	spdk_bit_array_clear(vol->allocated_chunk_maps, chunk_map_index);
1155 }
1156 
1157 static void
1158 _write_write_done(void *_req, int reduce_errno)
1159 {
1160 	struct spdk_reduce_vol_request *req = _req;
1161 	struct spdk_reduce_vol *vol = req->vol;
1162 	uint64_t old_chunk_map_index;
1163 
1164 	if (reduce_errno != 0) {
1165 		req->reduce_errno = reduce_errno;
1166 	}
1167 
1168 	assert(req->num_backing_ops > 0);
1169 	if (--req->num_backing_ops > 0) {
1170 		return;
1171 	}
1172 
1173 	if (req->reduce_errno != 0) {
1174 		_reduce_vol_reset_chunk(vol, req->chunk_map_index);
1175 		_reduce_vol_complete_req(req, req->reduce_errno);
1176 		return;
1177 	}
1178 
1179 	old_chunk_map_index = vol->pm_logical_map[req->logical_map_index];
1180 	if (old_chunk_map_index != REDUCE_EMPTY_MAP_ENTRY) {
1181 		_reduce_vol_reset_chunk(vol, old_chunk_map_index);
1182 	}
1183 
1184 	/*
1185 	 * We don't need to persist the clearing of the old chunk map here.  The old chunk map
1186 	 * becomes invalid after we update the logical map, since the old chunk map will no
1187 	 * longer have a reference to it in the logical map.
1188 	 */
1189 
1190 	/* Persist the new chunk map.  This must be persisted before we update the logical map. */
1191 	_reduce_persist(vol, req->chunk,
1192 			_reduce_vol_get_chunk_struct_size(vol->backing_io_units_per_chunk));
1193 
1194 	vol->pm_logical_map[req->logical_map_index] = req->chunk_map_index;
1195 
1196 	_reduce_persist(vol, &vol->pm_logical_map[req->logical_map_index], sizeof(uint64_t));
1197 
1198 	_reduce_vol_complete_req(req, 0);
1199 }
1200 
1201 static struct spdk_reduce_backing_io *
1202 _reduce_vol_req_get_backing_io(struct spdk_reduce_vol_request *req, uint32_t index)
1203 {
1204 	struct spdk_reduce_backing_dev *backing_dev = req->vol->backing_dev;
1205 	struct spdk_reduce_backing_io *backing_io;
1206 
1207 	backing_io = (struct spdk_reduce_backing_io *)((uint8_t *)req->backing_io +
1208 			(sizeof(*backing_io) + backing_dev->user_ctx_size) * index);
1209 
1210 	return backing_io;
1211 
1212 }
1213 
1214 struct reduce_merged_io_desc {
1215 	uint64_t io_unit_index;
1216 	uint32_t num_io_units;
1217 };
1218 
1219 static void
1220 _issue_backing_ops_without_merge(struct spdk_reduce_vol_request *req, struct spdk_reduce_vol *vol,
1221 				 reduce_request_fn next_fn, bool is_write)
1222 {
1223 	struct iovec *iov;
1224 	struct spdk_reduce_backing_io *backing_io;
1225 	uint8_t *buf;
1226 	uint32_t i;
1227 
1228 	if (req->chunk_is_compressed) {
1229 		iov = req->comp_buf_iov;
1230 		buf = req->comp_buf;
1231 	} else {
1232 		iov = req->decomp_buf_iov;
1233 		buf = req->decomp_buf;
1234 	}
1235 
1236 	req->num_backing_ops = req->num_io_units;
1237 	req->backing_cb_args.cb_fn = next_fn;
1238 	req->backing_cb_args.cb_arg = req;
1239 	for (i = 0; i < req->num_io_units; i++) {
1240 		backing_io = _reduce_vol_req_get_backing_io(req, i);
1241 		iov[i].iov_base = buf + i * vol->params.backing_io_unit_size;
1242 		iov[i].iov_len = vol->params.backing_io_unit_size;
1243 		backing_io->dev  = vol->backing_dev;
1244 		backing_io->iov = &iov[i];
1245 		backing_io->iovcnt = 1;
1246 		backing_io->lba = req->chunk->io_unit_index[i] * vol->backing_lba_per_io_unit;
1247 		backing_io->lba_count = vol->backing_lba_per_io_unit;
1248 		backing_io->backing_cb_args = &req->backing_cb_args;
1249 		if (is_write) {
1250 			backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_WRITE;
1251 		} else {
1252 			backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_READ;
1253 		}
1254 		vol->backing_dev->submit_backing_io(backing_io);
1255 	}
1256 }
1257 
1258 static void
1259 _issue_backing_ops(struct spdk_reduce_vol_request *req, struct spdk_reduce_vol *vol,
1260 		   reduce_request_fn next_fn, bool is_write)
1261 {
1262 	struct iovec *iov;
1263 	struct spdk_reduce_backing_io *backing_io;
1264 	struct reduce_merged_io_desc merged_io_desc[4];
1265 	uint8_t *buf;
1266 	bool merge = false;
1267 	uint32_t num_io = 0;
1268 	uint32_t io_unit_counts = 0;
1269 	uint32_t merged_io_idx = 0;
1270 	uint32_t i;
1271 
1272 	/* The merged_io_desc value is defined here to contain four elements,
1273 	 * and the chunk size must be four times the maximum of the io unit.
1274 	 * if chunk size is too big, don't merge IO.
1275 	 */
1276 	if (vol->backing_io_units_per_chunk > 4) {
1277 		_issue_backing_ops_without_merge(req, vol, next_fn, is_write);
1278 		return;
1279 	}
1280 
1281 	if (req->chunk_is_compressed) {
1282 		iov = req->comp_buf_iov;
1283 		buf = req->comp_buf;
1284 	} else {
1285 		iov = req->decomp_buf_iov;
1286 		buf = req->decomp_buf;
1287 	}
1288 
1289 	for (i = 0; i < req->num_io_units; i++) {
1290 		if (!merge) {
1291 			merged_io_desc[merged_io_idx].io_unit_index = req->chunk->io_unit_index[i];
1292 			merged_io_desc[merged_io_idx].num_io_units = 1;
1293 			num_io++;
1294 		}
1295 
1296 		if (i + 1 == req->num_io_units) {
1297 			break;
1298 		}
1299 
1300 		if (req->chunk->io_unit_index[i] + 1 == req->chunk->io_unit_index[i + 1]) {
1301 			merged_io_desc[merged_io_idx].num_io_units += 1;
1302 			merge = true;
1303 			continue;
1304 		}
1305 		merge = false;
1306 		merged_io_idx++;
1307 	}
1308 
1309 	req->num_backing_ops = num_io;
1310 	req->backing_cb_args.cb_fn = next_fn;
1311 	req->backing_cb_args.cb_arg = req;
1312 	for (i = 0; i < num_io; i++) {
1313 		backing_io = _reduce_vol_req_get_backing_io(req, i);
1314 		iov[i].iov_base = buf + io_unit_counts * vol->params.backing_io_unit_size;
1315 		iov[i].iov_len = vol->params.backing_io_unit_size * merged_io_desc[i].num_io_units;
1316 		backing_io->dev  = vol->backing_dev;
1317 		backing_io->iov = &iov[i];
1318 		backing_io->iovcnt = 1;
1319 		backing_io->lba = merged_io_desc[i].io_unit_index * vol->backing_lba_per_io_unit;
1320 		backing_io->lba_count = vol->backing_lba_per_io_unit * merged_io_desc[i].num_io_units;
1321 		backing_io->backing_cb_args = &req->backing_cb_args;
1322 		if (is_write) {
1323 			backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_WRITE;
1324 		} else {
1325 			backing_io->backing_io_type = SPDK_REDUCE_BACKING_IO_READ;
1326 		}
1327 		vol->backing_dev->submit_backing_io(backing_io);
1328 
1329 		/* Collects the number of processed I/O. */
1330 		io_unit_counts += merged_io_desc[i].num_io_units;
1331 	}
1332 }
1333 
1334 static void
1335 _reduce_vol_write_chunk(struct spdk_reduce_vol_request *req, reduce_request_fn next_fn,
1336 			uint32_t compressed_size)
1337 {
1338 	struct spdk_reduce_vol *vol = req->vol;
1339 	uint32_t i;
1340 	uint64_t chunk_offset, remainder, free_index, total_len = 0;
1341 	uint8_t *buf;
1342 	bool success;
1343 	int j;
1344 
1345 	success = queue_dequeue(&vol->free_chunks_queue, &free_index);
1346 	if (success) {
1347 		req->chunk_map_index = free_index;
1348 	} else {
1349 		req->chunk_map_index = spdk_bit_array_find_first_clear(vol->allocated_chunk_maps,
1350 				       vol->find_chunk_offset);
1351 		vol->find_chunk_offset = req->chunk_map_index + 1;
1352 	}
1353 
1354 	/* TODO: fail if no chunk map found - but really this should not happen if we
1355 	 * size the number of requests similarly to number of extra chunk maps
1356 	 */
1357 	assert(req->chunk_map_index != UINT32_MAX);
1358 	spdk_bit_array_set(vol->allocated_chunk_maps, req->chunk_map_index);
1359 
1360 	req->chunk = _reduce_vol_get_chunk_map(vol, req->chunk_map_index);
1361 	req->num_io_units = spdk_divide_round_up(compressed_size,
1362 			    vol->params.backing_io_unit_size);
1363 	req->chunk_is_compressed = (req->num_io_units != vol->backing_io_units_per_chunk);
1364 	req->chunk->compressed_size =
1365 		req->chunk_is_compressed ? compressed_size : vol->params.chunk_size;
1366 
1367 	/* if the chunk is uncompressed we need to copy the data from the host buffers. */
1368 	if (req->chunk_is_compressed == false) {
1369 		chunk_offset = req->offset % vol->logical_blocks_per_chunk;
1370 		buf = req->decomp_buf;
1371 		total_len = chunk_offset * vol->params.logical_block_size;
1372 
1373 		/* zero any offset into chunk */
1374 		if (req->rmw == false && chunk_offset) {
1375 			memset(buf, 0, total_len);
1376 		}
1377 		buf += total_len;
1378 
1379 		/* copy the data */
1380 		for (j = 0; j < req->iovcnt; j++) {
1381 			memcpy(buf, req->iov[j].iov_base, req->iov[j].iov_len);
1382 			buf += req->iov[j].iov_len;
1383 			total_len += req->iov[j].iov_len;
1384 		}
1385 
1386 		/* zero any remainder */
1387 		remainder = vol->params.chunk_size - total_len;
1388 		total_len += remainder;
1389 		if (req->rmw == false && remainder) {
1390 			memset(buf, 0, remainder);
1391 		}
1392 		assert(total_len == vol->params.chunk_size);
1393 	}
1394 
1395 	for (i = 0; i < req->num_io_units; i++) {
1396 		success = queue_dequeue(&vol->free_backing_blocks_queue, &free_index);
1397 		if (success) {
1398 			req->chunk->io_unit_index[i] = free_index;
1399 		} else {
1400 			req->chunk->io_unit_index[i] = spdk_bit_array_find_first_clear(vol->allocated_backing_io_units,
1401 						       vol->find_block_offset);
1402 			vol->find_block_offset = req->chunk->io_unit_index[i] + 1;
1403 		}
1404 		/* TODO: fail if no backing block found - but really this should also not
1405 		 * happen (see comment above).
1406 		 */
1407 		assert(req->chunk->io_unit_index[i] != UINT32_MAX);
1408 		spdk_bit_array_set(vol->allocated_backing_io_units, req->chunk->io_unit_index[i]);
1409 	}
1410 
1411 	_issue_backing_ops(req, vol, next_fn, true /* write */);
1412 }
1413 
1414 static void
1415 _write_compress_done(void *_req, int reduce_errno)
1416 {
1417 	struct spdk_reduce_vol_request *req = _req;
1418 
1419 	/* Negative reduce_errno indicates failure for compression operations.
1420 	 * Just write the uncompressed data instead.  Force this to happen
1421 	 * by just passing the full chunk size to _reduce_vol_write_chunk.
1422 	 * When it sees the data couldn't be compressed, it will just write
1423 	 * the uncompressed buffer to disk.
1424 	 */
1425 	if (reduce_errno < 0) {
1426 		req->backing_cb_args.output_size = req->vol->params.chunk_size;
1427 	}
1428 
1429 	_reduce_vol_write_chunk(req, _write_write_done, req->backing_cb_args.output_size);
1430 }
1431 
1432 static void
1433 _reduce_vol_compress_chunk(struct spdk_reduce_vol_request *req, reduce_request_fn next_fn)
1434 {
1435 	struct spdk_reduce_vol *vol = req->vol;
1436 
1437 	req->backing_cb_args.cb_fn = next_fn;
1438 	req->backing_cb_args.cb_arg = req;
1439 	req->comp_buf_iov[0].iov_base = req->comp_buf;
1440 	req->comp_buf_iov[0].iov_len = vol->params.chunk_size;
1441 	vol->backing_dev->compress(vol->backing_dev,
1442 				   req->decomp_iov, req->decomp_iovcnt, req->comp_buf_iov, 1,
1443 				   &req->backing_cb_args);
1444 }
1445 
1446 static void
1447 _reduce_vol_decompress_chunk_scratch(struct spdk_reduce_vol_request *req, reduce_request_fn next_fn)
1448 {
1449 	struct spdk_reduce_vol *vol = req->vol;
1450 
1451 	req->backing_cb_args.cb_fn = next_fn;
1452 	req->backing_cb_args.cb_arg = req;
1453 	req->comp_buf_iov[0].iov_base = req->comp_buf;
1454 	req->comp_buf_iov[0].iov_len = req->chunk->compressed_size;
1455 	req->decomp_buf_iov[0].iov_base = req->decomp_buf;
1456 	req->decomp_buf_iov[0].iov_len = vol->params.chunk_size;
1457 	vol->backing_dev->decompress(vol->backing_dev,
1458 				     req->comp_buf_iov, 1, req->decomp_buf_iov, 1,
1459 				     &req->backing_cb_args);
1460 }
1461 
1462 static void
1463 _reduce_vol_decompress_chunk(struct spdk_reduce_vol_request *req, reduce_request_fn next_fn)
1464 {
1465 	struct spdk_reduce_vol *vol = req->vol;
1466 	uint64_t chunk_offset, remainder = 0;
1467 	uint64_t ttl_len = 0;
1468 	size_t iov_len;
1469 	int i;
1470 
1471 	req->decomp_iovcnt = 0;
1472 	chunk_offset = req->offset % vol->logical_blocks_per_chunk;
1473 
1474 	/* If backing device doesn't support SGL output then we should copy the result of decompression to user's buffer
1475 	 * if at least one of the conditions below is true:
1476 	 * 1. User's buffer is fragmented
1477 	 * 2. Length of the user's buffer is less than the chunk
1478 	 * 3. User's buffer is contig, equals chunk_size but crosses huge page boundary */
1479 	iov_len = req->iov[0].iov_len;
1480 	req->copy_after_decompress = !vol->backing_dev->sgl_out && (req->iovcnt > 1 ||
1481 				     req->iov[0].iov_len < vol->params.chunk_size ||
1482 				     _addr_crosses_huge_page(req->iov[0].iov_base, &iov_len));
1483 	if (req->copy_after_decompress) {
1484 		req->decomp_iov[0].iov_base = req->decomp_buf;
1485 		req->decomp_iov[0].iov_len = vol->params.chunk_size;
1486 		req->decomp_iovcnt = 1;
1487 		goto decompress;
1488 	}
1489 
1490 	if (chunk_offset) {
1491 		/* first iov point to our scratch buffer for any offset into the chunk */
1492 		req->decomp_iov[0].iov_base = req->decomp_buf;
1493 		req->decomp_iov[0].iov_len = chunk_offset * vol->params.logical_block_size;
1494 		ttl_len += req->decomp_iov[0].iov_len;
1495 		req->decomp_iovcnt = 1;
1496 	}
1497 
1498 	/* now the user data iov, direct to the user buffer */
1499 	for (i = 0; i < req->iovcnt; i++) {
1500 		req->decomp_iov[i + req->decomp_iovcnt].iov_base = req->iov[i].iov_base;
1501 		req->decomp_iov[i + req->decomp_iovcnt].iov_len = req->iov[i].iov_len;
1502 		ttl_len += req->decomp_iov[i + req->decomp_iovcnt].iov_len;
1503 	}
1504 	req->decomp_iovcnt += req->iovcnt;
1505 
1506 	/* send the rest of the chunk to our scratch buffer */
1507 	remainder = vol->params.chunk_size - ttl_len;
1508 	if (remainder) {
1509 		req->decomp_iov[req->decomp_iovcnt].iov_base = req->decomp_buf + ttl_len;
1510 		req->decomp_iov[req->decomp_iovcnt].iov_len = remainder;
1511 		ttl_len += req->decomp_iov[req->decomp_iovcnt].iov_len;
1512 		req->decomp_iovcnt++;
1513 	}
1514 	assert(ttl_len == vol->params.chunk_size);
1515 
1516 decompress:
1517 	assert(!req->copy_after_decompress || (req->copy_after_decompress && req->decomp_iovcnt == 1));
1518 	req->backing_cb_args.cb_fn = next_fn;
1519 	req->backing_cb_args.cb_arg = req;
1520 	req->comp_buf_iov[0].iov_base = req->comp_buf;
1521 	req->comp_buf_iov[0].iov_len = req->chunk->compressed_size;
1522 	vol->backing_dev->decompress(vol->backing_dev,
1523 				     req->comp_buf_iov, 1, req->decomp_iov, req->decomp_iovcnt,
1524 				     &req->backing_cb_args);
1525 }
1526 
1527 static inline void
1528 _prepare_compress_chunk_copy_user_buffers(struct spdk_reduce_vol_request *req, bool zero_paddings)
1529 {
1530 	struct spdk_reduce_vol *vol = req->vol;
1531 	char *padding_buffer = zero_paddings ? g_zero_buf : req->decomp_buf;
1532 	uint64_t chunk_offset, ttl_len = 0;
1533 	uint64_t remainder = 0;
1534 	char *copy_offset = NULL;
1535 	uint32_t lbsize = vol->params.logical_block_size;
1536 	int i;
1537 
1538 	req->decomp_iov[0].iov_base = req->decomp_buf;
1539 	req->decomp_iov[0].iov_len = vol->params.chunk_size;
1540 	req->decomp_iovcnt = 1;
1541 	copy_offset = req->decomp_iov[0].iov_base;
1542 	chunk_offset = req->offset % vol->logical_blocks_per_chunk;
1543 
1544 	if (chunk_offset) {
1545 		ttl_len += chunk_offset * lbsize;
1546 		/* copy_offset already points to padding buffer if zero_paddings=false */
1547 		if (zero_paddings) {
1548 			memcpy(copy_offset, padding_buffer, ttl_len);
1549 		}
1550 		copy_offset += ttl_len;
1551 	}
1552 
1553 	/* now the user data iov, direct from the user buffer */
1554 	for (i = 0; i < req->iovcnt; i++) {
1555 		memcpy(copy_offset, req->iov[i].iov_base, req->iov[i].iov_len);
1556 		copy_offset += req->iov[i].iov_len;
1557 		ttl_len += req->iov[i].iov_len;
1558 	}
1559 
1560 	remainder = vol->params.chunk_size - ttl_len;
1561 	if (remainder) {
1562 		/* copy_offset already points to padding buffer if zero_paddings=false */
1563 		if (zero_paddings) {
1564 			memcpy(copy_offset, padding_buffer + ttl_len, remainder);
1565 		}
1566 		ttl_len += remainder;
1567 	}
1568 
1569 	assert(ttl_len == req->vol->params.chunk_size);
1570 }
1571 
1572 /* This function can be called when we are compressing a new data or in case of read-modify-write
1573  * In the first case possible paddings should be filled with zeroes, in the second case the paddings
1574  * should point to already read and decompressed buffer */
1575 static inline void
1576 _prepare_compress_chunk(struct spdk_reduce_vol_request *req, bool zero_paddings)
1577 {
1578 	struct spdk_reduce_vol *vol = req->vol;
1579 	char *padding_buffer = zero_paddings ? g_zero_buf : req->decomp_buf;
1580 	uint64_t chunk_offset, ttl_len = 0;
1581 	uint64_t remainder = 0;
1582 	uint32_t lbsize = vol->params.logical_block_size;
1583 	size_t iov_len;
1584 	int i;
1585 
1586 	/* If backing device doesn't support SGL input then we should copy user's buffer into decomp_buf
1587 	 * if at least one of the conditions below is true:
1588 	 * 1. User's buffer is fragmented
1589 	 * 2. Length of the user's buffer is less than the chunk
1590 	 * 3. User's buffer is contig, equals chunk_size but crosses huge page boundary */
1591 	iov_len = req->iov[0].iov_len;
1592 	if (!vol->backing_dev->sgl_in && (req->iovcnt > 1 ||
1593 					  req->iov[0].iov_len < vol->params.chunk_size ||
1594 					  _addr_crosses_huge_page(req->iov[0].iov_base, &iov_len))) {
1595 		_prepare_compress_chunk_copy_user_buffers(req, zero_paddings);
1596 		return;
1597 	}
1598 
1599 	req->decomp_iovcnt = 0;
1600 	chunk_offset = req->offset % vol->logical_blocks_per_chunk;
1601 
1602 	if (chunk_offset != 0) {
1603 		ttl_len += chunk_offset * lbsize;
1604 		req->decomp_iov[0].iov_base = padding_buffer;
1605 		req->decomp_iov[0].iov_len = ttl_len;
1606 		req->decomp_iovcnt = 1;
1607 	}
1608 
1609 	/* now the user data iov, direct from the user buffer */
1610 	for (i = 0; i < req->iovcnt; i++) {
1611 		req->decomp_iov[i + req->decomp_iovcnt].iov_base = req->iov[i].iov_base;
1612 		req->decomp_iov[i + req->decomp_iovcnt].iov_len = req->iov[i].iov_len;
1613 		ttl_len += req->iov[i].iov_len;
1614 	}
1615 	req->decomp_iovcnt += req->iovcnt;
1616 
1617 	remainder = vol->params.chunk_size - ttl_len;
1618 	if (remainder) {
1619 		req->decomp_iov[req->decomp_iovcnt].iov_base = padding_buffer + ttl_len;
1620 		req->decomp_iov[req->decomp_iovcnt].iov_len = remainder;
1621 		req->decomp_iovcnt++;
1622 		ttl_len += remainder;
1623 	}
1624 	assert(ttl_len == req->vol->params.chunk_size);
1625 }
1626 
1627 static void
1628 _write_decompress_done(void *_req, int reduce_errno)
1629 {
1630 	struct spdk_reduce_vol_request *req = _req;
1631 
1632 	/* Negative reduce_errno indicates failure for compression operations. */
1633 	if (reduce_errno < 0) {
1634 		_reduce_vol_complete_req(req, reduce_errno);
1635 		return;
1636 	}
1637 
1638 	/* Positive reduce_errno indicates that the output size field in the backing_cb_args
1639 	 * represents the output_size.
1640 	 */
1641 	if (req->backing_cb_args.output_size != req->vol->params.chunk_size) {
1642 		_reduce_vol_complete_req(req, -EIO);
1643 		return;
1644 	}
1645 
1646 	_prepare_compress_chunk(req, false);
1647 	_reduce_vol_compress_chunk(req, _write_compress_done);
1648 }
1649 
1650 static void
1651 _write_read_done(void *_req, int reduce_errno)
1652 {
1653 	struct spdk_reduce_vol_request *req = _req;
1654 
1655 	if (reduce_errno != 0) {
1656 		req->reduce_errno = reduce_errno;
1657 	}
1658 
1659 	assert(req->num_backing_ops > 0);
1660 	if (--req->num_backing_ops > 0) {
1661 		return;
1662 	}
1663 
1664 	if (req->reduce_errno != 0) {
1665 		_reduce_vol_complete_req(req, req->reduce_errno);
1666 		return;
1667 	}
1668 
1669 	if (req->chunk_is_compressed) {
1670 		_reduce_vol_decompress_chunk_scratch(req, _write_decompress_done);
1671 	} else {
1672 		req->backing_cb_args.output_size = req->chunk->compressed_size;
1673 
1674 		_write_decompress_done(req, 0);
1675 	}
1676 }
1677 
1678 static void
1679 _read_decompress_done(void *_req, int reduce_errno)
1680 {
1681 	struct spdk_reduce_vol_request *req = _req;
1682 	struct spdk_reduce_vol *vol = req->vol;
1683 
1684 	/* Negative reduce_errno indicates failure for compression operations. */
1685 	if (reduce_errno < 0) {
1686 		_reduce_vol_complete_req(req, reduce_errno);
1687 		return;
1688 	}
1689 
1690 	/* Positive reduce_errno indicates that the output size field in the backing_cb_args
1691 	 * represents the output_size.
1692 	 */
1693 	if (req->backing_cb_args.output_size != vol->params.chunk_size) {
1694 		_reduce_vol_complete_req(req, -EIO);
1695 		return;
1696 	}
1697 
1698 	if (req->copy_after_decompress) {
1699 		uint64_t chunk_offset = req->offset % vol->logical_blocks_per_chunk;
1700 		char *decomp_buffer = (char *)req->decomp_buf + chunk_offset * vol->params.logical_block_size;
1701 		int i;
1702 
1703 		for (i = 0; i < req->iovcnt; i++) {
1704 			memcpy(req->iov[i].iov_base, decomp_buffer, req->iov[i].iov_len);
1705 			decomp_buffer += req->iov[i].iov_len;
1706 			assert(decomp_buffer <= (char *)req->decomp_buf + vol->params.chunk_size);
1707 		}
1708 	}
1709 
1710 	_reduce_vol_complete_req(req, 0);
1711 }
1712 
1713 static void
1714 _read_read_done(void *_req, int reduce_errno)
1715 {
1716 	struct spdk_reduce_vol_request *req = _req;
1717 	uint64_t chunk_offset;
1718 	uint8_t *buf;
1719 	int i;
1720 
1721 	if (reduce_errno != 0) {
1722 		req->reduce_errno = reduce_errno;
1723 	}
1724 
1725 	assert(req->num_backing_ops > 0);
1726 	if (--req->num_backing_ops > 0) {
1727 		return;
1728 	}
1729 
1730 	if (req->reduce_errno != 0) {
1731 		_reduce_vol_complete_req(req, req->reduce_errno);
1732 		return;
1733 	}
1734 
1735 	if (req->chunk_is_compressed) {
1736 		_reduce_vol_decompress_chunk(req, _read_decompress_done);
1737 	} else {
1738 
1739 		/* If the chunk was compressed, the data would have been sent to the
1740 		 *  host buffers by the decompression operation, if not we need to memcpy here.
1741 		 */
1742 		chunk_offset = req->offset % req->vol->logical_blocks_per_chunk;
1743 		buf = req->decomp_buf + chunk_offset * req->vol->params.logical_block_size;
1744 		for (i = 0; i < req->iovcnt; i++) {
1745 			memcpy(req->iov[i].iov_base, buf, req->iov[i].iov_len);
1746 			buf += req->iov[i].iov_len;
1747 		}
1748 
1749 		req->backing_cb_args.output_size = req->chunk->compressed_size;
1750 
1751 		_read_decompress_done(req, 0);
1752 	}
1753 }
1754 
1755 static void
1756 _reduce_vol_read_chunk(struct spdk_reduce_vol_request *req, reduce_request_fn next_fn)
1757 {
1758 	struct spdk_reduce_vol *vol = req->vol;
1759 
1760 	req->chunk_map_index = vol->pm_logical_map[req->logical_map_index];
1761 	assert(req->chunk_map_index != UINT32_MAX);
1762 
1763 	req->chunk = _reduce_vol_get_chunk_map(vol, req->chunk_map_index);
1764 	req->num_io_units = spdk_divide_round_up(req->chunk->compressed_size,
1765 			    vol->params.backing_io_unit_size);
1766 	req->chunk_is_compressed = (req->num_io_units != vol->backing_io_units_per_chunk);
1767 
1768 	_issue_backing_ops(req, vol, next_fn, false /* read */);
1769 }
1770 
1771 static bool
1772 _iov_array_is_valid(struct spdk_reduce_vol *vol, struct iovec *iov, int iovcnt,
1773 		    uint64_t length)
1774 {
1775 	uint64_t size = 0;
1776 	int i;
1777 
1778 	if (iovcnt > REDUCE_MAX_IOVECS) {
1779 		return false;
1780 	}
1781 
1782 	for (i = 0; i < iovcnt; i++) {
1783 		size += iov[i].iov_len;
1784 	}
1785 
1786 	return size == (length * vol->params.logical_block_size);
1787 }
1788 
1789 static bool
1790 _check_overlap(struct spdk_reduce_vol *vol, uint64_t logical_map_index)
1791 {
1792 	struct spdk_reduce_vol_request req;
1793 
1794 	req.logical_map_index = logical_map_index;
1795 
1796 	return (NULL != RB_FIND(executing_req_tree, &vol->executing_requests, &req));
1797 }
1798 
1799 static void
1800 _start_readv_request(struct spdk_reduce_vol_request *req)
1801 {
1802 	RB_INSERT(executing_req_tree, &req->vol->executing_requests, req);
1803 	_reduce_vol_read_chunk(req, _read_read_done);
1804 }
1805 
1806 void
1807 spdk_reduce_vol_readv(struct spdk_reduce_vol *vol,
1808 		      struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
1809 		      spdk_reduce_vol_op_complete cb_fn, void *cb_arg)
1810 {
1811 	struct spdk_reduce_vol_request *req;
1812 	uint64_t logical_map_index;
1813 	bool overlapped;
1814 	int i;
1815 
1816 	if (length == 0) {
1817 		cb_fn(cb_arg, 0);
1818 		return;
1819 	}
1820 
1821 	if (_request_spans_chunk_boundary(vol, offset, length)) {
1822 		cb_fn(cb_arg, -EINVAL);
1823 		return;
1824 	}
1825 
1826 	if (!_iov_array_is_valid(vol, iov, iovcnt, length)) {
1827 		cb_fn(cb_arg, -EINVAL);
1828 		return;
1829 	}
1830 
1831 	logical_map_index = offset / vol->logical_blocks_per_chunk;
1832 	overlapped = _check_overlap(vol, logical_map_index);
1833 
1834 	if (!overlapped && vol->pm_logical_map[logical_map_index] == REDUCE_EMPTY_MAP_ENTRY) {
1835 		/*
1836 		 * This chunk hasn't been allocated.  So treat the data as all
1837 		 * zeroes for this chunk - do the memset and immediately complete
1838 		 * the operation.
1839 		 */
1840 		for (i = 0; i < iovcnt; i++) {
1841 			memset(iov[i].iov_base, 0, iov[i].iov_len);
1842 		}
1843 		cb_fn(cb_arg, 0);
1844 		return;
1845 	}
1846 
1847 	req = TAILQ_FIRST(&vol->free_requests);
1848 	if (req == NULL) {
1849 		cb_fn(cb_arg, -ENOMEM);
1850 		return;
1851 	}
1852 
1853 	TAILQ_REMOVE(&vol->free_requests, req, tailq);
1854 	req->type = REDUCE_IO_READV;
1855 	req->vol = vol;
1856 	req->iov = iov;
1857 	req->iovcnt = iovcnt;
1858 	req->offset = offset;
1859 	req->logical_map_index = logical_map_index;
1860 	req->length = length;
1861 	req->copy_after_decompress = false;
1862 	req->cb_fn = cb_fn;
1863 	req->cb_arg = cb_arg;
1864 
1865 	if (!overlapped) {
1866 		_start_readv_request(req);
1867 	} else {
1868 		TAILQ_INSERT_TAIL(&vol->queued_requests, req, tailq);
1869 	}
1870 }
1871 
1872 static void
1873 _start_writev_request(struct spdk_reduce_vol_request *req)
1874 {
1875 	struct spdk_reduce_vol *vol = req->vol;
1876 
1877 	RB_INSERT(executing_req_tree, &req->vol->executing_requests, req);
1878 	if (vol->pm_logical_map[req->logical_map_index] != REDUCE_EMPTY_MAP_ENTRY) {
1879 		if ((req->length * vol->params.logical_block_size) < vol->params.chunk_size) {
1880 			/* Read old chunk, then overwrite with data from this write
1881 			 *  operation.
1882 			 */
1883 			req->rmw = true;
1884 			_reduce_vol_read_chunk(req, _write_read_done);
1885 			return;
1886 		}
1887 	}
1888 
1889 	req->rmw = false;
1890 
1891 	_prepare_compress_chunk(req, true);
1892 	_reduce_vol_compress_chunk(req, _write_compress_done);
1893 }
1894 
1895 void
1896 spdk_reduce_vol_writev(struct spdk_reduce_vol *vol,
1897 		       struct iovec *iov, int iovcnt, uint64_t offset, uint64_t length,
1898 		       spdk_reduce_vol_op_complete cb_fn, void *cb_arg)
1899 {
1900 	struct spdk_reduce_vol_request *req;
1901 	uint64_t logical_map_index;
1902 	bool overlapped;
1903 
1904 	if (length == 0) {
1905 		cb_fn(cb_arg, 0);
1906 		return;
1907 	}
1908 
1909 	if (_request_spans_chunk_boundary(vol, offset, length)) {
1910 		cb_fn(cb_arg, -EINVAL);
1911 		return;
1912 	}
1913 
1914 	if (!_iov_array_is_valid(vol, iov, iovcnt, length)) {
1915 		cb_fn(cb_arg, -EINVAL);
1916 		return;
1917 	}
1918 
1919 	logical_map_index = offset / vol->logical_blocks_per_chunk;
1920 	overlapped = _check_overlap(vol, logical_map_index);
1921 
1922 	req = TAILQ_FIRST(&vol->free_requests);
1923 	if (req == NULL) {
1924 		cb_fn(cb_arg, -ENOMEM);
1925 		return;
1926 	}
1927 
1928 	TAILQ_REMOVE(&vol->free_requests, req, tailq);
1929 	req->type = REDUCE_IO_WRITEV;
1930 	req->vol = vol;
1931 	req->iov = iov;
1932 	req->iovcnt = iovcnt;
1933 	req->offset = offset;
1934 	req->logical_map_index = logical_map_index;
1935 	req->length = length;
1936 	req->copy_after_decompress = false;
1937 	req->cb_fn = cb_fn;
1938 	req->cb_arg = cb_arg;
1939 
1940 	if (!overlapped) {
1941 		_start_writev_request(req);
1942 	} else {
1943 		TAILQ_INSERT_TAIL(&vol->queued_requests, req, tailq);
1944 	}
1945 }
1946 
1947 const struct spdk_reduce_vol_params *
1948 spdk_reduce_vol_get_params(struct spdk_reduce_vol *vol)
1949 {
1950 	return &vol->params;
1951 }
1952 
1953 const char *
1954 spdk_reduce_vol_get_pm_path(const struct spdk_reduce_vol *vol)
1955 {
1956 	return vol->pm_file.path;
1957 }
1958 
1959 void
1960 spdk_reduce_vol_print_info(struct spdk_reduce_vol *vol)
1961 {
1962 	uint64_t logical_map_size, num_chunks, ttl_chunk_sz;
1963 	uint32_t struct_size;
1964 	uint64_t chunk_map_size;
1965 
1966 	SPDK_NOTICELOG("vol info:\n");
1967 	SPDK_NOTICELOG("\tvol->params.backing_io_unit_size = 0x%x\n", vol->params.backing_io_unit_size);
1968 	SPDK_NOTICELOG("\tvol->params.logical_block_size = 0x%x\n", vol->params.logical_block_size);
1969 	SPDK_NOTICELOG("\tvol->params.chunk_size = 0x%x\n", vol->params.chunk_size);
1970 	SPDK_NOTICELOG("\tvol->params.vol_size = 0x%" PRIx64 "\n", vol->params.vol_size);
1971 	num_chunks = _get_total_chunks(vol->params.vol_size, vol->params.chunk_size);
1972 	SPDK_NOTICELOG("\ttotal chunks (including extra) = 0x%" PRIx64 "\n", num_chunks);
1973 	SPDK_NOTICELOG("\ttotal chunks (excluding extra) = 0x%" PRIx64 "\n",
1974 		       vol->params.vol_size / vol->params.chunk_size);
1975 	ttl_chunk_sz = _get_pm_total_chunks_size(vol->params.vol_size, vol->params.chunk_size,
1976 			vol->params.backing_io_unit_size);
1977 	SPDK_NOTICELOG("\ttotal_chunks_size = 0x%" PRIx64 "\n", ttl_chunk_sz);
1978 	struct_size = _reduce_vol_get_chunk_struct_size(vol->backing_io_units_per_chunk);
1979 	SPDK_NOTICELOG("\tchunk_struct_size = 0x%x\n", struct_size);
1980 
1981 	SPDK_NOTICELOG("pmem info:\n");
1982 	SPDK_NOTICELOG("\tvol->pm_file.size = 0x%" PRIx64 "\n", vol->pm_file.size);
1983 	SPDK_NOTICELOG("\tvol->pm_file.pm_buf = %p\n", (void *)vol->pm_file.pm_buf);
1984 	SPDK_NOTICELOG("\tvol->pm_super = %p\n", (void *)vol->pm_super);
1985 	SPDK_NOTICELOG("\tvol->pm_logical_map = %p\n", (void *)vol->pm_logical_map);
1986 	logical_map_size = _get_pm_logical_map_size(vol->params.vol_size,
1987 			   vol->params.chunk_size);
1988 	SPDK_NOTICELOG("\tlogical_map_size = 0x%" PRIx64 "\n", logical_map_size);
1989 	SPDK_NOTICELOG("\tvol->pm_chunk_maps = %p\n", (void *)vol->pm_chunk_maps);
1990 	chunk_map_size = _get_pm_total_chunks_size(vol->params.vol_size, vol->params.chunk_size,
1991 			 vol->params.backing_io_unit_size);
1992 	SPDK_NOTICELOG("\tchunk_map_size = 0x%" PRIx64 "\n", chunk_map_size);
1993 }
1994 
1995 SPDK_LOG_REGISTER_COMPONENT(reduce)
1996