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