xref: /titanic_50/usr/src/uts/common/io/lofi.c (revision 5bd55801d6fb883418913e3f9f6d13fb29003956)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 /*
26  * lofi (loopback file) driver - allows you to attach a file to a device,
27  * which can then be accessed through that device. The simple model is that
28  * you tell lofi to open a file, and then use the block device you get as
29  * you would any block device. lofi translates access to the block device
30  * into I/O on the underlying file. This is mostly useful for
31  * mounting images of filesystems.
32  *
33  * lofi is controlled through /dev/lofictl - this is the only device exported
34  * during attach, and is minor number 0. lofiadm communicates with lofi through
35  * ioctls on this device. When a file is attached to lofi, block and character
36  * devices are exported in /dev/lofi and /dev/rlofi. Currently, these devices
37  * are identified by their minor number, and the minor number is also used
38  * as the name in /dev/lofi. If we ever decide to support virtual disks,
39  * we'll have to divide the minor number space to identify fdisk partitions
40  * and slices, and the name will then be the minor number shifted down a
41  * few bits. Minor devices are tracked with state structures handled with
42  * ddi_soft_state(9F) for simplicity.
43  *
44  * A file attached to lofi is opened when attached and not closed until
45  * explicitly detached from lofi. This seems more sensible than deferring
46  * the open until the /dev/lofi device is opened, for a number of reasons.
47  * One is that any failure is likely to be noticed by the person (or script)
48  * running lofiadm. Another is that it would be a security problem if the
49  * file was replaced by another one after being added but before being opened.
50  *
51  * The only hard part about lofi is the ioctls. In order to support things
52  * like 'newfs' on a lofi device, it needs to support certain disk ioctls.
53  * So it has to fake disk geometry and partition information. More may need
54  * to be faked if your favorite utility doesn't work and you think it should
55  * (fdformat doesn't work because it really wants to know the type of floppy
56  * controller to talk to, and that didn't seem easy to fake. Or possibly even
57  * necessary, since we have mkfs_pcfs now).
58  *
59  * Normally, a lofi device cannot be detached if it is open (i.e. busy).  To
60  * support simulation of hotplug events, an optional force flag is provided.
61  * If a lofi device is open when a force detach is requested, then the
62  * underlying file is closed and any subsequent operations return EIO.  When the
63  * device is closed for the last time, it will be cleaned up at that time.  In
64  * addition, the DKIOCSTATE ioctl will return DKIO_DEV_GONE when the device is
65  * detached but not removed.
66  *
67  * Known problems:
68  *
69  *	UFS logging. Mounting a UFS filesystem image "logging"
70  *	works for basic copy testing but wedges during a build of ON through
71  *	that image. Some deadlock in lufs holding the log mutex and then
72  *	getting stuck on a buf. So for now, don't do that.
73  *
74  *	Direct I/O. Since the filesystem data is being cached in the buffer
75  *	cache, _and_ again in the underlying filesystem, it's tempting to
76  *	enable direct I/O on the underlying file. Don't, because that deadlocks.
77  *	I think to fix the cache-twice problem we might need filesystem support.
78  *
79  *	lofi on itself. The simple lock strategy (lofi_lock) precludes this
80  *	because you'll be in lofi_ioctl, holding the lock when you open the
81  *	file, which, if it's lofi, will grab lofi_lock. We prevent this for
82  *	now, though not using ddi_soft_state(9F) would make it possible to
83  *	do. Though it would still be silly.
84  *
85  * Interesting things to do:
86  *
87  *	Allow multiple files for each device. A poor-man's metadisk, basically.
88  *
89  *	Pass-through ioctls on block devices. You can (though it's not
90  *	documented), give lofi a block device as a file name. Then we shouldn't
91  *	need to fake a geometry, however, it may be relevant if you're replacing
92  *	metadisk, or using lofi to get crypto.
93  *	It makes sense to do lofiadm -c aes -a /dev/dsk/c0t0d0s4 /dev/lofi/1
94  *	and then in /etc/vfstab have an entry for /dev/lofi/1 as /export/home.
95  *	In fact this even makes sense if you have lofi "above" metadisk.
96  *
97  * Encryption:
98  *	Each lofi device can have its own symmetric key and cipher.
99  *	They are passed to us by lofiadm(1m) in the correct format for use
100  *	with the misc/kcf crypto_* routines.
101  *
102  *	Each block has its own IV, that is calculated in lofi_blk_mech(), based
103  *	on the "master" key held in the lsp and the block number of the buffer.
104  */
105 
106 #include <sys/types.h>
107 #include <netinet/in.h>
108 #include <sys/sysmacros.h>
109 #include <sys/uio.h>
110 #include <sys/kmem.h>
111 #include <sys/cred.h>
112 #include <sys/mman.h>
113 #include <sys/errno.h>
114 #include <sys/aio_req.h>
115 #include <sys/stat.h>
116 #include <sys/file.h>
117 #include <sys/modctl.h>
118 #include <sys/conf.h>
119 #include <sys/debug.h>
120 #include <sys/vnode.h>
121 #include <sys/lofi.h>
122 #include <sys/fcntl.h>
123 #include <sys/pathname.h>
124 #include <sys/filio.h>
125 #include <sys/fdio.h>
126 #include <sys/open.h>
127 #include <sys/disp.h>
128 #include <vm/seg_map.h>
129 #include <sys/ddi.h>
130 #include <sys/sunddi.h>
131 #include <sys/zmod.h>
132 #include <sys/crypto/common.h>
133 #include <sys/crypto/api.h>
134 #include <LzmaDec.h>
135 
136 /*
137  * The basis for CRYOFF is derived from usr/src/uts/common/sys/fs/ufs_fs.h.
138  * Crypto metadata, if it exists, is located at the end of the boot block
139  * (BBOFF + BBSIZE, which is SBOFF).  The super block and everything after
140  * is offset by the size of the crypto metadata which is handled by
141  * lsp->ls_crypto_offset.
142  */
143 #define	CRYOFF	((off_t)8192)
144 
145 #define	NBLOCKS_PROP_NAME	"Nblocks"
146 #define	SIZE_PROP_NAME		"Size"
147 
148 #define	SETUP_C_DATA(cd, buf, len) 		\
149 	(cd).cd_format = CRYPTO_DATA_RAW;	\
150 	(cd).cd_offset = 0;			\
151 	(cd).cd_miscdata = NULL;		\
152 	(cd).cd_length = (len);			\
153 	(cd).cd_raw.iov_base = (buf);		\
154 	(cd).cd_raw.iov_len = (len);
155 
156 #define	UIO_CHECK(uio)	\
157 	if (((uio)->uio_loffset % DEV_BSIZE) != 0 || \
158 	    ((uio)->uio_resid % DEV_BSIZE) != 0) { \
159 		return (EINVAL); \
160 	}
161 
162 static dev_info_t *lofi_dip = NULL;
163 static void *lofi_statep = NULL;
164 static kmutex_t lofi_lock;		/* state lock */
165 
166 /*
167  * Because lofi_taskq_nthreads limits the actual swamping of the device, the
168  * maxalloc parameter (lofi_taskq_maxalloc) should be tuned conservatively
169  * high.  If we want to be assured that the underlying device is always busy,
170  * we must be sure that the number of bytes enqueued when the number of
171  * enqueued tasks exceeds maxalloc is sufficient to keep the device busy for
172  * the duration of the sleep time in taskq_ent_alloc().  That is, lofi should
173  * set maxalloc to be the maximum throughput (in bytes per second) of the
174  * underlying device divided by the minimum I/O size.  We assume a realistic
175  * maximum throughput of one hundred megabytes per second; we set maxalloc on
176  * the lofi task queue to be 104857600 divided by DEV_BSIZE.
177  */
178 static int lofi_taskq_maxalloc = 104857600 / DEV_BSIZE;
179 static int lofi_taskq_nthreads = 4;	/* # of taskq threads per device */
180 
181 uint32_t lofi_max_files = LOFI_MAX_FILES;
182 const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC;
183 
184 /*
185  * To avoid decompressing data in a compressed segment multiple times
186  * when accessing small parts of a segment's data, we cache and reuse
187  * the uncompressed segment's data.
188  *
189  * A single cached segment is sufficient to avoid lots of duplicate
190  * segment decompress operations. A small cache size also reduces the
191  * memory footprint.
192  *
193  * lofi_max_comp_cache is the maximum number of decompressed data segments
194  * cached for each compressed lofi image. It can be set to 0 to disable
195  * caching.
196  */
197 
198 uint32_t lofi_max_comp_cache = 1;
199 
200 static int gzip_decompress(void *src, size_t srclen, void *dst,
201 	size_t *destlen, int level);
202 
203 static int lzma_decompress(void *src, size_t srclen, void *dst,
204 	size_t *dstlen, int level);
205 
206 lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
207 	{gzip_decompress,	NULL,	6,	"gzip"}, /* default */
208 	{gzip_decompress,	NULL,	6,	"gzip-6"},
209 	{gzip_decompress,	NULL,	9,	"gzip-9"},
210 	{lzma_decompress,	NULL,	0,	"lzma"}
211 };
212 
213 /*ARGSUSED*/
214 static void
215 *SzAlloc(void *p, size_t size)
216 {
217 	return (kmem_alloc(size, KM_SLEEP));
218 }
219 
220 /*ARGSUSED*/
221 static void
222 SzFree(void *p, void *address, size_t size)
223 {
224 	kmem_free(address, size);
225 }
226 
227 static ISzAlloc g_Alloc = { SzAlloc, SzFree };
228 
229 /*
230  * Free data referenced by the linked list of cached uncompressed
231  * segments.
232  */
233 static void
234 lofi_free_comp_cache(struct lofi_state *lsp)
235 {
236 	struct lofi_comp_cache *lc;
237 
238 	while ((lc = list_remove_head(&lsp->ls_comp_cache)) != NULL) {
239 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
240 		kmem_free(lc, sizeof (struct lofi_comp_cache));
241 		lsp->ls_comp_cache_count--;
242 	}
243 	ASSERT(lsp->ls_comp_cache_count == 0);
244 }
245 
246 static int
247 lofi_busy(void)
248 {
249 	minor_t	minor;
250 
251 	/*
252 	 * We need to make sure no mappings exist - mod_remove won't
253 	 * help because the device isn't open.
254 	 */
255 	mutex_enter(&lofi_lock);
256 	for (minor = 1; minor <= lofi_max_files; minor++) {
257 		if (ddi_get_soft_state(lofi_statep, minor) != NULL) {
258 			mutex_exit(&lofi_lock);
259 			return (EBUSY);
260 		}
261 	}
262 	mutex_exit(&lofi_lock);
263 	return (0);
264 }
265 
266 static int
267 is_opened(struct lofi_state *lsp)
268 {
269 	ASSERT(mutex_owned(&lofi_lock));
270 	return (lsp->ls_chr_open || lsp->ls_blk_open || lsp->ls_lyr_open_count);
271 }
272 
273 static int
274 mark_opened(struct lofi_state *lsp, int otyp)
275 {
276 	ASSERT(mutex_owned(&lofi_lock));
277 	switch (otyp) {
278 	case OTYP_CHR:
279 		lsp->ls_chr_open = 1;
280 		break;
281 	case OTYP_BLK:
282 		lsp->ls_blk_open = 1;
283 		break;
284 	case OTYP_LYR:
285 		lsp->ls_lyr_open_count++;
286 		break;
287 	default:
288 		return (-1);
289 	}
290 	return (0);
291 }
292 
293 static void
294 mark_closed(struct lofi_state *lsp, int otyp)
295 {
296 	ASSERT(mutex_owned(&lofi_lock));
297 	switch (otyp) {
298 	case OTYP_CHR:
299 		lsp->ls_chr_open = 0;
300 		break;
301 	case OTYP_BLK:
302 		lsp->ls_blk_open = 0;
303 		break;
304 	case OTYP_LYR:
305 		lsp->ls_lyr_open_count--;
306 		break;
307 	default:
308 		break;
309 	}
310 }
311 
312 static void
313 lofi_free_crypto(struct lofi_state *lsp)
314 {
315 	ASSERT(mutex_owned(&lofi_lock));
316 
317 	if (lsp->ls_crypto_enabled) {
318 		/*
319 		 * Clean up the crypto state so that it doesn't hang around
320 		 * in memory after we are done with it.
321 		 */
322 		bzero(lsp->ls_key.ck_data,
323 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
324 		kmem_free(lsp->ls_key.ck_data,
325 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
326 		lsp->ls_key.ck_data = NULL;
327 		lsp->ls_key.ck_length = 0;
328 
329 		if (lsp->ls_mech.cm_param != NULL) {
330 			kmem_free(lsp->ls_mech.cm_param,
331 			    lsp->ls_mech.cm_param_len);
332 			lsp->ls_mech.cm_param = NULL;
333 			lsp->ls_mech.cm_param_len = 0;
334 		}
335 
336 		if (lsp->ls_iv_mech.cm_param != NULL) {
337 			kmem_free(lsp->ls_iv_mech.cm_param,
338 			    lsp->ls_iv_mech.cm_param_len);
339 			lsp->ls_iv_mech.cm_param = NULL;
340 			lsp->ls_iv_mech.cm_param_len = 0;
341 		}
342 
343 		mutex_destroy(&lsp->ls_crypto_lock);
344 	}
345 }
346 
347 static void
348 lofi_free_handle(dev_t dev, minor_t minor, struct lofi_state *lsp,
349     cred_t *credp)
350 {
351 	dev_t	newdev;
352 	char	namebuf[50];
353 
354 	ASSERT(mutex_owned(&lofi_lock));
355 
356 	lofi_free_crypto(lsp);
357 
358 	if (lsp->ls_vp) {
359 		(void) VOP_CLOSE(lsp->ls_vp, lsp->ls_openflag,
360 		    1, 0, credp, NULL);
361 		VN_RELE(lsp->ls_vp);
362 		lsp->ls_vp = NULL;
363 	}
364 
365 	newdev = makedevice(getmajor(dev), minor);
366 	(void) ddi_prop_remove(newdev, lofi_dip, SIZE_PROP_NAME);
367 	(void) ddi_prop_remove(newdev, lofi_dip, NBLOCKS_PROP_NAME);
368 
369 	(void) snprintf(namebuf, sizeof (namebuf), "%d", minor);
370 	ddi_remove_minor_node(lofi_dip, namebuf);
371 	(void) snprintf(namebuf, sizeof (namebuf), "%d,raw", minor);
372 	ddi_remove_minor_node(lofi_dip, namebuf);
373 
374 	kmem_free(lsp->ls_filename, lsp->ls_filename_sz);
375 	taskq_destroy(lsp->ls_taskq);
376 	if (lsp->ls_kstat) {
377 		kstat_delete(lsp->ls_kstat);
378 		mutex_destroy(&lsp->ls_kstat_lock);
379 	}
380 
381 	/*
382 	 * Free cached decompressed segment data
383 	 */
384 	lofi_free_comp_cache(lsp);
385 	list_destroy(&lsp->ls_comp_cache);
386 	mutex_destroy(&lsp->ls_comp_cache_lock);
387 
388 	if (lsp->ls_uncomp_seg_sz > 0) {
389 		kmem_free(lsp->ls_comp_index_data, lsp->ls_comp_index_data_sz);
390 		lsp->ls_uncomp_seg_sz = 0;
391 	}
392 
393 	mutex_destroy(&lsp->ls_vp_lock);
394 
395 	ddi_soft_state_free(lofi_statep, minor);
396 }
397 
398 /*ARGSUSED*/
399 static int
400 lofi_open(dev_t *devp, int flag, int otyp, struct cred *credp)
401 {
402 	minor_t	minor;
403 	struct lofi_state *lsp;
404 
405 	mutex_enter(&lofi_lock);
406 	minor = getminor(*devp);
407 	if (minor == 0) {
408 		/* master control device */
409 		/* must be opened exclusively */
410 		if (((flag & FEXCL) != FEXCL) || (otyp != OTYP_CHR)) {
411 			mutex_exit(&lofi_lock);
412 			return (EINVAL);
413 		}
414 		lsp = ddi_get_soft_state(lofi_statep, 0);
415 		if (lsp == NULL) {
416 			mutex_exit(&lofi_lock);
417 			return (ENXIO);
418 		}
419 		if (is_opened(lsp)) {
420 			mutex_exit(&lofi_lock);
421 			return (EBUSY);
422 		}
423 		(void) mark_opened(lsp, OTYP_CHR);
424 		mutex_exit(&lofi_lock);
425 		return (0);
426 	}
427 
428 	/* otherwise, the mapping should already exist */
429 	lsp = ddi_get_soft_state(lofi_statep, minor);
430 	if (lsp == NULL) {
431 		mutex_exit(&lofi_lock);
432 		return (EINVAL);
433 	}
434 
435 	if (lsp->ls_vp == NULL) {
436 		mutex_exit(&lofi_lock);
437 		return (ENXIO);
438 	}
439 
440 	if (mark_opened(lsp, otyp) == -1) {
441 		mutex_exit(&lofi_lock);
442 		return (EINVAL);
443 	}
444 
445 	mutex_exit(&lofi_lock);
446 	return (0);
447 }
448 
449 /*ARGSUSED*/
450 static int
451 lofi_close(dev_t dev, int flag, int otyp, struct cred *credp)
452 {
453 	minor_t	minor;
454 	struct lofi_state *lsp;
455 
456 	mutex_enter(&lofi_lock);
457 	minor = getminor(dev);
458 	lsp = ddi_get_soft_state(lofi_statep, minor);
459 	if (lsp == NULL) {
460 		mutex_exit(&lofi_lock);
461 		return (EINVAL);
462 	}
463 	mark_closed(lsp, otyp);
464 
465 	/*
466 	 * If we forcibly closed the underlying device (li_force), or
467 	 * asked for cleanup (li_cleanup), finish up if we're the last
468 	 * out of the door.
469 	 */
470 	if (minor != 0 && !is_opened(lsp) &&
471 	    (lsp->ls_cleanup || lsp->ls_vp == NULL))
472 		lofi_free_handle(dev, minor, lsp, credp);
473 
474 	mutex_exit(&lofi_lock);
475 	return (0);
476 }
477 
478 /*
479  * Sets the mechanism's initialization vector (IV) if one is needed.
480  * The IV is computed from the data block number.  lsp->ls_mech is
481  * altered so that:
482  *	lsp->ls_mech.cm_param_len is set to the IV len.
483  *	lsp->ls_mech.cm_param is set to the IV.
484  */
485 static int
486 lofi_blk_mech(struct lofi_state *lsp, longlong_t lblkno)
487 {
488 	int	ret;
489 	crypto_data_t cdata;
490 	char	*iv;
491 	size_t	iv_len;
492 	size_t	min;
493 	void	*data;
494 	size_t	datasz;
495 
496 	ASSERT(mutex_owned(&lsp->ls_crypto_lock));
497 
498 	if (lsp == NULL)
499 		return (CRYPTO_DEVICE_ERROR);
500 
501 	/* lsp->ls_mech.cm_param{_len} has already been set for static iv */
502 	if (lsp->ls_iv_type == IVM_NONE) {
503 		return (CRYPTO_SUCCESS);
504 	}
505 
506 	/*
507 	 * if kmem already alloced from previous call and it's the same size
508 	 * we need now, just recycle it; allocate new kmem only if we have to
509 	 */
510 	if (lsp->ls_mech.cm_param == NULL ||
511 	    lsp->ls_mech.cm_param_len != lsp->ls_iv_len) {
512 		iv_len = lsp->ls_iv_len;
513 		iv = kmem_zalloc(iv_len, KM_SLEEP);
514 	} else {
515 		iv_len = lsp->ls_mech.cm_param_len;
516 		iv = lsp->ls_mech.cm_param;
517 		bzero(iv, iv_len);
518 	}
519 
520 	switch (lsp->ls_iv_type) {
521 	case IVM_ENC_BLKNO:
522 		/* iv is not static, lblkno changes each time */
523 		data = &lblkno;
524 		datasz = sizeof (lblkno);
525 		break;
526 	default:
527 		data = 0;
528 		datasz = 0;
529 		break;
530 	}
531 
532 	/*
533 	 * write blkno into the iv buffer padded on the left in case
534 	 * blkno ever grows bigger than its current longlong_t size
535 	 * or a variation other than blkno is used for the iv data
536 	 */
537 	min = MIN(datasz, iv_len);
538 	bcopy(data, iv + (iv_len - min), min);
539 
540 	/* encrypt the data in-place to get the IV */
541 	SETUP_C_DATA(cdata, iv, iv_len);
542 
543 	ret = crypto_encrypt(&lsp->ls_iv_mech, &cdata, &lsp->ls_key,
544 	    NULL, NULL, NULL);
545 	if (ret != CRYPTO_SUCCESS) {
546 		cmn_err(CE_WARN, "failed to create iv for block %lld: (0x%x)",
547 		    lblkno, ret);
548 		if (lsp->ls_mech.cm_param != iv)
549 			kmem_free(iv, iv_len);
550 
551 		return (ret);
552 	}
553 
554 	/* clean up the iv from the last computation */
555 	if (lsp->ls_mech.cm_param != NULL && lsp->ls_mech.cm_param != iv)
556 		kmem_free(lsp->ls_mech.cm_param, lsp->ls_mech.cm_param_len);
557 
558 	lsp->ls_mech.cm_param_len = iv_len;
559 	lsp->ls_mech.cm_param = iv;
560 
561 	return (CRYPTO_SUCCESS);
562 }
563 
564 /*
565  * Performs encryption and decryption of a chunk of data of size "len",
566  * one DEV_BSIZE block at a time.  "len" is assumed to be a multiple of
567  * DEV_BSIZE.
568  */
569 static int
570 lofi_crypto(struct lofi_state *lsp, struct buf *bp, caddr_t plaintext,
571     caddr_t ciphertext, size_t len, boolean_t op_encrypt)
572 {
573 	crypto_data_t cdata;
574 	crypto_data_t wdata;
575 	int ret;
576 	longlong_t lblkno = bp->b_lblkno;
577 
578 	mutex_enter(&lsp->ls_crypto_lock);
579 
580 	/*
581 	 * though we could encrypt/decrypt entire "len" chunk of data, we need
582 	 * to break it into DEV_BSIZE pieces to capture blkno incrementing
583 	 */
584 	SETUP_C_DATA(cdata, plaintext, len);
585 	cdata.cd_length = DEV_BSIZE;
586 	if (ciphertext != NULL) {		/* not in-place crypto */
587 		SETUP_C_DATA(wdata, ciphertext, len);
588 		wdata.cd_length = DEV_BSIZE;
589 	}
590 
591 	do {
592 		ret = lofi_blk_mech(lsp, lblkno);
593 		if (ret != CRYPTO_SUCCESS)
594 			continue;
595 
596 		if (op_encrypt) {
597 			ret = crypto_encrypt(&lsp->ls_mech, &cdata,
598 			    &lsp->ls_key, NULL,
599 			    ((ciphertext != NULL) ? &wdata : NULL), NULL);
600 		} else {
601 			ret = crypto_decrypt(&lsp->ls_mech, &cdata,
602 			    &lsp->ls_key, NULL,
603 			    ((ciphertext != NULL) ? &wdata : NULL), NULL);
604 		}
605 
606 		cdata.cd_offset += DEV_BSIZE;
607 		if (ciphertext != NULL)
608 			wdata.cd_offset += DEV_BSIZE;
609 		lblkno++;
610 	} while (ret == CRYPTO_SUCCESS && cdata.cd_offset < len);
611 
612 	mutex_exit(&lsp->ls_crypto_lock);
613 
614 	if (ret != CRYPTO_SUCCESS) {
615 		cmn_err(CE_WARN, "%s failed for block %lld:  (0x%x)",
616 		    op_encrypt ? "crypto_encrypt()" : "crypto_decrypt()",
617 		    lblkno, ret);
618 	}
619 
620 	return (ret);
621 }
622 
623 #define	RDWR_RAW	1
624 #define	RDWR_BCOPY	2
625 
626 static int
627 lofi_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp,
628     struct lofi_state *lsp, size_t len, int method, caddr_t bcopy_locn)
629 {
630 	ssize_t resid;
631 	int isread;
632 	int error;
633 
634 	/*
635 	 * Handles reads/writes for both plain and encrypted lofi
636 	 * Note:  offset is already shifted by lsp->ls_crypto_offset
637 	 * when it gets here.
638 	 */
639 
640 	isread = bp->b_flags & B_READ;
641 	if (isread) {
642 		if (method == RDWR_BCOPY) {
643 			/* DO NOT update bp->b_resid for bcopy */
644 			bcopy(bcopy_locn, bufaddr, len);
645 			error = 0;
646 		} else {		/* RDWR_RAW */
647 			error = vn_rdwr(UIO_READ, lsp->ls_vp, bufaddr, len,
648 			    offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred,
649 			    &resid);
650 			bp->b_resid = resid;
651 		}
652 		if (lsp->ls_crypto_enabled && error == 0) {
653 			if (lofi_crypto(lsp, bp, bufaddr, NULL, len,
654 			    B_FALSE) != CRYPTO_SUCCESS) {
655 				/*
656 				 * XXX: original code didn't set residual
657 				 * back to len because no error was expected
658 				 * from bcopy() if encryption is not enabled
659 				 */
660 				if (method != RDWR_BCOPY)
661 					bp->b_resid = len;
662 				error = EIO;
663 			}
664 		}
665 		return (error);
666 	} else {
667 		void *iobuf = bufaddr;
668 
669 		if (lsp->ls_crypto_enabled) {
670 			/* don't do in-place crypto to keep bufaddr intact */
671 			iobuf = kmem_alloc(len, KM_SLEEP);
672 			if (lofi_crypto(lsp, bp, bufaddr, iobuf, len,
673 			    B_TRUE) != CRYPTO_SUCCESS) {
674 				kmem_free(iobuf, len);
675 				if (method != RDWR_BCOPY)
676 					bp->b_resid = len;
677 				return (EIO);
678 			}
679 		}
680 		if (method == RDWR_BCOPY) {
681 			/* DO NOT update bp->b_resid for bcopy */
682 			bcopy(iobuf, bcopy_locn, len);
683 			error = 0;
684 		} else {		/* RDWR_RAW */
685 			error = vn_rdwr(UIO_WRITE, lsp->ls_vp, iobuf, len,
686 			    offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred,
687 			    &resid);
688 			bp->b_resid = resid;
689 		}
690 		if (lsp->ls_crypto_enabled) {
691 			kmem_free(iobuf, len);
692 		}
693 		return (error);
694 	}
695 }
696 
697 static int
698 lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp,
699     struct lofi_state *lsp)
700 {
701 	int error;
702 	offset_t alignedoffset, mapoffset;
703 	size_t	xfersize;
704 	int	isread;
705 	int	smflags;
706 	caddr_t	mapaddr;
707 	size_t	len;
708 	enum seg_rw srw;
709 	int	save_error;
710 
711 	/*
712 	 * Note:  offset is already shifted by lsp->ls_crypto_offset
713 	 * when it gets here.
714 	 */
715 	if (lsp->ls_crypto_enabled)
716 		ASSERT(lsp->ls_vp_comp_size == lsp->ls_vp_size);
717 
718 	/*
719 	 * segmap always gives us an 8K (MAXBSIZE) chunk, aligned on
720 	 * an 8K boundary, but the buf transfer address may not be
721 	 * aligned on more than a 512-byte boundary (we don't enforce
722 	 * that even though we could). This matters since the initial
723 	 * part of the transfer may not start at offset 0 within the
724 	 * segmap'd chunk. So we have to compensate for that with
725 	 * 'mapoffset'. Subsequent chunks always start off at the
726 	 * beginning, and the last is capped by b_resid
727 	 *
728 	 * Visually, where "|" represents page map boundaries:
729 	 *   alignedoffset (mapaddr begins at this segmap boundary)
730 	 *    |   offset (from beginning of file)
731 	 *    |    |	   len
732 	 *    v    v	    v
733 	 * ===|====X========|====...======|========X====|====
734 	 *	   /-------------...---------------/
735 	 *		^ bp->b_bcount/bp->b_resid at start
736 	 *    /----/--------/----...------/--------/
737 	 *	^	^	^   ^		^
738 	 *	|	|	|   |		nth xfersize (<= MAXBSIZE)
739 	 *	|	|	2nd thru n-1st xfersize (= MAXBSIZE)
740 	 *	|	1st xfersize (<= MAXBSIZE)
741 	 *    mapoffset (offset into 1st segmap, non-0 1st time, 0 thereafter)
742 	 *
743 	 * Notes: "alignedoffset" is "offset" rounded down to nearest
744 	 * MAXBSIZE boundary.  "len" is next page boundary of size
745 	 * PAGESIZE after "alignedoffset".
746 	 */
747 	mapoffset = offset & MAXBOFFSET;
748 	alignedoffset = offset - mapoffset;
749 	bp->b_resid = bp->b_bcount;
750 	isread = bp->b_flags & B_READ;
751 	srw = isread ? S_READ : S_WRITE;
752 	do {
753 		xfersize = MIN(lsp->ls_vp_comp_size - offset,
754 		    MIN(MAXBSIZE - mapoffset, bp->b_resid));
755 		len = roundup(mapoffset + xfersize, PAGESIZE);
756 		mapaddr = segmap_getmapflt(segkmap, lsp->ls_vp,
757 		    alignedoffset, MAXBSIZE, 1, srw);
758 		/*
759 		 * Now fault in the pages. This lets us check
760 		 * for errors before we reference mapaddr and
761 		 * try to resolve the fault in bcopy (which would
762 		 * panic instead). And this can easily happen,
763 		 * particularly if you've lofi'd a file over NFS
764 		 * and someone deletes the file on the server.
765 		 */
766 		error = segmap_fault(kas.a_hat, segkmap, mapaddr,
767 		    len, F_SOFTLOCK, srw);
768 		if (error) {
769 			(void) segmap_release(segkmap, mapaddr, 0);
770 			if (FC_CODE(error) == FC_OBJERR)
771 				error = FC_ERRNO(error);
772 			else
773 				error = EIO;
774 			break;
775 		}
776 		/* error may be non-zero for encrypted lofi */
777 		error = lofi_rdwr(bufaddr, 0, bp, lsp, xfersize,
778 		    RDWR_BCOPY, mapaddr + mapoffset);
779 		if (error == 0) {
780 			bp->b_resid -= xfersize;
781 			bufaddr += xfersize;
782 			offset += xfersize;
783 		}
784 		smflags = 0;
785 		if (isread) {
786 			smflags |= SM_FREE;
787 			/*
788 			 * If we're reading an entire page starting
789 			 * at a page boundary, there's a good chance
790 			 * we won't need it again. Put it on the
791 			 * head of the freelist.
792 			 */
793 			if (mapoffset == 0 && xfersize == MAXBSIZE)
794 				smflags |= SM_DONTNEED;
795 		} else {
796 			/*
797 			 * Write back good pages, it is okay to
798 			 * always release asynchronous here as we'll
799 			 * follow with VOP_FSYNC for B_SYNC buffers.
800 			 */
801 			if (error == 0)
802 				smflags |= SM_WRITE | SM_ASYNC;
803 		}
804 		(void) segmap_fault(kas.a_hat, segkmap, mapaddr,
805 		    len, F_SOFTUNLOCK, srw);
806 		save_error = segmap_release(segkmap, mapaddr, smflags);
807 		if (error == 0)
808 			error = save_error;
809 		/* only the first map may start partial */
810 		mapoffset = 0;
811 		alignedoffset += MAXBSIZE;
812 	} while ((error == 0) && (bp->b_resid > 0) &&
813 	    (offset < lsp->ls_vp_comp_size));
814 
815 	return (error);
816 }
817 
818 /*
819  * Check if segment seg_index is present in the decompressed segment
820  * data cache.
821  *
822  * Returns a pointer to the decompressed segment data cache entry if
823  * found, and NULL when decompressed data for this segment is not yet
824  * cached.
825  */
826 static struct lofi_comp_cache *
827 lofi_find_comp_data(struct lofi_state *lsp, uint64_t seg_index)
828 {
829 	struct lofi_comp_cache *lc;
830 
831 	ASSERT(mutex_owned(&lsp->ls_comp_cache_lock));
832 
833 	for (lc = list_head(&lsp->ls_comp_cache); lc != NULL;
834 	    lc = list_next(&lsp->ls_comp_cache, lc)) {
835 		if (lc->lc_index == seg_index) {
836 			/*
837 			 * Decompressed segment data was found in the
838 			 * cache.
839 			 *
840 			 * The cache uses an LRU replacement strategy;
841 			 * move the entry to head of list.
842 			 */
843 			list_remove(&lsp->ls_comp_cache, lc);
844 			list_insert_head(&lsp->ls_comp_cache, lc);
845 			return (lc);
846 		}
847 	}
848 	return (NULL);
849 }
850 
851 /*
852  * Add the data for a decompressed segment at segment index
853  * seg_index to the cache of the decompressed segments.
854  *
855  * Returns a pointer to the cache element structure in case
856  * the data was added to the cache; returns NULL when the data
857  * wasn't cached.
858  */
859 static struct lofi_comp_cache *
860 lofi_add_comp_data(struct lofi_state *lsp, uint64_t seg_index,
861     uchar_t *data)
862 {
863 	struct lofi_comp_cache *lc;
864 
865 	ASSERT(mutex_owned(&lsp->ls_comp_cache_lock));
866 
867 	while (lsp->ls_comp_cache_count > lofi_max_comp_cache) {
868 		lc = list_remove_tail(&lsp->ls_comp_cache);
869 		ASSERT(lc != NULL);
870 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
871 		kmem_free(lc, sizeof (struct lofi_comp_cache));
872 		lsp->ls_comp_cache_count--;
873 	}
874 
875 	/*
876 	 * Do not cache when disabled by tunable variable
877 	 */
878 	if (lofi_max_comp_cache == 0)
879 		return (NULL);
880 
881 	/*
882 	 * When the cache has not yet reached the maximum allowed
883 	 * number of segments, allocate a new cache element.
884 	 * Otherwise the cache is full; reuse the last list element
885 	 * (LRU) for caching the decompressed segment data.
886 	 *
887 	 * The cache element for the new decompressed segment data is
888 	 * added to the head of the list.
889 	 */
890 	if (lsp->ls_comp_cache_count < lofi_max_comp_cache) {
891 		lc = kmem_alloc(sizeof (struct lofi_comp_cache), KM_SLEEP);
892 		lc->lc_data = NULL;
893 		list_insert_head(&lsp->ls_comp_cache, lc);
894 		lsp->ls_comp_cache_count++;
895 	} else {
896 		lc = list_remove_tail(&lsp->ls_comp_cache);
897 		if (lc == NULL)
898 			return (NULL);
899 		list_insert_head(&lsp->ls_comp_cache, lc);
900 	}
901 
902 	/*
903 	 * Free old uncompressed segment data when reusing a cache
904 	 * entry.
905 	 */
906 	if (lc->lc_data != NULL)
907 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
908 
909 	lc->lc_data = data;
910 	lc->lc_index = seg_index;
911 	return (lc);
912 }
913 
914 
915 /*ARGSUSED*/
916 static int
917 gzip_decompress(void *src, size_t srclen, void *dst,
918     size_t *dstlen, int level)
919 {
920 	ASSERT(*dstlen >= srclen);
921 
922 	if (z_uncompress(dst, dstlen, src, srclen) != Z_OK)
923 		return (-1);
924 	return (0);
925 }
926 
927 #define	LZMA_HEADER_SIZE	(LZMA_PROPS_SIZE + 8)
928 /*ARGSUSED*/
929 static int
930 lzma_decompress(void *src, size_t srclen, void *dst,
931 	size_t *dstlen, int level)
932 {
933 	size_t insizepure;
934 	void *actual_src;
935 	ELzmaStatus status;
936 
937 	insizepure = srclen - LZMA_HEADER_SIZE;
938 	actual_src = (void *)((Byte *)src + LZMA_HEADER_SIZE);
939 
940 	if (LzmaDecode((Byte *)dst, (size_t *)dstlen,
941 	    (const Byte *)actual_src, &insizepure,
942 	    (const Byte *)src, LZMA_PROPS_SIZE, LZMA_FINISH_ANY, &status,
943 	    &g_Alloc) != SZ_OK) {
944 		return (-1);
945 	}
946 	return (0);
947 }
948 
949 /*
950  * This is basically what strategy used to be before we found we
951  * needed task queues.
952  */
953 static void
954 lofi_strategy_task(void *arg)
955 {
956 	struct buf *bp = (struct buf *)arg;
957 	int error;
958 	int syncflag = 0;
959 	struct lofi_state *lsp;
960 	offset_t offset;
961 	caddr_t	bufaddr;
962 	size_t	len;
963 	size_t	xfersize;
964 	boolean_t bufinited = B_FALSE;
965 
966 	lsp = ddi_get_soft_state(lofi_statep, getminor(bp->b_edev));
967 	if (lsp == NULL) {
968 		error = ENXIO;
969 		goto errout;
970 	}
971 	if (lsp->ls_kstat) {
972 		mutex_enter(lsp->ls_kstat->ks_lock);
973 		kstat_waitq_to_runq(KSTAT_IO_PTR(lsp->ls_kstat));
974 		mutex_exit(lsp->ls_kstat->ks_lock);
975 	}
976 	bp_mapin(bp);
977 	bufaddr = bp->b_un.b_addr;
978 	offset = bp->b_lblkno * DEV_BSIZE;	/* offset within file */
979 	if (lsp->ls_crypto_enabled) {
980 		/* encrypted data really begins after crypto header */
981 		offset += lsp->ls_crypto_offset;
982 	}
983 	len = bp->b_bcount;
984 	bufinited = B_TRUE;
985 
986 	if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) {
987 		error = EIO;
988 		goto errout;
989 	}
990 
991 	/*
992 	 * If we're writing and the buffer was not B_ASYNC
993 	 * we'll follow up with a VOP_FSYNC() to force any
994 	 * asynchronous I/O to stable storage.
995 	 */
996 	if (!(bp->b_flags & B_READ) && !(bp->b_flags & B_ASYNC))
997 		syncflag = FSYNC;
998 
999 	/*
1000 	 * We used to always use vn_rdwr here, but we cannot do that because
1001 	 * we might decide to read or write from the the underlying
1002 	 * file during this call, which would be a deadlock because
1003 	 * we have the rw_lock. So instead we page, unless it's not
1004 	 * mapable or it's a character device or it's an encrypted lofi.
1005 	 */
1006 	if ((lsp->ls_vp->v_flag & VNOMAP) || (lsp->ls_vp->v_type == VCHR) ||
1007 	    lsp->ls_crypto_enabled) {
1008 		error = lofi_rdwr(bufaddr, offset, bp, lsp, len, RDWR_RAW,
1009 		    NULL);
1010 	} else if (lsp->ls_uncomp_seg_sz == 0) {
1011 		error = lofi_mapped_rdwr(bufaddr, offset, bp, lsp);
1012 	} else {
1013 		uchar_t *compressed_seg = NULL, *cmpbuf;
1014 		uchar_t *uncompressed_seg = NULL;
1015 		lofi_compress_info_t *li;
1016 		size_t oblkcount;
1017 		ulong_t seglen;
1018 		uint64_t sblkno, eblkno, cmpbytes;
1019 		uint64_t uncompressed_seg_index;
1020 		struct lofi_comp_cache *lc;
1021 		offset_t sblkoff, eblkoff;
1022 		u_offset_t salign, ealign;
1023 		u_offset_t sdiff;
1024 		uint32_t comp_data_sz;
1025 		uint64_t i;
1026 
1027 		/*
1028 		 * From here on we're dealing primarily with compressed files
1029 		 */
1030 		ASSERT(!lsp->ls_crypto_enabled);
1031 
1032 		/*
1033 		 * Compressed files can only be read from and
1034 		 * not written to
1035 		 */
1036 		if (!(bp->b_flags & B_READ)) {
1037 			bp->b_resid = bp->b_bcount;
1038 			error = EROFS;
1039 			goto done;
1040 		}
1041 
1042 		ASSERT(lsp->ls_comp_algorithm_index >= 0);
1043 		li = &lofi_compress_table[lsp->ls_comp_algorithm_index];
1044 		/*
1045 		 * Compute starting and ending compressed segment numbers
1046 		 * We use only bitwise operations avoiding division and
1047 		 * modulus because we enforce the compression segment size
1048 		 * to a power of 2
1049 		 */
1050 		sblkno = offset >> lsp->ls_comp_seg_shift;
1051 		sblkoff = offset & (lsp->ls_uncomp_seg_sz - 1);
1052 		eblkno = (offset + bp->b_bcount) >> lsp->ls_comp_seg_shift;
1053 		eblkoff = (offset + bp->b_bcount) & (lsp->ls_uncomp_seg_sz - 1);
1054 
1055 		/*
1056 		 * Check the decompressed segment cache.
1057 		 *
1058 		 * The cache is used only when the requested data
1059 		 * is within a segment. Requests that cross
1060 		 * segment boundaries bypass the cache.
1061 		 */
1062 		if (sblkno == eblkno ||
1063 		    (sblkno + 1 == eblkno && eblkoff == 0)) {
1064 			/*
1065 			 * Request doesn't cross a segment boundary,
1066 			 * now check the cache.
1067 			 */
1068 			mutex_enter(&lsp->ls_comp_cache_lock);
1069 			lc = lofi_find_comp_data(lsp, sblkno);
1070 			if (lc != NULL) {
1071 				/*
1072 				 * We've found the decompressed segment
1073 				 * data in the cache; reuse it.
1074 				 */
1075 				bcopy(lc->lc_data + sblkoff, bufaddr,
1076 				    bp->b_bcount);
1077 				mutex_exit(&lsp->ls_comp_cache_lock);
1078 				bp->b_resid = 0;
1079 				error = 0;
1080 				goto done;
1081 			}
1082 			mutex_exit(&lsp->ls_comp_cache_lock);
1083 		}
1084 
1085 		/*
1086 		 * Align start offset to block boundary for segmap
1087 		 */
1088 		salign = lsp->ls_comp_seg_index[sblkno];
1089 		sdiff = salign & (DEV_BSIZE - 1);
1090 		salign -= sdiff;
1091 		if (eblkno >= (lsp->ls_comp_index_sz - 1)) {
1092 			/*
1093 			 * We're dealing with the last segment of
1094 			 * the compressed file -- the size of this
1095 			 * segment *may not* be the same as the
1096 			 * segment size for the file
1097 			 */
1098 			eblkoff = (offset + bp->b_bcount) &
1099 			    (lsp->ls_uncomp_last_seg_sz - 1);
1100 			ealign = lsp->ls_vp_comp_size;
1101 		} else {
1102 			ealign = lsp->ls_comp_seg_index[eblkno + 1];
1103 		}
1104 
1105 		/*
1106 		 * Preserve original request paramaters
1107 		 */
1108 		oblkcount = bp->b_bcount;
1109 
1110 		/*
1111 		 * Assign the calculated parameters
1112 		 */
1113 		comp_data_sz = ealign - salign;
1114 		bp->b_bcount = comp_data_sz;
1115 
1116 		/*
1117 		 * Allocate fixed size memory blocks to hold compressed
1118 		 * segments and one uncompressed segment since we
1119 		 * uncompress segments one at a time
1120 		 */
1121 		compressed_seg = kmem_alloc(bp->b_bcount, KM_SLEEP);
1122 		uncompressed_seg = kmem_alloc(lsp->ls_uncomp_seg_sz, KM_SLEEP);
1123 		/*
1124 		 * Map in the calculated number of blocks
1125 		 */
1126 		error = lofi_mapped_rdwr((caddr_t)compressed_seg, salign,
1127 		    bp, lsp);
1128 
1129 		bp->b_bcount = oblkcount;
1130 		bp->b_resid = oblkcount;
1131 		if (error != 0)
1132 			goto done;
1133 
1134 		/*
1135 		 * We have the compressed blocks, now uncompress them
1136 		 */
1137 		cmpbuf = compressed_seg + sdiff;
1138 		for (i = sblkno; i <= eblkno; i++) {
1139 			ASSERT(i < lsp->ls_comp_index_sz - 1);
1140 
1141 			/*
1142 			 * The last segment is special in that it is
1143 			 * most likely not going to be the same
1144 			 * (uncompressed) size as the other segments.
1145 			 */
1146 			if (i == (lsp->ls_comp_index_sz - 2)) {
1147 				seglen = lsp->ls_uncomp_last_seg_sz;
1148 			} else {
1149 				seglen = lsp->ls_uncomp_seg_sz;
1150 			}
1151 
1152 			/*
1153 			 * Each of the segment index entries contains
1154 			 * the starting block number for that segment.
1155 			 * The number of compressed bytes in a segment
1156 			 * is thus the difference between the starting
1157 			 * block number of this segment and the starting
1158 			 * block number of the next segment.
1159 			 */
1160 			cmpbytes = lsp->ls_comp_seg_index[i + 1] -
1161 			    lsp->ls_comp_seg_index[i];
1162 
1163 			/*
1164 			 * The first byte in a compressed segment is a flag
1165 			 * that indicates whether this segment is compressed
1166 			 * at all
1167 			 */
1168 			if (*cmpbuf == UNCOMPRESSED) {
1169 				bcopy((cmpbuf + SEGHDR), uncompressed_seg,
1170 				    (cmpbytes - SEGHDR));
1171 			} else {
1172 				if (li->l_decompress((cmpbuf + SEGHDR),
1173 				    (cmpbytes - SEGHDR), uncompressed_seg,
1174 				    &seglen, li->l_level) != 0) {
1175 					error = EIO;
1176 					goto done;
1177 				}
1178 			}
1179 
1180 			uncompressed_seg_index = i;
1181 
1182 			/*
1183 			 * Determine how much uncompressed data we
1184 			 * have to copy and copy it
1185 			 */
1186 			xfersize = lsp->ls_uncomp_seg_sz - sblkoff;
1187 			if (i == eblkno)
1188 				xfersize -= (lsp->ls_uncomp_seg_sz - eblkoff);
1189 
1190 			bcopy((uncompressed_seg + sblkoff), bufaddr, xfersize);
1191 
1192 			cmpbuf += cmpbytes;
1193 			bufaddr += xfersize;
1194 			bp->b_resid -= xfersize;
1195 			sblkoff = 0;
1196 
1197 			if (bp->b_resid == 0)
1198 				break;
1199 		}
1200 
1201 		/*
1202 		 * Add the data for the last decopressed segment to
1203 		 * the cache.
1204 		 *
1205 		 * In case the uncompressed segment data was added to (and
1206 		 * is referenced by) the cache, make sure we don't free it
1207 		 * here.
1208 		 */
1209 		mutex_enter(&lsp->ls_comp_cache_lock);
1210 		if ((lc = lofi_add_comp_data(lsp, uncompressed_seg_index,
1211 		    uncompressed_seg)) != NULL) {
1212 			uncompressed_seg = NULL;
1213 		}
1214 		mutex_exit(&lsp->ls_comp_cache_lock);
1215 
1216 done:
1217 		if (compressed_seg != NULL)
1218 			kmem_free(compressed_seg, comp_data_sz);
1219 		if (uncompressed_seg != NULL)
1220 			kmem_free(uncompressed_seg, lsp->ls_uncomp_seg_sz);
1221 	} /* end of handling compressed files */
1222 
1223 	if ((error == 0) && (syncflag != 0))
1224 		error = VOP_FSYNC(lsp->ls_vp, syncflag, kcred, NULL);
1225 
1226 errout:
1227 	if (bufinited && lsp->ls_kstat) {
1228 		size_t n_done = bp->b_bcount - bp->b_resid;
1229 		kstat_io_t *kioptr;
1230 
1231 		mutex_enter(lsp->ls_kstat->ks_lock);
1232 		kioptr = KSTAT_IO_PTR(lsp->ls_kstat);
1233 		if (bp->b_flags & B_READ) {
1234 			kioptr->nread += n_done;
1235 			kioptr->reads++;
1236 		} else {
1237 			kioptr->nwritten += n_done;
1238 			kioptr->writes++;
1239 		}
1240 		kstat_runq_exit(kioptr);
1241 		mutex_exit(lsp->ls_kstat->ks_lock);
1242 	}
1243 
1244 	mutex_enter(&lsp->ls_vp_lock);
1245 	if (--lsp->ls_vp_iocount == 0)
1246 		cv_broadcast(&lsp->ls_vp_cv);
1247 	mutex_exit(&lsp->ls_vp_lock);
1248 
1249 	bioerror(bp, error);
1250 	biodone(bp);
1251 }
1252 
1253 static int
1254 lofi_strategy(struct buf *bp)
1255 {
1256 	struct lofi_state *lsp;
1257 	offset_t	offset;
1258 
1259 	/*
1260 	 * We cannot just do I/O here, because the current thread
1261 	 * _might_ end up back in here because the underlying filesystem
1262 	 * wants a buffer, which eventually gets into bio_recycle and
1263 	 * might call into lofi to write out a delayed-write buffer.
1264 	 * This is bad if the filesystem above lofi is the same as below.
1265 	 *
1266 	 * We could come up with a complex strategy using threads to
1267 	 * do the I/O asynchronously, or we could use task queues. task
1268 	 * queues were incredibly easy so they win.
1269 	 */
1270 	lsp = ddi_get_soft_state(lofi_statep, getminor(bp->b_edev));
1271 	if (lsp == NULL) {
1272 		bioerror(bp, ENXIO);
1273 		biodone(bp);
1274 		return (0);
1275 	}
1276 
1277 	mutex_enter(&lsp->ls_vp_lock);
1278 	if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) {
1279 		bioerror(bp, EIO);
1280 		biodone(bp);
1281 		mutex_exit(&lsp->ls_vp_lock);
1282 		return (0);
1283 	}
1284 
1285 	offset = bp->b_lblkno * DEV_BSIZE;	/* offset within file */
1286 	if (lsp->ls_crypto_enabled) {
1287 		/* encrypted data really begins after crypto header */
1288 		offset += lsp->ls_crypto_offset;
1289 	}
1290 	if (offset == lsp->ls_vp_size) {
1291 		/* EOF */
1292 		if ((bp->b_flags & B_READ) != 0) {
1293 			bp->b_resid = bp->b_bcount;
1294 			bioerror(bp, 0);
1295 		} else {
1296 			/* writes should fail */
1297 			bioerror(bp, ENXIO);
1298 		}
1299 		biodone(bp);
1300 		mutex_exit(&lsp->ls_vp_lock);
1301 		return (0);
1302 	}
1303 	if (offset > lsp->ls_vp_size) {
1304 		bioerror(bp, ENXIO);
1305 		biodone(bp);
1306 		mutex_exit(&lsp->ls_vp_lock);
1307 		return (0);
1308 	}
1309 	lsp->ls_vp_iocount++;
1310 	mutex_exit(&lsp->ls_vp_lock);
1311 
1312 	if (lsp->ls_kstat) {
1313 		mutex_enter(lsp->ls_kstat->ks_lock);
1314 		kstat_waitq_enter(KSTAT_IO_PTR(lsp->ls_kstat));
1315 		mutex_exit(lsp->ls_kstat->ks_lock);
1316 	}
1317 	(void) taskq_dispatch(lsp->ls_taskq, lofi_strategy_task, bp, KM_SLEEP);
1318 	return (0);
1319 }
1320 
1321 /*ARGSUSED2*/
1322 static int
1323 lofi_read(dev_t dev, struct uio *uio, struct cred *credp)
1324 {
1325 	if (getminor(dev) == 0)
1326 		return (EINVAL);
1327 	UIO_CHECK(uio);
1328 	return (physio(lofi_strategy, NULL, dev, B_READ, minphys, uio));
1329 }
1330 
1331 /*ARGSUSED2*/
1332 static int
1333 lofi_write(dev_t dev, struct uio *uio, struct cred *credp)
1334 {
1335 	if (getminor(dev) == 0)
1336 		return (EINVAL);
1337 	UIO_CHECK(uio);
1338 	return (physio(lofi_strategy, NULL, dev, B_WRITE, minphys, uio));
1339 }
1340 
1341 /*ARGSUSED2*/
1342 static int
1343 lofi_aread(dev_t dev, struct aio_req *aio, struct cred *credp)
1344 {
1345 	if (getminor(dev) == 0)
1346 		return (EINVAL);
1347 	UIO_CHECK(aio->aio_uio);
1348 	return (aphysio(lofi_strategy, anocancel, dev, B_READ, minphys, aio));
1349 }
1350 
1351 /*ARGSUSED2*/
1352 static int
1353 lofi_awrite(dev_t dev, struct aio_req *aio, struct cred *credp)
1354 {
1355 	if (getminor(dev) == 0)
1356 		return (EINVAL);
1357 	UIO_CHECK(aio->aio_uio);
1358 	return (aphysio(lofi_strategy, anocancel, dev, B_WRITE, minphys, aio));
1359 }
1360 
1361 /*ARGSUSED*/
1362 static int
1363 lofi_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1364 {
1365 	switch (infocmd) {
1366 	case DDI_INFO_DEVT2DEVINFO:
1367 		*result = lofi_dip;
1368 		return (DDI_SUCCESS);
1369 	case DDI_INFO_DEVT2INSTANCE:
1370 		*result = 0;
1371 		return (DDI_SUCCESS);
1372 	}
1373 	return (DDI_FAILURE);
1374 }
1375 
1376 static int
1377 lofi_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
1378 {
1379 	int	error;
1380 
1381 	if (cmd != DDI_ATTACH)
1382 		return (DDI_FAILURE);
1383 	error = ddi_soft_state_zalloc(lofi_statep, 0);
1384 	if (error == DDI_FAILURE) {
1385 		return (DDI_FAILURE);
1386 	}
1387 	error = ddi_create_minor_node(dip, LOFI_CTL_NODE, S_IFCHR, 0,
1388 	    DDI_PSEUDO, NULL);
1389 	if (error == DDI_FAILURE) {
1390 		ddi_soft_state_free(lofi_statep, 0);
1391 		return (DDI_FAILURE);
1392 	}
1393 	/* driver handles kernel-issued IOCTLs */
1394 	if (ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
1395 	    DDI_KERNEL_IOCTL, NULL, 0) != DDI_PROP_SUCCESS) {
1396 		ddi_remove_minor_node(dip, NULL);
1397 		ddi_soft_state_free(lofi_statep, 0);
1398 		return (DDI_FAILURE);
1399 	}
1400 	lofi_dip = dip;
1401 	ddi_report_dev(dip);
1402 	return (DDI_SUCCESS);
1403 }
1404 
1405 static int
1406 lofi_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
1407 {
1408 	if (cmd != DDI_DETACH)
1409 		return (DDI_FAILURE);
1410 	if (lofi_busy())
1411 		return (DDI_FAILURE);
1412 	lofi_dip = NULL;
1413 	ddi_remove_minor_node(dip, NULL);
1414 	ddi_prop_remove_all(dip);
1415 	ddi_soft_state_free(lofi_statep, 0);
1416 	return (DDI_SUCCESS);
1417 }
1418 
1419 /*
1420  * With addition of encryption, be careful that encryption key is wiped before
1421  * kernel memory structures are freed, and also that key is not accidentally
1422  * passed out into userland structures.
1423  */
1424 static void
1425 free_lofi_ioctl(struct lofi_ioctl *klip)
1426 {
1427 	/* Make sure this encryption key doesn't stick around */
1428 	bzero(klip->li_key, sizeof (klip->li_key));
1429 	kmem_free(klip, sizeof (struct lofi_ioctl));
1430 }
1431 
1432 /*
1433  * These two just simplify the rest of the ioctls that need to copyin/out
1434  * the lofi_ioctl structure.
1435  */
1436 struct lofi_ioctl *
1437 copy_in_lofi_ioctl(const struct lofi_ioctl *ulip, int flag)
1438 {
1439 	struct lofi_ioctl *klip;
1440 	int	error;
1441 
1442 	klip = kmem_alloc(sizeof (struct lofi_ioctl), KM_SLEEP);
1443 	error = ddi_copyin(ulip, klip, sizeof (struct lofi_ioctl), flag);
1444 	if (error) {
1445 		free_lofi_ioctl(klip);
1446 		return (NULL);
1447 	}
1448 
1449 	/* make sure filename is always null-terminated */
1450 	klip->li_filename[MAXPATHLEN-1] = '\0';
1451 
1452 	/* validate minor number */
1453 	if (klip->li_minor > lofi_max_files) {
1454 		free_lofi_ioctl(klip);
1455 		cmn_err(CE_WARN, "attempt to map more than lofi_max_files (%d)",
1456 		    lofi_max_files);
1457 		return (NULL);
1458 	}
1459 	return (klip);
1460 }
1461 
1462 int
1463 copy_out_lofi_ioctl(const struct lofi_ioctl *klip, struct lofi_ioctl *ulip,
1464 	int flag)
1465 {
1466 	int	error;
1467 
1468 	/*
1469 	 * NOTE: Do NOT copy the crypto_key_t "back" to userland.
1470 	 * This ensures that an attacker can't trivially find the
1471 	 * key for a mapping just by issuing the ioctl.
1472 	 *
1473 	 * It can still be found by poking around in kmem with mdb(1),
1474 	 * but there is no point in making it easy when the info isn't
1475 	 * of any use in this direction anyway.
1476 	 *
1477 	 * Either way we don't actually have the raw key stored in
1478 	 * a form that we can get it anyway, since we just used it
1479 	 * to create a ctx template and didn't keep "the original".
1480 	 */
1481 	error = ddi_copyout(klip, ulip, sizeof (struct lofi_ioctl), flag);
1482 	if (error)
1483 		return (EFAULT);
1484 	return (0);
1485 }
1486 
1487 /*
1488  * Return the minor number 'filename' is mapped to, if it is.
1489  */
1490 static int
1491 file_to_minor(char *filename)
1492 {
1493 	minor_t	minor;
1494 	struct lofi_state *lsp;
1495 
1496 	ASSERT(mutex_owned(&lofi_lock));
1497 	for (minor = 1; minor <= lofi_max_files; minor++) {
1498 		lsp = ddi_get_soft_state(lofi_statep, minor);
1499 		if (lsp == NULL)
1500 			continue;
1501 		if (strcmp(lsp->ls_filename, filename) == 0)
1502 			return (minor);
1503 	}
1504 	return (0);
1505 }
1506 
1507 /*
1508  * lofiadm does some validation, but since Joe Random (or crashme) could
1509  * do our ioctls, we need to do some validation too.
1510  */
1511 static int
1512 valid_filename(const char *filename)
1513 {
1514 	static char *blkprefix = "/dev/" LOFI_BLOCK_NAME "/";
1515 	static char *charprefix = "/dev/" LOFI_CHAR_NAME "/";
1516 
1517 	/* must be absolute path */
1518 	if (filename[0] != '/')
1519 		return (0);
1520 	/* must not be lofi */
1521 	if (strncmp(filename, blkprefix, strlen(blkprefix)) == 0)
1522 		return (0);
1523 	if (strncmp(filename, charprefix, strlen(charprefix)) == 0)
1524 		return (0);
1525 	return (1);
1526 }
1527 
1528 /*
1529  * Fakes up a disk geometry, and one big partition, based on the size
1530  * of the file. This is needed because we allow newfs'ing the device,
1531  * and newfs will do several disk ioctls to figure out the geometry and
1532  * partition information. It uses that information to determine the parameters
1533  * to pass to mkfs. Geometry is pretty much irrelevant these days, but we
1534  * have to support it.
1535  */
1536 static void
1537 fake_disk_geometry(struct lofi_state *lsp)
1538 {
1539 	u_offset_t dsize = lsp->ls_vp_size - lsp->ls_crypto_offset;
1540 
1541 	/* dk_geom - see dkio(7I) */
1542 	/*
1543 	 * dkg_ncyl _could_ be set to one here (one big cylinder with gobs
1544 	 * of sectors), but that breaks programs like fdisk which want to
1545 	 * partition a disk by cylinder. With one cylinder, you can't create
1546 	 * an fdisk partition and put pcfs on it for testing (hard to pick
1547 	 * a number between one and one).
1548 	 *
1549 	 * The cheezy floppy test is an attempt to not have too few cylinders
1550 	 * for a small file, or so many on a big file that you waste space
1551 	 * for backup superblocks or cylinder group structures.
1552 	 */
1553 	if (dsize < (2 * 1024 * 1024)) /* floppy? */
1554 		lsp->ls_dkg.dkg_ncyl = dsize / (100 * 1024);
1555 	else
1556 		lsp->ls_dkg.dkg_ncyl = dsize / (300 * 1024);
1557 	/* in case file file is < 100k */
1558 	if (lsp->ls_dkg.dkg_ncyl == 0)
1559 		lsp->ls_dkg.dkg_ncyl = 1;
1560 	lsp->ls_dkg.dkg_acyl = 0;
1561 	lsp->ls_dkg.dkg_bcyl = 0;
1562 	lsp->ls_dkg.dkg_nhead = 1;
1563 	lsp->ls_dkg.dkg_obs1 = 0;
1564 	lsp->ls_dkg.dkg_intrlv = 0;
1565 	lsp->ls_dkg.dkg_obs2 = 0;
1566 	lsp->ls_dkg.dkg_obs3 = 0;
1567 	lsp->ls_dkg.dkg_apc = 0;
1568 	lsp->ls_dkg.dkg_rpm = 7200;
1569 	lsp->ls_dkg.dkg_pcyl = lsp->ls_dkg.dkg_ncyl + lsp->ls_dkg.dkg_acyl;
1570 	lsp->ls_dkg.dkg_nsect = dsize / (DEV_BSIZE * lsp->ls_dkg.dkg_ncyl);
1571 	lsp->ls_dkg.dkg_write_reinstruct = 0;
1572 	lsp->ls_dkg.dkg_read_reinstruct = 0;
1573 
1574 	/* vtoc - see dkio(7I) */
1575 	bzero(&lsp->ls_vtoc, sizeof (struct vtoc));
1576 	lsp->ls_vtoc.v_sanity = VTOC_SANE;
1577 	lsp->ls_vtoc.v_version = V_VERSION;
1578 	(void) strncpy(lsp->ls_vtoc.v_volume, LOFI_DRIVER_NAME,
1579 	    sizeof (lsp->ls_vtoc.v_volume));
1580 	lsp->ls_vtoc.v_sectorsz = DEV_BSIZE;
1581 	lsp->ls_vtoc.v_nparts = 1;
1582 	lsp->ls_vtoc.v_part[0].p_tag = V_UNASSIGNED;
1583 
1584 	/*
1585 	 * A compressed file is read-only, other files can
1586 	 * be read-write
1587 	 */
1588 	if (lsp->ls_uncomp_seg_sz > 0) {
1589 		lsp->ls_vtoc.v_part[0].p_flag = V_UNMNT | V_RONLY;
1590 	} else {
1591 		lsp->ls_vtoc.v_part[0].p_flag = V_UNMNT;
1592 	}
1593 	lsp->ls_vtoc.v_part[0].p_start = (daddr_t)0;
1594 	/*
1595 	 * The partition size cannot just be the number of sectors, because
1596 	 * that might not end on a cylinder boundary. And if that's the case,
1597 	 * newfs/mkfs will print a scary warning. So just figure the size
1598 	 * based on the number of cylinders and sectors/cylinder.
1599 	 */
1600 	lsp->ls_vtoc.v_part[0].p_size = lsp->ls_dkg.dkg_pcyl *
1601 	    lsp->ls_dkg.dkg_nsect * lsp->ls_dkg.dkg_nhead;
1602 
1603 	/* dk_cinfo - see dkio(7I) */
1604 	bzero(&lsp->ls_ci, sizeof (struct dk_cinfo));
1605 	(void) strcpy(lsp->ls_ci.dki_cname, LOFI_DRIVER_NAME);
1606 	lsp->ls_ci.dki_ctype = DKC_MD;
1607 	lsp->ls_ci.dki_flags = 0;
1608 	lsp->ls_ci.dki_cnum = 0;
1609 	lsp->ls_ci.dki_addr = 0;
1610 	lsp->ls_ci.dki_space = 0;
1611 	lsp->ls_ci.dki_prio = 0;
1612 	lsp->ls_ci.dki_vec = 0;
1613 	(void) strcpy(lsp->ls_ci.dki_dname, LOFI_DRIVER_NAME);
1614 	lsp->ls_ci.dki_unit = 0;
1615 	lsp->ls_ci.dki_slave = 0;
1616 	lsp->ls_ci.dki_partition = 0;
1617 	/*
1618 	 * newfs uses this to set maxcontig. Must not be < 16, or it
1619 	 * will be 0 when newfs multiplies it by DEV_BSIZE and divides
1620 	 * it by the block size. Then tunefs doesn't work because
1621 	 * maxcontig is 0.
1622 	 */
1623 	lsp->ls_ci.dki_maxtransfer = 16;
1624 }
1625 
1626 /*
1627  * map in a compressed file
1628  *
1629  * Read in the header and the index that follows.
1630  *
1631  * The header is as follows -
1632  *
1633  * Signature (name of the compression algorithm)
1634  * Compression segment size (a multiple of 512)
1635  * Number of index entries
1636  * Size of the last block
1637  * The array containing the index entries
1638  *
1639  * The header information is always stored in
1640  * network byte order on disk.
1641  */
1642 static int
1643 lofi_map_compressed_file(struct lofi_state *lsp, char *buf)
1644 {
1645 	uint32_t index_sz, header_len, i;
1646 	ssize_t	resid;
1647 	enum uio_rw rw;
1648 	char *tbuf = buf;
1649 	int error;
1650 
1651 	/* The signature has already been read */
1652 	tbuf += sizeof (lsp->ls_comp_algorithm);
1653 	bcopy(tbuf, &(lsp->ls_uncomp_seg_sz), sizeof (lsp->ls_uncomp_seg_sz));
1654 	lsp->ls_uncomp_seg_sz = ntohl(lsp->ls_uncomp_seg_sz);
1655 
1656 	/*
1657 	 * The compressed segment size must be a power of 2
1658 	 */
1659 	if (lsp->ls_uncomp_seg_sz < DEV_BSIZE ||
1660 	    !ISP2(lsp->ls_uncomp_seg_sz))
1661 		return (EINVAL);
1662 
1663 	for (i = 0; !((lsp->ls_uncomp_seg_sz >> i) & 1); i++)
1664 		;
1665 
1666 	lsp->ls_comp_seg_shift = i;
1667 
1668 	tbuf += sizeof (lsp->ls_uncomp_seg_sz);
1669 	bcopy(tbuf, &(lsp->ls_comp_index_sz), sizeof (lsp->ls_comp_index_sz));
1670 	lsp->ls_comp_index_sz = ntohl(lsp->ls_comp_index_sz);
1671 
1672 	tbuf += sizeof (lsp->ls_comp_index_sz);
1673 	bcopy(tbuf, &(lsp->ls_uncomp_last_seg_sz),
1674 	    sizeof (lsp->ls_uncomp_last_seg_sz));
1675 	lsp->ls_uncomp_last_seg_sz = ntohl(lsp->ls_uncomp_last_seg_sz);
1676 
1677 	/*
1678 	 * Compute the total size of the uncompressed data
1679 	 * for use in fake_disk_geometry and other calculations.
1680 	 * Disk geometry has to be faked with respect to the
1681 	 * actual uncompressed data size rather than the
1682 	 * compressed file size.
1683 	 */
1684 	lsp->ls_vp_size =
1685 	    (u_offset_t)(lsp->ls_comp_index_sz - 2) * lsp->ls_uncomp_seg_sz
1686 	    + lsp->ls_uncomp_last_seg_sz;
1687 
1688 	/*
1689 	 * Index size is rounded up to DEV_BSIZE for ease
1690 	 * of segmapping
1691 	 */
1692 	index_sz = sizeof (*lsp->ls_comp_seg_index) * lsp->ls_comp_index_sz;
1693 	header_len = sizeof (lsp->ls_comp_algorithm) +
1694 	    sizeof (lsp->ls_uncomp_seg_sz) +
1695 	    sizeof (lsp->ls_comp_index_sz) +
1696 	    sizeof (lsp->ls_uncomp_last_seg_sz);
1697 	lsp->ls_comp_offbase = header_len + index_sz;
1698 
1699 	index_sz += header_len;
1700 	index_sz = roundup(index_sz, DEV_BSIZE);
1701 
1702 	lsp->ls_comp_index_data = kmem_alloc(index_sz, KM_SLEEP);
1703 	lsp->ls_comp_index_data_sz = index_sz;
1704 
1705 	/*
1706 	 * Read in the index -- this has a side-effect
1707 	 * of reading in the header as well
1708 	 */
1709 	rw = UIO_READ;
1710 	error = vn_rdwr(rw, lsp->ls_vp, lsp->ls_comp_index_data, index_sz,
1711 	    0, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
1712 
1713 	if (error != 0)
1714 		return (error);
1715 
1716 	/* Skip the header, this is where the index really begins */
1717 	lsp->ls_comp_seg_index =
1718 	    /*LINTED*/
1719 	    (uint64_t *)(lsp->ls_comp_index_data + header_len);
1720 
1721 	/*
1722 	 * Now recompute offsets in the index to account for
1723 	 * the header length
1724 	 */
1725 	for (i = 0; i < lsp->ls_comp_index_sz; i++) {
1726 		lsp->ls_comp_seg_index[i] = lsp->ls_comp_offbase +
1727 		    BE_64(lsp->ls_comp_seg_index[i]);
1728 	}
1729 
1730 	return (error);
1731 }
1732 
1733 /*
1734  * Check to see if the passed in signature is a valid
1735  * one.  If it is valid, return the index into
1736  * lofi_compress_table.
1737  *
1738  * Return -1 if it is invalid
1739  */
1740 static int lofi_compress_select(char *signature)
1741 {
1742 	int i;
1743 
1744 	for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
1745 		if (strcmp(lofi_compress_table[i].l_name, signature) == 0)
1746 			return (i);
1747 	}
1748 
1749 	return (-1);
1750 }
1751 
1752 /*
1753  * map a file to a minor number. Return the minor number.
1754  */
1755 static int
1756 lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor,
1757     int *rvalp, struct cred *credp, int ioctl_flag)
1758 {
1759 	minor_t	newminor;
1760 	struct lofi_state *lsp;
1761 	struct lofi_ioctl *klip;
1762 	int	error;
1763 	struct vnode *vp;
1764 	int64_t	Nblocks_prop_val;
1765 	int64_t	Size_prop_val;
1766 	int	compress_index;
1767 	vattr_t	vattr;
1768 	int	flag;
1769 	enum vtype v_type;
1770 	int zalloced = 0;
1771 	dev_t	newdev;
1772 	char	namebuf[50];
1773 	char	buf[DEV_BSIZE];
1774 	char	crybuf[DEV_BSIZE];
1775 	ssize_t	resid;
1776 	boolean_t need_vn_close = B_FALSE;
1777 	boolean_t keycopied = B_FALSE;
1778 	boolean_t need_size_update = B_FALSE;
1779 
1780 	klip = copy_in_lofi_ioctl(ulip, ioctl_flag);
1781 	if (klip == NULL)
1782 		return (EFAULT);
1783 
1784 	mutex_enter(&lofi_lock);
1785 
1786 	if (!valid_filename(klip->li_filename)) {
1787 		error = EINVAL;
1788 		goto out;
1789 	}
1790 
1791 	if (file_to_minor(klip->li_filename) != 0) {
1792 		error = EBUSY;
1793 		goto out;
1794 	}
1795 
1796 	if (pickminor) {
1797 		/* Find a free one */
1798 		for (newminor = 1; newminor <= lofi_max_files; newminor++)
1799 			if (ddi_get_soft_state(lofi_statep, newminor) == NULL)
1800 				break;
1801 		if (newminor >= lofi_max_files) {
1802 			error = EAGAIN;
1803 			goto out;
1804 		}
1805 	} else {
1806 		newminor = klip->li_minor;
1807 		if (ddi_get_soft_state(lofi_statep, newminor) != NULL) {
1808 			error = EEXIST;
1809 			goto out;
1810 		}
1811 	}
1812 
1813 	/* make sure it's valid */
1814 	error = lookupname(klip->li_filename, UIO_SYSSPACE, FOLLOW,
1815 	    NULLVPP, &vp);
1816 	if (error) {
1817 		goto out;
1818 	}
1819 	v_type = vp->v_type;
1820 	VN_RELE(vp);
1821 	if (!V_ISLOFIABLE(v_type)) {
1822 		error = EINVAL;
1823 		goto out;
1824 	}
1825 	flag = FREAD | FWRITE | FOFFMAX | FEXCL;
1826 	error = vn_open(klip->li_filename, UIO_SYSSPACE, flag, 0, &vp, 0, 0);
1827 	if (error) {
1828 		/* try read-only */
1829 		flag &= ~FWRITE;
1830 		error = vn_open(klip->li_filename, UIO_SYSSPACE, flag, 0,
1831 		    &vp, 0, 0);
1832 		if (error) {
1833 			goto out;
1834 		}
1835 	}
1836 	need_vn_close = B_TRUE;
1837 
1838 	vattr.va_mask = AT_SIZE;
1839 	error = VOP_GETATTR(vp, &vattr, 0, credp, NULL);
1840 	if (error) {
1841 		goto out;
1842 	}
1843 	/* the file needs to be a multiple of the block size */
1844 	if ((vattr.va_size % DEV_BSIZE) != 0) {
1845 		error = EINVAL;
1846 		goto out;
1847 	}
1848 	newdev = makedevice(getmajor(dev), newminor);
1849 	Size_prop_val = vattr.va_size;
1850 	if ((ddi_prop_update_int64(newdev, lofi_dip,
1851 	    SIZE_PROP_NAME, Size_prop_val)) != DDI_PROP_SUCCESS) {
1852 		error = EINVAL;
1853 		goto out;
1854 	}
1855 	Nblocks_prop_val = vattr.va_size / DEV_BSIZE;
1856 	if ((ddi_prop_update_int64(newdev, lofi_dip,
1857 	    NBLOCKS_PROP_NAME, Nblocks_prop_val)) != DDI_PROP_SUCCESS) {
1858 		error = EINVAL;
1859 		goto propout;
1860 	}
1861 	error = ddi_soft_state_zalloc(lofi_statep, newminor);
1862 	if (error == DDI_FAILURE) {
1863 		error = ENOMEM;
1864 		goto propout;
1865 	}
1866 	zalloced = 1;
1867 	(void) snprintf(namebuf, sizeof (namebuf), "%d", newminor);
1868 	error = ddi_create_minor_node(lofi_dip, namebuf, S_IFBLK, newminor,
1869 	    DDI_PSEUDO, NULL);
1870 	if (error != DDI_SUCCESS) {
1871 		error = ENXIO;
1872 		goto propout;
1873 	}
1874 	(void) snprintf(namebuf, sizeof (namebuf), "%d,raw", newminor);
1875 	error = ddi_create_minor_node(lofi_dip, namebuf, S_IFCHR, newminor,
1876 	    DDI_PSEUDO, NULL);
1877 	if (error != DDI_SUCCESS) {
1878 		/* remove block node */
1879 		(void) snprintf(namebuf, sizeof (namebuf), "%d", newminor);
1880 		ddi_remove_minor_node(lofi_dip, namebuf);
1881 		error = ENXIO;
1882 		goto propout;
1883 	}
1884 	lsp = ddi_get_soft_state(lofi_statep, newminor);
1885 	lsp->ls_filename_sz = strlen(klip->li_filename) + 1;
1886 	lsp->ls_filename = kmem_alloc(lsp->ls_filename_sz, KM_SLEEP);
1887 	(void) snprintf(namebuf, sizeof (namebuf), "%s_taskq_%d",
1888 	    LOFI_DRIVER_NAME, newminor);
1889 	lsp->ls_taskq = taskq_create(namebuf, lofi_taskq_nthreads,
1890 	    minclsyspri, 1, lofi_taskq_maxalloc, 0);
1891 	lsp->ls_kstat = kstat_create(LOFI_DRIVER_NAME, newminor,
1892 	    NULL, "disk", KSTAT_TYPE_IO, 1, 0);
1893 	if (lsp->ls_kstat) {
1894 		mutex_init(&lsp->ls_kstat_lock, NULL, MUTEX_DRIVER, NULL);
1895 		lsp->ls_kstat->ks_lock = &lsp->ls_kstat_lock;
1896 		kstat_install(lsp->ls_kstat);
1897 	}
1898 	cv_init(&lsp->ls_vp_cv, NULL, CV_DRIVER, NULL);
1899 	mutex_init(&lsp->ls_vp_lock, NULL, MUTEX_DRIVER, NULL);
1900 
1901 	list_create(&lsp->ls_comp_cache, sizeof (struct lofi_comp_cache),
1902 	    offsetof(struct lofi_comp_cache, lc_list));
1903 	mutex_init(&lsp->ls_comp_cache_lock, NULL, MUTEX_DRIVER, NULL);
1904 
1905 	/*
1906 	 * save open mode so file can be closed properly and vnode counts
1907 	 * updated correctly.
1908 	 */
1909 	lsp->ls_openflag = flag;
1910 
1911 	/*
1912 	 * Try to handle stacked lofs vnodes.
1913 	 */
1914 	if (vp->v_type == VREG) {
1915 		if (VOP_REALVP(vp, &lsp->ls_vp, NULL) != 0) {
1916 			lsp->ls_vp = vp;
1917 		} else {
1918 			/*
1919 			 * Even though vp was obtained via vn_open(), we
1920 			 * can't call vn_close() on it, since lofs will
1921 			 * pass the VOP_CLOSE() on down to the realvp
1922 			 * (which we are about to use). Hence we merely
1923 			 * drop the reference to the lofs vnode and hold
1924 			 * the realvp so things behave as if we've
1925 			 * opened the realvp without any interaction
1926 			 * with lofs.
1927 			 */
1928 			VN_HOLD(lsp->ls_vp);
1929 			VN_RELE(vp);
1930 		}
1931 	} else {
1932 		lsp->ls_vp = vp;
1933 	}
1934 	lsp->ls_vp_size = vattr.va_size;
1935 	(void) strcpy(lsp->ls_filename, klip->li_filename);
1936 	if (rvalp)
1937 		*rvalp = (int)newminor;
1938 	klip->li_minor = newminor;
1939 
1940 	/*
1941 	 * Initialize crypto details for encrypted lofi
1942 	 */
1943 	if (klip->li_crypto_enabled) {
1944 		int ret;
1945 
1946 		mutex_init(&lsp->ls_crypto_lock, NULL, MUTEX_DRIVER, NULL);
1947 
1948 		lsp->ls_mech.cm_type = crypto_mech2id(klip->li_cipher);
1949 		if (lsp->ls_mech.cm_type == CRYPTO_MECH_INVALID) {
1950 			cmn_err(CE_WARN, "invalid cipher %s requested for %s",
1951 			    klip->li_cipher, lsp->ls_filename);
1952 			error = EINVAL;
1953 			goto propout;
1954 		}
1955 
1956 		/* this is just initialization here */
1957 		lsp->ls_mech.cm_param = NULL;
1958 		lsp->ls_mech.cm_param_len = 0;
1959 
1960 		lsp->ls_iv_type = klip->li_iv_type;
1961 		lsp->ls_iv_mech.cm_type = crypto_mech2id(klip->li_iv_cipher);
1962 		if (lsp->ls_iv_mech.cm_type == CRYPTO_MECH_INVALID) {
1963 			cmn_err(CE_WARN, "invalid iv cipher %s requested"
1964 			    " for %s", klip->li_iv_cipher, lsp->ls_filename);
1965 			error = EINVAL;
1966 			goto propout;
1967 		}
1968 
1969 		/* iv mech must itself take a null iv */
1970 		lsp->ls_iv_mech.cm_param = NULL;
1971 		lsp->ls_iv_mech.cm_param_len = 0;
1972 		lsp->ls_iv_len = klip->li_iv_len;
1973 
1974 		/*
1975 		 * Create ctx using li_cipher & the raw li_key after checking
1976 		 * that it isn't a weak key.
1977 		 */
1978 		lsp->ls_key.ck_format = CRYPTO_KEY_RAW;
1979 		lsp->ls_key.ck_length = klip->li_key_len;
1980 		lsp->ls_key.ck_data = kmem_alloc(
1981 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length), KM_SLEEP);
1982 		bcopy(klip->li_key, lsp->ls_key.ck_data,
1983 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
1984 		keycopied = B_TRUE;
1985 
1986 		ret = crypto_key_check(&lsp->ls_mech, &lsp->ls_key);
1987 		if (ret != CRYPTO_SUCCESS) {
1988 			error = EINVAL;
1989 			cmn_err(CE_WARN, "weak key check failed for cipher "
1990 			    "%s on file %s (0x%x)", klip->li_cipher,
1991 			    lsp->ls_filename, ret);
1992 			goto propout;
1993 		}
1994 	}
1995 	lsp->ls_crypto_enabled = klip->li_crypto_enabled;
1996 
1997 	/*
1998 	 * Read the file signature to check if it is compressed or encrypted.
1999 	 * Crypto signature is in a different location; both areas should
2000 	 * read to keep compression and encryption mutually exclusive.
2001 	 */
2002 	if (lsp->ls_crypto_enabled) {
2003 		error = vn_rdwr(UIO_READ, lsp->ls_vp, crybuf, DEV_BSIZE,
2004 		    CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
2005 		if (error != 0)
2006 			goto propout;
2007 	}
2008 	error = vn_rdwr(UIO_READ, lsp->ls_vp, buf, DEV_BSIZE, 0, UIO_SYSSPACE,
2009 	    0, RLIM64_INFINITY, kcred, &resid);
2010 	if (error != 0)
2011 		goto propout;
2012 
2013 	/* initialize these variables for all lofi files */
2014 	lsp->ls_uncomp_seg_sz = 0;
2015 	lsp->ls_vp_comp_size = lsp->ls_vp_size;
2016 	lsp->ls_comp_algorithm[0] = '\0';
2017 
2018 	/* encrypted lofi reads/writes shifted by crypto metadata size */
2019 	lsp->ls_crypto_offset = 0;
2020 
2021 	/* this is a compressed lofi */
2022 	if ((compress_index = lofi_compress_select(buf)) != -1) {
2023 
2024 		/* compression and encryption are mutually exclusive */
2025 		if (klip->li_crypto_enabled) {
2026 			error = ENOTSUP;
2027 			goto propout;
2028 		}
2029 
2030 		/* initialize compression info for compressed lofi */
2031 		lsp->ls_comp_algorithm_index = compress_index;
2032 		(void) strlcpy(lsp->ls_comp_algorithm,
2033 		    lofi_compress_table[compress_index].l_name,
2034 		    sizeof (lsp->ls_comp_algorithm));
2035 
2036 		error = lofi_map_compressed_file(lsp, buf);
2037 		if (error != 0)
2038 			goto propout;
2039 		need_size_update = B_TRUE;
2040 
2041 	/* this is an encrypted lofi */
2042 	} else if (strncmp(crybuf, lofi_crypto_magic,
2043 	    sizeof (lofi_crypto_magic)) == 0) {
2044 
2045 		char *marker = crybuf;
2046 
2047 		/*
2048 		 * This is the case where the header in the lofi image is
2049 		 * already initialized to indicate it is encrypted.
2050 		 * There is another case (see below) where encryption is
2051 		 * requested but the lofi image has never been used yet,
2052 		 * so the header needs to be written with encryption magic.
2053 		 */
2054 
2055 		/* indicate this must be an encrypted lofi due to magic */
2056 		klip->li_crypto_enabled = B_TRUE;
2057 
2058 		/*
2059 		 * The encryption header information is laid out this way:
2060 		 *	6 bytes:	hex "CFLOFI"
2061 		 *	2 bytes:	version = 0 ... for now
2062 		 *	96 bytes:	reserved1 (not implemented yet)
2063 		 *	4 bytes:	data_sector = 2 ... for now
2064 		 *	more...		not implemented yet
2065 		 */
2066 
2067 		/* copy the magic */
2068 		bcopy(marker, lsp->ls_crypto.magic,
2069 		    sizeof (lsp->ls_crypto.magic));
2070 		marker += sizeof (lsp->ls_crypto.magic);
2071 
2072 		/* read the encryption version number */
2073 		bcopy(marker, &(lsp->ls_crypto.version),
2074 		    sizeof (lsp->ls_crypto.version));
2075 		lsp->ls_crypto.version = ntohs(lsp->ls_crypto.version);
2076 		marker += sizeof (lsp->ls_crypto.version);
2077 
2078 		/* read a chunk of reserved data */
2079 		bcopy(marker, lsp->ls_crypto.reserved1,
2080 		    sizeof (lsp->ls_crypto.reserved1));
2081 		marker += sizeof (lsp->ls_crypto.reserved1);
2082 
2083 		/* read block number where encrypted data begins */
2084 		bcopy(marker, &(lsp->ls_crypto.data_sector),
2085 		    sizeof (lsp->ls_crypto.data_sector));
2086 		lsp->ls_crypto.data_sector = ntohl(lsp->ls_crypto.data_sector);
2087 		marker += sizeof (lsp->ls_crypto.data_sector);
2088 
2089 		/* and ignore the rest until it is implemented */
2090 
2091 		lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE;
2092 		need_size_update = B_TRUE;
2093 
2094 	/* neither compressed nor encrypted, BUT could be new encrypted lofi */
2095 	} else if (klip->li_crypto_enabled) {
2096 
2097 		/*
2098 		 * This is the case where encryption was requested but the
2099 		 * appears to be entirely blank where the encryption header
2100 		 * would have been in the lofi image.  If it is blank,
2101 		 * assume it is a brand new lofi image and initialize the
2102 		 * header area with encryption magic and current version
2103 		 * header data.  If it is not blank, that's an error.
2104 		 */
2105 		int	i;
2106 		char	*marker;
2107 		struct crypto_meta	chead;
2108 
2109 		for (i = 0; i < sizeof (struct crypto_meta); i++)
2110 			if (crybuf[i] != '\0')
2111 				break;
2112 		if (i != sizeof (struct crypto_meta)) {
2113 			error = EINVAL;
2114 			goto propout;
2115 		}
2116 
2117 		/* nothing there, initialize as encrypted lofi */
2118 		marker = crybuf;
2119 		bcopy(lofi_crypto_magic, marker, sizeof (lofi_crypto_magic));
2120 		marker += sizeof (lofi_crypto_magic);
2121 		chead.version = htons(LOFI_CRYPTO_VERSION);
2122 		bcopy(&(chead.version), marker, sizeof (chead.version));
2123 		marker += sizeof (chead.version);
2124 		marker += sizeof (chead.reserved1);
2125 		chead.data_sector = htonl(LOFI_CRYPTO_DATA_SECTOR);
2126 		bcopy(&(chead.data_sector), marker, sizeof (chead.data_sector));
2127 
2128 		/* write the header */
2129 		error = vn_rdwr(UIO_WRITE, lsp->ls_vp, crybuf, DEV_BSIZE,
2130 		    CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
2131 		if (error != 0)
2132 			goto propout;
2133 
2134 		/* fix things up so it looks like we read this info */
2135 		bcopy(lofi_crypto_magic, lsp->ls_crypto.magic,
2136 		    sizeof (lofi_crypto_magic));
2137 		lsp->ls_crypto.version = LOFI_CRYPTO_VERSION;
2138 		lsp->ls_crypto.data_sector = LOFI_CRYPTO_DATA_SECTOR;
2139 
2140 		lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE;
2141 		need_size_update = B_TRUE;
2142 	}
2143 
2144 	/*
2145 	 * Either lsp->ls_vp_size or lsp->ls_crypto_offset changed;
2146 	 * for encrypted lofi, advertise that it is somewhat shorter
2147 	 * due to embedded crypto metadata section
2148 	 */
2149 	if (need_size_update) {
2150 		/* update DDI properties */
2151 		Size_prop_val = lsp->ls_vp_size - lsp->ls_crypto_offset;
2152 		if ((ddi_prop_update_int64(newdev, lofi_dip, SIZE_PROP_NAME,
2153 		    Size_prop_val)) != DDI_PROP_SUCCESS) {
2154 			error = EINVAL;
2155 			goto propout;
2156 		}
2157 		Nblocks_prop_val =
2158 		    (lsp->ls_vp_size - lsp->ls_crypto_offset) / DEV_BSIZE;
2159 		if ((ddi_prop_update_int64(newdev, lofi_dip, NBLOCKS_PROP_NAME,
2160 		    Nblocks_prop_val)) != DDI_PROP_SUCCESS) {
2161 			error = EINVAL;
2162 			goto propout;
2163 		}
2164 	}
2165 
2166 	fake_disk_geometry(lsp);
2167 	mutex_exit(&lofi_lock);
2168 	(void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2169 	free_lofi_ioctl(klip);
2170 	return (0);
2171 
2172 propout:
2173 	if (keycopied) {
2174 		bzero(lsp->ls_key.ck_data,
2175 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
2176 		kmem_free(lsp->ls_key.ck_data,
2177 		    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
2178 		lsp->ls_key.ck_data = NULL;
2179 		lsp->ls_key.ck_length = 0;
2180 	}
2181 
2182 	if (zalloced)
2183 		ddi_soft_state_free(lofi_statep, newminor);
2184 
2185 	(void) ddi_prop_remove(newdev, lofi_dip, SIZE_PROP_NAME);
2186 	(void) ddi_prop_remove(newdev, lofi_dip, NBLOCKS_PROP_NAME);
2187 
2188 out:
2189 	if (need_vn_close) {
2190 		(void) VOP_CLOSE(vp, flag, 1, 0, credp, NULL);
2191 		VN_RELE(vp);
2192 	}
2193 
2194 	mutex_exit(&lofi_lock);
2195 	free_lofi_ioctl(klip);
2196 	return (error);
2197 }
2198 
2199 /*
2200  * unmap a file.
2201  */
2202 static int
2203 lofi_unmap_file(dev_t dev, struct lofi_ioctl *ulip, int byfilename,
2204     struct cred *credp, int ioctl_flag)
2205 {
2206 	struct lofi_state *lsp;
2207 	struct lofi_ioctl *klip;
2208 	minor_t	minor;
2209 
2210 	klip = copy_in_lofi_ioctl(ulip, ioctl_flag);
2211 	if (klip == NULL)
2212 		return (EFAULT);
2213 
2214 	mutex_enter(&lofi_lock);
2215 	if (byfilename) {
2216 		minor = file_to_minor(klip->li_filename);
2217 	} else {
2218 		minor = klip->li_minor;
2219 	}
2220 	if (minor == 0) {
2221 		mutex_exit(&lofi_lock);
2222 		free_lofi_ioctl(klip);
2223 		return (ENXIO);
2224 	}
2225 	lsp = ddi_get_soft_state(lofi_statep, minor);
2226 	if (lsp == NULL || lsp->ls_vp == NULL) {
2227 		mutex_exit(&lofi_lock);
2228 		free_lofi_ioctl(klip);
2229 		return (ENXIO);
2230 	}
2231 
2232 	/*
2233 	 * If it's still held open, we'll do one of three things:
2234 	 *
2235 	 * If no flag is set, just return EBUSY.
2236 	 *
2237 	 * If the 'cleanup' flag is set, unmap and remove the device when
2238 	 * the last user finishes.
2239 	 *
2240 	 * If the 'force' flag is set, then we forcibly close the underlying
2241 	 * file.  Subsequent operations will fail, and the DKIOCSTATE ioctl
2242 	 * will return DKIO_DEV_GONE.  When the device is last closed, the
2243 	 * device will be cleaned up appropriately.
2244 	 *
2245 	 * This is complicated by the fact that we may have outstanding
2246 	 * dispatched I/Os.  Rather than having a single mutex to serialize all
2247 	 * I/O, we keep a count of the number of outstanding I/O requests
2248 	 * (ls_vp_iocount), as well as a flag to indicate that no new I/Os
2249 	 * should be dispatched (ls_vp_closereq).
2250 	 *
2251 	 * We set the flag, wait for the number of outstanding I/Os to reach 0,
2252 	 * and then close the underlying vnode.
2253 	 */
2254 	if (is_opened(lsp)) {
2255 		if (klip->li_force) {
2256 			mutex_enter(&lsp->ls_vp_lock);
2257 			lsp->ls_vp_closereq = B_TRUE;
2258 			/* wake up any threads waiting on dkiocstate */
2259 			cv_broadcast(&lsp->ls_vp_cv);
2260 			while (lsp->ls_vp_iocount > 0)
2261 				cv_wait(&lsp->ls_vp_cv, &lsp->ls_vp_lock);
2262 			mutex_exit(&lsp->ls_vp_lock);
2263 			lofi_free_handle(dev, minor, lsp, credp);
2264 
2265 			klip->li_minor = minor;
2266 			mutex_exit(&lofi_lock);
2267 			(void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2268 			free_lofi_ioctl(klip);
2269 			return (0);
2270 		} else if (klip->li_cleanup) {
2271 			lsp->ls_cleanup = 1;
2272 			mutex_exit(&lofi_lock);
2273 			free_lofi_ioctl(klip);
2274 			return (0);
2275 		}
2276 
2277 		mutex_exit(&lofi_lock);
2278 		free_lofi_ioctl(klip);
2279 		return (EBUSY);
2280 	}
2281 
2282 	lofi_free_handle(dev, minor, lsp, credp);
2283 
2284 	klip->li_minor = minor;
2285 	mutex_exit(&lofi_lock);
2286 	(void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2287 	free_lofi_ioctl(klip);
2288 	return (0);
2289 }
2290 
2291 /*
2292  * get the filename given the minor number, or the minor number given
2293  * the name.
2294  */
2295 /*ARGSUSED*/
2296 static int
2297 lofi_get_info(dev_t dev, struct lofi_ioctl *ulip, int which,
2298     struct cred *credp, int ioctl_flag)
2299 {
2300 	struct lofi_state *lsp;
2301 	struct lofi_ioctl *klip;
2302 	int	error;
2303 	minor_t	minor;
2304 
2305 	klip = copy_in_lofi_ioctl(ulip, ioctl_flag);
2306 	if (klip == NULL)
2307 		return (EFAULT);
2308 
2309 	switch (which) {
2310 	case LOFI_GET_FILENAME:
2311 		minor = klip->li_minor;
2312 		if (minor == 0) {
2313 			free_lofi_ioctl(klip);
2314 			return (EINVAL);
2315 		}
2316 
2317 		mutex_enter(&lofi_lock);
2318 		lsp = ddi_get_soft_state(lofi_statep, minor);
2319 		if (lsp == NULL) {
2320 			mutex_exit(&lofi_lock);
2321 			free_lofi_ioctl(klip);
2322 			return (ENXIO);
2323 		}
2324 		(void) strcpy(klip->li_filename, lsp->ls_filename);
2325 		(void) strlcpy(klip->li_algorithm, lsp->ls_comp_algorithm,
2326 		    sizeof (klip->li_algorithm));
2327 		klip->li_crypto_enabled = lsp->ls_crypto_enabled;
2328 		mutex_exit(&lofi_lock);
2329 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2330 		free_lofi_ioctl(klip);
2331 		return (error);
2332 	case LOFI_GET_MINOR:
2333 		mutex_enter(&lofi_lock);
2334 		klip->li_minor = file_to_minor(klip->li_filename);
2335 		/* caller should not depend on klip->li_crypto_enabled here */
2336 		mutex_exit(&lofi_lock);
2337 		if (klip->li_minor == 0) {
2338 			free_lofi_ioctl(klip);
2339 			return (ENOENT);
2340 		}
2341 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2342 		free_lofi_ioctl(klip);
2343 		return (error);
2344 	case LOFI_CHECK_COMPRESSED:
2345 		mutex_enter(&lofi_lock);
2346 		klip->li_minor = file_to_minor(klip->li_filename);
2347 		mutex_exit(&lofi_lock);
2348 		if (klip->li_minor == 0) {
2349 			free_lofi_ioctl(klip);
2350 			return (ENOENT);
2351 		}
2352 		mutex_enter(&lofi_lock);
2353 		lsp = ddi_get_soft_state(lofi_statep, klip->li_minor);
2354 		if (lsp == NULL) {
2355 			mutex_exit(&lofi_lock);
2356 			free_lofi_ioctl(klip);
2357 			return (ENXIO);
2358 		}
2359 		ASSERT(strcmp(klip->li_filename, lsp->ls_filename) == 0);
2360 
2361 		(void) strlcpy(klip->li_algorithm, lsp->ls_comp_algorithm,
2362 		    sizeof (klip->li_algorithm));
2363 		mutex_exit(&lofi_lock);
2364 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2365 		free_lofi_ioctl(klip);
2366 		return (error);
2367 	default:
2368 		free_lofi_ioctl(klip);
2369 		return (EINVAL);
2370 	}
2371 
2372 }
2373 
2374 static int
2375 lofi_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *credp,
2376     int *rvalp)
2377 {
2378 	int	error;
2379 	enum dkio_state dkstate;
2380 	struct lofi_state *lsp;
2381 	minor_t	minor;
2382 
2383 	minor = getminor(dev);
2384 	/* lofi ioctls only apply to the master device */
2385 	if (minor == 0) {
2386 		struct lofi_ioctl *lip = (struct lofi_ioctl *)arg;
2387 
2388 		/*
2389 		 * the query command only need read-access - i.e., normal
2390 		 * users are allowed to do those on the ctl device as
2391 		 * long as they can open it read-only.
2392 		 */
2393 		switch (cmd) {
2394 		case LOFI_MAP_FILE:
2395 			if ((flag & FWRITE) == 0)
2396 				return (EPERM);
2397 			return (lofi_map_file(dev, lip, 1, rvalp, credp, flag));
2398 		case LOFI_MAP_FILE_MINOR:
2399 			if ((flag & FWRITE) == 0)
2400 				return (EPERM);
2401 			return (lofi_map_file(dev, lip, 0, rvalp, credp, flag));
2402 		case LOFI_UNMAP_FILE:
2403 			if ((flag & FWRITE) == 0)
2404 				return (EPERM);
2405 			return (lofi_unmap_file(dev, lip, 1, credp, flag));
2406 		case LOFI_UNMAP_FILE_MINOR:
2407 			if ((flag & FWRITE) == 0)
2408 				return (EPERM);
2409 			return (lofi_unmap_file(dev, lip, 0, credp, flag));
2410 		case LOFI_GET_FILENAME:
2411 			return (lofi_get_info(dev, lip, LOFI_GET_FILENAME,
2412 			    credp, flag));
2413 		case LOFI_GET_MINOR:
2414 			return (lofi_get_info(dev, lip, LOFI_GET_MINOR,
2415 			    credp, flag));
2416 		case LOFI_GET_MAXMINOR:
2417 			error = ddi_copyout(&lofi_max_files, &lip->li_minor,
2418 			    sizeof (lofi_max_files), flag);
2419 			if (error)
2420 				return (EFAULT);
2421 			return (0);
2422 		case LOFI_CHECK_COMPRESSED:
2423 			return (lofi_get_info(dev, lip, LOFI_CHECK_COMPRESSED,
2424 			    credp, flag));
2425 		default:
2426 			break;
2427 		}
2428 	}
2429 
2430 	mutex_enter(&lofi_lock);
2431 	lsp = ddi_get_soft_state(lofi_statep, minor);
2432 	if (lsp == NULL || lsp->ls_vp_closereq) {
2433 		mutex_exit(&lofi_lock);
2434 		return (ENXIO);
2435 	}
2436 	mutex_exit(&lofi_lock);
2437 
2438 	/*
2439 	 * We explicitly allow DKIOCSTATE, but all other ioctls should fail with
2440 	 * EIO as if the device was no longer present.
2441 	 */
2442 	if (lsp->ls_vp == NULL && cmd != DKIOCSTATE)
2443 		return (EIO);
2444 
2445 	/* these are for faking out utilities like newfs */
2446 	switch (cmd) {
2447 	case DKIOCGVTOC:
2448 		switch (ddi_model_convert_from(flag & FMODELS)) {
2449 		case DDI_MODEL_ILP32: {
2450 			struct vtoc32 vtoc32;
2451 
2452 			vtoctovtoc32(lsp->ls_vtoc, vtoc32);
2453 			if (ddi_copyout(&vtoc32, (void *)arg,
2454 			    sizeof (struct vtoc32), flag))
2455 				return (EFAULT);
2456 			break;
2457 			}
2458 
2459 		case DDI_MODEL_NONE:
2460 			if (ddi_copyout(&lsp->ls_vtoc, (void *)arg,
2461 			    sizeof (struct vtoc), flag))
2462 				return (EFAULT);
2463 			break;
2464 		}
2465 		return (0);
2466 	case DKIOCINFO:
2467 		error = ddi_copyout(&lsp->ls_ci, (void *)arg,
2468 		    sizeof (struct dk_cinfo), flag);
2469 		if (error)
2470 			return (EFAULT);
2471 		return (0);
2472 	case DKIOCG_VIRTGEOM:
2473 	case DKIOCG_PHYGEOM:
2474 	case DKIOCGGEOM:
2475 		error = ddi_copyout(&lsp->ls_dkg, (void *)arg,
2476 		    sizeof (struct dk_geom), flag);
2477 		if (error)
2478 			return (EFAULT);
2479 		return (0);
2480 	case DKIOCSTATE:
2481 		/*
2482 		 * Normally, lofi devices are always in the INSERTED state.  If
2483 		 * a device is forcefully unmapped, then the device transitions
2484 		 * to the DKIO_DEV_GONE state.
2485 		 */
2486 		if (ddi_copyin((void *)arg, &dkstate, sizeof (dkstate),
2487 		    flag) != 0)
2488 			return (EFAULT);
2489 
2490 		mutex_enter(&lsp->ls_vp_lock);
2491 		lsp->ls_vp_iocount++;
2492 		while (((dkstate == DKIO_INSERTED && lsp->ls_vp != NULL) ||
2493 		    (dkstate == DKIO_DEV_GONE && lsp->ls_vp == NULL)) &&
2494 		    !lsp->ls_vp_closereq) {
2495 			/*
2496 			 * By virtue of having the device open, we know that
2497 			 * 'lsp' will remain valid when we return.
2498 			 */
2499 			if (!cv_wait_sig(&lsp->ls_vp_cv,
2500 			    &lsp->ls_vp_lock)) {
2501 				lsp->ls_vp_iocount--;
2502 				cv_broadcast(&lsp->ls_vp_cv);
2503 				mutex_exit(&lsp->ls_vp_lock);
2504 				return (EINTR);
2505 			}
2506 		}
2507 
2508 		dkstate = (!lsp->ls_vp_closereq && lsp->ls_vp != NULL ?
2509 		    DKIO_INSERTED : DKIO_DEV_GONE);
2510 		lsp->ls_vp_iocount--;
2511 		cv_broadcast(&lsp->ls_vp_cv);
2512 		mutex_exit(&lsp->ls_vp_lock);
2513 
2514 		if (ddi_copyout(&dkstate, (void *)arg,
2515 		    sizeof (dkstate), flag) != 0)
2516 			return (EFAULT);
2517 		return (0);
2518 	default:
2519 		return (ENOTTY);
2520 	}
2521 }
2522 
2523 static struct cb_ops lofi_cb_ops = {
2524 	lofi_open,		/* open */
2525 	lofi_close,		/* close */
2526 	lofi_strategy,		/* strategy */
2527 	nodev,			/* print */
2528 	nodev,			/* dump */
2529 	lofi_read,		/* read */
2530 	lofi_write,		/* write */
2531 	lofi_ioctl,		/* ioctl */
2532 	nodev,			/* devmap */
2533 	nodev,			/* mmap */
2534 	nodev,			/* segmap */
2535 	nochpoll,		/* poll */
2536 	ddi_prop_op,		/* prop_op */
2537 	0,			/* streamtab  */
2538 	D_64BIT | D_NEW | D_MP,	/* Driver compatibility flag */
2539 	CB_REV,
2540 	lofi_aread,
2541 	lofi_awrite
2542 };
2543 
2544 static struct dev_ops lofi_ops = {
2545 	DEVO_REV,		/* devo_rev, */
2546 	0,			/* refcnt  */
2547 	lofi_info,		/* info */
2548 	nulldev,		/* identify */
2549 	nulldev,		/* probe */
2550 	lofi_attach,		/* attach */
2551 	lofi_detach,		/* detach */
2552 	nodev,			/* reset */
2553 	&lofi_cb_ops,		/* driver operations */
2554 	NULL,			/* no bus operations */
2555 	NULL,			/* power */
2556 	ddi_quiesce_not_needed,	/* quiesce */
2557 };
2558 
2559 static struct modldrv modldrv = {
2560 	&mod_driverops,
2561 	"loopback file driver",
2562 	&lofi_ops,
2563 };
2564 
2565 static struct modlinkage modlinkage = {
2566 	MODREV_1,
2567 	&modldrv,
2568 	NULL
2569 };
2570 
2571 int
2572 _init(void)
2573 {
2574 	int error;
2575 
2576 	error = ddi_soft_state_init(&lofi_statep,
2577 	    sizeof (struct lofi_state), 0);
2578 	if (error)
2579 		return (error);
2580 
2581 	mutex_init(&lofi_lock, NULL, MUTEX_DRIVER, NULL);
2582 	error = mod_install(&modlinkage);
2583 	if (error) {
2584 		mutex_destroy(&lofi_lock);
2585 		ddi_soft_state_fini(&lofi_statep);
2586 	}
2587 
2588 	return (error);
2589 }
2590 
2591 int
2592 _fini(void)
2593 {
2594 	int	error;
2595 
2596 	if (lofi_busy())
2597 		return (EBUSY);
2598 
2599 	error = mod_remove(&modlinkage);
2600 	if (error)
2601 		return (error);
2602 
2603 	mutex_destroy(&lofi_lock);
2604 	ddi_soft_state_fini(&lofi_statep);
2605 
2606 	return (error);
2607 }
2608 
2609 int
2610 _info(struct modinfo *modinfop)
2611 {
2612 	return (mod_info(&modlinkage, modinfop));
2613 }
2614