xref: /linux/tools/testing/selftests/ublk/kublk.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 /* SPDX-License-Identifier: MIT */
2 /*
3  * Description: uring_cmd based ublk
4  */
5 
6 #include <linux/fs.h>
7 #include <sys/un.h>
8 #include "kublk.h"
9 
10 #define MAX_NR_TGT_ARG 	64
11 #define KUBLK_PARAM_LOGICAL_BS_SHIFT		9
12 #define KUBLK_PARAM_PHYSICAL_BS_SHIFT		12
13 #define KUBLK_PARAM_ZONE_SECTORS		128
14 #define KUBLK_PARAM_NR_ZONES			16
15 #define KUBLK_PARAM_DEV_SECTORS			\
16 	(KUBLK_PARAM_ZONE_SECTORS * KUBLK_PARAM_NR_ZONES)
17 #define KUBLK_PARAM_ZONE_APPEND_SECTORS		8
18 
19 unsigned int ublk_dbg_mask = UBLK_LOG;
20 static const struct ublk_tgt_ops *tgt_ops_list[] = {
21 	&null_tgt_ops,
22 	&loop_tgt_ops,
23 	&stripe_tgt_ops,
24 	&fault_inject_tgt_ops,
25 };
26 
27 static const struct ublk_tgt_ops *ublk_find_tgt(const char *name)
28 {
29 	int i;
30 
31 	if (name == NULL)
32 		return NULL;
33 
34 	for (i = 0; i < ARRAY_SIZE(tgt_ops_list); i++)
35 		if (strcmp(tgt_ops_list[i]->name, name) == 0)
36 			return tgt_ops_list[i];
37 	return NULL;
38 }
39 
40 static int parse_param_types(const char *arg, __u32 *types)
41 {
42 	char buf[128], *save = NULL, *tok;
43 
44 	if (strlen(arg) >= sizeof(buf))
45 		return -EINVAL;
46 
47 	strcpy(buf, arg);
48 	*types = 0;
49 	tok = strtok_r(buf, ",", &save);
50 	while (tok) {
51 		if (!strcmp(tok, "none"))
52 			;
53 		else if (!strcmp(tok, "basic"))
54 			*types |= UBLK_PARAM_TYPE_BASIC;
55 		else if (!strcmp(tok, "zoned"))
56 			*types |= UBLK_PARAM_TYPE_ZONED;
57 		else
58 			return -EINVAL;
59 		tok = strtok_r(NULL, ",", &save);
60 	}
61 
62 	return 0;
63 }
64 
65 static void ublk_init_params_from_ctx(const struct dev_ctx *ctx,
66 				      struct ublk_params *params)
67 {
68 	const struct params_ctx *p = &ctx->params;
69 
70 	*params = (struct ublk_params) {
71 		.types = p->types,
72 		.basic = {
73 			.logical_bs_shift	= p->logical_bs_shift,
74 			.physical_bs_shift	= p->physical_bs_shift,
75 			.io_min_shift		= p->io_min_shift,
76 			.io_opt_shift		= p->io_opt_shift,
77 			.max_sectors		= p->max_sectors,
78 			.chunk_sectors		= p->chunk_sectors,
79 			.dev_sectors		= p->dev_sectors,
80 		},
81 		.zoned = {
82 			.max_open_zones		= p->max_open_zones,
83 			.max_active_zones	= p->max_active_zones,
84 			.max_zone_append_sectors = p->max_zone_append_sectors,
85 		},
86 	};
87 }
88 
89 static const char *ublk_dev_state_desc(struct ublk_dev *dev)
90 {
91 	switch (dev->dev_info.state) {
92 	case UBLK_S_DEV_DEAD:
93 		return "DEAD";
94 	case UBLK_S_DEV_LIVE:
95 		return "LIVE";
96 	case UBLK_S_DEV_QUIESCED:
97 		return "QUIESCED";
98 	default:
99 		return "UNKNOWN";
100 	};
101 }
102 
103 static void ublk_print_cpu_set(const cpu_set_t *set, char *buf, unsigned len)
104 {
105 	unsigned done = 0;
106 	int i;
107 
108 	for (i = 0; i < CPU_SETSIZE; i++) {
109 		if (CPU_ISSET(i, set))
110 			done += snprintf(&buf[done], len - done, "%d ", i);
111 	}
112 }
113 
114 static void ublk_adjust_affinity(cpu_set_t *set)
115 {
116 	int j, updated = 0;
117 
118 	/*
119 	 * Just keep the 1st CPU now.
120 	 *
121 	 * In future, auto affinity selection can be tried.
122 	 */
123 	for (j = 0; j < CPU_SETSIZE; j++) {
124 		if (CPU_ISSET(j, set)) {
125 			if (!updated) {
126 				updated = 1;
127 				continue;
128 			}
129 			CPU_CLR(j, set);
130 		}
131 	}
132 }
133 
134 /* Caller must free the allocated buffer */
135 static int ublk_ctrl_get_affinity(struct ublk_dev *ctrl_dev, cpu_set_t **ptr_buf)
136 {
137 	struct ublk_ctrl_cmd_data data = {
138 		.cmd_op	= UBLK_U_CMD_GET_QUEUE_AFFINITY,
139 		.flags	= CTRL_CMD_HAS_DATA | CTRL_CMD_HAS_BUF,
140 	};
141 	cpu_set_t *buf;
142 	int i, ret;
143 
144 	buf = malloc(sizeof(cpu_set_t) * ctrl_dev->dev_info.nr_hw_queues);
145 	if (!buf)
146 		return -ENOMEM;
147 
148 	for (i = 0; i < ctrl_dev->dev_info.nr_hw_queues; i++) {
149 		data.data[0] = i;
150 		data.len = sizeof(cpu_set_t);
151 		data.addr = (__u64)(uintptr_t)&buf[i];
152 
153 		ret = __ublk_ctrl_cmd(ctrl_dev, &data);
154 		if (ret < 0) {
155 			free(buf);
156 			return ret;
157 		}
158 		ublk_adjust_affinity(&buf[i]);
159 	}
160 
161 	*ptr_buf = buf;
162 	return 0;
163 }
164 
165 static void ublk_ctrl_dump(struct ublk_dev *dev)
166 {
167 	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
168 	struct ublk_params p;
169 	cpu_set_t *affinity;
170 	int ret;
171 
172 	ret = ublk_ctrl_get_params(dev, &p);
173 	if (ret < 0) {
174 		ublk_err("failed to get params %d %s\n", ret, strerror(-ret));
175 		return;
176 	}
177 
178 	ret = ublk_ctrl_get_affinity(dev, &affinity);
179 	if (ret < 0) {
180 		ublk_err("failed to get affinity %m\n");
181 		return;
182 	}
183 
184 	ublk_log("dev id %d: nr_hw_queues %d queue_depth %d block size %d dev_capacity %lld\n",
185 			info->dev_id, info->nr_hw_queues, info->queue_depth,
186 			1 << p.basic.logical_bs_shift, p.basic.dev_sectors);
187 	ublk_log("\tmax rq size %d daemon pid %d flags 0x%llx state %s\n",
188 			info->max_io_buf_bytes, info->ublksrv_pid, info->flags,
189 			ublk_dev_state_desc(dev));
190 	if (info->flags & UBLK_F_IO_DESC_SIZE)
191 		ublk_log("\tio_desc_size %u\n", info->io_desc_size);
192 
193 	if (affinity) {
194 		char buf[512];
195 		int i;
196 
197 		for (i = 0; i < info->nr_hw_queues; i++) {
198 			ublk_print_cpu_set(&affinity[i], buf, sizeof(buf));
199 			printf("\tqueue %u: affinity(%s)\n",
200 					i, buf);
201 		}
202 		free(affinity);
203 	}
204 
205 	fflush(stdout);
206 }
207 
208 static size_t __ublk_queue_cmd_buf_sz(const struct ublk_queue *q, __u16 depth)
209 {
210 	size_t size = depth * (size_t)q->io_desc_size;
211 	size_t page_sz = getpagesize();
212 
213 	return round_up(size, page_sz);
214 }
215 
216 static size_t ublk_queue_max_cmd_buf_sz(const struct ublk_queue *q)
217 {
218 	return __ublk_queue_cmd_buf_sz(q, UBLK_MAX_QUEUE_DEPTH);
219 }
220 
221 static size_t ublk_queue_cmd_buf_sz(const struct ublk_queue *q)
222 {
223 	return __ublk_queue_cmd_buf_sz(q, q->q_depth);
224 }
225 
226 static void ublk_queue_deinit(struct ublk_queue *q)
227 {
228 	int i;
229 	int nr_ios = q->q_depth;
230 
231 	if (q->io_cmd_buf)
232 		munmap(q->io_cmd_buf, ublk_queue_cmd_buf_sz(q));
233 
234 	for (i = 0; i < nr_ios; i++) {
235 		free(q->ios[i].buf_addr);
236 		free(q->ios[i].integrity_buf);
237 	}
238 }
239 
240 static void ublk_thread_deinit(struct ublk_thread *t)
241 {
242 	io_uring_unregister_buffers(&t->ring);
243 
244 	ublk_batch_free_buf(t);
245 
246 	io_uring_unregister_ring_fd(&t->ring);
247 
248 	if (t->ring.ring_fd > 0) {
249 		io_uring_unregister_files(&t->ring);
250 		close(t->ring.ring_fd);
251 		t->ring.ring_fd = -1;
252 	}
253 }
254 
255 static int ublk_queue_init(struct ublk_queue *q, unsigned long long extra_flags,
256 			   __u8 metadata_size)
257 {
258 	struct ublk_dev *dev = q->dev;
259 	int depth = dev->dev_info.queue_depth;
260 	int i;
261 	size_t cmd_buf_size, io_buf_size, integrity_size;
262 	unsigned long off;
263 
264 	pthread_spin_init(&q->lock, PTHREAD_PROCESS_PRIVATE);
265 	q->tgt_ops = dev->tgt.ops;
266 	q->flags = 0;
267 	q->q_depth = depth;
268 	q->flags = dev->dev_info.flags;
269 	q->flags |= extra_flags;
270 	q->metadata_size = metadata_size;
271 	q->io_desc_size = dev->dev_info.io_desc_size;
272 
273 	/* Cache fd in queue for fast path access */
274 	q->ublk_fd = dev->fds[0];
275 
276 	cmd_buf_size = ublk_queue_cmd_buf_sz(q);
277 	off = UBLKSRV_CMD_BUF_OFFSET + q->q_id * ublk_queue_max_cmd_buf_sz(q);
278 	q->io_cmd_buf = mmap(0, cmd_buf_size, PROT_READ,
279 			MAP_SHARED | MAP_POPULATE, dev->fds[0], off);
280 	if (q->io_cmd_buf == MAP_FAILED) {
281 		ublk_err("ublk dev %d queue %d map io_cmd_buf failed %m\n",
282 				q->dev->dev_info.dev_id, q->q_id);
283 		goto fail;
284 	}
285 
286 	io_buf_size = dev->dev_info.max_io_buf_bytes;
287 	integrity_size = ublk_integrity_len(q, io_buf_size);
288 	for (i = 0; i < q->q_depth; i++) {
289 		q->ios[i].buf_addr = NULL;
290 		q->ios[i].flags = UBLKS_IO_NEED_FETCH_RQ | UBLKS_IO_FREE;
291 		q->ios[i].tag = i;
292 
293 		if (integrity_size) {
294 			q->ios[i].integrity_buf = malloc(integrity_size);
295 			if (!q->ios[i].integrity_buf) {
296 				ublk_err("ublk dev %d queue %d io %d malloc(%d) failed: %m\n",
297 					 dev->dev_info.dev_id, q->q_id, i,
298 					 integrity_size);
299 				goto fail;
300 			}
301 		}
302 
303 
304 		if (ublk_queue_no_buf(q))
305 			continue;
306 
307 		if (posix_memalign((void **)&q->ios[i].buf_addr,
308 					getpagesize(), io_buf_size)) {
309 			ublk_err("ublk dev %d queue %d io %d posix_memalign failed %m\n",
310 					dev->dev_info.dev_id, q->q_id, i);
311 			goto fail;
312 		}
313 	}
314 
315 	return 0;
316  fail:
317 	ublk_queue_deinit(q);
318 	ublk_err("ublk dev %d queue %d failed\n",
319 			dev->dev_info.dev_id, q->q_id);
320 	return -ENOMEM;
321 }
322 
323 static int ublk_thread_init(struct ublk_thread *t, unsigned long long extra_flags)
324 {
325 	struct ublk_dev *dev = t->dev;
326 	unsigned long long flags = dev->dev_info.flags | extra_flags;
327 	int ring_depth = dev->tgt.sq_depth, cq_depth = dev->tgt.cq_depth;
328 	int ret;
329 
330 	/* FETCH_IO_CMDS is multishot, so increase cq depth for BATCH_IO */
331 	if (ublk_dev_batch_io(dev))
332 		cq_depth += dev->dev_info.queue_depth * 2;
333 
334 	ret = ublk_setup_ring(&t->ring, ring_depth, cq_depth,
335 			IORING_SETUP_COOP_TASKRUN |
336 			IORING_SETUP_SINGLE_ISSUER |
337 			IORING_SETUP_DEFER_TASKRUN);
338 	if (ret < 0) {
339 		ublk_err("ublk dev %d thread %d setup io_uring failed %d\n",
340 				dev->dev_info.dev_id, t->idx, ret);
341 		goto fail;
342 	}
343 
344 	if (dev->dev_info.flags & (UBLK_F_SUPPORT_ZERO_COPY | UBLK_F_AUTO_BUF_REG)) {
345 		unsigned nr_ios = dev->dev_info.queue_depth * dev->dev_info.nr_hw_queues;
346 		unsigned max_nr_ios_per_thread = nr_ios / dev->nthreads;
347 		max_nr_ios_per_thread += !!(nr_ios % dev->nthreads);
348 
349 		t->auto_buf_stride = max_nr_ios_per_thread;
350 		t->nr_bufs = max_nr_ios_per_thread;
351 		if ((extra_flags & UBLKS_Q_ROTATE_AUTO_BUF) &&
352 		    (dev->dev_info.flags & UBLK_F_AUTO_BUF_REG))
353 			t->nr_bufs *= 2;
354 	} else {
355 		t->nr_bufs = 0;
356 		t->auto_buf_stride = 0;
357 	}
358 
359 	if (ublk_dev_batch_io(dev))
360 		 ublk_batch_prepare(t);
361 
362 	if (t->nr_bufs) {
363 		ret = io_uring_register_buffers_sparse(&t->ring, t->nr_bufs);
364 		if (ret) {
365 			ublk_err("ublk dev %d thread %d register spare buffers failed %d\n",
366 					dev->dev_info.dev_id, t->idx, ret);
367 			goto fail;
368 		}
369 	}
370 
371 	if (ublk_dev_batch_io(dev)) {
372 		ret = ublk_batch_alloc_buf(t);
373 		if (ret) {
374 			ublk_err("ublk dev %d thread %d alloc batch buf failed %d\n",
375 				dev->dev_info.dev_id, t->idx, ret);
376 			goto fail;
377 		}
378 	}
379 
380 	io_uring_register_ring_fd(&t->ring);
381 
382 	if (flags & UBLKS_Q_NO_UBLK_FIXED_FD) {
383 		/* Register only backing files starting from index 1, exclude ublk control device */
384 		if (dev->nr_fds > 1) {
385 			ret = io_uring_register_files(&t->ring, &dev->fds[1], dev->nr_fds - 1);
386 		} else {
387 			/* No backing files to register, skip file registration */
388 			ret = 0;
389 		}
390 	} else {
391 		ret = io_uring_register_files(&t->ring, dev->fds, dev->nr_fds);
392 	}
393 	if (ret) {
394 		ublk_err("ublk dev %d thread %d register files failed %d\n",
395 				t->dev->dev_info.dev_id, t->idx, ret);
396 		goto fail;
397 	}
398 
399 	return 0;
400 fail:
401 	ublk_thread_deinit(t);
402 	ublk_err("ublk dev %d thread %d init failed\n",
403 			dev->dev_info.dev_id, t->idx);
404 	return -ENOMEM;
405 }
406 
407 #define WAIT_USEC 	100000
408 #define MAX_WAIT_USEC 	(3 * 1000000)
409 static int ublk_dev_prep(const struct dev_ctx *ctx, struct ublk_dev *dev)
410 {
411 	int dev_id = dev->dev_info.dev_id;
412 	unsigned int wait_usec = 0;
413 	int ret = 0, fd = -1;
414 	char buf[64];
415 
416 	snprintf(buf, 64, "%s%d", UBLKC_DEV, dev_id);
417 
418 	while (wait_usec < MAX_WAIT_USEC) {
419 		fd = open(buf, O_RDWR);
420 		if (fd >= 0)
421 			break;
422 		usleep(WAIT_USEC);
423 		wait_usec += WAIT_USEC;
424 	}
425 	if (fd < 0) {
426 		ublk_err("can't open %s %s\n", buf, strerror(errno));
427 		return -1;
428 	}
429 
430 	dev->fds[0] = fd;
431 	if (dev->tgt.ops->init_tgt)
432 		ret = dev->tgt.ops->init_tgt(ctx, dev);
433 	if (ret)
434 		close(dev->fds[0]);
435 	return ret;
436 }
437 
438 static void ublk_dev_unprep(struct ublk_dev *dev)
439 {
440 	if (dev->tgt.ops->deinit_tgt)
441 		dev->tgt.ops->deinit_tgt(dev);
442 	close(dev->fds[0]);
443 }
444 
445 static void ublk_set_auto_buf_reg(const struct ublk_thread *t,
446 				  const struct ublk_queue *q,
447 				  struct io_uring_sqe *sqe,
448 				  unsigned short tag)
449 {
450 	struct ublk_auto_buf_reg buf = {};
451 
452 	if (q->tgt_ops->buf_index)
453 		buf.index = q->tgt_ops->buf_index(t, q, tag);
454 	else
455 		buf.index = ublk_io_buf_idx(t, q, tag);
456 
457 	if (ublk_queue_auto_zc_fallback(q))
458 		buf.flags = UBLK_AUTO_BUF_REG_FALLBACK;
459 
460 	sqe->addr = ublk_auto_buf_reg_to_sqe_addr(&buf);
461 }
462 
463 /* Copy in pieces to test the buffer offset logic */
464 #define UBLK_USER_COPY_LEN 2048
465 
466 static void ublk_user_copy(const struct ublk_io *io, __u8 match_ublk_op)
467 {
468 	const struct ublk_queue *q = ublk_io_to_queue(io);
469 	const struct ublksrv_io_desc *iod = ublk_get_iod(q, io->tag);
470 	__u64 off = ublk_user_copy_offset(q->q_id, io->tag);
471 	__u8 ublk_op = ublksrv_get_op(iod);
472 	__u32 len = iod->nr_sectors << 9;
473 	void *addr = io->buf_addr;
474 	ssize_t copied;
475 
476 	if (ublk_op != match_ublk_op)
477 		return;
478 
479 	while (len) {
480 		__u32 copy_len = min(len, UBLK_USER_COPY_LEN);
481 
482 		if (ublk_op == UBLK_IO_OP_WRITE)
483 			copied = pread(q->ublk_fd, addr, copy_len, off);
484 		else if (ublk_op == UBLK_IO_OP_READ)
485 			copied = pwrite(q->ublk_fd, addr, copy_len, off);
486 		else
487 			assert(0);
488 		assert(copied == (ssize_t)copy_len);
489 		addr += copy_len;
490 		off += copy_len;
491 		len -= copy_len;
492 	}
493 
494 	if (!(iod->op_flags & UBLK_IO_F_INTEGRITY))
495 		return;
496 
497 	len = ublk_integrity_len(q, iod->nr_sectors << 9);
498 	off = ublk_user_copy_offset(q->q_id, io->tag);
499 	off |= UBLKSRV_IO_INTEGRITY_FLAG;
500 	if (ublk_op == UBLK_IO_OP_WRITE)
501 		copied = pread(q->ublk_fd, io->integrity_buf, len, off);
502 	else if (ublk_op == UBLK_IO_OP_READ)
503 		copied = pwrite(q->ublk_fd, io->integrity_buf, len, off);
504 	else
505 		assert(0);
506 	assert(copied == (ssize_t)len);
507 }
508 
509 int ublk_queue_io_cmd(struct ublk_thread *t, struct ublk_io *io)
510 {
511 	struct ublk_queue *q = ublk_io_to_queue(io);
512 	struct ublksrv_io_cmd *cmd;
513 	struct io_uring_sqe *sqe[1];
514 	unsigned int cmd_op = 0;
515 	__u64 user_data;
516 
517 	/* only freed io can be issued */
518 	if (!(io->flags & UBLKS_IO_FREE))
519 		return 0;
520 
521 	/*
522 	 * we issue because we need either fetching or committing or
523 	 * getting data
524 	 */
525 	if (!(io->flags &
526 		(UBLKS_IO_NEED_FETCH_RQ | UBLKS_IO_NEED_COMMIT_RQ_COMP | UBLKS_IO_NEED_GET_DATA)))
527 		return 0;
528 
529 	if (io->flags & UBLKS_IO_NEED_GET_DATA)
530 		cmd_op = UBLK_U_IO_NEED_GET_DATA;
531 	else if (io->flags & UBLKS_IO_NEED_COMMIT_RQ_COMP) {
532 		if (ublk_queue_use_user_copy(q))
533 			ublk_user_copy(io, UBLK_IO_OP_READ);
534 
535 		cmd_op = UBLK_U_IO_COMMIT_AND_FETCH_REQ;
536 	} else if (io->flags & UBLKS_IO_NEED_FETCH_RQ)
537 		cmd_op = UBLK_U_IO_FETCH_REQ;
538 
539 	if (io_uring_sq_space_left(&t->ring) < 1)
540 		io_uring_submit(&t->ring);
541 
542 	ublk_io_alloc_sqes(t, sqe, 1);
543 	if (!sqe[0]) {
544 		ublk_err("%s: run out of sqe. thread %u, tag %d\n",
545 				__func__, t->idx, io->tag);
546 		return -1;
547 	}
548 
549 	cmd = (struct ublksrv_io_cmd *)ublk_get_sqe_cmd(sqe[0]);
550 
551 	if (cmd_op == UBLK_U_IO_COMMIT_AND_FETCH_REQ)
552 		cmd->result = io->result;
553 
554 	/* These fields should be written once, never change */
555 	ublk_set_sqe_cmd_op(sqe[0], cmd_op);
556 	sqe[0]->fd	= ublk_get_registered_fd(q, 0);	/* dev->fds[0] */
557 	sqe[0]->opcode	= IORING_OP_URING_CMD;
558 	if (q->flags & UBLKS_Q_NO_UBLK_FIXED_FD)
559 		sqe[0]->flags	= 0;  /* Use raw FD, not fixed file */
560 	else
561 		sqe[0]->flags	= IOSQE_FIXED_FILE;
562 	sqe[0]->rw_flags	= 0;
563 	cmd->tag	= io->tag;
564 	cmd->q_id	= q->q_id;
565 	if (!ublk_queue_no_buf(q) && !ublk_queue_use_user_copy(q))
566 		cmd->addr	= (__u64) (uintptr_t) io->buf_addr;
567 	else
568 		cmd->addr	= 0;
569 
570 	if (ublk_queue_use_auto_zc(q))
571 		ublk_set_auto_buf_reg(t, q, sqe[0], io->tag);
572 
573 	user_data = build_user_data(io->tag, _IOC_NR(cmd_op), 0, q->q_id, 0);
574 	io_uring_sqe_set_data64(sqe[0], user_data);
575 
576 	io->flags = 0;
577 
578 	t->cmd_inflight += 1;
579 
580 	ublk_dbg(UBLK_DBG_IO_CMD, "%s: (thread %u qid %d tag %u cmd_op %u) iof %x stopping %d\n",
581 			__func__, t->idx, q->q_id, io->tag, cmd_op,
582 			io->flags, !!(t->state & UBLKS_T_STOPPING));
583 	return 1;
584 }
585 
586 static void ublk_submit_fetch_commands(struct ublk_thread *t)
587 {
588 	struct ublk_queue *q;
589 	struct ublk_io *io;
590 	int i = 0, j = 0;
591 
592 	if (t->dev->per_io_tasks) {
593 		/*
594 		 * Lexicographically order all the (qid,tag) pairs, with
595 		 * qid taking priority (so (1,0) > (0,1)). Then make
596 		 * this thread the daemon for every Nth entry in this
597 		 * list (N is the number of threads), starting at this
598 		 * thread's index. This ensures that each queue is
599 		 * handled by as many ublk server threads as possible,
600 		 * so that load that is concentrated on one or a few
601 		 * queues can make use of all ublk server threads.
602 		 */
603 		const struct ublksrv_ctrl_dev_info *dinfo = &t->dev->dev_info;
604 		int nr_ios = dinfo->nr_hw_queues * dinfo->queue_depth;
605 		for (i = t->idx; i < nr_ios; i += t->dev->nthreads) {
606 			int q_id = i / dinfo->queue_depth;
607 			int tag = i % dinfo->queue_depth;
608 			q = &t->dev->q[q_id];
609 			io = &q->ios[tag];
610 			io->buf_index = j++;
611 			if (q->tgt_ops->pre_fetch_io)
612 				q->tgt_ops->pre_fetch_io(t, q, tag, false);
613 			ublk_queue_io_cmd(t, io);
614 		}
615 	} else {
616 		/*
617 		 * Service exclusively the queue whose q_id matches our
618 		 * thread index.
619 		 */
620 		struct ublk_queue *q = &t->dev->q[t->idx];
621 		for (i = 0; i < q->q_depth; i++) {
622 			io = &q->ios[i];
623 			io->buf_index = i;
624 			if (q->tgt_ops->pre_fetch_io)
625 				q->tgt_ops->pre_fetch_io(t, q, i, false);
626 			ublk_queue_io_cmd(t, io);
627 		}
628 	}
629 }
630 
631 static int ublk_thread_is_idle(struct ublk_thread *t)
632 {
633 	return !io_uring_sq_ready(&t->ring) && !t->io_inflight;
634 }
635 
636 static int ublk_thread_is_done(struct ublk_thread *t)
637 {
638 	return (t->state & UBLKS_T_STOPPING) && ublk_thread_is_idle(t) && !t->cmd_inflight;
639 }
640 
641 static inline void ublksrv_handle_tgt_cqe(struct ublk_thread *t,
642 					  struct ublk_queue *q,
643 					  struct io_uring_cqe *cqe)
644 {
645 	if (cqe->res < 0 && cqe->res != -EAGAIN)
646 		ublk_err("%s: failed tgt io: res %d qid %u tag %u, cmd_op %u\n",
647 			__func__, cqe->res, q->q_id,
648 			user_data_to_tag(cqe->user_data),
649 			user_data_to_op(cqe->user_data));
650 
651 	if (q->tgt_ops->tgt_io_done)
652 		q->tgt_ops->tgt_io_done(t, q, cqe);
653 }
654 
655 static void ublk_handle_uring_cmd(struct ublk_thread *t,
656 				  struct ublk_queue *q,
657 				  const struct io_uring_cqe *cqe)
658 {
659 	int fetch = (cqe->res != UBLK_IO_RES_ABORT) &&
660 		!(t->state & UBLKS_T_STOPPING);
661 	unsigned tag = user_data_to_tag(cqe->user_data);
662 	struct ublk_io *io = &q->ios[tag];
663 
664 	t->cmd_inflight--;
665 
666 	if (!fetch) {
667 		t->state |= UBLKS_T_STOPPING;
668 		io->flags &= ~UBLKS_IO_NEED_FETCH_RQ;
669 	}
670 
671 	if (cqe->res == UBLK_IO_RES_OK) {
672 		ublk_assert(tag < q->q_depth);
673 
674 		if (ublk_queue_use_user_copy(q))
675 			ublk_user_copy(io, UBLK_IO_OP_WRITE);
676 
677 		if (q->tgt_ops->queue_io)
678 			q->tgt_ops->queue_io(t, q, tag);
679 	} else if (cqe->res == UBLK_IO_RES_NEED_GET_DATA) {
680 		io->flags |= UBLKS_IO_NEED_GET_DATA | UBLKS_IO_FREE;
681 		ublk_queue_io_cmd(t, io);
682 	} else {
683 		/*
684 		 * COMMIT_REQ will be completed immediately since no fetching
685 		 * piggyback is required.
686 		 *
687 		 * Marking IO_FREE only, then this io won't be issued since
688 		 * we only issue io with (UBLKS_IO_FREE | UBLKSRV_NEED_*)
689 		 *
690 		 * */
691 		io->flags = UBLKS_IO_FREE;
692 	}
693 }
694 
695 static void ublk_handle_cqe(struct ublk_thread *t,
696 		struct io_uring_cqe *cqe, void *data)
697 {
698 	struct ublk_dev *dev = t->dev;
699 	unsigned q_id = user_data_to_q_id(cqe->user_data);
700 	unsigned cmd_op = user_data_to_op(cqe->user_data);
701 
702 	if (cqe->res < 0 && cqe->res != -ENODEV && cqe->res != -ENOBUFS)
703 		ublk_err("%s: res %d userdata %llx thread state %x\n", __func__,
704 				cqe->res, cqe->user_data, t->state);
705 
706 	ublk_dbg(UBLK_DBG_IO_CMD, "%s: res %d (thread %d qid %d tag %u cmd_op %x "
707 			"data %lx target %d/%d) stopping %d\n",
708 			__func__, cqe->res, t->idx, q_id,
709 			user_data_to_tag(cqe->user_data),
710 			cmd_op, cqe->user_data, is_target_io(cqe->user_data),
711 			user_data_to_tgt_data(cqe->user_data),
712 			(t->state & UBLKS_T_STOPPING));
713 
714 	/* Don't retrieve io in case of target io */
715 	if (is_target_io(cqe->user_data)) {
716 		ublksrv_handle_tgt_cqe(t, &dev->q[q_id], cqe);
717 		return;
718 	}
719 
720 	if (ublk_thread_batch_io(t))
721 		ublk_batch_compl_cmd(t, cqe);
722 	else
723 		ublk_handle_uring_cmd(t, &dev->q[q_id], cqe);
724 }
725 
726 static int ublk_reap_events_uring(struct ublk_thread *t)
727 {
728 	struct io_uring_cqe *cqe;
729 	unsigned head;
730 	int count = 0;
731 
732 	io_uring_for_each_cqe(&t->ring, head, cqe) {
733 		ublk_handle_cqe(t, cqe, NULL);
734 		count += 1;
735 	}
736 	io_uring_cq_advance(&t->ring, count);
737 
738 	return count;
739 }
740 
741 static int ublk_process_io(struct ublk_thread *t)
742 {
743 	int ret, reapped;
744 
745 	ublk_dbg(UBLK_DBG_THREAD, "dev%d-t%u: to_submit %d inflight cmd %u stopping %d\n",
746 				t->dev->dev_info.dev_id,
747 				t->idx, io_uring_sq_ready(&t->ring),
748 				t->cmd_inflight,
749 				(t->state & UBLKS_T_STOPPING));
750 
751 	if (ublk_thread_is_done(t))
752 		return -ENODEV;
753 
754 	ret = io_uring_submit_and_wait(&t->ring, 1);
755 	if (ublk_thread_batch_io(t)) {
756 		ublk_batch_prep_commit(t);
757 		reapped = ublk_reap_events_uring(t);
758 		ublk_batch_commit_io_cmds(t);
759 	} else {
760 		reapped = ublk_reap_events_uring(t);
761 	}
762 
763 	ublk_dbg(UBLK_DBG_THREAD, "submit result %d, reapped %d stop %d idle %d\n",
764 			ret, reapped, (t->state & UBLKS_T_STOPPING),
765 			(t->state & UBLKS_T_IDLE));
766 
767 	return reapped;
768 }
769 
770 struct ublk_thread_info {
771 	struct ublk_dev 	*dev;
772 	pthread_t		thread;
773 	unsigned		idx;
774 	sem_t 			*ready;
775 	cpu_set_t 		*affinity;
776 	unsigned long long	extra_flags;
777 	unsigned char		(*q_thread_map)[UBLK_MAX_QUEUES];
778 };
779 
780 static void ublk_thread_set_sched_affinity(const struct ublk_thread_info *info)
781 {
782 	if (pthread_setaffinity_np(pthread_self(), sizeof(*info->affinity), info->affinity) < 0)
783 		ublk_err("ublk dev %u thread %u set affinity failed",
784 				info->dev->dev_info.dev_id, info->idx);
785 }
786 
787 static void ublk_batch_setup_queues(struct ublk_thread *t)
788 {
789 	int i;
790 
791 	for (i = 0; i < t->dev->dev_info.nr_hw_queues; i++) {
792 		struct ublk_queue *q = &t->dev->q[i];
793 		int ret;
794 
795 		/*
796 		 * Only prepare io commands in the mapped thread context,
797 		 * otherwise io command buffer index may not work as expected
798 		 */
799 		if (t->q_map[i] == 0)
800 			continue;
801 
802 		if (q->tgt_ops->pre_fetch_io)
803 			q->tgt_ops->pre_fetch_io(t, q, 0, true);
804 
805 		ret = ublk_batch_queue_prep_io_cmds(t, q);
806 		ublk_assert(ret >= 0);
807 	}
808 }
809 
810 static __attribute__((noinline)) int __ublk_io_handler_fn(struct ublk_thread_info *info)
811 {
812 	struct ublk_thread t = {
813 		.dev = info->dev,
814 		.idx = info->idx,
815 	};
816 	int dev_id = info->dev->dev_info.dev_id;
817 	int ret;
818 
819 	/* Copy per-thread queue mapping into thread-local variable */
820 	if (info->q_thread_map)
821 		memcpy(t.q_map, info->q_thread_map[info->idx], sizeof(t.q_map));
822 
823 	ret = ublk_thread_init(&t, info->extra_flags);
824 	if (ret) {
825 		ublk_err("ublk dev %d thread %u init failed\n",
826 				dev_id, t.idx);
827 		return ret;
828 	}
829 	sem_post(info->ready);
830 
831 	ublk_dbg(UBLK_DBG_THREAD, "tid %d: ublk dev %d thread %u started\n",
832 			gettid(), dev_id, t.idx);
833 
834 	if (!ublk_thread_batch_io(&t)) {
835 		/* submit all io commands to ublk driver */
836 		ublk_submit_fetch_commands(&t);
837 	} else {
838 		ublk_batch_setup_queues(&t);
839 		ublk_batch_start_fetch(&t);
840 	}
841 
842 	do {
843 		if (ublk_process_io(&t) < 0)
844 			break;
845 	} while (1);
846 
847 	ublk_dbg(UBLK_DBG_THREAD, "tid %d: ublk dev %d thread %d exiting\n",
848 		 gettid(), dev_id, t.idx);
849 	ublk_thread_deinit(&t);
850 	return 0;
851 }
852 
853 static void *ublk_io_handler_fn(void *data)
854 {
855 	struct ublk_thread_info *info = data;
856 
857 	/*
858 	 * IO perf is sensitive with queue pthread affinity on NUMA machine
859 	 *
860 	 * Set sched_affinity at beginning, so following allocated memory/pages
861 	 * could be CPU/NUMA aware.
862 	 */
863 	if (info->affinity)
864 		ublk_thread_set_sched_affinity(info);
865 
866 	__ublk_io_handler_fn(info);
867 
868 	return NULL;
869 }
870 
871 static void ublk_set_parameters(struct ublk_dev *dev)
872 {
873 	int ret;
874 
875 	ret = ublk_ctrl_set_params(dev, &dev->tgt.params);
876 	if (ret)
877 		ublk_err("dev %d set basic parameter failed %d\n",
878 				dev->dev_info.dev_id, ret);
879 }
880 
881 static int ublk_send_dev_event(const struct dev_ctx *ctx, struct ublk_dev *dev, int dev_id)
882 {
883 	uint64_t id;
884 	int evtfd = ctx->_evtfd;
885 
886 	if (evtfd < 0)
887 		return -EBADF;
888 
889 	if (dev_id >= 0)
890 		id = dev_id + 1;
891 	else
892 		id = ERROR_EVTFD_DEVID;
893 
894 	if (dev && ctx->shadow_dev)
895 		memcpy(&ctx->shadow_dev->q, &dev->q, sizeof(dev->q));
896 
897 	if (write(evtfd, &id, sizeof(id)) != sizeof(id))
898 		return -EINVAL;
899 
900 	close(evtfd);
901 	shmdt(ctx->shadow_dev);
902 
903 	return 0;
904 }
905 
906 
907 /*
908  * Shared memory registration socket listener.
909  *
910  * The parent daemon context listens on a per-device unix socket at
911  * /run/ublk/ublkb<dev_id>.sock for shared memory registration requests
912  * from clients. Clients send a memfd via SCM_RIGHTS; the server
913  * registers it with the kernel, mmaps it, and returns the assigned index.
914  */
915 #define UBLK_SHMEM_SOCK_DIR	"/run/ublk"
916 
917 /* defined in kublk.h, shared with file_backed.c (loop target) */
918 struct ublk_shmem_entry shmem_table[UBLK_BUF_MAX];
919 int shmem_count;
920 
921 static void ublk_shmem_sock_path(int dev_id, char *buf, size_t len)
922 {
923 	snprintf(buf, len, "%s/ublkb%d.sock", UBLK_SHMEM_SOCK_DIR, dev_id);
924 }
925 
926 static int ublk_shmem_sock_create(int dev_id)
927 {
928 	struct sockaddr_un addr = { .sun_family = AF_UNIX };
929 	char path[108];
930 	int fd;
931 
932 	mkdir(UBLK_SHMEM_SOCK_DIR, 0755);
933 	ublk_shmem_sock_path(dev_id, path, sizeof(path));
934 	unlink(path);
935 
936 	fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
937 	if (fd < 0)
938 		return -1;
939 
940 	snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path);
941 	if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
942 		close(fd);
943 		return -1;
944 	}
945 
946 	listen(fd, 4);
947 	ublk_dbg(UBLK_DBG_DEV, "shmem socket created: %s\n", path);
948 	return fd;
949 }
950 
951 static void ublk_shmem_sock_destroy(int dev_id, int sock_fd)
952 {
953 	char path[108];
954 
955 	if (sock_fd >= 0)
956 		close(sock_fd);
957 	ublk_shmem_sock_path(dev_id, path, sizeof(path));
958 	unlink(path);
959 }
960 
961 /* Receive a memfd from a client via SCM_RIGHTS */
962 static int ublk_shmem_recv_fd(int client_fd)
963 {
964 	char buf[1];
965 	struct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) };
966 	union {
967 		char cmsg_buf[CMSG_SPACE(sizeof(int))];
968 		struct cmsghdr align;
969 	} u;
970 	struct msghdr msg = {
971 		.msg_iov = &iov,
972 		.msg_iovlen = 1,
973 		.msg_control = u.cmsg_buf,
974 		.msg_controllen = sizeof(u.cmsg_buf),
975 	};
976 	struct cmsghdr *cmsg;
977 
978 	if (recvmsg(client_fd, &msg, 0) <= 0)
979 		return -1;
980 
981 	cmsg = CMSG_FIRSTHDR(&msg);
982 	if (!cmsg || cmsg->cmsg_level != SOL_SOCKET ||
983 	    cmsg->cmsg_type != SCM_RIGHTS)
984 		return -1;
985 
986 	return *(int *)CMSG_DATA(cmsg);
987 }
988 
989 /* Register a shared memory buffer: store fd, mmap it, return index */
990 static int ublk_shmem_register(int shmem_fd)
991 {
992 	off_t size;
993 	void *base;
994 	int idx;
995 
996 	if (shmem_count >= UBLK_BUF_MAX)
997 		return -1;
998 
999 	size = lseek(shmem_fd, 0, SEEK_END);
1000 	if (size <= 0)
1001 		return -1;
1002 
1003 	base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED,
1004 		    shmem_fd, 0);
1005 	if (base == MAP_FAILED)
1006 		return -1;
1007 
1008 	idx = shmem_count++;
1009 	shmem_table[idx].fd = shmem_fd;
1010 	shmem_table[idx].mmap_base = base;
1011 	shmem_table[idx].size = size;
1012 
1013 	ublk_dbg(UBLK_DBG_DEV, "shmem registered: index=%d fd=%d size=%zu\n",
1014 		 idx, shmem_fd, (size_t)size);
1015 	return idx;
1016 }
1017 
1018 static void ublk_shmem_unregister_all(void)
1019 {
1020 	int i;
1021 
1022 	for (i = 0; i < shmem_count; i++) {
1023 		if (shmem_table[i].mmap_base) {
1024 			munmap(shmem_table[i].mmap_base,
1025 			       shmem_table[i].size);
1026 			close(shmem_table[i].fd);
1027 			shmem_table[i].mmap_base = NULL;
1028 		}
1029 	}
1030 	shmem_count = 0;
1031 }
1032 
1033 /*
1034  * Handle one client connection: receive memfd, mmap it, register
1035  * the VA range with kernel, send back the assigned index.
1036  */
1037 static void ublk_shmem_handle_client(int sock_fd, struct ublk_dev *dev)
1038 {
1039 	int client_fd, memfd, idx, ret;
1040 	int32_t reply;
1041 	off_t size;
1042 	void *base;
1043 
1044 	client_fd = accept(sock_fd, NULL, NULL);
1045 	if (client_fd < 0)
1046 		return;
1047 
1048 	memfd = ublk_shmem_recv_fd(client_fd);
1049 	if (memfd < 0) {
1050 		reply = -1;
1051 		goto out;
1052 	}
1053 
1054 	/* mmap the memfd in server address space */
1055 	size = lseek(memfd, 0, SEEK_END);
1056 	if (size <= 0) {
1057 		reply = -1;
1058 		close(memfd);
1059 		goto out;
1060 	}
1061 	base = mmap(NULL, size, PROT_READ | PROT_WRITE,
1062 		    MAP_SHARED | MAP_POPULATE, memfd, 0);
1063 	if (base == MAP_FAILED) {
1064 		reply = -1;
1065 		close(memfd);
1066 		goto out;
1067 	}
1068 
1069 	/* Register server's VA range with kernel for PFN matching */
1070 	ret = ublk_ctrl_reg_buf(dev, base, size, 0);
1071 	if (ret < 0) {
1072 		ublk_dbg(UBLK_DBG_DEV,
1073 			 "shmem_zc: kernel reg failed %d\n", ret);
1074 		munmap(base, size);
1075 		close(memfd);
1076 		reply = ret;
1077 		goto out;
1078 	}
1079 
1080 	/* Store in table for I/O handling */
1081 	idx = ublk_shmem_register(memfd);
1082 	if (idx >= 0) {
1083 		shmem_table[idx].mmap_base = base;
1084 		shmem_table[idx].size = size;
1085 	}
1086 	reply = idx;
1087 out:
1088 	send(client_fd, &reply, sizeof(reply), 0);
1089 	close(client_fd);
1090 }
1091 
1092 struct shmem_listener_info {
1093 	int dev_id;
1094 	int stop_efd;		/* eventfd to signal listener to stop */
1095 	int sock_fd;		/* listener socket fd (output) */
1096 	struct ublk_dev *dev;
1097 };
1098 
1099 /*
1100  * Socket listener thread: runs in the parent daemon context alongside
1101  * the I/O threads. Accepts shared memory registration requests from
1102  * clients via SCM_RIGHTS. Exits when stop_efd is signaled.
1103  */
1104 static void *ublk_shmem_listener_fn(void *data)
1105 {
1106 	struct shmem_listener_info *info = data;
1107 	struct pollfd pfds[2];
1108 
1109 	info->sock_fd = ublk_shmem_sock_create(info->dev_id);
1110 	if (info->sock_fd < 0)
1111 		return NULL;
1112 
1113 	pfds[0].fd = info->sock_fd;
1114 	pfds[0].events = POLLIN;
1115 	pfds[1].fd = info->stop_efd;
1116 	pfds[1].events = POLLIN;
1117 
1118 	while (1) {
1119 		int ret = poll(pfds, 2, -1);
1120 
1121 		if (ret < 0)
1122 			break;
1123 
1124 		/* Stop signal from parent */
1125 		if (pfds[1].revents & POLLIN)
1126 			break;
1127 
1128 		/* Client connection */
1129 		if (pfds[0].revents & POLLIN)
1130 			ublk_shmem_handle_client(info->sock_fd, info->dev);
1131 	}
1132 
1133 	return NULL;
1134 }
1135 
1136 static int ublk_shmem_htlb_setup(const struct dev_ctx *ctx,
1137 				 struct ublk_dev *dev)
1138 {
1139 	int fd, idx, ret;
1140 	struct stat st;
1141 	void *base;
1142 
1143 	fd = open(ctx->htlb_path, O_RDWR);
1144 	if (fd < 0) {
1145 		ublk_err("htlb: can't open %s\n", ctx->htlb_path);
1146 		return -errno;
1147 	}
1148 
1149 	if (fstat(fd, &st) < 0 || st.st_size <= 0) {
1150 		ublk_err("htlb: invalid file size\n");
1151 		close(fd);
1152 		return -EINVAL;
1153 	}
1154 
1155 	base = mmap(NULL, st.st_size,
1156 		    ctx->rdonly_shmem_buf ? PROT_READ : PROT_READ | PROT_WRITE,
1157 		    MAP_SHARED | MAP_POPULATE, fd, 0);
1158 	if (base == MAP_FAILED) {
1159 		ublk_err("htlb: mmap failed\n");
1160 		close(fd);
1161 		return -ENOMEM;
1162 	}
1163 
1164 	ret = ublk_ctrl_reg_buf(dev, base, st.st_size,
1165 			       ctx->rdonly_shmem_buf ? UBLK_SHMEM_BUF_READ_ONLY : 0);
1166 	if (ret < 0) {
1167 		ublk_err("htlb: reg_buf failed: %d\n", ret);
1168 		munmap(base, st.st_size);
1169 		close(fd);
1170 		return ret;
1171 	}
1172 
1173 	if (shmem_count >= UBLK_BUF_MAX) {
1174 		munmap(base, st.st_size);
1175 		close(fd);
1176 		return -ENOMEM;
1177 	}
1178 
1179 	idx = shmem_count++;
1180 	shmem_table[idx].fd = fd;
1181 	shmem_table[idx].mmap_base = base;
1182 	shmem_table[idx].size = st.st_size;
1183 
1184 	ublk_dbg(UBLK_DBG_DEV, "htlb registered: index=%d size=%zu\n",
1185 		 idx, (size_t)st.st_size);
1186 	return 0;
1187 }
1188 
1189 static int ublk_start_daemon(const struct dev_ctx *ctx, struct ublk_dev *dev)
1190 {
1191 	const struct ublksrv_ctrl_dev_info *dinfo = &dev->dev_info;
1192 	struct shmem_listener_info linfo = {};
1193 	struct ublk_thread_info *tinfo;
1194 	unsigned long long extra_flags = 0;
1195 	cpu_set_t *affinity_buf;
1196 	unsigned char (*q_thread_map)[UBLK_MAX_QUEUES] = NULL;
1197 	uint64_t stop_val = 1;
1198 	pthread_t listener;
1199 	void *thread_ret;
1200 	sem_t ready;
1201 	int ret, i;
1202 
1203 	ublk_dbg(UBLK_DBG_DEV, "%s enter\n", __func__);
1204 
1205 	tinfo = calloc(sizeof(struct ublk_thread_info), dev->nthreads);
1206 	if (!tinfo)
1207 		return -ENOMEM;
1208 
1209 	sem_init(&ready, 0, 0);
1210 	ret = ublk_dev_prep(ctx, dev);
1211 	if (ret)
1212 		return ret;
1213 
1214 	ret = ublk_ctrl_get_affinity(dev, &affinity_buf);
1215 	if (ret)
1216 		return ret;
1217 
1218 	if (ublk_dev_batch_io(dev)) {
1219 		q_thread_map = calloc(dev->nthreads, sizeof(*q_thread_map));
1220 		if (!q_thread_map) {
1221 			ret = -ENOMEM;
1222 			goto fail;
1223 		}
1224 		ublk_batch_setup_map(q_thread_map, dev->nthreads,
1225 				     dinfo->nr_hw_queues);
1226 	}
1227 
1228 	if (ctx->auto_zc_fallback)
1229 		extra_flags = UBLKS_Q_AUTO_BUF_REG_FALLBACK;
1230 	if (ctx->no_ublk_fixed_fd)
1231 		extra_flags |= UBLKS_Q_NO_UBLK_FIXED_FD;
1232 	if (ctx->rotate_auto_buf)
1233 		extra_flags |= UBLKS_Q_ROTATE_AUTO_BUF;
1234 
1235 	for (i = 0; i < dinfo->nr_hw_queues; i++) {
1236 		dev->q[i].dev = dev;
1237 		dev->q[i].q_id = i;
1238 
1239 		ret = ublk_queue_init(&dev->q[i], extra_flags,
1240 				      ctx->metadata_size);
1241 		if (ret) {
1242 			ublk_err("ublk dev %d queue %d init queue failed\n",
1243 				 dinfo->dev_id, i);
1244 			goto fail;
1245 		}
1246 	}
1247 
1248 	for (i = 0; i < dev->nthreads; i++) {
1249 		tinfo[i].dev = dev;
1250 		tinfo[i].idx = i;
1251 		tinfo[i].ready = &ready;
1252 		tinfo[i].extra_flags = extra_flags;
1253 		tinfo[i].q_thread_map = q_thread_map;
1254 
1255 		/*
1256 		 * If threads are not tied 1:1 to queues, setting thread
1257 		 * affinity based on queue affinity makes little sense.
1258 		 * However, thread CPU affinity has significant impact
1259 		 * on performance, so to compare fairly, we'll still set
1260 		 * thread CPU affinity based on queue affinity where
1261 		 * possible.
1262 		 */
1263 		if (dev->nthreads == dinfo->nr_hw_queues)
1264 			tinfo[i].affinity = &affinity_buf[i];
1265 		pthread_create(&tinfo[i].thread, NULL,
1266 				ublk_io_handler_fn,
1267 				&tinfo[i]);
1268 	}
1269 
1270 	for (i = 0; i < dev->nthreads; i++)
1271 		sem_wait(&ready);
1272 	free(affinity_buf);
1273 	free(q_thread_map);
1274 
1275 	/* everything is fine now, start us */
1276 	if (ctx->recovery)
1277 		ret = ublk_ctrl_end_user_recovery(dev, getpid());
1278 	else {
1279 		ublk_set_parameters(dev);
1280 		ret = ublk_ctrl_start_dev(dev, getpid());
1281 	}
1282 	if (ret < 0) {
1283 		ublk_err("%s: ublk_ctrl_start_dev failed: %d\n", __func__, ret);
1284 		/* stop device so that inflight uring_cmd can be cancelled */
1285 		ublk_ctrl_stop_dev(dev);
1286 		goto fail_start;
1287 	}
1288 
1289 	if (ctx->htlb_path) {
1290 		ret = ublk_shmem_htlb_setup(ctx, dev);
1291 		if (ret < 0) {
1292 			ublk_err("htlb setup failed: %d\n", ret);
1293 			ublk_ctrl_stop_dev(dev);
1294 			goto fail_start;
1295 		}
1296 	}
1297 
1298 	ublk_ctrl_get_info(dev);
1299 	if (ctx->fg)
1300 		ublk_ctrl_dump(dev);
1301 	else
1302 		ublk_send_dev_event(ctx, dev, dev->dev_info.dev_id);
1303 fail_start:
1304 	/*
1305 	 * Wait for I/O threads to exit. While waiting, a listener
1306 	 * thread accepts shared memory registration requests from
1307 	 * clients via a per-device unix socket (SCM_RIGHTS fd passing).
1308 	 */
1309 	linfo.dev_id = dinfo->dev_id;
1310 	linfo.dev = dev;
1311 	linfo.stop_efd = eventfd(0, 0);
1312 	if (linfo.stop_efd >= 0)
1313 		pthread_create(&listener, NULL,
1314 			       ublk_shmem_listener_fn, &linfo);
1315 
1316 	for (i = 0; i < (int)dev->nthreads; i++)
1317 		pthread_join(tinfo[i].thread, &thread_ret);
1318 
1319 	/* Signal listener thread to stop and wait for it */
1320 	if (linfo.stop_efd >= 0) {
1321 		(void)!write(linfo.stop_efd, &stop_val, sizeof(stop_val));
1322 		pthread_join(listener, NULL);
1323 		close(linfo.stop_efd);
1324 		ublk_shmem_sock_destroy(dinfo->dev_id, linfo.sock_fd);
1325 	}
1326 	ublk_shmem_unregister_all();
1327 	free(tinfo);
1328  fail:
1329 	for (i = 0; i < dinfo->nr_hw_queues; i++)
1330 		ublk_queue_deinit(&dev->q[i]);
1331 	ublk_dev_unprep(dev);
1332 	ublk_dbg(UBLK_DBG_DEV, "%s exit\n", __func__);
1333 
1334 	return ret;
1335 }
1336 
1337 static int wait_ublk_dev(const char *path, int evt_mask, unsigned timeout)
1338 {
1339 #define EV_SIZE (sizeof(struct inotify_event))
1340 #define EV_BUF_LEN (128 * (EV_SIZE + 16))
1341 	struct pollfd pfd;
1342 	int fd, wd;
1343 	int ret = -EINVAL;
1344 	const char *dev_name = basename(path);
1345 
1346 	fd = inotify_init();
1347 	if (fd < 0) {
1348 		ublk_dbg(UBLK_DBG_DEV, "%s: inotify init failed\n", __func__);
1349 		return fd;
1350 	}
1351 
1352 	wd = inotify_add_watch(fd, "/dev", evt_mask);
1353 	if (wd == -1) {
1354 		ublk_dbg(UBLK_DBG_DEV, "%s: add watch for /dev failed\n", __func__);
1355 		goto fail;
1356 	}
1357 
1358 	pfd.fd = fd;
1359 	pfd.events = POLL_IN;
1360 	while (1) {
1361 		int i = 0;
1362 		char buffer[EV_BUF_LEN];
1363 		ret = poll(&pfd, 1, 1000 * timeout);
1364 
1365 		if (ret == -1) {
1366 			ublk_err("%s: poll inotify failed: %d\n", __func__, ret);
1367 			goto rm_watch;
1368 		} else if (ret == 0) {
1369 			ublk_err("%s: poll inotify timeout\n", __func__);
1370 			ret = -ETIMEDOUT;
1371 			goto rm_watch;
1372 		}
1373 
1374 		ret = read(fd, buffer, EV_BUF_LEN);
1375 		if (ret < 0) {
1376 			ublk_err("%s: read inotify fd failed\n", __func__);
1377 			goto rm_watch;
1378 		}
1379 
1380 		while (i < ret) {
1381 			struct inotify_event *event = (struct inotify_event *)&buffer[i];
1382 
1383 			ublk_dbg(UBLK_DBG_DEV, "%s: inotify event %x %s\n",
1384 					__func__, event->mask, event->name);
1385 			if (event->mask & evt_mask) {
1386 				if (!strcmp(event->name, dev_name)) {
1387 					ret = 0;
1388 					goto rm_watch;
1389 				}
1390 			}
1391 			i += EV_SIZE + event->len;
1392 		}
1393 	}
1394 rm_watch:
1395 	inotify_rm_watch(fd, wd);
1396 fail:
1397 	close(fd);
1398 	return ret;
1399 }
1400 
1401 static int ublk_stop_io_daemon(const struct ublk_dev *dev)
1402 {
1403 	int daemon_pid = dev->dev_info.ublksrv_pid;
1404 	int dev_id = dev->dev_info.dev_id;
1405 	char ublkc[64];
1406 	int ret = 0;
1407 
1408 	if (daemon_pid < 0)
1409 		return 0;
1410 
1411 	/* daemon may be dead already */
1412 	if (kill(daemon_pid, 0) < 0)
1413 		goto wait;
1414 
1415 	snprintf(ublkc, sizeof(ublkc), "/dev/%s%d", "ublkc", dev_id);
1416 
1417 	/* ublk char device may be gone already */
1418 	if (access(ublkc, F_OK) != 0)
1419 		goto wait;
1420 
1421 	/* Wait until ublk char device is closed, when the daemon is shutdown */
1422 	ret = wait_ublk_dev(ublkc, IN_CLOSE, 10);
1423 	/* double check and since it may be closed before starting inotify */
1424 	if (ret == -ETIMEDOUT)
1425 		ret = kill(daemon_pid, 0) < 0;
1426 wait:
1427 	waitpid(daemon_pid, NULL, 0);
1428 	ublk_dbg(UBLK_DBG_DEV, "%s: pid %d dev_id %d ret %d\n",
1429 			__func__, daemon_pid, dev_id, ret);
1430 
1431 	return ret;
1432 }
1433 
1434 static int __cmd_dev_add(const struct dev_ctx *ctx)
1435 {
1436 	unsigned nthreads = ctx->nthreads;
1437 	unsigned nr_queues = ctx->nr_hw_queues;
1438 	const char *tgt_type = ctx->tgt_type;
1439 	unsigned depth = ctx->queue_depth;
1440 	__u64 features;
1441 	const struct ublk_tgt_ops *ops;
1442 	struct ublksrv_ctrl_dev_info *info;
1443 	struct ublk_dev *dev = NULL;
1444 	int dev_id = ctx->dev_id;
1445 	int ret, i;
1446 
1447 	ops = ublk_find_tgt(tgt_type);
1448 	if (!ops) {
1449 		ublk_err("%s: no such tgt type, type %s\n",
1450 				__func__, tgt_type);
1451 		ret = -ENODEV;
1452 		goto fail;
1453 	}
1454 
1455 	if (nr_queues > UBLK_MAX_QUEUES || depth > UBLK_QUEUE_DEPTH) {
1456 		ublk_err("%s: invalid nr_queues or depth queues %u depth %u\n",
1457 				__func__, nr_queues, depth);
1458 		ret = -EINVAL;
1459 		goto fail;
1460 	}
1461 
1462 	/* default to 1:1 threads:queues if nthreads is unspecified */
1463 	if (!nthreads)
1464 		nthreads = nr_queues;
1465 
1466 	if (nthreads > UBLK_MAX_THREADS) {
1467 		ublk_err("%s: %u is too many threads (max %u)\n",
1468 				__func__, nthreads, UBLK_MAX_THREADS);
1469 		ret = -EINVAL;
1470 		goto fail;
1471 	}
1472 
1473 	if (nthreads != nr_queues && (!ctx->per_io_tasks &&
1474 				!(ctx->flags & UBLK_F_BATCH_IO))) {
1475 		ublk_err("%s: threads %u must be same as queues %u if "
1476 			"not using per_io_tasks\n",
1477 			__func__, nthreads, nr_queues);
1478 		ret = -EINVAL;
1479 		goto fail;
1480 	}
1481 
1482 	dev = ublk_ctrl_init();
1483 	if (!dev) {
1484 		ublk_err("%s: can't alloc dev id %d, type %s\n",
1485 				__func__, dev_id, tgt_type);
1486 		ret = -ENOMEM;
1487 		goto fail;
1488 	}
1489 
1490 	/* kernel doesn't support get_features */
1491 	ret = ublk_ctrl_get_features(dev, &features);
1492 	if (ret < 0) {
1493 		ret = -EINVAL;
1494 		goto fail;
1495 	}
1496 
1497 	if (!(features & UBLK_F_CMD_IOCTL_ENCODE)) {
1498 		ret = -ENOTSUP;
1499 		goto fail;
1500 	}
1501 
1502 	info = &dev->dev_info;
1503 	info->dev_id = ctx->dev_id;
1504 	info->nr_hw_queues = nr_queues;
1505 	info->queue_depth = depth;
1506 	info->io_desc_size = ctx->io_desc_size;
1507 	info->flags = ctx->flags;
1508 	if ((features & UBLK_F_QUIESCE) &&
1509 			(info->flags & UBLK_F_USER_RECOVERY))
1510 		info->flags |= UBLK_F_QUIESCE;
1511 	dev->nthreads = nthreads;
1512 	dev->per_io_tasks = ctx->per_io_tasks;
1513 	dev->tgt.ops = ops;
1514 	dev->tgt.sq_depth = depth;
1515 	dev->tgt.cq_depth = depth;
1516 
1517 	for (i = 0; i < MAX_BACK_FILES; i++) {
1518 		if (ctx->files[i]) {
1519 			strcpy(dev->tgt.backing_file[i], ctx->files[i]);
1520 			dev->tgt.nr_backing_files++;
1521 		}
1522 	}
1523 
1524 	if (ctx->recovery)
1525 		ret = ublk_ctrl_start_user_recovery(dev);
1526 	else
1527 		ret = ublk_ctrl_add_dev(dev);
1528 	if (ret < 0) {
1529 		ublk_err("%s: can't add dev id %d, type %s ret %d\n",
1530 				__func__, dev_id, tgt_type, ret);
1531 		goto fail;
1532 	}
1533 
1534 	/*
1535 	 * The kernel may reduce nr_hw_queues (e.g. capped to nr_cpu_ids).
1536 	 * Cap nthreads to the actual queue count to avoid creating extra
1537 	 * handler threads that will hang during device removal.
1538 	 *
1539 	 * per_io_tasks mode is excluded: threads interleave across all
1540 	 * queues so nthreads > nr_hw_queues is valid and intentional.
1541 	 */
1542 	if (!ctx->per_io_tasks && dev->nthreads > info->nr_hw_queues)
1543 		dev->nthreads = info->nr_hw_queues;
1544 
1545 	ret = ublk_start_daemon(ctx, dev);
1546 	ublk_dbg(UBLK_DBG_DEV, "%s: daemon exit %d\n", __func__, ret);
1547 	if (ret < 0)
1548 		ublk_ctrl_del_dev(dev);
1549 
1550 fail:
1551 	if (ret < 0)
1552 		ublk_send_dev_event(ctx, dev, -1);
1553 	if (dev)
1554 		ublk_ctrl_deinit(dev);
1555 	return ret;
1556 }
1557 
1558 static int __cmd_dev_list(struct dev_ctx *ctx);
1559 
1560 static int cmd_dev_set_params(struct dev_ctx *ctx)
1561 {
1562 	struct ublksrv_ctrl_dev_info *info;
1563 	struct ublk_params params;
1564 	struct ublk_dev *dev;
1565 	__u64 features;
1566 	int ret, del_ret;
1567 
1568 	dev = ublk_ctrl_init();
1569 	if (!dev)
1570 		return -ENODEV;
1571 
1572 	ret = ublk_ctrl_get_features(dev, &features);
1573 	if (ret < 0)
1574 		goto out;
1575 
1576 	if (!(features & UBLK_F_CMD_IOCTL_ENCODE)) {
1577 		ret = -ENOTSUP;
1578 		goto out;
1579 	}
1580 
1581 	info = &dev->dev_info;
1582 	info->dev_id = ctx->dev_id;
1583 	info->nr_hw_queues = ctx->nr_hw_queues;
1584 	info->queue_depth = ctx->queue_depth;
1585 	info->io_desc_size = ctx->io_desc_size;
1586 	info->flags = ctx->flags;
1587 
1588 	ret = ublk_ctrl_add_dev(dev);
1589 	if (ret < 0)
1590 		goto out;
1591 
1592 	ublk_init_params_from_ctx(ctx, &params);
1593 
1594 	ret = ublk_ctrl_set_params(dev, &params);
1595 	printf("SET_PARAMS returned %d\n", ret);
1596 
1597 	del_ret = ublk_ctrl_del_dev(dev);
1598 	if (del_ret < 0 && ret == 0)
1599 		ret = del_ret;
1600 out:
1601 	ublk_ctrl_deinit(dev);
1602 	return ret < 0 ? ret : 0;
1603 }
1604 
1605 static int cmd_dev_add(struct dev_ctx *ctx)
1606 {
1607 	int res;
1608 
1609 	if (ctx->fg)
1610 		goto run;
1611 
1612 	ctx->_shmid = shmget(IPC_PRIVATE, sizeof(struct ublk_dev), IPC_CREAT | 0666);
1613 	if (ctx->_shmid < 0) {
1614 		ublk_err("%s: failed to shmget %s\n", __func__, strerror(errno));
1615 		exit(-1);
1616 	}
1617 	ctx->shadow_dev = (struct ublk_dev *)shmat(ctx->_shmid, NULL, 0);
1618 	if (ctx->shadow_dev == (struct ublk_dev *)-1) {
1619 		ublk_err("%s: failed to shmat %s\n", __func__, strerror(errno));
1620 		exit(-1);
1621 	}
1622 	ctx->_evtfd = eventfd(0, 0);
1623 	if (ctx->_evtfd < 0) {
1624 		ublk_err("%s: failed to create eventfd %s\n", __func__, strerror(errno));
1625 		exit(-1);
1626 	}
1627 
1628 	res = fork();
1629 	if (res == 0) {
1630 		int res2;
1631 
1632 		setsid();
1633 		res2 = fork();
1634 		if (res2 == 0) {
1635 			/* prepare for detaching */
1636 			close(STDIN_FILENO);
1637 			close(STDOUT_FILENO);
1638 			close(STDERR_FILENO);
1639 run:
1640 			res = __cmd_dev_add(ctx);
1641 			return res;
1642 		} else {
1643 			/* detached from the foreground task */
1644 			exit(EXIT_SUCCESS);
1645 		}
1646 	} else if (res > 0) {
1647 		uint64_t id;
1648 		int exit_code = EXIT_FAILURE;
1649 
1650 		res = read(ctx->_evtfd, &id, sizeof(id));
1651 		close(ctx->_evtfd);
1652 		if (res == sizeof(id) && id != ERROR_EVTFD_DEVID) {
1653 			ctx->dev_id = id - 1;
1654 			if (__cmd_dev_list(ctx) >= 0)
1655 				exit_code = EXIT_SUCCESS;
1656 		}
1657 		shmdt(ctx->shadow_dev);
1658 		shmctl(ctx->_shmid, IPC_RMID, NULL);
1659 		/* wait for child and detach from it */
1660 		wait(NULL);
1661 		if (exit_code == EXIT_FAILURE)
1662 			ublk_err("%s: command failed\n", __func__);
1663 		exit(exit_code);
1664 	} else {
1665 		exit(EXIT_FAILURE);
1666 	}
1667 }
1668 
1669 static int __cmd_dev_del(struct dev_ctx *ctx)
1670 {
1671 	int number = ctx->dev_id;
1672 	struct ublk_dev *dev;
1673 	int ret;
1674 
1675 	dev = ublk_ctrl_init();
1676 	dev->dev_info.dev_id = number;
1677 
1678 	ret = ublk_ctrl_get_info(dev);
1679 	if (ret < 0)
1680 		goto fail;
1681 
1682 	ret = ublk_ctrl_stop_dev(dev);
1683 	if (ret < 0)
1684 		ublk_err("%s: stop dev %d failed ret %d\n", __func__, number, ret);
1685 
1686 	ret = ublk_stop_io_daemon(dev);
1687 	if (ret < 0)
1688 		ublk_err("%s: stop daemon id %d dev %d, ret %d\n",
1689 				__func__, dev->dev_info.ublksrv_pid, number, ret);
1690 	ublk_ctrl_del_dev(dev);
1691 fail:
1692 	ublk_ctrl_deinit(dev);
1693 
1694 	return (ret >= 0) ? 0 : ret;
1695 }
1696 
1697 static int cmd_dev_del(struct dev_ctx *ctx)
1698 {
1699 	int i;
1700 
1701 	if (ctx->dev_id >= 0 || !ctx->all)
1702 		return __cmd_dev_del(ctx);
1703 
1704 	for (i = 0; i < 255; i++) {
1705 		ctx->dev_id = i;
1706 		__cmd_dev_del(ctx);
1707 	}
1708 	return 0;
1709 }
1710 
1711 static int cmd_dev_stop(struct dev_ctx *ctx)
1712 {
1713 	int number = ctx->dev_id;
1714 	struct ublk_dev *dev;
1715 	int ret;
1716 
1717 	if (number < 0) {
1718 		ublk_err("%s: device id is required\n", __func__);
1719 		return -EINVAL;
1720 	}
1721 
1722 	dev = ublk_ctrl_init();
1723 	dev->dev_info.dev_id = number;
1724 
1725 	ret = ublk_ctrl_get_info(dev);
1726 	if (ret < 0)
1727 		goto fail;
1728 
1729 	if (ctx->safe_stop) {
1730 		ret = ublk_ctrl_try_stop_dev(dev);
1731 		if (ret < 0)
1732 			ublk_err("%s: try_stop dev %d failed ret %d\n",
1733 					__func__, number, ret);
1734 	} else {
1735 		ret = ublk_ctrl_stop_dev(dev);
1736 		if (ret < 0)
1737 			ublk_err("%s: stop dev %d failed ret %d\n",
1738 					__func__, number, ret);
1739 	}
1740 
1741 fail:
1742 	ublk_ctrl_deinit(dev);
1743 
1744 	return ret;
1745 }
1746 
1747 static int __cmd_dev_list(struct dev_ctx *ctx)
1748 {
1749 	struct ublk_dev *dev = ublk_ctrl_init();
1750 	int ret;
1751 
1752 	if (!dev)
1753 		return -ENODEV;
1754 
1755 	dev->dev_info.dev_id = ctx->dev_id;
1756 
1757 	ret = ublk_ctrl_get_info(dev);
1758 	if (ret < 0) {
1759 		if (ctx->logging)
1760 			ublk_err("%s: can't get dev info from %d: %d\n",
1761 					__func__, ctx->dev_id, ret);
1762 	} else {
1763 		if (ctx->shadow_dev)
1764 			memcpy(&dev->q, ctx->shadow_dev->q, sizeof(dev->q));
1765 
1766 		ublk_ctrl_dump(dev);
1767 	}
1768 
1769 	ublk_ctrl_deinit(dev);
1770 
1771 	return ret;
1772 }
1773 
1774 static int cmd_dev_list(struct dev_ctx *ctx)
1775 {
1776 	int i;
1777 
1778 	if (ctx->dev_id >= 0 || !ctx->all)
1779 		return __cmd_dev_list(ctx);
1780 
1781 	ctx->logging = false;
1782 	for (i = 0; i < 255; i++) {
1783 		ctx->dev_id = i;
1784 		__cmd_dev_list(ctx);
1785 	}
1786 	return 0;
1787 }
1788 
1789 static int cmd_dev_get_features(void)
1790 {
1791 #define const_ilog2(x) (63 - __builtin_clzll(x))
1792 #define FEAT_NAME(f) [const_ilog2(f)] = #f
1793 	static const char *feat_map[] = {
1794 		FEAT_NAME(UBLK_F_SUPPORT_ZERO_COPY),
1795 		FEAT_NAME(UBLK_F_URING_CMD_COMP_IN_TASK),
1796 		FEAT_NAME(UBLK_F_NEED_GET_DATA),
1797 		FEAT_NAME(UBLK_F_USER_RECOVERY),
1798 		FEAT_NAME(UBLK_F_USER_RECOVERY_REISSUE),
1799 		FEAT_NAME(UBLK_F_UNPRIVILEGED_DEV),
1800 		FEAT_NAME(UBLK_F_CMD_IOCTL_ENCODE),
1801 		FEAT_NAME(UBLK_F_USER_COPY),
1802 		FEAT_NAME(UBLK_F_ZONED),
1803 		FEAT_NAME(UBLK_F_USER_RECOVERY_FAIL_IO),
1804 		FEAT_NAME(UBLK_F_UPDATE_SIZE),
1805 		FEAT_NAME(UBLK_F_AUTO_BUF_REG),
1806 		FEAT_NAME(UBLK_F_QUIESCE),
1807 		FEAT_NAME(UBLK_F_PER_IO_DAEMON),
1808 		FEAT_NAME(UBLK_F_BUF_REG_OFF_DAEMON),
1809 		FEAT_NAME(UBLK_F_INTEGRITY),
1810 		FEAT_NAME(UBLK_F_SAFE_STOP_DEV),
1811 		FEAT_NAME(UBLK_F_BATCH_IO),
1812 		FEAT_NAME(UBLK_F_NO_AUTO_PART_SCAN),
1813 		FEAT_NAME(UBLK_F_SHMEM_ZC),
1814 		FEAT_NAME(UBLK_F_IO_DESC_SIZE),
1815 	};
1816 	struct ublk_dev *dev;
1817 	__u64 features = 0;
1818 	int ret;
1819 
1820 	dev = ublk_ctrl_init();
1821 	if (!dev) {
1822 		fprintf(stderr, "ublksrv_ctrl_init failed id\n");
1823 		return -EOPNOTSUPP;
1824 	}
1825 
1826 	ret = ublk_ctrl_get_features(dev, &features);
1827 	if (!ret) {
1828 		int i;
1829 
1830 		printf("ublk_drv features: 0x%llx\n", features);
1831 
1832 		for (i = 0; i < sizeof(features) * 8; i++) {
1833 			const char *feat;
1834 
1835 			if (!((1ULL << i)  & features))
1836 				continue;
1837 			if (i < ARRAY_SIZE(feat_map))
1838 				feat = feat_map[i];
1839 			else
1840 				feat = "unknown";
1841 			printf("0x%-16llx: %s\n", 1ULL << i, feat);
1842 		}
1843 	}
1844 
1845 	return ret;
1846 }
1847 
1848 static int cmd_dev_update_size(struct dev_ctx *ctx)
1849 {
1850 	struct ublk_dev *dev = ublk_ctrl_init();
1851 	struct ublk_params p;
1852 	int ret = -EINVAL;
1853 
1854 	if (!dev)
1855 		return -ENODEV;
1856 
1857 	if (ctx->dev_id < 0) {
1858 		fprintf(stderr, "device id isn't provided\n");
1859 		goto out;
1860 	}
1861 
1862 	dev->dev_info.dev_id = ctx->dev_id;
1863 	ret = ublk_ctrl_get_params(dev, &p);
1864 	if (ret < 0) {
1865 		ublk_err("failed to get params %d %s\n", ret, strerror(-ret));
1866 		goto out;
1867 	}
1868 
1869 	if (ctx->size & ((1 << p.basic.logical_bs_shift) - 1)) {
1870 		ublk_err("size isn't aligned with logical block size\n");
1871 		ret = -EINVAL;
1872 		goto out;
1873 	}
1874 
1875 	ret = ublk_ctrl_update_size(dev, ctx->size >> 9);
1876 out:
1877 	ublk_ctrl_deinit(dev);
1878 	return ret;
1879 }
1880 
1881 static int cmd_dev_quiesce(struct dev_ctx *ctx)
1882 {
1883 	struct ublk_dev *dev = ublk_ctrl_init();
1884 	int ret = -EINVAL;
1885 
1886 	if (!dev)
1887 		return -ENODEV;
1888 
1889 	if (ctx->dev_id < 0) {
1890 		fprintf(stderr, "device id isn't provided for quiesce\n");
1891 		goto out;
1892 	}
1893 	dev->dev_info.dev_id = ctx->dev_id;
1894 	ret = ublk_ctrl_quiesce_dev(dev, 10000);
1895 
1896 out:
1897 	ublk_ctrl_deinit(dev);
1898 	return ret;
1899 }
1900 
1901 static void __cmd_create_help(char *exe, bool recovery)
1902 {
1903 	int i;
1904 
1905 	printf("%s %s -t [null|loop|stripe|fault_inject] [-q nr_queues] [-d depth] [-n dev_id]\n",
1906 			exe, recovery ? "recover" : "add");
1907 	printf("\t[--foreground] [--quiet] [-z] [--auto_zc] [--auto_zc_fallback] [--debug_mask mask] [-r 0|1] [-g] [-u]\n");
1908 	printf("\t[-e 0|1 ] [-i 0|1] [--no_ublk_fixed_fd]\n");
1909 	printf("\t[--nthreads threads] [--per_io_tasks]\n");
1910 	printf("\t[--integrity_capable] [--integrity_reftag] [--metadata_size SIZE] "
1911 		 "[--pi_offset OFFSET] [--csum_type ip|t10dif|nvme] [--tag_size SIZE]\n");
1912 	printf("\t[--batch|-b] [--rotate_auto_buf] [--no_auto_part_scan]\n");
1913 	printf("\t[--io_desc_size SIZE]\n");
1914 	printf("\t[target options] [backfile1] [backfile2] ...\n");
1915 	printf("\tdefault: nr_queues=2(max 32), depth=128(max 1024), dev_id=-1(auto allocation)\n");
1916 	printf("\tdefault: nthreads=nr_queues");
1917 
1918 	for (i = 0; i < ARRAY_SIZE(tgt_ops_list); i++) {
1919 		const struct ublk_tgt_ops *ops = tgt_ops_list[i];
1920 
1921 		if (ops->usage)
1922 			ops->usage(ops);
1923 	}
1924 }
1925 
1926 static void cmd_add_help(char *exe)
1927 {
1928 	__cmd_create_help(exe, false);
1929 	printf("\n");
1930 }
1931 
1932 static void cmd_recover_help(char *exe)
1933 {
1934 	__cmd_create_help(exe, true);
1935 	printf("\tPlease provide exact command line for creating this device with real dev_id\n");
1936 	printf("\n");
1937 }
1938 
1939 static int cmd_dev_help(char *exe)
1940 {
1941 	cmd_add_help(exe);
1942 	cmd_recover_help(exe);
1943 
1944 	printf("%s del [-n dev_id] -a \n", exe);
1945 	printf("\t -a delete all devices -n delete specified device\n\n");
1946 	printf("%s stop -n dev_id [--safe]\n", exe);
1947 	printf("\t --safe only stop if device has no active openers\n\n");
1948 	printf("%s list [-n dev_id] -a \n", exe);
1949 	printf("\t -a list all devices, -n list specified device, default -a \n\n");
1950 	printf("%s set_params [-n dev_id] [-q nr_queues] [-d depth] [-u] [--zoned]\n", exe);
1951 	printf("\t[--param_types basic[,zoned]|none]\n");
1952 	printf("\t issue ADD_DEV, SET_PARAMS and DEL_DEV without START_DEV\n\n");
1953 	printf("%s features\n", exe);
1954 	printf("%s update_size -n dev_id -s|--size size_in_bytes \n", exe);
1955 	printf("%s quiesce -n dev_id\n", exe);
1956 	return 0;
1957 }
1958 
1959 int main(int argc, char *argv[])
1960 {
1961 	static const struct option longopts[] = {
1962 		{ "all",		0,	NULL, 'a' },
1963 		{ "type",		1,	NULL, 't' },
1964 		{ "number",		1,	NULL, 'n' },
1965 		{ "queues",		1,	NULL, 'q' },
1966 		{ "depth",		1,	NULL, 'd' },
1967 		{ "debug_mask",		1,	NULL,  0  },
1968 		{ "quiet",		0,	NULL,  0  },
1969 		{ "zero_copy",          0,      NULL, 'z' },
1970 		{ "foreground",		0,	NULL,  0  },
1971 		{ "recovery", 		1,      NULL, 'r' },
1972 		{ "recovery_fail_io",	1,	NULL, 'e'},
1973 		{ "recovery_reissue",	1,	NULL, 'i'},
1974 		{ "get_data",		1,	NULL, 'g'},
1975 		{ "auto_zc",		0,	NULL,  0 },
1976 		{ "auto_zc_fallback", 	0,	NULL,  0 },
1977 		{ "user_copy",		0,	NULL, 'u'},
1978 		{ "size",		1,	NULL, 's'},
1979 		{ "nthreads",		1,	NULL,  0 },
1980 		{ "per_io_tasks",	0,	NULL,  0 },
1981 		{ "no_ublk_fixed_fd",	0,	NULL,  0 },
1982 		{ "integrity_capable",	0,	NULL,  0 },
1983 		{ "integrity_reftag",	0,	NULL,  0 },
1984 		{ "metadata_size",	1,	NULL,  0 },
1985 		{ "pi_offset",		1,	NULL,  0 },
1986 		{ "csum_type",		1,	NULL,  0 },
1987 		{ "tag_size",		1,	NULL,  0 },
1988 		{ "safe",		0,	NULL,  0 },
1989 		{ "batch",              0,      NULL, 'b'},
1990 		{ "rotate_auto_buf",	0,	NULL,  0 },
1991 		{ "no_auto_part_scan",	0,	NULL,  0 },
1992 		{ "shmem_zc",		0,	NULL,  0  },
1993 		{ "htlb",		1,	NULL,  0  },
1994 		{ "rdonly_shmem_buf",	0,	NULL,  0  },
1995 		{ "io_desc_size",	1,	NULL,  0  },
1996 		{ "zoned",		0,	NULL,  0  },
1997 		{ "param_types",	1,	NULL,  0  },
1998 		{ "logical_bs_shift",	1,	NULL,  0  },
1999 		{ "physical_bs_shift",	1,	NULL,  0  },
2000 		{ "io_min_shift",	1,	NULL,  0  },
2001 		{ "io_opt_shift",	1,	NULL,  0  },
2002 		{ "max_sectors",	1,	NULL,  0  },
2003 		{ "chunk_sectors",	1,	NULL,  0  },
2004 		{ "dev_sectors",	1,	NULL,  0  },
2005 		{ "max_zone_append_sectors", 1, NULL,  0  },
2006 		{ "max_open_zones",	1,	NULL,  0  },
2007 		{ "max_active_zones",	1,	NULL,  0  },
2008 		{ 0, 0, 0, 0 }
2009 	};
2010 	const struct ublk_tgt_ops *ops = NULL;
2011 	int option_idx, opt;
2012 	const char *cmd = argv[1];
2013 	struct dev_ctx ctx = {
2014 		._evtfd         =       -1,
2015 		.queue_depth	=	128,
2016 		.nr_hw_queues	=	2,
2017 		.dev_id		=	-1,
2018 		.tgt_type	=	"unknown",
2019 		.csum_type	=	LBMD_PI_CSUM_NONE,
2020 		.io_desc_size	=	sizeof(struct ublksrv_io_desc),
2021 		.params = {
2022 			.types			= UBLK_PARAM_TYPE_BASIC,
2023 			.logical_bs_shift	= KUBLK_PARAM_LOGICAL_BS_SHIFT,
2024 			.physical_bs_shift	= KUBLK_PARAM_PHYSICAL_BS_SHIFT,
2025 			.io_min_shift		= KUBLK_PARAM_LOGICAL_BS_SHIFT,
2026 			.io_opt_shift		= KUBLK_PARAM_PHYSICAL_BS_SHIFT,
2027 			.max_sectors		=
2028 				UBLK_IO_MAX_BYTES >> KUBLK_PARAM_LOGICAL_BS_SHIFT,
2029 			.chunk_sectors		= KUBLK_PARAM_ZONE_SECTORS,
2030 			.dev_sectors		= KUBLK_PARAM_DEV_SECTORS,
2031 			.max_zone_append_sectors =
2032 				KUBLK_PARAM_ZONE_APPEND_SECTORS,
2033 		},
2034 	};
2035 	int ret = -EINVAL, i;
2036 	int tgt_argc = 1;
2037 	char *tgt_argv[MAX_NR_TGT_ARG] = { NULL };
2038 	int value;
2039 
2040 	if (argc == 1)
2041 		return ret;
2042 
2043 	opterr = 0;
2044 	optind = 2;
2045 	while ((opt = getopt_long(argc, argv, "t:n:d:q:r:e:i:s:gazub",
2046 				  longopts, &option_idx)) != -1) {
2047 		switch (opt) {
2048 		case 'a':
2049 			ctx.all = 1;
2050 			break;
2051 		case 'b':
2052 			ctx.flags |= UBLK_F_BATCH_IO;
2053 			break;
2054 		case 'n':
2055 			ctx.dev_id = strtol(optarg, NULL, 10);
2056 			break;
2057 		case 't':
2058 			if (strlen(optarg) < sizeof(ctx.tgt_type))
2059 				strcpy(ctx.tgt_type, optarg);
2060 			break;
2061 		case 'q':
2062 			ctx.nr_hw_queues = strtol(optarg, NULL, 10);
2063 			break;
2064 		case 'd':
2065 			ctx.queue_depth = strtol(optarg, NULL, 10);
2066 			break;
2067 		case 'z':
2068 			ctx.flags |= UBLK_F_SUPPORT_ZERO_COPY;
2069 			break;
2070 		case 'r':
2071 			value = strtol(optarg, NULL, 10);
2072 			if (value)
2073 				ctx.flags |= UBLK_F_USER_RECOVERY;
2074 			break;
2075 		case 'e':
2076 			value = strtol(optarg, NULL, 10);
2077 			if (value)
2078 				ctx.flags |= UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO;
2079 			break;
2080 		case 'i':
2081 			value = strtol(optarg, NULL, 10);
2082 			if (value)
2083 				ctx.flags |= UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE;
2084 			break;
2085 		case 'g':
2086 			ctx.flags |= UBLK_F_NEED_GET_DATA;
2087 			break;
2088 		case 'u':
2089 			ctx.flags |= UBLK_F_USER_COPY;
2090 			break;
2091 		case 's':
2092 			ctx.size = strtoull(optarg, NULL, 10);
2093 			break;
2094 		case 0:
2095 			if (!strcmp(longopts[option_idx].name, "debug_mask"))
2096 				ublk_dbg_mask = strtol(optarg, NULL, 16);
2097 			if (!strcmp(longopts[option_idx].name, "quiet"))
2098 				ublk_dbg_mask = 0;
2099 			if (!strcmp(longopts[option_idx].name, "foreground"))
2100 				ctx.fg = 1;
2101 			if (!strcmp(longopts[option_idx].name, "auto_zc"))
2102 				ctx.flags |= UBLK_F_AUTO_BUF_REG;
2103 			if (!strcmp(longopts[option_idx].name, "auto_zc_fallback"))
2104 				ctx.auto_zc_fallback = 1;
2105 			if (!strcmp(longopts[option_idx].name, "rotate_auto_buf"))
2106 				ctx.rotate_auto_buf = 1;
2107 			if (!strcmp(longopts[option_idx].name, "nthreads"))
2108 				ctx.nthreads = strtol(optarg, NULL, 10);
2109 			if (!strcmp(longopts[option_idx].name, "per_io_tasks"))
2110 				ctx.per_io_tasks = 1;
2111 			if (!strcmp(longopts[option_idx].name, "no_ublk_fixed_fd"))
2112 				ctx.no_ublk_fixed_fd = 1;
2113 			if (!strcmp(longopts[option_idx].name, "integrity_capable"))
2114 				ctx.integrity_flags |= LBMD_PI_CAP_INTEGRITY;
2115 			if (!strcmp(longopts[option_idx].name, "integrity_reftag"))
2116 				ctx.integrity_flags |= LBMD_PI_CAP_REFTAG;
2117 			if (!strcmp(longopts[option_idx].name, "metadata_size"))
2118 				ctx.metadata_size = strtoul(optarg, NULL, 0);
2119 			if (!strcmp(longopts[option_idx].name, "pi_offset"))
2120 				ctx.pi_offset = strtoul(optarg, NULL, 0);
2121 			if (!strcmp(longopts[option_idx].name, "csum_type")) {
2122 				if (!strcmp(optarg, "ip")) {
2123 					ctx.csum_type = LBMD_PI_CSUM_IP;
2124 				} else if (!strcmp(optarg, "t10dif")) {
2125 					ctx.csum_type = LBMD_PI_CSUM_CRC16_T10DIF;
2126 				} else if (!strcmp(optarg, "nvme")) {
2127 					ctx.csum_type = LBMD_PI_CSUM_CRC64_NVME;
2128 				} else {
2129 					ublk_err("invalid csum_type: %s\n", optarg);
2130 					return -EINVAL;
2131 				}
2132 			}
2133 			if (!strcmp(longopts[option_idx].name, "tag_size"))
2134 				ctx.tag_size = strtoul(optarg, NULL, 0);
2135 			if (!strcmp(longopts[option_idx].name, "safe"))
2136 				ctx.safe_stop = 1;
2137 			if (!strcmp(longopts[option_idx].name, "no_auto_part_scan"))
2138 				ctx.flags |= UBLK_F_NO_AUTO_PART_SCAN;
2139 			if (!strcmp(longopts[option_idx].name, "shmem_zc"))
2140 				ctx.flags |= UBLK_F_SHMEM_ZC;
2141 			if (!strcmp(longopts[option_idx].name, "htlb"))
2142 				ctx.htlb_path = strdup(optarg);
2143 			if (!strcmp(longopts[option_idx].name, "rdonly_shmem_buf"))
2144 				ctx.rdonly_shmem_buf = 1;
2145 			if (!strcmp(longopts[option_idx].name, "io_desc_size")) {
2146 				ctx.flags |= UBLK_F_IO_DESC_SIZE;
2147 				ctx.io_desc_size = strtoul(optarg, NULL, 0);
2148 			}
2149 			if (!strcmp(longopts[option_idx].name, "zoned"))
2150 				ctx.flags |= UBLK_F_ZONED;
2151 			if (!strcmp(longopts[option_idx].name, "param_types")) {
2152 				ret = parse_param_types(optarg, &ctx.params.types);
2153 				if (ret)
2154 					return ret;
2155 			}
2156 			if (!strcmp(longopts[option_idx].name, "logical_bs_shift"))
2157 				ctx.params.logical_bs_shift = strtoul(optarg, NULL, 0);
2158 			if (!strcmp(longopts[option_idx].name, "physical_bs_shift"))
2159 				ctx.params.physical_bs_shift = strtoul(optarg, NULL, 0);
2160 			if (!strcmp(longopts[option_idx].name, "io_min_shift"))
2161 				ctx.params.io_min_shift = strtoul(optarg, NULL, 0);
2162 			if (!strcmp(longopts[option_idx].name, "io_opt_shift"))
2163 				ctx.params.io_opt_shift = strtoul(optarg, NULL, 0);
2164 			if (!strcmp(longopts[option_idx].name, "max_sectors"))
2165 				ctx.params.max_sectors = strtoul(optarg, NULL, 0);
2166 			if (!strcmp(longopts[option_idx].name, "chunk_sectors"))
2167 				ctx.params.chunk_sectors = strtoul(optarg, NULL, 0);
2168 			if (!strcmp(longopts[option_idx].name, "dev_sectors"))
2169 				ctx.params.dev_sectors = strtoull(optarg, NULL, 0);
2170 			if (!strcmp(longopts[option_idx].name, "max_zone_append_sectors"))
2171 				ctx.params.max_zone_append_sectors =
2172 					strtoul(optarg, NULL, 0);
2173 			if (!strcmp(longopts[option_idx].name, "max_open_zones"))
2174 				ctx.params.max_open_zones = strtoul(optarg, NULL, 0);
2175 			if (!strcmp(longopts[option_idx].name, "max_active_zones"))
2176 				ctx.params.max_active_zones = strtoul(optarg, NULL, 0);
2177 			break;
2178 		case '?':
2179 			/*
2180 			 * target requires every option must have argument
2181 			 */
2182 			if (argv[optind][0] == '-' || argv[optind - 1][0] != '-') {
2183 				fprintf(stderr, "every target option requires argument: %s %s\n",
2184 						argv[optind - 1], argv[optind]);
2185 				exit(EXIT_FAILURE);
2186 			}
2187 
2188 			if (tgt_argc < (MAX_NR_TGT_ARG - 1) / 2) {
2189 				tgt_argv[tgt_argc++] = argv[optind - 1];
2190 				tgt_argv[tgt_argc++] = argv[optind];
2191 			} else {
2192 				fprintf(stderr, "too many target options\n");
2193 				exit(EXIT_FAILURE);
2194 			}
2195 			optind += 1;
2196 			break;
2197 		}
2198 	}
2199 
2200 	if (ctx.per_io_tasks && (ctx.flags & UBLK_F_BATCH_IO)) {
2201 		ublk_err("per_io_task and F_BATCH_IO conflict\n");
2202 		return -EINVAL;
2203 	}
2204 
2205 	/* auto_zc_fallback depends on F_AUTO_BUF_REG & F_SUPPORT_ZERO_COPY */
2206 	if (ctx.auto_zc_fallback &&
2207 	    !((ctx.flags & UBLK_F_AUTO_BUF_REG) &&
2208 		    (ctx.flags & UBLK_F_SUPPORT_ZERO_COPY))) {
2209 		ublk_err("%s: auto_zc_fallback is set but neither "
2210 				"F_AUTO_BUF_REG nor F_SUPPORT_ZERO_COPY is enabled\n",
2211 					__func__);
2212 		return -EINVAL;
2213 	}
2214 
2215 	if (!!(ctx.flags & UBLK_F_NEED_GET_DATA) +
2216 	    !!(ctx.flags & UBLK_F_USER_COPY) +
2217 	    (ctx.flags & UBLK_F_SUPPORT_ZERO_COPY && !ctx.auto_zc_fallback) +
2218 	    (ctx.flags & UBLK_F_AUTO_BUF_REG && !ctx.auto_zc_fallback) +
2219 	    ctx.auto_zc_fallback > 1) {
2220 		fprintf(stderr, "too many data copy modes specified\n");
2221 		return -EINVAL;
2222 	}
2223 
2224 	if (ctx.metadata_size) {
2225 		if (!(ctx.flags & UBLK_F_USER_COPY)) {
2226 			ublk_err("integrity requires user_copy\n");
2227 			return -EINVAL;
2228 		}
2229 
2230 		ctx.flags |= UBLK_F_INTEGRITY;
2231 	} else if (ctx.integrity_flags ||
2232 		   ctx.pi_offset ||
2233 		   ctx.csum_type != LBMD_PI_CSUM_NONE ||
2234 		   ctx.tag_size) {
2235 		ublk_err("integrity parameters require metadata_size\n");
2236 		return -EINVAL;
2237 	}
2238 
2239 	if ((ctx.flags & UBLK_F_AUTO_BUF_REG) &&
2240 			(ctx.flags & UBLK_F_BATCH_IO) &&
2241 			(ctx.nthreads > ctx.nr_hw_queues)) {
2242 		ublk_err("too many threads for F_AUTO_BUF_REG & F_BATCH_IO\n");
2243 		return -EINVAL;
2244 	}
2245 
2246 	if (ctx.rotate_auto_buf &&
2247 	    !((ctx.flags & UBLK_F_AUTO_BUF_REG) &&
2248 	      (ctx.flags & UBLK_F_BATCH_IO))) {
2249 		ublk_err("rotate_auto_buf requires --auto_zc and --batch\n");
2250 		return -EINVAL;
2251 	}
2252 
2253 	i = optind;
2254 	while (i < argc && ctx.nr_files < MAX_BACK_FILES) {
2255 		ctx.files[ctx.nr_files++] = argv[i++];
2256 	}
2257 
2258 	ops = ublk_find_tgt(ctx.tgt_type);
2259 	if (ops && ops->parse_cmd_line) {
2260 		optind = 0;
2261 
2262 		tgt_argv[0] = ctx.tgt_type;
2263 		ops->parse_cmd_line(&ctx, tgt_argc, tgt_argv);
2264 	}
2265 
2266 	if (!strcmp(cmd, "set_params"))
2267 		ret = cmd_dev_set_params(&ctx);
2268 	else if (!strcmp(cmd, "add"))
2269 		ret = cmd_dev_add(&ctx);
2270 	else if (!strcmp(cmd, "recover")) {
2271 		if (ctx.dev_id < 0) {
2272 			fprintf(stderr, "device id isn't provided for recovering\n");
2273 			ret = -EINVAL;
2274 		} else {
2275 			ctx.recovery = 1;
2276 			ret = cmd_dev_add(&ctx);
2277 		}
2278 	} else if (!strcmp(cmd, "del"))
2279 		ret = cmd_dev_del(&ctx);
2280 	else if (!strcmp(cmd, "stop"))
2281 		ret = cmd_dev_stop(&ctx);
2282 	else if (!strcmp(cmd, "list")) {
2283 		ctx.all = 1;
2284 		ret = cmd_dev_list(&ctx);
2285 	} else if (!strcmp(cmd, "help"))
2286 		ret = cmd_dev_help(argv[0]);
2287 	else if (!strcmp(cmd, "features"))
2288 		ret = cmd_dev_get_features();
2289 	else if (!strcmp(cmd, "update_size"))
2290 		ret = cmd_dev_update_size(&ctx);
2291 	else if (!strcmp(cmd, "quiesce"))
2292 		ret = cmd_dev_quiesce(&ctx);
2293 	else
2294 		cmd_dev_help(argv[0]);
2295 
2296 	return ret;
2297 }
2298