xref: /titanic_51/usr/src/uts/common/io/lofi.c (revision 110570ceb08d1961475cc4922fdf73e6ffc65924)
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  * Copyright 2013 Nexenta Systems, Inc. All rights reserved.
25  * Copyright 2016 Toomas Soome <tsoome@me.com>
26  */
27 
28 /*
29  * lofi (loopback file) driver - allows you to attach a file to a device,
30  * which can then be accessed through that device. The simple model is that
31  * you tell lofi to open a file, and then use the block device you get as
32  * you would any block device. lofi translates access to the block device
33  * into I/O on the underlying file. This is mostly useful for
34  * mounting images of filesystems.
35  *
36  * lofi is controlled through /dev/lofictl - this is the only device exported
37  * during attach, and is instance number 0. lofiadm communicates with lofi
38  * through ioctls on this device. When a file is attached to lofi, block and
39  * character devices are exported in /dev/lofi and /dev/rlofi. These devices
40  * are identified by lofi instance number, and the instance number is also used
41  * as the name in /dev/lofi.
42  *
43  * Virtual disks, or, labeled lofi, implements virtual disk support to
44  * support partition table and related tools. Such mappings will cause
45  * block and character devices to be exported in /dev/dsk and /dev/rdsk
46  * directories.
47  *
48  * To support virtual disks, the instance number space is divided to two
49  * parts, upper part for instance number and lower part for minor number
50  * space to identify partitions and slices. The virtual disk support is
51  * implemented by stacking cmlb module. For virtual disks, the partition
52  * related ioctl calls are routed to cmlb module. Compression and encryption
53  * is not supported for virtual disks.
54  *
55  * Mapped devices are tracked with state structures handled with
56  * ddi_soft_state(9F) for simplicity.
57  *
58  * A file attached to lofi is opened when attached and not closed until
59  * explicitly detached from lofi. This seems more sensible than deferring
60  * the open until the /dev/lofi device is opened, for a number of reasons.
61  * One is that any failure is likely to be noticed by the person (or script)
62  * running lofiadm. Another is that it would be a security problem if the
63  * file was replaced by another one after being added but before being opened.
64  *
65  * The only hard part about lofi is the ioctls. In order to support things
66  * like 'newfs' on a lofi device, it needs to support certain disk ioctls.
67  * So it has to fake disk geometry and partition information. More may need
68  * to be faked if your favorite utility doesn't work and you think it should
69  * (fdformat doesn't work because it really wants to know the type of floppy
70  * controller to talk to, and that didn't seem easy to fake. Or possibly even
71  * necessary, since we have mkfs_pcfs now).
72  *
73  * Normally, a lofi device cannot be detached if it is open (i.e. busy).  To
74  * support simulation of hotplug events, an optional force flag is provided.
75  * If a lofi device is open when a force detach is requested, then the
76  * underlying file is closed and any subsequent operations return EIO.  When the
77  * device is closed for the last time, it will be cleaned up at that time.  In
78  * addition, the DKIOCSTATE ioctl will return DKIO_DEV_GONE when the device is
79  * detached but not removed.
80  *
81  * Known problems:
82  *
83  *	UFS logging. Mounting a UFS filesystem image "logging"
84  *	works for basic copy testing but wedges during a build of ON through
85  *	that image. Some deadlock in lufs holding the log mutex and then
86  *	getting stuck on a buf. So for now, don't do that.
87  *
88  *	Direct I/O. Since the filesystem data is being cached in the buffer
89  *	cache, _and_ again in the underlying filesystem, it's tempting to
90  *	enable direct I/O on the underlying file. Don't, because that deadlocks.
91  *	I think to fix the cache-twice problem we might need filesystem support.
92  *
93  * Interesting things to do:
94  *
95  *	Allow multiple files for each device. A poor-man's metadisk, basically.
96  *
97  *	Pass-through ioctls on block devices. You can (though it's not
98  *	documented), give lofi a block device as a file name. Then we shouldn't
99  *	need to fake a geometry, however, it may be relevant if you're replacing
100  *	metadisk, or using lofi to get crypto.
101  *	It makes sense to do lofiadm -c aes -a /dev/dsk/c0t0d0s4 /dev/lofi/1
102  *	and then in /etc/vfstab have an entry for /dev/lofi/1 as /export/home.
103  *	In fact this even makes sense if you have lofi "above" metadisk.
104  *
105  * Encryption:
106  *	Each lofi device can have its own symmetric key and cipher.
107  *	They are passed to us by lofiadm(1m) in the correct format for use
108  *	with the misc/kcf crypto_* routines.
109  *
110  *	Each block has its own IV, that is calculated in lofi_blk_mech(), based
111  *	on the "master" key held in the lsp and the block number of the buffer.
112  */
113 
114 #include <sys/types.h>
115 #include <netinet/in.h>
116 #include <sys/sysmacros.h>
117 #include <sys/uio.h>
118 #include <sys/kmem.h>
119 #include <sys/cred.h>
120 #include <sys/mman.h>
121 #include <sys/errno.h>
122 #include <sys/aio_req.h>
123 #include <sys/stat.h>
124 #include <sys/file.h>
125 #include <sys/modctl.h>
126 #include <sys/conf.h>
127 #include <sys/debug.h>
128 #include <sys/vnode.h>
129 #include <sys/lofi.h>
130 #include <sys/fcntl.h>
131 #include <sys/pathname.h>
132 #include <sys/filio.h>
133 #include <sys/fdio.h>
134 #include <sys/open.h>
135 #include <sys/disp.h>
136 #include <vm/seg_map.h>
137 #include <sys/ddi.h>
138 #include <sys/sunddi.h>
139 #include <sys/zmod.h>
140 #include <sys/id_space.h>
141 #include <sys/mkdev.h>
142 #include <sys/crypto/common.h>
143 #include <sys/crypto/api.h>
144 #include <sys/rctl.h>
145 #include <sys/vtoc.h>
146 #include <sys/scsi/scsi.h>	/* for DTYPE_DIRECT */
147 #include <sys/scsi/impl/uscsi.h>
148 #include <sys/sysevent/dev.h>
149 #include <LzmaDec.h>
150 
151 /*
152  * The basis for CRYOFF is derived from usr/src/uts/common/sys/fs/ufs_fs.h.
153  * Crypto metadata, if it exists, is located at the end of the boot block
154  * (BBOFF + BBSIZE, which is SBOFF).  The super block and everything after
155  * is offset by the size of the crypto metadata which is handled by
156  * lsp->ls_crypto_offset.
157  */
158 #define	CRYOFF	((off_t)8192)
159 
160 #define	NBLOCKS_PROP_NAME	"Nblocks"
161 #define	SIZE_PROP_NAME		"Size"
162 #define	ZONE_PROP_NAME		"zone"
163 
164 #define	SETUP_C_DATA(cd, buf, len) 		\
165 	(cd).cd_format = CRYPTO_DATA_RAW;	\
166 	(cd).cd_offset = 0;			\
167 	(cd).cd_miscdata = NULL;		\
168 	(cd).cd_length = (len);			\
169 	(cd).cd_raw.iov_base = (buf);		\
170 	(cd).cd_raw.iov_len = (len);
171 
172 #define	UIO_CHECK(uio)	\
173 	if (((uio)->uio_loffset % DEV_BSIZE) != 0 || \
174 	    ((uio)->uio_resid % DEV_BSIZE) != 0) { \
175 		return (EINVAL); \
176 	}
177 
178 #define	DEVFS_CHANNEL	"devfsadm_event_channel"
179 #define	LOFI_TIMEOUT	30
180 static evchan_t *lofi_chan;
181 static kmutex_t lofi_chan_lock;
182 static kcondvar_t lofi_chan_cv;
183 static nvlist_t *lofi_devlink_cache;
184 
185 static void *lofi_statep;
186 static kmutex_t lofi_lock;		/* state lock */
187 static id_space_t *lofi_id;		/* lofi ID values */
188 static list_t lofi_list;
189 static zone_key_t lofi_zone_key;
190 
191 /*
192  * Because lofi_taskq_nthreads limits the actual swamping of the device, the
193  * maxalloc parameter (lofi_taskq_maxalloc) should be tuned conservatively
194  * high.  If we want to be assured that the underlying device is always busy,
195  * we must be sure that the number of bytes enqueued when the number of
196  * enqueued tasks exceeds maxalloc is sufficient to keep the device busy for
197  * the duration of the sleep time in taskq_ent_alloc().  That is, lofi should
198  * set maxalloc to be the maximum throughput (in bytes per second) of the
199  * underlying device divided by the minimum I/O size.  We assume a realistic
200  * maximum throughput of one hundred megabytes per second; we set maxalloc on
201  * the lofi task queue to be 104857600 divided by DEV_BSIZE.
202  */
203 static int lofi_taskq_maxalloc = 104857600 / DEV_BSIZE;
204 static int lofi_taskq_nthreads = 4;	/* # of taskq threads per device */
205 
206 const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC;
207 
208 /*
209  * To avoid decompressing data in a compressed segment multiple times
210  * when accessing small parts of a segment's data, we cache and reuse
211  * the uncompressed segment's data.
212  *
213  * A single cached segment is sufficient to avoid lots of duplicate
214  * segment decompress operations. A small cache size also reduces the
215  * memory footprint.
216  *
217  * lofi_max_comp_cache is the maximum number of decompressed data segments
218  * cached for each compressed lofi image. It can be set to 0 to disable
219  * caching.
220  */
221 
222 uint32_t lofi_max_comp_cache = 1;
223 
224 static int gzip_decompress(void *src, size_t srclen, void *dst,
225 	size_t *destlen, int level);
226 
227 static int lzma_decompress(void *src, size_t srclen, void *dst,
228 	size_t *dstlen, int level);
229 
230 lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
231 	{gzip_decompress,	NULL,	6,	"gzip"}, /* default */
232 	{gzip_decompress,	NULL,	6,	"gzip-6"},
233 	{gzip_decompress,	NULL,	9,	"gzip-9"},
234 	{lzma_decompress,	NULL,	0,	"lzma"}
235 };
236 
237 static void lofi_strategy_task(void *);
238 static int lofi_tg_rdwr(dev_info_t *, uchar_t, void *, diskaddr_t,
239     size_t, void *);
240 static int lofi_tg_getinfo(dev_info_t *, int, void *, void *);
241 
242 struct cmlb_tg_ops lofi_tg_ops = {
243 	TG_DK_OPS_VERSION_1,
244 	lofi_tg_rdwr,
245 	lofi_tg_getinfo
246 };
247 
248 /*ARGSUSED*/
249 static void
250 *SzAlloc(void *p, size_t size)
251 {
252 	return (kmem_alloc(size, KM_SLEEP));
253 }
254 
255 /*ARGSUSED*/
256 static void
257 SzFree(void *p, void *address, size_t size)
258 {
259 	kmem_free(address, size);
260 }
261 
262 static ISzAlloc g_Alloc = { SzAlloc, SzFree };
263 
264 /*
265  * Free data referenced by the linked list of cached uncompressed
266  * segments.
267  */
268 static void
269 lofi_free_comp_cache(struct lofi_state *lsp)
270 {
271 	struct lofi_comp_cache *lc;
272 
273 	while ((lc = list_remove_head(&lsp->ls_comp_cache)) != NULL) {
274 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
275 		kmem_free(lc, sizeof (struct lofi_comp_cache));
276 		lsp->ls_comp_cache_count--;
277 	}
278 	ASSERT(lsp->ls_comp_cache_count == 0);
279 }
280 
281 static int
282 is_opened(struct lofi_state *lsp)
283 {
284 	int i;
285 	boolean_t last = B_TRUE;
286 
287 	ASSERT(MUTEX_HELD(&lofi_lock));
288 	for (i = 0; i < LOFI_PART_MAX; i++) {
289 		if (lsp->ls_open_lyr[i]) {
290 			last = B_FALSE;
291 			break;
292 		}
293 	}
294 
295 	for (i = 0; last && (i < OTYP_LYR); i++) {
296 		if (lsp->ls_open_reg[i]) {
297 			last = B_FALSE;
298 		}
299 	}
300 
301 	return (!last);
302 }
303 
304 static void
305 lofi_free_crypto(struct lofi_state *lsp)
306 {
307 	ASSERT(MUTEX_HELD(&lofi_lock));
308 
309 	if (lsp->ls_crypto_enabled) {
310 		/*
311 		 * Clean up the crypto state so that it doesn't hang around
312 		 * in memory after we are done with it.
313 		 */
314 		if (lsp->ls_key.ck_data != NULL) {
315 			bzero(lsp->ls_key.ck_data,
316 			    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
317 			kmem_free(lsp->ls_key.ck_data,
318 			    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
319 			lsp->ls_key.ck_data = NULL;
320 			lsp->ls_key.ck_length = 0;
321 		}
322 
323 		if (lsp->ls_mech.cm_param != NULL) {
324 			kmem_free(lsp->ls_mech.cm_param,
325 			    lsp->ls_mech.cm_param_len);
326 			lsp->ls_mech.cm_param = NULL;
327 			lsp->ls_mech.cm_param_len = 0;
328 		}
329 
330 		if (lsp->ls_iv_mech.cm_param != NULL) {
331 			kmem_free(lsp->ls_iv_mech.cm_param,
332 			    lsp->ls_iv_mech.cm_param_len);
333 			lsp->ls_iv_mech.cm_param = NULL;
334 			lsp->ls_iv_mech.cm_param_len = 0;
335 		}
336 
337 		mutex_destroy(&lsp->ls_crypto_lock);
338 	}
339 }
340 
341 /* ARGSUSED */
342 static int
343 lofi_tg_rdwr(dev_info_t *dip, uchar_t cmd, void *bufaddr, diskaddr_t start,
344     size_t length, void *tg_cookie)
345 {
346 	struct lofi_state *lsp;
347 	buf_t	*bp;
348 	int	instance;
349 	int	rv = 0;
350 
351 	instance = ddi_get_instance(dip);
352 	if (instance == 0)	/* control node does not have disk */
353 		return (ENXIO);
354 
355 	lsp = ddi_get_soft_state(lofi_statep, instance);
356 
357 	if (lsp == NULL)
358 		return (ENXIO);
359 
360 	if (cmd != TG_READ && cmd != TG_WRITE)
361 		return (EINVAL);
362 
363 	/*
364 	 * Make sure the mapping is set up by checking lsp->ls_vp_ready.
365 	 */
366 	mutex_enter(&lsp->ls_vp_lock);
367 	while (lsp->ls_vp_ready == B_FALSE)
368 		cv_wait(&lsp->ls_vp_cv, &lsp->ls_vp_lock);
369 	mutex_exit(&lsp->ls_vp_lock);
370 
371 	if (P2PHASE(length, (1U << lsp->ls_lbshift)) != 0) {
372 		/* We can only transfer whole blocks at a time! */
373 		return (EINVAL);
374 	}
375 
376 	bp = getrbuf(KM_SLEEP);
377 
378 	if (cmd == TG_READ) {
379 		bp->b_flags = B_READ;
380 	} else {
381 		if (lsp->ls_readonly == B_TRUE) {
382 			freerbuf(bp);
383 			return (EROFS);
384 		}
385 		bp->b_flags = B_WRITE;
386 	}
387 
388 	bp->b_un.b_addr = bufaddr;
389 	bp->b_bcount = length;
390 	bp->b_lblkno = start;
391 	bp->b_private = NULL;
392 	bp->b_edev = lsp->ls_dev;
393 
394 	if (lsp->ls_kstat) {
395 		mutex_enter(lsp->ls_kstat->ks_lock);
396 		kstat_waitq_enter(KSTAT_IO_PTR(lsp->ls_kstat));
397 		mutex_exit(lsp->ls_kstat->ks_lock);
398 	}
399 	(void) taskq_dispatch(lsp->ls_taskq, lofi_strategy_task, bp, KM_SLEEP);
400 	(void) biowait(bp);
401 
402 	rv = geterror(bp);
403 	freerbuf(bp);
404 	return (rv);
405 }
406 
407 /*
408  * Get device geometry info for cmlb.
409  *
410  * We have mapped disk image as virtual block device and have to report
411  * physical/virtual geometry to cmlb.
412  *
413  * So we have two principal cases:
414  * 1. Uninitialised image without any existing labels,
415  *    for this case we fabricate the data based on mapped image.
416  * 2. Image with existing label information.
417  *    Since we have no information how the image was created (it may be
418  *    dump from some physical device), we need to rely on label information
419  *    from image, or we get "corrupted label" errors.
420  *    NOTE: label can be MBR, MBR+SMI, GPT
421  */
422 static int
423 lofi_tg_getinfo(dev_info_t *dip, int cmd, void *arg, void *tg_cookie)
424 {
425 	struct lofi_state *lsp;
426 	int instance;
427 	int ashift;
428 
429 	_NOTE(ARGUNUSED(tg_cookie));
430 	instance = ddi_get_instance(dip);
431 	if (instance == 0)		/* control device has no storage */
432 		return (ENXIO);
433 
434 	lsp = ddi_get_soft_state(lofi_statep, instance);
435 
436 	if (lsp == NULL)
437 		return (ENXIO);
438 
439 	/*
440 	 * Make sure the mapping is set up by checking lsp->ls_vp_ready.
441 	 *
442 	 * When mapping is created, new lofi instance is created and
443 	 * lofi_attach() will call cmlb_attach() as part of the procedure
444 	 * to set the mapping up. This chain of events will happen in
445 	 * the same thread.
446 	 * Since cmlb_attach() will call lofi_tg_getinfo to get
447 	 * capacity, we return error on that call if cookie is set,
448 	 * otherwise lofi_attach will be stuck as the mapping is not yet
449 	 * finalized and lofi is not yet ready.
450 	 * Note, such error is not fatal for cmlb, as the label setup
451 	 * will be finalized when cmlb_validate() is called.
452 	 */
453 	mutex_enter(&lsp->ls_vp_lock);
454 	if (tg_cookie != NULL && lsp->ls_vp_ready == B_FALSE) {
455 		mutex_exit(&lsp->ls_vp_lock);
456 		return (ENXIO);
457 	}
458 	while (lsp->ls_vp_ready == B_FALSE)
459 		cv_wait(&lsp->ls_vp_cv, &lsp->ls_vp_lock);
460 	mutex_exit(&lsp->ls_vp_lock);
461 
462 	ashift = lsp->ls_lbshift;
463 
464 	switch (cmd) {
465 	case TG_GETPHYGEOM: {
466 		cmlb_geom_t *geomp = arg;
467 
468 		geomp->g_capacity	=
469 		    (lsp->ls_vp_size - lsp->ls_crypto_offset) >> ashift;
470 		geomp->g_nsect		= lsp->ls_dkg.dkg_nsect;
471 		geomp->g_nhead		= lsp->ls_dkg.dkg_nhead;
472 		geomp->g_acyl		= lsp->ls_dkg.dkg_acyl;
473 		geomp->g_ncyl		= lsp->ls_dkg.dkg_ncyl;
474 		geomp->g_secsize	= (1U << ashift);
475 		geomp->g_intrlv		= lsp->ls_dkg.dkg_intrlv;
476 		geomp->g_rpm		= lsp->ls_dkg.dkg_rpm;
477 		return (0);
478 	}
479 
480 	case TG_GETCAPACITY:
481 		*(diskaddr_t *)arg =
482 		    (lsp->ls_vp_size - lsp->ls_crypto_offset) >> ashift;
483 		return (0);
484 
485 	case TG_GETBLOCKSIZE:
486 		*(uint32_t *)arg = (1U << ashift);
487 		return (0);
488 
489 	case TG_GETATTR: {
490 		tg_attribute_t *tgattr = arg;
491 
492 		tgattr->media_is_writable = !lsp->ls_readonly;
493 		tgattr->media_is_solid_state = B_FALSE;
494 		return (0);
495 	}
496 
497 	default:
498 		return (EINVAL);
499 	}
500 }
501 
502 static void
503 lofi_destroy(struct lofi_state *lsp, cred_t *credp)
504 {
505 	int id = LOFI_MINOR2ID(getminor(lsp->ls_dev));
506 	int i;
507 
508 	ASSERT(MUTEX_HELD(&lofi_lock));
509 
510 	list_remove(&lofi_list, lsp);
511 
512 	lofi_free_crypto(lsp);
513 
514 	/*
515 	 * Free pre-allocated compressed buffers
516 	 */
517 	if (lsp->ls_comp_bufs != NULL) {
518 		for (i = 0; i < lofi_taskq_nthreads; i++) {
519 			if (lsp->ls_comp_bufs[i].bufsize > 0)
520 				kmem_free(lsp->ls_comp_bufs[i].buf,
521 				    lsp->ls_comp_bufs[i].bufsize);
522 		}
523 		kmem_free(lsp->ls_comp_bufs,
524 		    sizeof (struct compbuf) * lofi_taskq_nthreads);
525 	}
526 
527 	if (lsp->ls_vp != NULL) {
528 		(void) VOP_PUTPAGE(lsp->ls_vp, 0, 0, B_INVAL, credp, NULL);
529 		(void) VOP_CLOSE(lsp->ls_vp, lsp->ls_openflag,
530 		    1, 0, credp, NULL);
531 		VN_RELE(lsp->ls_vp);
532 	}
533 	if (lsp->ls_stacked_vp != lsp->ls_vp)
534 		VN_RELE(lsp->ls_stacked_vp);
535 
536 	if (lsp->ls_taskq != NULL)
537 		taskq_destroy(lsp->ls_taskq);
538 
539 	if (lsp->ls_kstat != NULL)
540 		kstat_delete(lsp->ls_kstat);
541 
542 	/*
543 	 * Free cached decompressed segment data
544 	 */
545 	lofi_free_comp_cache(lsp);
546 	list_destroy(&lsp->ls_comp_cache);
547 
548 	if (lsp->ls_uncomp_seg_sz > 0) {
549 		kmem_free(lsp->ls_comp_index_data, lsp->ls_comp_index_data_sz);
550 		lsp->ls_uncomp_seg_sz = 0;
551 	}
552 
553 	rctl_decr_lofi(lsp->ls_zone.zref_zone, 1);
554 	zone_rele_ref(&lsp->ls_zone, ZONE_REF_LOFI);
555 
556 	mutex_destroy(&lsp->ls_comp_cache_lock);
557 	mutex_destroy(&lsp->ls_comp_bufs_lock);
558 	mutex_destroy(&lsp->ls_kstat_lock);
559 	mutex_destroy(&lsp->ls_vp_lock);
560 	cv_destroy(&lsp->ls_vp_cv);
561 	lsp->ls_vp_ready = B_FALSE;
562 
563 	ASSERT(ddi_get_soft_state(lofi_statep, id) == lsp);
564 	(void) ndi_devi_offline(lsp->ls_dip, NDI_DEVI_REMOVE);
565 	id_free(lofi_id, id);
566 }
567 
568 static void
569 lofi_free_dev(struct lofi_state *lsp)
570 {
571 	ASSERT(MUTEX_HELD(&lofi_lock));
572 
573 	if (lsp->ls_cmlbhandle != NULL) {
574 		cmlb_invalidate(lsp->ls_cmlbhandle, 0);
575 		cmlb_detach(lsp->ls_cmlbhandle, 0);
576 		cmlb_free_handle(&lsp->ls_cmlbhandle);
577 		lsp->ls_cmlbhandle = NULL;
578 	}
579 	(void) ddi_prop_remove_all(lsp->ls_dip);
580 	ddi_remove_minor_node(lsp->ls_dip, NULL);
581 }
582 
583 /*ARGSUSED*/
584 static void
585 lofi_zone_shutdown(zoneid_t zoneid, void *arg)
586 {
587 	struct lofi_state *lsp;
588 	struct lofi_state *next;
589 
590 	mutex_enter(&lofi_lock);
591 
592 	for (lsp = list_head(&lofi_list); lsp != NULL; lsp = next) {
593 
594 		/* lofi_destroy() frees lsp */
595 		next = list_next(&lofi_list, lsp);
596 
597 		if (lsp->ls_zone.zref_zone->zone_id != zoneid)
598 			continue;
599 
600 		/*
601 		 * No in-zone processes are running, but something has this
602 		 * open.  It's either a global zone process, or a lofi
603 		 * mount.  In either case we set ls_cleanup so the last
604 		 * user destroys the device.
605 		 */
606 		if (is_opened(lsp)) {
607 			lsp->ls_cleanup = 1;
608 		} else {
609 			lofi_free_dev(lsp);
610 			lofi_destroy(lsp, kcred);
611 		}
612 	}
613 
614 	mutex_exit(&lofi_lock);
615 }
616 
617 /*ARGSUSED*/
618 static int
619 lofi_open(dev_t *devp, int flag, int otyp, struct cred *credp)
620 {
621 	int id;
622 	minor_t	part;
623 	uint64_t mask;
624 	diskaddr_t nblks;
625 	diskaddr_t lba;
626 	boolean_t ndelay;
627 
628 	struct lofi_state *lsp;
629 
630 	if (otyp >= OTYPCNT)
631 		return (EINVAL);
632 
633 	ndelay = (flag & (FNDELAY | FNONBLOCK)) ? B_TRUE : B_FALSE;
634 
635 	/*
636 	 * lofiadm -a /dev/lofi/1 gets us here.
637 	 */
638 	if (mutex_owner(&lofi_lock) == curthread)
639 		return (EINVAL);
640 
641 	mutex_enter(&lofi_lock);
642 
643 	id = LOFI_MINOR2ID(getminor(*devp));
644 	part = LOFI_PART(getminor(*devp));
645 	mask = (1U << part);
646 
647 	/* master control device */
648 	if (id == 0) {
649 		mutex_exit(&lofi_lock);
650 		return (0);
651 	}
652 
653 	/* otherwise, the mapping should already exist */
654 	lsp = ddi_get_soft_state(lofi_statep, id);
655 	if (lsp == NULL) {
656 		mutex_exit(&lofi_lock);
657 		return (EINVAL);
658 	}
659 
660 	if (lsp->ls_vp == NULL) {
661 		mutex_exit(&lofi_lock);
662 		return (ENXIO);
663 	}
664 
665 	if (lsp->ls_readonly && (flag & FWRITE)) {
666 		mutex_exit(&lofi_lock);
667 		return (EROFS);
668 	}
669 
670 	if ((lsp->ls_open_excl) & (mask)) {
671 		mutex_exit(&lofi_lock);
672 		return (EBUSY);
673 	}
674 
675 	if (flag & FEXCL) {
676 		if (lsp->ls_open_lyr[part]) {
677 			mutex_exit(&lofi_lock);
678 			return (EBUSY);
679 		}
680 		for (int i = 0; i < OTYP_LYR; i++) {
681 			if (lsp->ls_open_reg[i] & mask) {
682 				mutex_exit(&lofi_lock);
683 				return (EBUSY);
684 			}
685 		}
686 	}
687 
688 	if (lsp->ls_cmlbhandle != NULL) {
689 		if (cmlb_validate(lsp->ls_cmlbhandle, 0, 0) != 0) {
690 			/*
691 			 * non-blocking opens are allowed to succeed to
692 			 * support format and fdisk to create partitioning.
693 			 */
694 			if (!ndelay) {
695 				mutex_exit(&lofi_lock);
696 				return (ENXIO);
697 			}
698 		} else if (cmlb_partinfo(lsp->ls_cmlbhandle, part, &nblks, &lba,
699 		    NULL, NULL, 0) == 0) {
700 			if ((!nblks) && ((!ndelay) || (otyp != OTYP_CHR))) {
701 				mutex_exit(&lofi_lock);
702 				return (ENXIO);
703 			}
704 		} else if (!ndelay) {
705 			mutex_exit(&lofi_lock);
706 			return (ENXIO);
707 		}
708 	}
709 
710 	if (otyp == OTYP_LYR) {
711 		lsp->ls_open_lyr[part]++;
712 	} else {
713 		lsp->ls_open_reg[otyp] |= mask;
714 	}
715 	if (flag & FEXCL) {
716 		lsp->ls_open_excl |= mask;
717 	}
718 
719 	mutex_exit(&lofi_lock);
720 	return (0);
721 }
722 
723 /*ARGSUSED*/
724 static int
725 lofi_close(dev_t dev, int flag, int otyp, struct cred *credp)
726 {
727 	minor_t	part;
728 	int id;
729 	uint64_t mask;
730 	struct lofi_state *lsp;
731 
732 	id = LOFI_MINOR2ID(getminor(dev));
733 	part = LOFI_PART(getminor(dev));
734 	mask = (1U << part);
735 
736 	mutex_enter(&lofi_lock);
737 	lsp = ddi_get_soft_state(lofi_statep, id);
738 	if (lsp == NULL) {
739 		mutex_exit(&lofi_lock);
740 		return (EINVAL);
741 	}
742 
743 	if (id == 0) {
744 		mutex_exit(&lofi_lock);
745 		return (0);
746 	}
747 
748 	if (lsp->ls_open_excl & mask)
749 		lsp->ls_open_excl &= ~mask;
750 
751 	if (otyp == OTYP_LYR) {
752 		lsp->ls_open_lyr[part]--;
753 	} else {
754 		lsp->ls_open_reg[otyp] &= ~mask;
755 	}
756 
757 	/*
758 	 * If we forcibly closed the underlying device (li_force), or
759 	 * asked for cleanup (li_cleanup), finish up if we're the last
760 	 * out of the door.
761 	 */
762 	if (!is_opened(lsp) && (lsp->ls_cleanup || lsp->ls_vp == NULL)) {
763 		lofi_free_dev(lsp);
764 		lofi_destroy(lsp, credp);
765 	}
766 
767 	mutex_exit(&lofi_lock);
768 	return (0);
769 }
770 
771 /*
772  * Sets the mechanism's initialization vector (IV) if one is needed.
773  * The IV is computed from the data block number.  lsp->ls_mech is
774  * altered so that:
775  *	lsp->ls_mech.cm_param_len is set to the IV len.
776  *	lsp->ls_mech.cm_param is set to the IV.
777  */
778 static int
779 lofi_blk_mech(struct lofi_state *lsp, longlong_t lblkno)
780 {
781 	int	ret;
782 	crypto_data_t cdata;
783 	char	*iv;
784 	size_t	iv_len;
785 	size_t	min;
786 	void	*data;
787 	size_t	datasz;
788 
789 	ASSERT(MUTEX_HELD(&lsp->ls_crypto_lock));
790 
791 	if (lsp == NULL)
792 		return (CRYPTO_DEVICE_ERROR);
793 
794 	/* lsp->ls_mech.cm_param{_len} has already been set for static iv */
795 	if (lsp->ls_iv_type == IVM_NONE) {
796 		return (CRYPTO_SUCCESS);
797 	}
798 
799 	/*
800 	 * if kmem already alloced from previous call and it's the same size
801 	 * we need now, just recycle it; allocate new kmem only if we have to
802 	 */
803 	if (lsp->ls_mech.cm_param == NULL ||
804 	    lsp->ls_mech.cm_param_len != lsp->ls_iv_len) {
805 		iv_len = lsp->ls_iv_len;
806 		iv = kmem_zalloc(iv_len, KM_SLEEP);
807 	} else {
808 		iv_len = lsp->ls_mech.cm_param_len;
809 		iv = lsp->ls_mech.cm_param;
810 		bzero(iv, iv_len);
811 	}
812 
813 	switch (lsp->ls_iv_type) {
814 	case IVM_ENC_BLKNO:
815 		/* iv is not static, lblkno changes each time */
816 		data = &lblkno;
817 		datasz = sizeof (lblkno);
818 		break;
819 	default:
820 		data = 0;
821 		datasz = 0;
822 		break;
823 	}
824 
825 	/*
826 	 * write blkno into the iv buffer padded on the left in case
827 	 * blkno ever grows bigger than its current longlong_t size
828 	 * or a variation other than blkno is used for the iv data
829 	 */
830 	min = MIN(datasz, iv_len);
831 	bcopy(data, iv + (iv_len - min), min);
832 
833 	/* encrypt the data in-place to get the IV */
834 	SETUP_C_DATA(cdata, iv, iv_len);
835 
836 	ret = crypto_encrypt(&lsp->ls_iv_mech, &cdata, &lsp->ls_key,
837 	    NULL, NULL, NULL);
838 	if (ret != CRYPTO_SUCCESS) {
839 		cmn_err(CE_WARN, "failed to create iv for block %lld: (0x%x)",
840 		    lblkno, ret);
841 		if (lsp->ls_mech.cm_param != iv)
842 			kmem_free(iv, iv_len);
843 
844 		return (ret);
845 	}
846 
847 	/* clean up the iv from the last computation */
848 	if (lsp->ls_mech.cm_param != NULL && lsp->ls_mech.cm_param != iv)
849 		kmem_free(lsp->ls_mech.cm_param, lsp->ls_mech.cm_param_len);
850 
851 	lsp->ls_mech.cm_param_len = iv_len;
852 	lsp->ls_mech.cm_param = iv;
853 
854 	return (CRYPTO_SUCCESS);
855 }
856 
857 /*
858  * Performs encryption and decryption of a chunk of data of size "len",
859  * one DEV_BSIZE block at a time.  "len" is assumed to be a multiple of
860  * DEV_BSIZE.
861  */
862 static int
863 lofi_crypto(struct lofi_state *lsp, struct buf *bp, caddr_t plaintext,
864     caddr_t ciphertext, size_t len, boolean_t op_encrypt)
865 {
866 	crypto_data_t cdata;
867 	crypto_data_t wdata;
868 	int ret;
869 	longlong_t lblkno = bp->b_lblkno;
870 
871 	mutex_enter(&lsp->ls_crypto_lock);
872 
873 	/*
874 	 * though we could encrypt/decrypt entire "len" chunk of data, we need
875 	 * to break it into DEV_BSIZE pieces to capture blkno incrementing
876 	 */
877 	SETUP_C_DATA(cdata, plaintext, len);
878 	cdata.cd_length = DEV_BSIZE;
879 	if (ciphertext != NULL) {		/* not in-place crypto */
880 		SETUP_C_DATA(wdata, ciphertext, len);
881 		wdata.cd_length = DEV_BSIZE;
882 	}
883 
884 	do {
885 		ret = lofi_blk_mech(lsp, lblkno);
886 		if (ret != CRYPTO_SUCCESS)
887 			continue;
888 
889 		if (op_encrypt) {
890 			ret = crypto_encrypt(&lsp->ls_mech, &cdata,
891 			    &lsp->ls_key, NULL,
892 			    ((ciphertext != NULL) ? &wdata : NULL), NULL);
893 		} else {
894 			ret = crypto_decrypt(&lsp->ls_mech, &cdata,
895 			    &lsp->ls_key, NULL,
896 			    ((ciphertext != NULL) ? &wdata : NULL), NULL);
897 		}
898 
899 		cdata.cd_offset += DEV_BSIZE;
900 		if (ciphertext != NULL)
901 			wdata.cd_offset += DEV_BSIZE;
902 		lblkno++;
903 	} while (ret == CRYPTO_SUCCESS && cdata.cd_offset < len);
904 
905 	mutex_exit(&lsp->ls_crypto_lock);
906 
907 	if (ret != CRYPTO_SUCCESS) {
908 		cmn_err(CE_WARN, "%s failed for block %lld:  (0x%x)",
909 		    op_encrypt ? "crypto_encrypt()" : "crypto_decrypt()",
910 		    lblkno, ret);
911 	}
912 
913 	return (ret);
914 }
915 
916 #define	RDWR_RAW	1
917 #define	RDWR_BCOPY	2
918 
919 static int
920 lofi_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp,
921     struct lofi_state *lsp, size_t len, int method, caddr_t bcopy_locn)
922 {
923 	ssize_t resid;
924 	int isread;
925 	int error;
926 
927 	/*
928 	 * Handles reads/writes for both plain and encrypted lofi
929 	 * Note:  offset is already shifted by lsp->ls_crypto_offset
930 	 * when it gets here.
931 	 */
932 
933 	isread = bp->b_flags & B_READ;
934 	if (isread) {
935 		if (method == RDWR_BCOPY) {
936 			/* DO NOT update bp->b_resid for bcopy */
937 			bcopy(bcopy_locn, bufaddr, len);
938 			error = 0;
939 		} else {		/* RDWR_RAW */
940 			error = vn_rdwr(UIO_READ, lsp->ls_vp, bufaddr, len,
941 			    offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred,
942 			    &resid);
943 			bp->b_resid = resid;
944 		}
945 		if (lsp->ls_crypto_enabled && error == 0) {
946 			if (lofi_crypto(lsp, bp, bufaddr, NULL, len,
947 			    B_FALSE) != CRYPTO_SUCCESS) {
948 				/*
949 				 * XXX: original code didn't set residual
950 				 * back to len because no error was expected
951 				 * from bcopy() if encryption is not enabled
952 				 */
953 				if (method != RDWR_BCOPY)
954 					bp->b_resid = len;
955 				error = EIO;
956 			}
957 		}
958 		return (error);
959 	} else {
960 		void *iobuf = bufaddr;
961 
962 		if (lsp->ls_crypto_enabled) {
963 			/* don't do in-place crypto to keep bufaddr intact */
964 			iobuf = kmem_alloc(len, KM_SLEEP);
965 			if (lofi_crypto(lsp, bp, bufaddr, iobuf, len,
966 			    B_TRUE) != CRYPTO_SUCCESS) {
967 				kmem_free(iobuf, len);
968 				if (method != RDWR_BCOPY)
969 					bp->b_resid = len;
970 				return (EIO);
971 			}
972 		}
973 		if (method == RDWR_BCOPY) {
974 			/* DO NOT update bp->b_resid for bcopy */
975 			bcopy(iobuf, bcopy_locn, len);
976 			error = 0;
977 		} else {		/* RDWR_RAW */
978 			error = vn_rdwr(UIO_WRITE, lsp->ls_vp, iobuf, len,
979 			    offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred,
980 			    &resid);
981 			bp->b_resid = resid;
982 		}
983 		if (lsp->ls_crypto_enabled) {
984 			kmem_free(iobuf, len);
985 		}
986 		return (error);
987 	}
988 }
989 
990 static int
991 lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp,
992     struct lofi_state *lsp)
993 {
994 	int error;
995 	offset_t alignedoffset, mapoffset;
996 	size_t	xfersize;
997 	int	isread;
998 	int	smflags;
999 	caddr_t	mapaddr;
1000 	size_t	len;
1001 	enum seg_rw srw;
1002 	int	save_error;
1003 
1004 	/*
1005 	 * Note:  offset is already shifted by lsp->ls_crypto_offset
1006 	 * when it gets here.
1007 	 */
1008 	if (lsp->ls_crypto_enabled)
1009 		ASSERT(lsp->ls_vp_comp_size == lsp->ls_vp_size);
1010 
1011 	/*
1012 	 * segmap always gives us an 8K (MAXBSIZE) chunk, aligned on
1013 	 * an 8K boundary, but the buf transfer address may not be
1014 	 * aligned on more than a 512-byte boundary (we don't enforce
1015 	 * that even though we could). This matters since the initial
1016 	 * part of the transfer may not start at offset 0 within the
1017 	 * segmap'd chunk. So we have to compensate for that with
1018 	 * 'mapoffset'. Subsequent chunks always start off at the
1019 	 * beginning, and the last is capped by b_resid
1020 	 *
1021 	 * Visually, where "|" represents page map boundaries:
1022 	 *   alignedoffset (mapaddr begins at this segmap boundary)
1023 	 *    |   offset (from beginning of file)
1024 	 *    |    |	   len
1025 	 *    v    v	    v
1026 	 * ===|====X========|====...======|========X====|====
1027 	 *	   /-------------...---------------/
1028 	 *		^ bp->b_bcount/bp->b_resid at start
1029 	 *    /----/--------/----...------/--------/
1030 	 *	^	^	^   ^		^
1031 	 *	|	|	|   |		nth xfersize (<= MAXBSIZE)
1032 	 *	|	|	2nd thru n-1st xfersize (= MAXBSIZE)
1033 	 *	|	1st xfersize (<= MAXBSIZE)
1034 	 *    mapoffset (offset into 1st segmap, non-0 1st time, 0 thereafter)
1035 	 *
1036 	 * Notes: "alignedoffset" is "offset" rounded down to nearest
1037 	 * MAXBSIZE boundary.  "len" is next page boundary of size
1038 	 * PAGESIZE after "alignedoffset".
1039 	 */
1040 	mapoffset = offset & MAXBOFFSET;
1041 	alignedoffset = offset - mapoffset;
1042 	bp->b_resid = bp->b_bcount;
1043 	isread = bp->b_flags & B_READ;
1044 	srw = isread ? S_READ : S_WRITE;
1045 	do {
1046 		xfersize = MIN(lsp->ls_vp_comp_size - offset,
1047 		    MIN(MAXBSIZE - mapoffset, bp->b_resid));
1048 		len = roundup(mapoffset + xfersize, PAGESIZE);
1049 		mapaddr = segmap_getmapflt(segkmap, lsp->ls_vp,
1050 		    alignedoffset, MAXBSIZE, 1, srw);
1051 		/*
1052 		 * Now fault in the pages. This lets us check
1053 		 * for errors before we reference mapaddr and
1054 		 * try to resolve the fault in bcopy (which would
1055 		 * panic instead). And this can easily happen,
1056 		 * particularly if you've lofi'd a file over NFS
1057 		 * and someone deletes the file on the server.
1058 		 */
1059 		error = segmap_fault(kas.a_hat, segkmap, mapaddr,
1060 		    len, F_SOFTLOCK, srw);
1061 		if (error) {
1062 			(void) segmap_release(segkmap, mapaddr, 0);
1063 			if (FC_CODE(error) == FC_OBJERR)
1064 				error = FC_ERRNO(error);
1065 			else
1066 				error = EIO;
1067 			break;
1068 		}
1069 		/* error may be non-zero for encrypted lofi */
1070 		error = lofi_rdwr(bufaddr, 0, bp, lsp, xfersize,
1071 		    RDWR_BCOPY, mapaddr + mapoffset);
1072 		if (error == 0) {
1073 			bp->b_resid -= xfersize;
1074 			bufaddr += xfersize;
1075 			offset += xfersize;
1076 		}
1077 		smflags = 0;
1078 		if (isread) {
1079 			smflags |= SM_FREE;
1080 			/*
1081 			 * If we're reading an entire page starting
1082 			 * at a page boundary, there's a good chance
1083 			 * we won't need it again. Put it on the
1084 			 * head of the freelist.
1085 			 */
1086 			if (mapoffset == 0 && xfersize == MAXBSIZE)
1087 				smflags |= SM_DONTNEED;
1088 		} else {
1089 			/*
1090 			 * Write back good pages, it is okay to
1091 			 * always release asynchronous here as we'll
1092 			 * follow with VOP_FSYNC for B_SYNC buffers.
1093 			 */
1094 			if (error == 0)
1095 				smflags |= SM_WRITE | SM_ASYNC;
1096 		}
1097 		(void) segmap_fault(kas.a_hat, segkmap, mapaddr,
1098 		    len, F_SOFTUNLOCK, srw);
1099 		save_error = segmap_release(segkmap, mapaddr, smflags);
1100 		if (error == 0)
1101 			error = save_error;
1102 		/* only the first map may start partial */
1103 		mapoffset = 0;
1104 		alignedoffset += MAXBSIZE;
1105 	} while ((error == 0) && (bp->b_resid > 0) &&
1106 	    (offset < lsp->ls_vp_comp_size));
1107 
1108 	return (error);
1109 }
1110 
1111 /*
1112  * Check if segment seg_index is present in the decompressed segment
1113  * data cache.
1114  *
1115  * Returns a pointer to the decompressed segment data cache entry if
1116  * found, and NULL when decompressed data for this segment is not yet
1117  * cached.
1118  */
1119 static struct lofi_comp_cache *
1120 lofi_find_comp_data(struct lofi_state *lsp, uint64_t seg_index)
1121 {
1122 	struct lofi_comp_cache *lc;
1123 
1124 	ASSERT(MUTEX_HELD(&lsp->ls_comp_cache_lock));
1125 
1126 	for (lc = list_head(&lsp->ls_comp_cache); lc != NULL;
1127 	    lc = list_next(&lsp->ls_comp_cache, lc)) {
1128 		if (lc->lc_index == seg_index) {
1129 			/*
1130 			 * Decompressed segment data was found in the
1131 			 * cache.
1132 			 *
1133 			 * The cache uses an LRU replacement strategy;
1134 			 * move the entry to head of list.
1135 			 */
1136 			list_remove(&lsp->ls_comp_cache, lc);
1137 			list_insert_head(&lsp->ls_comp_cache, lc);
1138 			return (lc);
1139 		}
1140 	}
1141 	return (NULL);
1142 }
1143 
1144 /*
1145  * Add the data for a decompressed segment at segment index
1146  * seg_index to the cache of the decompressed segments.
1147  *
1148  * Returns a pointer to the cache element structure in case
1149  * the data was added to the cache; returns NULL when the data
1150  * wasn't cached.
1151  */
1152 static struct lofi_comp_cache *
1153 lofi_add_comp_data(struct lofi_state *lsp, uint64_t seg_index,
1154     uchar_t *data)
1155 {
1156 	struct lofi_comp_cache *lc;
1157 
1158 	ASSERT(MUTEX_HELD(&lsp->ls_comp_cache_lock));
1159 
1160 	while (lsp->ls_comp_cache_count > lofi_max_comp_cache) {
1161 		lc = list_remove_tail(&lsp->ls_comp_cache);
1162 		ASSERT(lc != NULL);
1163 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
1164 		kmem_free(lc, sizeof (struct lofi_comp_cache));
1165 		lsp->ls_comp_cache_count--;
1166 	}
1167 
1168 	/*
1169 	 * Do not cache when disabled by tunable variable
1170 	 */
1171 	if (lofi_max_comp_cache == 0)
1172 		return (NULL);
1173 
1174 	/*
1175 	 * When the cache has not yet reached the maximum allowed
1176 	 * number of segments, allocate a new cache element.
1177 	 * Otherwise the cache is full; reuse the last list element
1178 	 * (LRU) for caching the decompressed segment data.
1179 	 *
1180 	 * The cache element for the new decompressed segment data is
1181 	 * added to the head of the list.
1182 	 */
1183 	if (lsp->ls_comp_cache_count < lofi_max_comp_cache) {
1184 		lc = kmem_alloc(sizeof (struct lofi_comp_cache), KM_SLEEP);
1185 		lc->lc_data = NULL;
1186 		list_insert_head(&lsp->ls_comp_cache, lc);
1187 		lsp->ls_comp_cache_count++;
1188 	} else {
1189 		lc = list_remove_tail(&lsp->ls_comp_cache);
1190 		if (lc == NULL)
1191 			return (NULL);
1192 		list_insert_head(&lsp->ls_comp_cache, lc);
1193 	}
1194 
1195 	/*
1196 	 * Free old uncompressed segment data when reusing a cache
1197 	 * entry.
1198 	 */
1199 	if (lc->lc_data != NULL)
1200 		kmem_free(lc->lc_data, lsp->ls_uncomp_seg_sz);
1201 
1202 	lc->lc_data = data;
1203 	lc->lc_index = seg_index;
1204 	return (lc);
1205 }
1206 
1207 
1208 /*ARGSUSED*/
1209 static int
1210 gzip_decompress(void *src, size_t srclen, void *dst,
1211     size_t *dstlen, int level)
1212 {
1213 	ASSERT(*dstlen >= srclen);
1214 
1215 	if (z_uncompress(dst, dstlen, src, srclen) != Z_OK)
1216 		return (-1);
1217 	return (0);
1218 }
1219 
1220 #define	LZMA_HEADER_SIZE	(LZMA_PROPS_SIZE + 8)
1221 /*ARGSUSED*/
1222 static int
1223 lzma_decompress(void *src, size_t srclen, void *dst,
1224     size_t *dstlen, int level)
1225 {
1226 	size_t insizepure;
1227 	void *actual_src;
1228 	ELzmaStatus status;
1229 
1230 	insizepure = srclen - LZMA_HEADER_SIZE;
1231 	actual_src = (void *)((Byte *)src + LZMA_HEADER_SIZE);
1232 
1233 	if (LzmaDecode((Byte *)dst, (size_t *)dstlen,
1234 	    (const Byte *)actual_src, &insizepure,
1235 	    (const Byte *)src, LZMA_PROPS_SIZE, LZMA_FINISH_ANY, &status,
1236 	    &g_Alloc) != SZ_OK) {
1237 		return (-1);
1238 	}
1239 	return (0);
1240 }
1241 
1242 /*
1243  * This is basically what strategy used to be before we found we
1244  * needed task queues.
1245  */
1246 static void
1247 lofi_strategy_task(void *arg)
1248 {
1249 	struct buf *bp = (struct buf *)arg;
1250 	int error;
1251 	int syncflag = 0;
1252 	struct lofi_state *lsp;
1253 	offset_t offset;
1254 	caddr_t	bufaddr;
1255 	size_t	len;
1256 	size_t	xfersize;
1257 	boolean_t bufinited = B_FALSE;
1258 
1259 	lsp = ddi_get_soft_state(lofi_statep,
1260 	    LOFI_MINOR2ID(getminor(bp->b_edev)));
1261 
1262 	if (lsp == NULL) {
1263 		error = ENXIO;
1264 		goto errout;
1265 	}
1266 	if (lsp->ls_kstat) {
1267 		mutex_enter(lsp->ls_kstat->ks_lock);
1268 		kstat_waitq_to_runq(KSTAT_IO_PTR(lsp->ls_kstat));
1269 		mutex_exit(lsp->ls_kstat->ks_lock);
1270 	}
1271 
1272 	mutex_enter(&lsp->ls_vp_lock);
1273 	lsp->ls_vp_iocount++;
1274 	mutex_exit(&lsp->ls_vp_lock);
1275 
1276 	bp_mapin(bp);
1277 	bufaddr = bp->b_un.b_addr;
1278 	offset = (bp->b_lblkno + (diskaddr_t)(uintptr_t)bp->b_private)
1279 	    << lsp->ls_lbshift;	/* offset within file */
1280 	if (lsp->ls_crypto_enabled) {
1281 		/* encrypted data really begins after crypto header */
1282 		offset += lsp->ls_crypto_offset;
1283 	}
1284 	len = bp->b_bcount;
1285 	bufinited = B_TRUE;
1286 
1287 	if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) {
1288 		error = EIO;
1289 		goto errout;
1290 	}
1291 
1292 	/*
1293 	 * If we're writing and the buffer was not B_ASYNC
1294 	 * we'll follow up with a VOP_FSYNC() to force any
1295 	 * asynchronous I/O to stable storage.
1296 	 */
1297 	if (!(bp->b_flags & B_READ) && !(bp->b_flags & B_ASYNC))
1298 		syncflag = FSYNC;
1299 
1300 	/*
1301 	 * We used to always use vn_rdwr here, but we cannot do that because
1302 	 * we might decide to read or write from the the underlying
1303 	 * file during this call, which would be a deadlock because
1304 	 * we have the rw_lock. So instead we page, unless it's not
1305 	 * mapable or it's a character device or it's an encrypted lofi.
1306 	 */
1307 	if ((lsp->ls_vp->v_flag & VNOMAP) || (lsp->ls_vp->v_type == VCHR) ||
1308 	    lsp->ls_crypto_enabled) {
1309 		error = lofi_rdwr(bufaddr, offset, bp, lsp, len, RDWR_RAW,
1310 		    NULL);
1311 	} else if (lsp->ls_uncomp_seg_sz == 0) {
1312 		error = lofi_mapped_rdwr(bufaddr, offset, bp, lsp);
1313 	} else {
1314 		uchar_t *compressed_seg = NULL, *cmpbuf;
1315 		uchar_t *uncompressed_seg = NULL;
1316 		lofi_compress_info_t *li;
1317 		size_t oblkcount;
1318 		ulong_t seglen;
1319 		uint64_t sblkno, eblkno, cmpbytes;
1320 		uint64_t uncompressed_seg_index;
1321 		struct lofi_comp_cache *lc;
1322 		offset_t sblkoff, eblkoff;
1323 		u_offset_t salign, ealign;
1324 		u_offset_t sdiff;
1325 		uint32_t comp_data_sz;
1326 		uint64_t i;
1327 		int j;
1328 
1329 		/*
1330 		 * From here on we're dealing primarily with compressed files
1331 		 */
1332 		ASSERT(!lsp->ls_crypto_enabled);
1333 
1334 		/*
1335 		 * Compressed files can only be read from and
1336 		 * not written to
1337 		 */
1338 		if (!(bp->b_flags & B_READ)) {
1339 			bp->b_resid = bp->b_bcount;
1340 			error = EROFS;
1341 			goto done;
1342 		}
1343 
1344 		ASSERT(lsp->ls_comp_algorithm_index >= 0);
1345 		li = &lofi_compress_table[lsp->ls_comp_algorithm_index];
1346 		/*
1347 		 * Compute starting and ending compressed segment numbers
1348 		 * We use only bitwise operations avoiding division and
1349 		 * modulus because we enforce the compression segment size
1350 		 * to a power of 2
1351 		 */
1352 		sblkno = offset >> lsp->ls_comp_seg_shift;
1353 		sblkoff = offset & (lsp->ls_uncomp_seg_sz - 1);
1354 		eblkno = (offset + bp->b_bcount) >> lsp->ls_comp_seg_shift;
1355 		eblkoff = (offset + bp->b_bcount) & (lsp->ls_uncomp_seg_sz - 1);
1356 
1357 		/*
1358 		 * Check the decompressed segment cache.
1359 		 *
1360 		 * The cache is used only when the requested data
1361 		 * is within a segment. Requests that cross
1362 		 * segment boundaries bypass the cache.
1363 		 */
1364 		if (sblkno == eblkno ||
1365 		    (sblkno + 1 == eblkno && eblkoff == 0)) {
1366 			/*
1367 			 * Request doesn't cross a segment boundary,
1368 			 * now check the cache.
1369 			 */
1370 			mutex_enter(&lsp->ls_comp_cache_lock);
1371 			lc = lofi_find_comp_data(lsp, sblkno);
1372 			if (lc != NULL) {
1373 				/*
1374 				 * We've found the decompressed segment
1375 				 * data in the cache; reuse it.
1376 				 */
1377 				bcopy(lc->lc_data + sblkoff, bufaddr,
1378 				    bp->b_bcount);
1379 				mutex_exit(&lsp->ls_comp_cache_lock);
1380 				bp->b_resid = 0;
1381 				error = 0;
1382 				goto done;
1383 			}
1384 			mutex_exit(&lsp->ls_comp_cache_lock);
1385 		}
1386 
1387 		/*
1388 		 * Align start offset to block boundary for segmap
1389 		 */
1390 		salign = lsp->ls_comp_seg_index[sblkno];
1391 		sdiff = salign & (DEV_BSIZE - 1);
1392 		salign -= sdiff;
1393 		if (eblkno >= (lsp->ls_comp_index_sz - 1)) {
1394 			/*
1395 			 * We're dealing with the last segment of
1396 			 * the compressed file -- the size of this
1397 			 * segment *may not* be the same as the
1398 			 * segment size for the file
1399 			 */
1400 			eblkoff = (offset + bp->b_bcount) &
1401 			    (lsp->ls_uncomp_last_seg_sz - 1);
1402 			ealign = lsp->ls_vp_comp_size;
1403 		} else {
1404 			ealign = lsp->ls_comp_seg_index[eblkno + 1];
1405 		}
1406 
1407 		/*
1408 		 * Preserve original request paramaters
1409 		 */
1410 		oblkcount = bp->b_bcount;
1411 
1412 		/*
1413 		 * Assign the calculated parameters
1414 		 */
1415 		comp_data_sz = ealign - salign;
1416 		bp->b_bcount = comp_data_sz;
1417 
1418 		/*
1419 		 * Buffers to hold compressed segments are pre-allocated
1420 		 * on a per-thread basis. Find a pre-allocated buffer
1421 		 * that is not currently in use and mark it for use.
1422 		 */
1423 		mutex_enter(&lsp->ls_comp_bufs_lock);
1424 		for (j = 0; j < lofi_taskq_nthreads; j++) {
1425 			if (lsp->ls_comp_bufs[j].inuse == 0) {
1426 				lsp->ls_comp_bufs[j].inuse = 1;
1427 				break;
1428 			}
1429 		}
1430 
1431 		mutex_exit(&lsp->ls_comp_bufs_lock);
1432 		ASSERT(j < lofi_taskq_nthreads);
1433 
1434 		/*
1435 		 * If the pre-allocated buffer size does not match
1436 		 * the size of the I/O request, re-allocate it with
1437 		 * the appropriate size
1438 		 */
1439 		if (lsp->ls_comp_bufs[j].bufsize < bp->b_bcount) {
1440 			if (lsp->ls_comp_bufs[j].bufsize > 0)
1441 				kmem_free(lsp->ls_comp_bufs[j].buf,
1442 				    lsp->ls_comp_bufs[j].bufsize);
1443 			lsp->ls_comp_bufs[j].buf = kmem_alloc(bp->b_bcount,
1444 			    KM_SLEEP);
1445 			lsp->ls_comp_bufs[j].bufsize = bp->b_bcount;
1446 		}
1447 		compressed_seg = lsp->ls_comp_bufs[j].buf;
1448 
1449 		/*
1450 		 * Map in the calculated number of blocks
1451 		 */
1452 		error = lofi_mapped_rdwr((caddr_t)compressed_seg, salign,
1453 		    bp, lsp);
1454 
1455 		bp->b_bcount = oblkcount;
1456 		bp->b_resid = oblkcount;
1457 		if (error != 0)
1458 			goto done;
1459 
1460 		/*
1461 		 * decompress compressed blocks start
1462 		 */
1463 		cmpbuf = compressed_seg + sdiff;
1464 		for (i = sblkno; i <= eblkno; i++) {
1465 			ASSERT(i < lsp->ls_comp_index_sz - 1);
1466 			uchar_t *useg;
1467 
1468 			/*
1469 			 * The last segment is special in that it is
1470 			 * most likely not going to be the same
1471 			 * (uncompressed) size as the other segments.
1472 			 */
1473 			if (i == (lsp->ls_comp_index_sz - 2)) {
1474 				seglen = lsp->ls_uncomp_last_seg_sz;
1475 			} else {
1476 				seglen = lsp->ls_uncomp_seg_sz;
1477 			}
1478 
1479 			/*
1480 			 * Each of the segment index entries contains
1481 			 * the starting block number for that segment.
1482 			 * The number of compressed bytes in a segment
1483 			 * is thus the difference between the starting
1484 			 * block number of this segment and the starting
1485 			 * block number of the next segment.
1486 			 */
1487 			cmpbytes = lsp->ls_comp_seg_index[i + 1] -
1488 			    lsp->ls_comp_seg_index[i];
1489 
1490 			/*
1491 			 * The first byte in a compressed segment is a flag
1492 			 * that indicates whether this segment is compressed
1493 			 * at all.
1494 			 *
1495 			 * The variable 'useg' is used (instead of
1496 			 * uncompressed_seg) in this loop to keep a
1497 			 * reference to the uncompressed segment.
1498 			 *
1499 			 * N.B. If 'useg' is replaced with uncompressed_seg,
1500 			 * it leads to memory leaks and heap corruption in
1501 			 * corner cases where compressed segments lie
1502 			 * adjacent to uncompressed segments.
1503 			 */
1504 			if (*cmpbuf == UNCOMPRESSED) {
1505 				useg = cmpbuf + SEGHDR;
1506 			} else {
1507 				if (uncompressed_seg == NULL)
1508 					uncompressed_seg =
1509 					    kmem_alloc(lsp->ls_uncomp_seg_sz,
1510 					    KM_SLEEP);
1511 				useg = uncompressed_seg;
1512 				uncompressed_seg_index = i;
1513 
1514 				if (li->l_decompress((cmpbuf + SEGHDR),
1515 				    (cmpbytes - SEGHDR), uncompressed_seg,
1516 				    &seglen, li->l_level) != 0) {
1517 					error = EIO;
1518 					goto done;
1519 				}
1520 			}
1521 
1522 			/*
1523 			 * Determine how much uncompressed data we
1524 			 * have to copy and copy it
1525 			 */
1526 			xfersize = lsp->ls_uncomp_seg_sz - sblkoff;
1527 			if (i == eblkno)
1528 				xfersize -= (lsp->ls_uncomp_seg_sz - eblkoff);
1529 
1530 			bcopy((useg + sblkoff), bufaddr, xfersize);
1531 
1532 			cmpbuf += cmpbytes;
1533 			bufaddr += xfersize;
1534 			bp->b_resid -= xfersize;
1535 			sblkoff = 0;
1536 
1537 			if (bp->b_resid == 0)
1538 				break;
1539 		} /* decompress compressed blocks ends */
1540 
1541 		/*
1542 		 * Skip to done if there is no uncompressed data to cache
1543 		 */
1544 		if (uncompressed_seg == NULL)
1545 			goto done;
1546 
1547 		/*
1548 		 * Add the data for the last decompressed segment to
1549 		 * the cache.
1550 		 *
1551 		 * In case the uncompressed segment data was added to (and
1552 		 * is referenced by) the cache, make sure we don't free it
1553 		 * here.
1554 		 */
1555 		mutex_enter(&lsp->ls_comp_cache_lock);
1556 		if ((lc = lofi_add_comp_data(lsp, uncompressed_seg_index,
1557 		    uncompressed_seg)) != NULL) {
1558 			uncompressed_seg = NULL;
1559 		}
1560 		mutex_exit(&lsp->ls_comp_cache_lock);
1561 
1562 done:
1563 		if (compressed_seg != NULL) {
1564 			mutex_enter(&lsp->ls_comp_bufs_lock);
1565 			lsp->ls_comp_bufs[j].inuse = 0;
1566 			mutex_exit(&lsp->ls_comp_bufs_lock);
1567 		}
1568 		if (uncompressed_seg != NULL)
1569 			kmem_free(uncompressed_seg, lsp->ls_uncomp_seg_sz);
1570 	} /* end of handling compressed files */
1571 
1572 	if ((error == 0) && (syncflag != 0))
1573 		error = VOP_FSYNC(lsp->ls_vp, syncflag, kcred, NULL);
1574 
1575 errout:
1576 	if (bufinited && lsp->ls_kstat) {
1577 		size_t n_done = bp->b_bcount - bp->b_resid;
1578 		kstat_io_t *kioptr;
1579 
1580 		mutex_enter(lsp->ls_kstat->ks_lock);
1581 		kioptr = KSTAT_IO_PTR(lsp->ls_kstat);
1582 		if (bp->b_flags & B_READ) {
1583 			kioptr->nread += n_done;
1584 			kioptr->reads++;
1585 		} else {
1586 			kioptr->nwritten += n_done;
1587 			kioptr->writes++;
1588 		}
1589 		kstat_runq_exit(kioptr);
1590 		mutex_exit(lsp->ls_kstat->ks_lock);
1591 	}
1592 
1593 	mutex_enter(&lsp->ls_vp_lock);
1594 	if (--lsp->ls_vp_iocount == 0)
1595 		cv_broadcast(&lsp->ls_vp_cv);
1596 	mutex_exit(&lsp->ls_vp_lock);
1597 
1598 	bioerror(bp, error);
1599 	biodone(bp);
1600 }
1601 
1602 static int
1603 lofi_strategy(struct buf *bp)
1604 {
1605 	struct lofi_state *lsp;
1606 	offset_t	offset;
1607 	minor_t		part;
1608 	diskaddr_t	p_lba;
1609 	diskaddr_t	p_nblks;
1610 	int		shift;
1611 
1612 	/*
1613 	 * We cannot just do I/O here, because the current thread
1614 	 * _might_ end up back in here because the underlying filesystem
1615 	 * wants a buffer, which eventually gets into bio_recycle and
1616 	 * might call into lofi to write out a delayed-write buffer.
1617 	 * This is bad if the filesystem above lofi is the same as below.
1618 	 *
1619 	 * We could come up with a complex strategy using threads to
1620 	 * do the I/O asynchronously, or we could use task queues. task
1621 	 * queues were incredibly easy so they win.
1622 	 */
1623 
1624 	lsp = ddi_get_soft_state(lofi_statep,
1625 	    LOFI_MINOR2ID(getminor(bp->b_edev)));
1626 	part = LOFI_PART(getminor(bp->b_edev));
1627 
1628 	if (lsp == NULL) {
1629 		bioerror(bp, ENXIO);
1630 		biodone(bp);
1631 		return (0);
1632 	}
1633 	shift = lsp->ls_lbshift;
1634 
1635 	p_lba = 0;
1636 	p_nblks = lsp->ls_vp_size >> shift;
1637 
1638 	if (lsp->ls_cmlbhandle != NULL) {
1639 		if (cmlb_partinfo(lsp->ls_cmlbhandle, part, &p_nblks, &p_lba,
1640 		    NULL, NULL, 0)) {
1641 			bioerror(bp, ENXIO);
1642 			biodone(bp);
1643 			return (0);
1644 		}
1645 	}
1646 
1647 	/* start block past partition end? */
1648 	if (bp->b_lblkno > p_nblks) {
1649 		bioerror(bp, ENXIO);
1650 		biodone(bp);
1651 		return (0);
1652 	}
1653 
1654 	offset = (bp->b_lblkno+p_lba) << shift;	/* offset within file */
1655 
1656 	mutex_enter(&lsp->ls_vp_lock);
1657 	if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) {
1658 		bioerror(bp, EIO);
1659 		biodone(bp);
1660 		mutex_exit(&lsp->ls_vp_lock);
1661 		return (0);
1662 	}
1663 
1664 	if (lsp->ls_crypto_enabled) {
1665 		/* encrypted data really begins after crypto header */
1666 		offset += lsp->ls_crypto_offset;
1667 	}
1668 
1669 	/* make sure we will not pass the file or partition size */
1670 	if (offset == lsp->ls_vp_size ||
1671 	    offset == (((p_lba + p_nblks) << shift) + lsp->ls_crypto_offset)) {
1672 		/* EOF */
1673 		if ((bp->b_flags & B_READ) != 0) {
1674 			bp->b_resid = bp->b_bcount;
1675 			bioerror(bp, 0);
1676 		} else {
1677 			/* writes should fail */
1678 			bioerror(bp, ENXIO);
1679 		}
1680 		biodone(bp);
1681 		mutex_exit(&lsp->ls_vp_lock);
1682 		return (0);
1683 	}
1684 	if ((offset > lsp->ls_vp_size) ||
1685 	    (offset > (((p_lba + p_nblks) << shift) + lsp->ls_crypto_offset)) ||
1686 	    ((offset + bp->b_bcount) > ((p_lba + p_nblks) << shift))) {
1687 		bioerror(bp, ENXIO);
1688 		biodone(bp);
1689 		mutex_exit(&lsp->ls_vp_lock);
1690 		return (0);
1691 	}
1692 
1693 	mutex_exit(&lsp->ls_vp_lock);
1694 
1695 	if (lsp->ls_kstat) {
1696 		mutex_enter(lsp->ls_kstat->ks_lock);
1697 		kstat_waitq_enter(KSTAT_IO_PTR(lsp->ls_kstat));
1698 		mutex_exit(lsp->ls_kstat->ks_lock);
1699 	}
1700 	bp->b_private = (void *)(uintptr_t)p_lba;	/* partition start */
1701 	(void) taskq_dispatch(lsp->ls_taskq, lofi_strategy_task, bp, KM_SLEEP);
1702 	return (0);
1703 }
1704 
1705 /*ARGSUSED2*/
1706 static int
1707 lofi_read(dev_t dev, struct uio *uio, struct cred *credp)
1708 {
1709 	if (getminor(dev) == 0)
1710 		return (EINVAL);
1711 	UIO_CHECK(uio);
1712 	return (physio(lofi_strategy, NULL, dev, B_READ, minphys, uio));
1713 }
1714 
1715 /*ARGSUSED2*/
1716 static int
1717 lofi_write(dev_t dev, struct uio *uio, struct cred *credp)
1718 {
1719 	if (getminor(dev) == 0)
1720 		return (EINVAL);
1721 	UIO_CHECK(uio);
1722 	return (physio(lofi_strategy, NULL, dev, B_WRITE, minphys, uio));
1723 }
1724 
1725 /*ARGSUSED2*/
1726 static int
1727 lofi_aread(dev_t dev, struct aio_req *aio, struct cred *credp)
1728 {
1729 	if (getminor(dev) == 0)
1730 		return (EINVAL);
1731 	UIO_CHECK(aio->aio_uio);
1732 	return (aphysio(lofi_strategy, anocancel, dev, B_READ, minphys, aio));
1733 }
1734 
1735 /*ARGSUSED2*/
1736 static int
1737 lofi_awrite(dev_t dev, struct aio_req *aio, struct cred *credp)
1738 {
1739 	if (getminor(dev) == 0)
1740 		return (EINVAL);
1741 	UIO_CHECK(aio->aio_uio);
1742 	return (aphysio(lofi_strategy, anocancel, dev, B_WRITE, minphys, aio));
1743 }
1744 
1745 /*ARGSUSED*/
1746 static int
1747 lofi_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1748 {
1749 	struct lofi_state *lsp;
1750 	dev_t	dev = (dev_t)arg;
1751 	int instance;
1752 
1753 	instance = LOFI_MINOR2ID(getminor(dev));
1754 	switch (infocmd) {
1755 	case DDI_INFO_DEVT2DEVINFO:
1756 		lsp = ddi_get_soft_state(lofi_statep, instance);
1757 		if (lsp == NULL)
1758 			return (DDI_FAILURE);
1759 		*result = lsp->ls_dip;
1760 		return (DDI_SUCCESS);
1761 	case DDI_INFO_DEVT2INSTANCE:
1762 		*result = (void *) (intptr_t)instance;
1763 		return (DDI_SUCCESS);
1764 	}
1765 	return (DDI_FAILURE);
1766 }
1767 
1768 static int
1769 lofi_create_minor_nodes(struct lofi_state *lsp, boolean_t labeled)
1770 {
1771 	int error = 0;
1772 	int instance = ddi_get_instance(lsp->ls_dip);
1773 
1774 	if (labeled == B_TRUE) {
1775 		cmlb_alloc_handle(&lsp->ls_cmlbhandle);
1776 		error = cmlb_attach(lsp->ls_dip, &lofi_tg_ops, DTYPE_DIRECT,
1777 		    B_FALSE, B_FALSE, DDI_NT_BLOCK_CHAN,
1778 		    CMLB_CREATE_P0_MINOR_NODE, lsp->ls_cmlbhandle, (void *)1);
1779 
1780 		if (error != DDI_SUCCESS) {
1781 			cmlb_free_handle(&lsp->ls_cmlbhandle);
1782 			lsp->ls_cmlbhandle = NULL;
1783 			error = ENXIO;
1784 		}
1785 	} else {
1786 		/* create minor nodes */
1787 		error = ddi_create_minor_node(lsp->ls_dip, LOFI_BLOCK_NODE,
1788 		    S_IFBLK, LOFI_ID2MINOR(instance), DDI_PSEUDO, 0);
1789 		if (error == DDI_SUCCESS) {
1790 			error = ddi_create_minor_node(lsp->ls_dip,
1791 			    LOFI_CHAR_NODE, S_IFCHR, LOFI_ID2MINOR(instance),
1792 			    DDI_PSEUDO, 0);
1793 			if (error != DDI_SUCCESS) {
1794 				ddi_remove_minor_node(lsp->ls_dip,
1795 				    LOFI_BLOCK_NODE);
1796 				error = ENXIO;
1797 			}
1798 		} else
1799 			error = ENXIO;
1800 	}
1801 	return (error);
1802 }
1803 
1804 static int
1805 lofi_zone_bind(struct lofi_state *lsp)
1806 {
1807 	int error = 0;
1808 
1809 	mutex_enter(&curproc->p_lock);
1810 	if ((error = rctl_incr_lofi(curproc, curproc->p_zone, 1)) != 0) {
1811 		mutex_exit(&curproc->p_lock);
1812 		return (error);
1813 	}
1814 	mutex_exit(&curproc->p_lock);
1815 
1816 	if (ddi_prop_update_string(lsp->ls_dev, lsp->ls_dip, ZONE_PROP_NAME,
1817 	    (char *)curproc->p_zone->zone_name) != DDI_PROP_SUCCESS) {
1818 		rctl_decr_lofi(curproc->p_zone, 1);
1819 		error = EINVAL;
1820 	} else {
1821 		zone_init_ref(&lsp->ls_zone);
1822 		zone_hold_ref(curzone, &lsp->ls_zone, ZONE_REF_LOFI);
1823 	}
1824 	return (error);
1825 }
1826 
1827 static void
1828 lofi_zone_unbind(struct lofi_state *lsp)
1829 {
1830 	(void) ddi_prop_remove(DDI_DEV_T_NONE, lsp->ls_dip, ZONE_PROP_NAME);
1831 	rctl_decr_lofi(curproc->p_zone, 1);
1832 	zone_rele_ref(&lsp->ls_zone, ZONE_REF_LOFI);
1833 }
1834 
1835 static int
1836 lofi_online_dev(dev_info_t *dip)
1837 {
1838 	boolean_t labeled;
1839 	int	error;
1840 	int	instance = ddi_get_instance(dip);
1841 	struct lofi_state *lsp;
1842 
1843 	labeled = B_FALSE;
1844 	if (ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "labeled"))
1845 		labeled = B_TRUE;
1846 
1847 	/* lsp alloc+init, soft state is freed in lofi_detach */
1848 	error = ddi_soft_state_zalloc(lofi_statep, instance);
1849 	if (error == DDI_FAILURE) {
1850 		return (ENOMEM);
1851 	}
1852 
1853 	lsp = ddi_get_soft_state(lofi_statep, instance);
1854 	lsp->ls_dip = dip;
1855 
1856 	if ((error = lofi_zone_bind(lsp)) != 0)
1857 		goto err;
1858 
1859 	cv_init(&lsp->ls_vp_cv, NULL, CV_DRIVER, NULL);
1860 	mutex_init(&lsp->ls_comp_cache_lock, NULL, MUTEX_DRIVER, NULL);
1861 	mutex_init(&lsp->ls_comp_bufs_lock, NULL, MUTEX_DRIVER, NULL);
1862 	mutex_init(&lsp->ls_kstat_lock, NULL, MUTEX_DRIVER, NULL);
1863 	mutex_init(&lsp->ls_vp_lock, NULL, MUTEX_DRIVER, NULL);
1864 
1865 	if ((error = lofi_create_minor_nodes(lsp, labeled)) != 0) {
1866 		lofi_zone_unbind(lsp);
1867 		goto lerr;
1868 	}
1869 
1870 	/* driver handles kernel-issued IOCTLs */
1871 	if (ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
1872 	    DDI_KERNEL_IOCTL, NULL, 0) != DDI_PROP_SUCCESS) {
1873 		error = DDI_FAILURE;
1874 		goto merr;
1875 	}
1876 
1877 	lsp->ls_kstat = kstat_create_zone(LOFI_DRIVER_NAME, instance,
1878 	    NULL, "disk", KSTAT_TYPE_IO, 1, 0, getzoneid());
1879 	if (lsp->ls_kstat == NULL) {
1880 		(void) ddi_prop_remove(DDI_DEV_T_NONE, lsp->ls_dip,
1881 		    DDI_KERNEL_IOCTL);
1882 		error = ENOMEM;
1883 		goto merr;
1884 	}
1885 
1886 	lsp->ls_kstat->ks_lock = &lsp->ls_kstat_lock;
1887 	kstat_zone_add(lsp->ls_kstat, GLOBAL_ZONEID);
1888 	kstat_install(lsp->ls_kstat);
1889 	return (DDI_SUCCESS);
1890 merr:
1891 	if (lsp->ls_cmlbhandle != NULL) {
1892 		cmlb_detach(lsp->ls_cmlbhandle, 0);
1893 		cmlb_free_handle(&lsp->ls_cmlbhandle);
1894 	}
1895 	ddi_remove_minor_node(dip, NULL);
1896 	lofi_zone_unbind(lsp);
1897 lerr:
1898 	mutex_destroy(&lsp->ls_comp_cache_lock);
1899 	mutex_destroy(&lsp->ls_comp_bufs_lock);
1900 	mutex_destroy(&lsp->ls_kstat_lock);
1901 	mutex_destroy(&lsp->ls_vp_lock);
1902 	cv_destroy(&lsp->ls_vp_cv);
1903 err:
1904 	ddi_soft_state_free(lofi_statep, instance);
1905 	return (error);
1906 }
1907 
1908 /*ARGSUSED*/
1909 static int
1910 lofi_dev_callback(sysevent_t *ev, void *cookie)
1911 {
1912 	nvlist_t *nvlist;
1913 	char *class, *driver;
1914 	char name[10];
1915 	int32_t instance;
1916 
1917 	class = sysevent_get_class_name(ev);
1918 	if (strcmp(class, EC_DEV_ADD) && strcmp(class, EC_DEV_REMOVE))
1919 		return (0);
1920 
1921 	(void) sysevent_get_attr_list(ev, &nvlist);
1922 	driver = fnvlist_lookup_string(nvlist, DEV_DRIVER_NAME);
1923 	instance = fnvlist_lookup_int32(nvlist, DEV_INSTANCE);
1924 
1925 	if (strcmp(driver, LOFI_DRIVER_NAME) != 0) {
1926 		fnvlist_free(nvlist);
1927 		return (0);
1928 	}
1929 
1930 	/*
1931 	 * insert or remove device info, then announce the change
1932 	 * via cv_broadcast.
1933 	 * This allows the MAP/UNMAP to monitor device change.
1934 	 */
1935 	(void) snprintf(name, sizeof (name), "%d", instance);
1936 	if (strcmp(class, EC_DEV_ADD) == 0) {
1937 		mutex_enter(&lofi_chan_lock);
1938 		fnvlist_add_nvlist(lofi_devlink_cache, name, nvlist);
1939 		cv_broadcast(&lofi_chan_cv);
1940 		mutex_exit(&lofi_chan_lock);
1941 	} else if (strcmp(class, EC_DEV_REMOVE) == 0) {
1942 		mutex_enter(&lofi_chan_lock);
1943 		/* Can not use fnvlist_remove() as we can get ENOENT. */
1944 		(void) nvlist_remove_all(lofi_devlink_cache, name);
1945 		cv_broadcast(&lofi_chan_cv);
1946 		mutex_exit(&lofi_chan_lock);
1947 	}
1948 
1949 	fnvlist_free(nvlist);
1950 	return (0);
1951 }
1952 
1953 static int
1954 lofi_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
1955 {
1956 	int	rv;
1957 	int	instance = ddi_get_instance(dip);
1958 	struct lofi_state *lsp;
1959 
1960 	if (cmd != DDI_ATTACH)
1961 		return (DDI_FAILURE);
1962 
1963 	/*
1964 	 * Instance 0 is control instance, attaching control instance
1965 	 * will set the lofi up and ready.
1966 	 */
1967 	if (instance == 0) {
1968 		rv = ddi_soft_state_zalloc(lofi_statep, 0);
1969 		if (rv == DDI_FAILURE) {
1970 			return (DDI_FAILURE);
1971 		}
1972 		lsp = ddi_get_soft_state(lofi_statep, instance);
1973 		rv = ddi_create_minor_node(dip, LOFI_CTL_NODE, S_IFCHR, 0,
1974 		    DDI_PSEUDO, 0);
1975 		if (rv == DDI_FAILURE) {
1976 			ddi_soft_state_free(lofi_statep, 0);
1977 			return (DDI_FAILURE);
1978 		}
1979 		/* driver handles kernel-issued IOCTLs */
1980 		if (ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP,
1981 		    DDI_KERNEL_IOCTL, NULL, 0) != DDI_PROP_SUCCESS) {
1982 			ddi_remove_minor_node(dip, NULL);
1983 			ddi_soft_state_free(lofi_statep, 0);
1984 			return (DDI_FAILURE);
1985 		}
1986 
1987 		rv = sysevent_evc_bind(DEVFS_CHANNEL, &lofi_chan,
1988 		    EVCH_CREAT | EVCH_HOLD_PEND);
1989 		if (rv == 0) {
1990 			rv = sysevent_evc_subscribe(lofi_chan, "lofi",
1991 			    EC_ALL, lofi_dev_callback, NULL, 0);
1992 			rv |= sysevent_evc_subscribe(lofi_chan, "disk",
1993 			    EC_ALL, lofi_dev_callback, NULL, 0);
1994 		} else
1995 			lofi_chan = NULL;
1996 		if (rv != 0) {
1997 			if (lofi_chan != NULL)
1998 				(void) sysevent_evc_unbind(lofi_chan);
1999 			ddi_prop_remove_all(dip);
2000 			ddi_remove_minor_node(dip, NULL);
2001 			ddi_soft_state_free(lofi_statep, 0);
2002 			return (DDI_FAILURE);
2003 		}
2004 		zone_key_create(&lofi_zone_key, NULL, lofi_zone_shutdown, NULL);
2005 
2006 		lsp->ls_dip = dip;
2007 	} else {
2008 		if (lofi_online_dev(dip) == DDI_FAILURE)
2009 			return (DDI_FAILURE);
2010 	}
2011 
2012 	ddi_report_dev(dip);
2013 	return (DDI_SUCCESS);
2014 }
2015 
2016 static int
2017 lofi_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
2018 {
2019 	struct lofi_state *lsp;
2020 	int instance = ddi_get_instance(dip);
2021 
2022 	if (cmd != DDI_DETACH)
2023 		return (DDI_FAILURE);
2024 
2025 	/*
2026 	 * If the instance is not 0, release state.
2027 	 * The instance 0 is control device, we can not detach it
2028 	 * before other instances are detached.
2029 	 */
2030 	if (instance != 0) {
2031 		lsp = ddi_get_soft_state(lofi_statep, instance);
2032 		if (lsp != NULL && lsp->ls_vp_ready == B_FALSE) {
2033 			ddi_soft_state_free(lofi_statep, instance);
2034 			return (DDI_SUCCESS);
2035 		} else
2036 			return (DDI_FAILURE);
2037 	}
2038 	mutex_enter(&lofi_lock);
2039 
2040 	if (!list_is_empty(&lofi_list)) {
2041 		mutex_exit(&lofi_lock);
2042 		return (DDI_FAILURE);
2043 	}
2044 
2045 	ddi_remove_minor_node(dip, NULL);
2046 	ddi_prop_remove_all(dip);
2047 
2048 	mutex_exit(&lofi_lock);
2049 
2050 	(void) sysevent_evc_unbind(lofi_chan);
2051 	if (zone_key_delete(lofi_zone_key) != 0)
2052 		cmn_err(CE_WARN, "failed to delete zone key");
2053 
2054 	ddi_soft_state_free(lofi_statep, 0);
2055 
2056 	return (DDI_SUCCESS);
2057 }
2058 
2059 /*
2060  * With the addition of encryption, we must be careful that encryption key is
2061  * wiped before kernel's data structures are freed so it cannot accidentally
2062  * slip out to userland through uninitialized data elsewhere.
2063  */
2064 static void
2065 free_lofi_ioctl(struct lofi_ioctl *klip)
2066 {
2067 	/* Make sure this encryption key doesn't stick around */
2068 	bzero(klip->li_key, sizeof (klip->li_key));
2069 	kmem_free(klip, sizeof (struct lofi_ioctl));
2070 }
2071 
2072 /*
2073  * These two functions simplify the rest of the ioctls that need to copyin/out
2074  * the lofi_ioctl structure.
2075  */
2076 int
2077 copy_in_lofi_ioctl(const struct lofi_ioctl *ulip, struct lofi_ioctl **klipp,
2078     int flag)
2079 {
2080 	struct lofi_ioctl *klip;
2081 	int	error;
2082 
2083 	klip = *klipp = kmem_alloc(sizeof (struct lofi_ioctl), KM_SLEEP);
2084 	error = ddi_copyin(ulip, klip, sizeof (struct lofi_ioctl), flag);
2085 	if (error)
2086 		goto err;
2087 
2088 	/* ensure NULL termination */
2089 	klip->li_filename[MAXPATHLEN-1] = '\0';
2090 	klip->li_devpath[MAXPATHLEN-1] = '\0';
2091 	klip->li_algorithm[MAXALGLEN-1] = '\0';
2092 	klip->li_cipher[CRYPTO_MAX_MECH_NAME-1] = '\0';
2093 	klip->li_iv_cipher[CRYPTO_MAX_MECH_NAME-1] = '\0';
2094 
2095 	if (klip->li_id > L_MAXMIN32) {
2096 		error = EINVAL;
2097 		goto err;
2098 	}
2099 
2100 	return (0);
2101 
2102 err:
2103 	free_lofi_ioctl(klip);
2104 	return (error);
2105 }
2106 
2107 int
2108 copy_out_lofi_ioctl(const struct lofi_ioctl *klip, struct lofi_ioctl *ulip,
2109     int flag)
2110 {
2111 	int	error;
2112 
2113 	/*
2114 	 * NOTE: Do NOT copy the crypto_key_t "back" to userland.
2115 	 * This ensures that an attacker can't trivially find the
2116 	 * key for a mapping just by issuing the ioctl.
2117 	 *
2118 	 * It can still be found by poking around in kmem with mdb(1),
2119 	 * but there is no point in making it easy when the info isn't
2120 	 * of any use in this direction anyway.
2121 	 *
2122 	 * Either way we don't actually have the raw key stored in
2123 	 * a form that we can get it anyway, since we just used it
2124 	 * to create a ctx template and didn't keep "the original".
2125 	 */
2126 	error = ddi_copyout(klip, ulip, sizeof (struct lofi_ioctl), flag);
2127 	if (error)
2128 		return (EFAULT);
2129 	return (0);
2130 }
2131 
2132 static int
2133 lofi_access(struct lofi_state *lsp)
2134 {
2135 	ASSERT(MUTEX_HELD(&lofi_lock));
2136 	if (INGLOBALZONE(curproc) || lsp->ls_zone.zref_zone == curzone)
2137 		return (0);
2138 	return (EPERM);
2139 }
2140 
2141 /*
2142  * Find the lofi state for the given filename. We compare by vnode to
2143  * allow the global zone visibility into NGZ lofi nodes.
2144  */
2145 static int
2146 file_to_lofi_nocheck(char *filename, boolean_t readonly,
2147     struct lofi_state **lspp)
2148 {
2149 	struct lofi_state *lsp;
2150 	vnode_t *vp = NULL;
2151 	int err = 0;
2152 	int rdfiles = 0;
2153 
2154 	ASSERT(MUTEX_HELD(&lofi_lock));
2155 
2156 	if ((err = lookupname(filename, UIO_SYSSPACE, FOLLOW,
2157 	    NULLVPP, &vp)) != 0)
2158 		goto out;
2159 
2160 	if (vp->v_type == VREG) {
2161 		vnode_t *realvp;
2162 		if (VOP_REALVP(vp, &realvp, NULL) == 0) {
2163 			VN_HOLD(realvp);
2164 			VN_RELE(vp);
2165 			vp = realvp;
2166 		}
2167 	}
2168 
2169 	for (lsp = list_head(&lofi_list); lsp != NULL;
2170 	    lsp = list_next(&lofi_list, lsp)) {
2171 		if (lsp->ls_vp == vp) {
2172 			if (lspp != NULL)
2173 				*lspp = lsp;
2174 			if (lsp->ls_readonly) {
2175 				rdfiles++;
2176 				/* Skip if '-r' is specified */
2177 				if (readonly)
2178 					continue;
2179 			}
2180 			goto out;
2181 		}
2182 	}
2183 
2184 	err = ENOENT;
2185 
2186 	/*
2187 	 * If a filename is given as an argument for lofi_unmap, we shouldn't
2188 	 * allow unmap if there are multiple read-only lofi devices associated
2189 	 * with this file.
2190 	 */
2191 	if (lspp != NULL) {
2192 		if (rdfiles == 1)
2193 			err = 0;
2194 		else if (rdfiles > 1)
2195 			err = EBUSY;
2196 	}
2197 
2198 out:
2199 	if (vp != NULL)
2200 		VN_RELE(vp);
2201 	return (err);
2202 }
2203 
2204 /*
2205  * Find the minor for the given filename, checking the zone can access
2206  * it.
2207  */
2208 static int
2209 file_to_lofi(char *filename, boolean_t readonly, struct lofi_state **lspp)
2210 {
2211 	int err = 0;
2212 
2213 	ASSERT(MUTEX_HELD(&lofi_lock));
2214 
2215 	if ((err = file_to_lofi_nocheck(filename, readonly, lspp)) != 0)
2216 		return (err);
2217 
2218 	if ((err = lofi_access(*lspp)) != 0)
2219 		return (err);
2220 
2221 	return (0);
2222 }
2223 
2224 /*
2225  * Fakes up a disk geometry based on the size of the file. This is needed
2226  * to support newfs on traditional lofi device, but also will provide
2227  * geometry hint for cmlb.
2228  */
2229 static void
2230 fake_disk_geometry(struct lofi_state *lsp)
2231 {
2232 	u_offset_t dsize = lsp->ls_vp_size - lsp->ls_crypto_offset;
2233 
2234 	/* dk_geom - see dkio(7I) */
2235 	/*
2236 	 * dkg_ncyl _could_ be set to one here (one big cylinder with gobs
2237 	 * of sectors), but that breaks programs like fdisk which want to
2238 	 * partition a disk by cylinder. With one cylinder, you can't create
2239 	 * an fdisk partition and put pcfs on it for testing (hard to pick
2240 	 * a number between one and one).
2241 	 *
2242 	 * The cheezy floppy test is an attempt to not have too few cylinders
2243 	 * for a small file, or so many on a big file that you waste space
2244 	 * for backup superblocks or cylinder group structures.
2245 	 */
2246 	bzero(&lsp->ls_dkg, sizeof (lsp->ls_dkg));
2247 	if (dsize < (2 * 1024 * 1024)) /* floppy? */
2248 		lsp->ls_dkg.dkg_ncyl = dsize / (100 * 1024);
2249 	else
2250 		lsp->ls_dkg.dkg_ncyl = dsize / (300 * 1024);
2251 	/* in case file file is < 100k */
2252 	if (lsp->ls_dkg.dkg_ncyl == 0)
2253 		lsp->ls_dkg.dkg_ncyl = 1;
2254 
2255 	lsp->ls_dkg.dkg_pcyl = lsp->ls_dkg.dkg_ncyl;
2256 	lsp->ls_dkg.dkg_nhead = 1;
2257 	lsp->ls_dkg.dkg_rpm = 7200;
2258 
2259 	lsp->ls_dkg.dkg_nsect = dsize /
2260 	    (lsp->ls_dkg.dkg_ncyl << lsp->ls_pbshift);
2261 }
2262 
2263 /*
2264  * build vtoc - see dkio(7I)
2265  *
2266  * Fakes one big partition based on the size of the file. This is needed
2267  * because we allow newfs'ing the traditional lofi device and newfs will
2268  * do several disk ioctls to figure out the geometry and partition information.
2269  * It uses that information to determine the parameters to pass to mkfs.
2270  */
2271 static void
2272 fake_disk_vtoc(struct lofi_state *lsp, struct vtoc *vt)
2273 {
2274 	bzero(vt, sizeof (struct vtoc));
2275 	vt->v_sanity = VTOC_SANE;
2276 	vt->v_version = V_VERSION;
2277 	(void) strncpy(vt->v_volume, LOFI_DRIVER_NAME,
2278 	    sizeof (vt->v_volume));
2279 	vt->v_sectorsz = 1 << lsp->ls_pbshift;
2280 	vt->v_nparts = 1;
2281 	vt->v_part[0].p_tag = V_UNASSIGNED;
2282 
2283 	/*
2284 	 * A compressed file is read-only, other files can
2285 	 * be read-write
2286 	 */
2287 	if (lsp->ls_uncomp_seg_sz > 0) {
2288 		vt->v_part[0].p_flag = V_UNMNT | V_RONLY;
2289 	} else {
2290 		vt->v_part[0].p_flag = V_UNMNT;
2291 	}
2292 	vt->v_part[0].p_start = (daddr_t)0;
2293 	/*
2294 	 * The partition size cannot just be the number of sectors, because
2295 	 * that might not end on a cylinder boundary. And if that's the case,
2296 	 * newfs/mkfs will print a scary warning. So just figure the size
2297 	 * based on the number of cylinders and sectors/cylinder.
2298 	 */
2299 	vt->v_part[0].p_size = lsp->ls_dkg.dkg_pcyl *
2300 	    lsp->ls_dkg.dkg_nsect * lsp->ls_dkg.dkg_nhead;
2301 }
2302 
2303 /*
2304  * build dk_cinfo - see dkio(7I)
2305  */
2306 static void
2307 fake_disk_info(dev_t dev, struct dk_cinfo *ci)
2308 {
2309 	bzero(ci, sizeof (struct dk_cinfo));
2310 	(void) strlcpy(ci->dki_cname, LOFI_DRIVER_NAME, sizeof (ci->dki_cname));
2311 	ci->dki_ctype = DKC_SCSI_CCS;
2312 	(void) strlcpy(ci->dki_dname, LOFI_DRIVER_NAME, sizeof (ci->dki_dname));
2313 	ci->dki_unit = LOFI_MINOR2ID(getminor(dev));
2314 	ci->dki_partition = LOFI_PART(getminor(dev));
2315 	/*
2316 	 * newfs uses this to set maxcontig. Must not be < 16, or it
2317 	 * will be 0 when newfs multiplies it by DEV_BSIZE and divides
2318 	 * it by the block size. Then tunefs doesn't work because
2319 	 * maxcontig is 0.
2320 	 */
2321 	ci->dki_maxtransfer = 16;
2322 }
2323 
2324 /*
2325  * map in a compressed file
2326  *
2327  * Read in the header and the index that follows.
2328  *
2329  * The header is as follows -
2330  *
2331  * Signature (name of the compression algorithm)
2332  * Compression segment size (a multiple of 512)
2333  * Number of index entries
2334  * Size of the last block
2335  * The array containing the index entries
2336  *
2337  * The header information is always stored in
2338  * network byte order on disk.
2339  */
2340 static int
2341 lofi_map_compressed_file(struct lofi_state *lsp, char *buf)
2342 {
2343 	uint32_t index_sz, header_len, i;
2344 	ssize_t	resid;
2345 	enum uio_rw rw;
2346 	char *tbuf = buf;
2347 	int error;
2348 
2349 	/* The signature has already been read */
2350 	tbuf += sizeof (lsp->ls_comp_algorithm);
2351 	bcopy(tbuf, &(lsp->ls_uncomp_seg_sz), sizeof (lsp->ls_uncomp_seg_sz));
2352 	lsp->ls_uncomp_seg_sz = ntohl(lsp->ls_uncomp_seg_sz);
2353 
2354 	/*
2355 	 * The compressed segment size must be a power of 2
2356 	 */
2357 	if (lsp->ls_uncomp_seg_sz < DEV_BSIZE ||
2358 	    !ISP2(lsp->ls_uncomp_seg_sz))
2359 		return (EINVAL);
2360 
2361 	for (i = 0; !((lsp->ls_uncomp_seg_sz >> i) & 1); i++)
2362 		;
2363 
2364 	lsp->ls_comp_seg_shift = i;
2365 
2366 	tbuf += sizeof (lsp->ls_uncomp_seg_sz);
2367 	bcopy(tbuf, &(lsp->ls_comp_index_sz), sizeof (lsp->ls_comp_index_sz));
2368 	lsp->ls_comp_index_sz = ntohl(lsp->ls_comp_index_sz);
2369 
2370 	tbuf += sizeof (lsp->ls_comp_index_sz);
2371 	bcopy(tbuf, &(lsp->ls_uncomp_last_seg_sz),
2372 	    sizeof (lsp->ls_uncomp_last_seg_sz));
2373 	lsp->ls_uncomp_last_seg_sz = ntohl(lsp->ls_uncomp_last_seg_sz);
2374 
2375 	/*
2376 	 * Compute the total size of the uncompressed data
2377 	 * for use in fake_disk_geometry and other calculations.
2378 	 * Disk geometry has to be faked with respect to the
2379 	 * actual uncompressed data size rather than the
2380 	 * compressed file size.
2381 	 */
2382 	lsp->ls_vp_size =
2383 	    (u_offset_t)(lsp->ls_comp_index_sz - 2) * lsp->ls_uncomp_seg_sz
2384 	    + lsp->ls_uncomp_last_seg_sz;
2385 
2386 	/*
2387 	 * Index size is rounded up to DEV_BSIZE for ease
2388 	 * of segmapping
2389 	 */
2390 	index_sz = sizeof (*lsp->ls_comp_seg_index) * lsp->ls_comp_index_sz;
2391 	header_len = sizeof (lsp->ls_comp_algorithm) +
2392 	    sizeof (lsp->ls_uncomp_seg_sz) +
2393 	    sizeof (lsp->ls_comp_index_sz) +
2394 	    sizeof (lsp->ls_uncomp_last_seg_sz);
2395 	lsp->ls_comp_offbase = header_len + index_sz;
2396 
2397 	index_sz += header_len;
2398 	index_sz = roundup(index_sz, DEV_BSIZE);
2399 
2400 	lsp->ls_comp_index_data = kmem_alloc(index_sz, KM_SLEEP);
2401 	lsp->ls_comp_index_data_sz = index_sz;
2402 
2403 	/*
2404 	 * Read in the index -- this has a side-effect
2405 	 * of reading in the header as well
2406 	 */
2407 	rw = UIO_READ;
2408 	error = vn_rdwr(rw, lsp->ls_vp, lsp->ls_comp_index_data, index_sz,
2409 	    0, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
2410 
2411 	if (error != 0)
2412 		return (error);
2413 
2414 	/* Skip the header, this is where the index really begins */
2415 	lsp->ls_comp_seg_index =
2416 	    /*LINTED*/
2417 	    (uint64_t *)(lsp->ls_comp_index_data + header_len);
2418 
2419 	/*
2420 	 * Now recompute offsets in the index to account for
2421 	 * the header length
2422 	 */
2423 	for (i = 0; i < lsp->ls_comp_index_sz; i++) {
2424 		lsp->ls_comp_seg_index[i] = lsp->ls_comp_offbase +
2425 		    BE_64(lsp->ls_comp_seg_index[i]);
2426 	}
2427 
2428 	return (error);
2429 }
2430 
2431 static int
2432 lofi_init_crypto(struct lofi_state *lsp, struct lofi_ioctl *klip)
2433 {
2434 	struct crypto_meta chead;
2435 	char buf[DEV_BSIZE];
2436 	ssize_t	resid;
2437 	char *marker;
2438 	int error;
2439 	int ret;
2440 	int i;
2441 
2442 	if (!klip->li_crypto_enabled)
2443 		return (0);
2444 
2445 	/*
2446 	 * All current algorithms have a max of 448 bits.
2447 	 */
2448 	if (klip->li_iv_len > CRYPTO_BITS2BYTES(512))
2449 		return (EINVAL);
2450 
2451 	if (CRYPTO_BITS2BYTES(klip->li_key_len) > sizeof (klip->li_key))
2452 		return (EINVAL);
2453 
2454 	lsp->ls_crypto_enabled = klip->li_crypto_enabled;
2455 
2456 	mutex_init(&lsp->ls_crypto_lock, NULL, MUTEX_DRIVER, NULL);
2457 
2458 	lsp->ls_mech.cm_type = crypto_mech2id(klip->li_cipher);
2459 	if (lsp->ls_mech.cm_type == CRYPTO_MECH_INVALID) {
2460 		cmn_err(CE_WARN, "invalid cipher %s requested for %s",
2461 		    klip->li_cipher, klip->li_filename);
2462 		return (EINVAL);
2463 	}
2464 
2465 	/* this is just initialization here */
2466 	lsp->ls_mech.cm_param = NULL;
2467 	lsp->ls_mech.cm_param_len = 0;
2468 
2469 	lsp->ls_iv_type = klip->li_iv_type;
2470 	lsp->ls_iv_mech.cm_type = crypto_mech2id(klip->li_iv_cipher);
2471 	if (lsp->ls_iv_mech.cm_type == CRYPTO_MECH_INVALID) {
2472 		cmn_err(CE_WARN, "invalid iv cipher %s requested"
2473 		    " for %s", klip->li_iv_cipher, klip->li_filename);
2474 		return (EINVAL);
2475 	}
2476 
2477 	/* iv mech must itself take a null iv */
2478 	lsp->ls_iv_mech.cm_param = NULL;
2479 	lsp->ls_iv_mech.cm_param_len = 0;
2480 	lsp->ls_iv_len = klip->li_iv_len;
2481 
2482 	/*
2483 	 * Create ctx using li_cipher & the raw li_key after checking
2484 	 * that it isn't a weak key.
2485 	 */
2486 	lsp->ls_key.ck_format = CRYPTO_KEY_RAW;
2487 	lsp->ls_key.ck_length = klip->li_key_len;
2488 	lsp->ls_key.ck_data = kmem_alloc(
2489 	    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length), KM_SLEEP);
2490 	bcopy(klip->li_key, lsp->ls_key.ck_data,
2491 	    CRYPTO_BITS2BYTES(lsp->ls_key.ck_length));
2492 
2493 	ret = crypto_key_check(&lsp->ls_mech, &lsp->ls_key);
2494 	if (ret != CRYPTO_SUCCESS) {
2495 		cmn_err(CE_WARN, "weak key check failed for cipher "
2496 		    "%s on file %s (0x%x)", klip->li_cipher,
2497 		    klip->li_filename, ret);
2498 		return (EINVAL);
2499 	}
2500 
2501 	error = vn_rdwr(UIO_READ, lsp->ls_vp, buf, DEV_BSIZE,
2502 	    CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
2503 	if (error != 0)
2504 		return (error);
2505 
2506 	/*
2507 	 * This is the case where the header in the lofi image is already
2508 	 * initialized to indicate it is encrypted.
2509 	 */
2510 	if (strncmp(buf, lofi_crypto_magic, sizeof (lofi_crypto_magic)) == 0) {
2511 		/*
2512 		 * The encryption header information is laid out this way:
2513 		 *	6 bytes:	hex "CFLOFI"
2514 		 *	2 bytes:	version = 0 ... for now
2515 		 *	96 bytes:	reserved1 (not implemented yet)
2516 		 *	4 bytes:	data_sector = 2 ... for now
2517 		 *	more...		not implemented yet
2518 		 */
2519 
2520 		marker = buf;
2521 
2522 		/* copy the magic */
2523 		bcopy(marker, lsp->ls_crypto.magic,
2524 		    sizeof (lsp->ls_crypto.magic));
2525 		marker += sizeof (lsp->ls_crypto.magic);
2526 
2527 		/* read the encryption version number */
2528 		bcopy(marker, &(lsp->ls_crypto.version),
2529 		    sizeof (lsp->ls_crypto.version));
2530 		lsp->ls_crypto.version = ntohs(lsp->ls_crypto.version);
2531 		marker += sizeof (lsp->ls_crypto.version);
2532 
2533 		/* read a chunk of reserved data */
2534 		bcopy(marker, lsp->ls_crypto.reserved1,
2535 		    sizeof (lsp->ls_crypto.reserved1));
2536 		marker += sizeof (lsp->ls_crypto.reserved1);
2537 
2538 		/* read block number where encrypted data begins */
2539 		bcopy(marker, &(lsp->ls_crypto.data_sector),
2540 		    sizeof (lsp->ls_crypto.data_sector));
2541 		lsp->ls_crypto.data_sector = ntohl(lsp->ls_crypto.data_sector);
2542 		marker += sizeof (lsp->ls_crypto.data_sector);
2543 
2544 		/* and ignore the rest until it is implemented */
2545 
2546 		lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE;
2547 		return (0);
2548 	}
2549 
2550 	/*
2551 	 * We've requested encryption, but no magic was found, so it must be
2552 	 * a new image.
2553 	 */
2554 
2555 	for (i = 0; i < sizeof (struct crypto_meta); i++) {
2556 		if (buf[i] != '\0')
2557 			return (EINVAL);
2558 	}
2559 
2560 	marker = buf;
2561 	bcopy(lofi_crypto_magic, marker, sizeof (lofi_crypto_magic));
2562 	marker += sizeof (lofi_crypto_magic);
2563 	chead.version = htons(LOFI_CRYPTO_VERSION);
2564 	bcopy(&(chead.version), marker, sizeof (chead.version));
2565 	marker += sizeof (chead.version);
2566 	marker += sizeof (chead.reserved1);
2567 	chead.data_sector = htonl(LOFI_CRYPTO_DATA_SECTOR);
2568 	bcopy(&(chead.data_sector), marker, sizeof (chead.data_sector));
2569 
2570 	/* write the header */
2571 	error = vn_rdwr(UIO_WRITE, lsp->ls_vp, buf, DEV_BSIZE,
2572 	    CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid);
2573 	if (error != 0)
2574 		return (error);
2575 
2576 	/* fix things up so it looks like we read this info */
2577 	bcopy(lofi_crypto_magic, lsp->ls_crypto.magic,
2578 	    sizeof (lofi_crypto_magic));
2579 	lsp->ls_crypto.version = LOFI_CRYPTO_VERSION;
2580 	lsp->ls_crypto.data_sector = LOFI_CRYPTO_DATA_SECTOR;
2581 	lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE;
2582 	return (0);
2583 }
2584 
2585 /*
2586  * Check to see if the passed in signature is a valid one.  If it is
2587  * valid, return the index into lofi_compress_table.
2588  *
2589  * Return -1 if it is invalid
2590  */
2591 static int
2592 lofi_compress_select(const char *signature)
2593 {
2594 	int i;
2595 
2596 	for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
2597 		if (strcmp(lofi_compress_table[i].l_name, signature) == 0)
2598 			return (i);
2599 	}
2600 
2601 	return (-1);
2602 }
2603 
2604 static int
2605 lofi_init_compress(struct lofi_state *lsp)
2606 {
2607 	char buf[DEV_BSIZE];
2608 	int compress_index;
2609 	ssize_t	resid;
2610 	int error;
2611 
2612 	error = vn_rdwr(UIO_READ, lsp->ls_vp, buf, DEV_BSIZE, 0, UIO_SYSSPACE,
2613 	    0, RLIM64_INFINITY, kcred, &resid);
2614 
2615 	if (error != 0)
2616 		return (error);
2617 
2618 	if ((compress_index = lofi_compress_select(buf)) == -1)
2619 		return (0);
2620 
2621 	/* compression and encryption are mutually exclusive */
2622 	if (lsp->ls_crypto_enabled)
2623 		return (ENOTSUP);
2624 
2625 	/* initialize compression info for compressed lofi */
2626 	lsp->ls_comp_algorithm_index = compress_index;
2627 	(void) strlcpy(lsp->ls_comp_algorithm,
2628 	    lofi_compress_table[compress_index].l_name,
2629 	    sizeof (lsp->ls_comp_algorithm));
2630 
2631 	/* Finally setup per-thread pre-allocated buffers */
2632 	lsp->ls_comp_bufs = kmem_zalloc(lofi_taskq_nthreads *
2633 	    sizeof (struct compbuf), KM_SLEEP);
2634 
2635 	return (lofi_map_compressed_file(lsp, buf));
2636 }
2637 
2638 /*
2639  * Allocate new or proposed id from lofi_id.
2640  *
2641  * Special cases for proposed id:
2642  * 0: not allowed, 0 is id for control device.
2643  * -1: allocate first usable id from lofi_id.
2644  * any other value is proposed value from userland
2645  *
2646  * returns DDI_SUCCESS or errno.
2647  */
2648 static int
2649 lofi_alloc_id(int *idp)
2650 {
2651 	int id, error = DDI_SUCCESS;
2652 
2653 	if (*idp == -1) {
2654 		id = id_allocff_nosleep(lofi_id);
2655 		if (id == -1) {
2656 			error = EAGAIN;
2657 			goto err;
2658 		}
2659 	} else if (*idp == 0) {
2660 		error = EINVAL;
2661 		goto err;
2662 	} else if (*idp > ((1 << (L_BITSMINOR - LOFI_CMLB_SHIFT)) - 1)) {
2663 		error = ERANGE;
2664 		goto err;
2665 	} else {
2666 		if (ddi_get_soft_state(lofi_statep, *idp) != NULL) {
2667 			error = EEXIST;
2668 			goto err;
2669 		}
2670 
2671 		id = id_alloc_specific_nosleep(lofi_id, *idp);
2672 		if (id == -1) {
2673 			error = EAGAIN;
2674 			goto err;
2675 		}
2676 	}
2677 	*idp = id;
2678 err:
2679 	return (error);
2680 }
2681 
2682 static int
2683 lofi_create_dev(struct lofi_ioctl *klip)
2684 {
2685 	dev_info_t *parent, *child;
2686 	struct lofi_state *lsp = NULL;
2687 	char namebuf[MAXNAMELEN];
2688 	int error, circ;
2689 
2690 	/* get control device */
2691 	lsp = ddi_get_soft_state(lofi_statep, 0);
2692 	parent = ddi_get_parent(lsp->ls_dip);
2693 
2694 	if ((error = lofi_alloc_id((int *)&klip->li_id)))
2695 		return (error);
2696 
2697 	(void) snprintf(namebuf, sizeof (namebuf), LOFI_DRIVER_NAME "@%d",
2698 	    klip->li_id);
2699 
2700 	ndi_devi_enter(parent, &circ);
2701 	child = ndi_devi_findchild(parent, namebuf);
2702 	ndi_devi_exit(parent, circ);
2703 
2704 	if (child == NULL) {
2705 		child = ddi_add_child(parent, LOFI_DRIVER_NAME,
2706 		    (pnode_t)DEVI_SID_NODEID, klip->li_id);
2707 		if ((error = ddi_prop_update_int(DDI_DEV_T_NONE, child,
2708 		    "instance", klip->li_id)) != DDI_PROP_SUCCESS)
2709 			goto err;
2710 
2711 		if (klip->li_labeled == B_TRUE) {
2712 			if ((error = ddi_prop_create(DDI_DEV_T_NONE, child,
2713 			    DDI_PROP_CANSLEEP, "labeled", 0, 0))
2714 			    != DDI_PROP_SUCCESS)
2715 				goto err;
2716 		}
2717 
2718 		if ((error = ndi_devi_online(child, NDI_ONLINE_ATTACH))
2719 		    != NDI_SUCCESS)
2720 			goto err;
2721 	} else {
2722 		id_free(lofi_id, klip->li_id);
2723 		error = EEXIST;
2724 		return (error);
2725 	}
2726 
2727 	goto done;
2728 
2729 err:
2730 	ddi_prop_remove_all(child);
2731 	(void) ndi_devi_offline(child, NDI_DEVI_REMOVE);
2732 	id_free(lofi_id, klip->li_id);
2733 done:
2734 
2735 	return (error);
2736 }
2737 
2738 static void
2739 lofi_create_inquiry(struct lofi_state *lsp, struct scsi_inquiry *inq)
2740 {
2741 	char *p = NULL;
2742 
2743 	(void) strlcpy(inq->inq_vid, LOFI_DRIVER_NAME, sizeof (inq->inq_vid));
2744 
2745 	mutex_enter(&lsp->ls_vp_lock);
2746 	if (lsp->ls_vp != NULL)
2747 		p = strrchr(lsp->ls_vp->v_path, '/');
2748 	if (p != NULL)
2749 		(void) strncpy(inq->inq_pid, p + 1, sizeof (inq->inq_pid));
2750 	mutex_exit(&lsp->ls_vp_lock);
2751 	(void) strlcpy(inq->inq_revision, "1.0", sizeof (inq->inq_revision));
2752 }
2753 
2754 /*
2755  * copy devlink name from event cache
2756  */
2757 static void
2758 lofi_copy_devpath(struct lofi_ioctl *klip)
2759 {
2760 	int	error;
2761 	char	namebuf[MAXNAMELEN], *str;
2762 	clock_t ticks;
2763 	nvlist_t *nvl;
2764 
2765 	if (klip->li_labeled == B_TRUE)
2766 		klip->li_devpath[0] = '\0';
2767 	else {
2768 		/* no need to wait for messages */
2769 		(void) snprintf(klip->li_devpath, sizeof (klip->li_devpath),
2770 		    "/dev/" LOFI_CHAR_NAME "/%d", klip->li_id);
2771 		return;
2772 	}
2773 
2774 	(void) snprintf(namebuf, sizeof (namebuf), "%d", klip->li_id);
2775 	ticks = ddi_get_lbolt() + LOFI_TIMEOUT * drv_usectohz(1000000);
2776 
2777 	nvl = NULL;
2778 
2779 	mutex_enter(&lofi_chan_lock);
2780 	while (nvlist_lookup_nvlist(lofi_devlink_cache, namebuf, &nvl) != 0) {
2781 		error = cv_timedwait(&lofi_chan_cv, &lofi_chan_lock, ticks);
2782 		if (error == -1)
2783 			break;
2784 	}
2785 
2786 	if (nvl != NULL) {
2787 		if (nvlist_lookup_string(nvl, DEV_NAME, &str) == 0) {
2788 			(void) strlcpy(klip->li_devpath, str,
2789 			    sizeof (klip->li_devpath));
2790 		}
2791 	}
2792 	mutex_exit(&lofi_chan_lock);
2793 }
2794 
2795 /*
2796  * map a file to a minor number. Return the minor number.
2797  */
2798 static int
2799 lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor,
2800     int *rvalp, struct cred *credp, int ioctl_flag)
2801 {
2802 	int	id = -1;
2803 	struct lofi_state *lsp = NULL;
2804 	struct lofi_ioctl *klip;
2805 	int	error;
2806 	struct vnode *vp = NULL;
2807 	vattr_t	vattr;
2808 	int	flag;
2809 	char	namebuf[MAXNAMELEN];
2810 
2811 	error = copy_in_lofi_ioctl(ulip, &klip, ioctl_flag);
2812 	if (error != 0)
2813 		return (error);
2814 
2815 	mutex_enter(&lofi_lock);
2816 
2817 	if (file_to_lofi_nocheck(klip->li_filename, klip->li_readonly,
2818 	    NULL) == 0) {
2819 		error = EBUSY;
2820 		goto err;
2821 	}
2822 
2823 	flag = FREAD | FWRITE | FOFFMAX | FEXCL;
2824 	error = vn_open(klip->li_filename, UIO_SYSSPACE, flag, 0, &vp, 0, 0);
2825 	if (error) {
2826 		/* try read-only */
2827 		flag &= ~FWRITE;
2828 		error = vn_open(klip->li_filename, UIO_SYSSPACE, flag, 0,
2829 		    &vp, 0, 0);
2830 		if (error)
2831 			goto err;
2832 	}
2833 
2834 	if (!V_ISLOFIABLE(vp->v_type)) {
2835 		error = EINVAL;
2836 		goto err;
2837 	}
2838 
2839 	vattr.va_mask = AT_SIZE;
2840 	error = VOP_GETATTR(vp, &vattr, 0, credp, NULL);
2841 	if (error)
2842 		goto err;
2843 
2844 	/* the file needs to be a multiple of the block size */
2845 	if ((vattr.va_size % DEV_BSIZE) != 0) {
2846 		error = EINVAL;
2847 		goto err;
2848 	}
2849 
2850 	if (pickminor) {
2851 		klip->li_id = (uint32_t)-1;
2852 	}
2853 	if ((error = lofi_create_dev(klip)) != 0)
2854 		goto err;
2855 
2856 	id = klip->li_id;
2857 	lsp = ddi_get_soft_state(lofi_statep, id);
2858 	if (lsp == NULL)
2859 		goto err;
2860 
2861 	/*
2862 	 * from this point lofi_destroy() is used to clean up on error
2863 	 * make sure the basic data is set
2864 	 */
2865 	lsp->ls_dev = makedevice(getmajor(dev), LOFI_ID2MINOR(id));
2866 
2867 	list_create(&lsp->ls_comp_cache, sizeof (struct lofi_comp_cache),
2868 	    offsetof(struct lofi_comp_cache, lc_list));
2869 
2870 	/*
2871 	 * save open mode so file can be closed properly and vnode counts
2872 	 * updated correctly.
2873 	 */
2874 	lsp->ls_openflag = flag;
2875 
2876 	lsp->ls_vp = vp;
2877 	lsp->ls_stacked_vp = vp;
2878 
2879 	lsp->ls_vp_size = vattr.va_size;
2880 	lsp->ls_vp_comp_size = lsp->ls_vp_size;
2881 
2882 	/*
2883 	 * Try to handle stacked lofs vnodes.
2884 	 */
2885 	if (vp->v_type == VREG) {
2886 		vnode_t *realvp;
2887 
2888 		if (VOP_REALVP(vp, &realvp, NULL) == 0) {
2889 			/*
2890 			 * We need to use the realvp for uniqueness
2891 			 * checking, but keep the stacked vp for
2892 			 * LOFI_GET_FILENAME display.
2893 			 */
2894 			VN_HOLD(realvp);
2895 			lsp->ls_vp = realvp;
2896 		}
2897 	}
2898 
2899 	lsp->ls_lbshift = highbit(DEV_BSIZE) - 1;
2900 	lsp->ls_pbshift = lsp->ls_lbshift;
2901 
2902 	lsp->ls_readonly = klip->li_readonly;
2903 	lsp->ls_uncomp_seg_sz = 0;
2904 	lsp->ls_comp_algorithm[0] = '\0';
2905 	lsp->ls_crypto_offset = 0;
2906 
2907 	(void) snprintf(namebuf, sizeof (namebuf), "%s_taskq_%d",
2908 	    LOFI_DRIVER_NAME, id);
2909 	lsp->ls_taskq = taskq_create_proc(namebuf, lofi_taskq_nthreads,
2910 	    minclsyspri, 1, lofi_taskq_maxalloc, curzone->zone_zsched, 0);
2911 
2912 	if ((error = lofi_init_crypto(lsp, klip)) != 0)
2913 		goto err;
2914 
2915 	if ((error = lofi_init_compress(lsp)) != 0)
2916 		goto err;
2917 
2918 	fake_disk_geometry(lsp);
2919 
2920 	if ((ddi_prop_update_int64(lsp->ls_dev, lsp->ls_dip, SIZE_PROP_NAME,
2921 	    lsp->ls_vp_size - lsp->ls_crypto_offset)) != DDI_PROP_SUCCESS) {
2922 		error = EINVAL;
2923 		goto err;
2924 	}
2925 
2926 	if ((ddi_prop_update_int64(lsp->ls_dev, lsp->ls_dip, NBLOCKS_PROP_NAME,
2927 	    (lsp->ls_vp_size - lsp->ls_crypto_offset) / DEV_BSIZE))
2928 	    != DDI_PROP_SUCCESS) {
2929 		error = EINVAL;
2930 		goto err;
2931 	}
2932 
2933 	list_insert_tail(&lofi_list, lsp);
2934 	/*
2935 	 * Notify we are ready to rock.
2936 	 */
2937 	mutex_enter(&lsp->ls_vp_lock);
2938 	lsp->ls_vp_ready = B_TRUE;
2939 	cv_broadcast(&lsp->ls_vp_cv);
2940 	mutex_exit(&lsp->ls_vp_lock);
2941 	mutex_exit(&lofi_lock);
2942 
2943 	lofi_copy_devpath(klip);
2944 
2945 	if (rvalp)
2946 		*rvalp = id;
2947 	(void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
2948 	free_lofi_ioctl(klip);
2949 	return (0);
2950 
2951 err:
2952 	if (lsp != NULL) {
2953 		lofi_destroy(lsp, credp);
2954 	} else {
2955 		if (vp != NULL) {
2956 			(void) VOP_PUTPAGE(vp, 0, 0, B_INVAL, credp, NULL);
2957 			(void) VOP_CLOSE(vp, flag, 1, 0, credp, NULL);
2958 			VN_RELE(vp);
2959 		}
2960 	}
2961 
2962 	mutex_exit(&lofi_lock);
2963 	free_lofi_ioctl(klip);
2964 	return (error);
2965 }
2966 
2967 /*
2968  * unmap a file.
2969  */
2970 static int
2971 lofi_unmap_file(struct lofi_ioctl *ulip, int byfilename,
2972     struct cred *credp, int ioctl_flag)
2973 {
2974 	struct lofi_state *lsp;
2975 	struct lofi_ioctl *klip;
2976 	nvlist_t *nvl = NULL;
2977 	clock_t ticks;
2978 	char name[MAXNAMELEN];
2979 	int err;
2980 
2981 	err = copy_in_lofi_ioctl(ulip, &klip, ioctl_flag);
2982 	if (err != 0)
2983 		return (err);
2984 
2985 	mutex_enter(&lofi_lock);
2986 	if (byfilename) {
2987 		if ((err = file_to_lofi(klip->li_filename, klip->li_readonly,
2988 		    &lsp)) != 0) {
2989 			mutex_exit(&lofi_lock);
2990 			return (err);
2991 		}
2992 	} else if (klip->li_id == 0) {
2993 		mutex_exit(&lofi_lock);
2994 		free_lofi_ioctl(klip);
2995 		return (ENXIO);
2996 	} else {
2997 		lsp = ddi_get_soft_state(lofi_statep, klip->li_id);
2998 	}
2999 
3000 	if (lsp == NULL || lsp->ls_vp == NULL || lofi_access(lsp) != 0) {
3001 		mutex_exit(&lofi_lock);
3002 		free_lofi_ioctl(klip);
3003 		return (ENXIO);
3004 	}
3005 
3006 	klip->li_id = LOFI_MINOR2ID(getminor(lsp->ls_dev));
3007 
3008 	/*
3009 	 * If it's still held open, we'll do one of three things:
3010 	 *
3011 	 * If no flag is set, just return EBUSY.
3012 	 *
3013 	 * If the 'cleanup' flag is set, unmap and remove the device when
3014 	 * the last user finishes.
3015 	 *
3016 	 * If the 'force' flag is set, then we forcibly close the underlying
3017 	 * file.  Subsequent operations will fail, and the DKIOCSTATE ioctl
3018 	 * will return DKIO_DEV_GONE.  When the device is last closed, the
3019 	 * device will be cleaned up appropriately.
3020 	 *
3021 	 * This is complicated by the fact that we may have outstanding
3022 	 * dispatched I/Os.  Rather than having a single mutex to serialize all
3023 	 * I/O, we keep a count of the number of outstanding I/O requests
3024 	 * (ls_vp_iocount), as well as a flag to indicate that no new I/Os
3025 	 * should be dispatched (ls_vp_closereq).
3026 	 *
3027 	 * We set the flag, wait for the number of outstanding I/Os to reach 0,
3028 	 * and then close the underlying vnode.
3029 	 */
3030 	if (is_opened(lsp)) {
3031 		if (klip->li_force) {
3032 			mutex_enter(&lsp->ls_vp_lock);
3033 			lsp->ls_vp_closereq = B_TRUE;
3034 			/* wake up any threads waiting on dkiocstate */
3035 			cv_broadcast(&lsp->ls_vp_cv);
3036 			while (lsp->ls_vp_iocount > 0)
3037 				cv_wait(&lsp->ls_vp_cv, &lsp->ls_vp_lock);
3038 			mutex_exit(&lsp->ls_vp_lock);
3039 
3040 			goto out;
3041 		} else if (klip->li_cleanup) {
3042 			lsp->ls_cleanup = 1;
3043 			mutex_exit(&lofi_lock);
3044 			free_lofi_ioctl(klip);
3045 			return (0);
3046 		}
3047 
3048 		mutex_exit(&lofi_lock);
3049 		free_lofi_ioctl(klip);
3050 		return (EBUSY);
3051 	}
3052 
3053 out:
3054 	lofi_free_dev(lsp);
3055 	lofi_destroy(lsp, credp);
3056 
3057 	/*
3058 	 * check the lofi_devlink_cache if device is really gone.
3059 	 * note: we just wait for timeout here and dont give error if
3060 	 * timer will expire. This check is to try to ensure the unmap is
3061 	 * really done when lofiadm -d completes.
3062 	 * Since lofi_lock is held, also hopefully the lofiadm -a calls
3063 	 * wont interfere the the unmap.
3064 	 */
3065 	(void) snprintf(name, sizeof (name), "%d", klip->li_id);
3066 	ticks = ddi_get_lbolt() + LOFI_TIMEOUT * drv_usectohz(1000000);
3067 	mutex_enter(&lofi_chan_lock);
3068 	while (nvlist_lookup_nvlist(lofi_devlink_cache, name, &nvl) == 0) {
3069 		err = cv_timedwait(&lofi_chan_cv, &lofi_chan_lock, ticks);
3070 		if (err == -1)
3071 			break;
3072 	}
3073 	mutex_exit(&lofi_chan_lock);
3074 
3075 	mutex_exit(&lofi_lock);
3076 	(void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
3077 	free_lofi_ioctl(klip);
3078 	return (0);
3079 }
3080 
3081 /*
3082  * get the filename given the minor number, or the minor number given
3083  * the name.
3084  */
3085 /*ARGSUSED*/
3086 static int
3087 lofi_get_info(dev_t dev, struct lofi_ioctl *ulip, int which,
3088     struct cred *credp, int ioctl_flag)
3089 {
3090 	struct lofi_ioctl *klip;
3091 	struct lofi_state *lsp;
3092 	int	error;
3093 
3094 	error = copy_in_lofi_ioctl(ulip, &klip, ioctl_flag);
3095 	if (error != 0)
3096 		return (error);
3097 
3098 	switch (which) {
3099 	case LOFI_GET_FILENAME:
3100 		if (klip->li_id == 0) {
3101 			free_lofi_ioctl(klip);
3102 			return (EINVAL);
3103 		}
3104 
3105 		mutex_enter(&lofi_lock);
3106 		lsp = ddi_get_soft_state(lofi_statep, klip->li_id);
3107 		if (lsp == NULL || lofi_access(lsp) != 0) {
3108 			mutex_exit(&lofi_lock);
3109 			free_lofi_ioctl(klip);
3110 			return (ENXIO);
3111 		}
3112 
3113 		/*
3114 		 * This may fail if, for example, we're trying to look
3115 		 * up a zoned NFS path from the global zone.
3116 		 */
3117 		if (vnodetopath(NULL, lsp->ls_stacked_vp, klip->li_filename,
3118 		    sizeof (klip->li_filename), CRED()) != 0) {
3119 			(void) strlcpy(klip->li_filename, "?",
3120 			    sizeof (klip->li_filename));
3121 		}
3122 
3123 		klip->li_readonly = lsp->ls_readonly;
3124 		klip->li_labeled = lsp->ls_cmlbhandle != NULL;
3125 
3126 		(void) strlcpy(klip->li_algorithm, lsp->ls_comp_algorithm,
3127 		    sizeof (klip->li_algorithm));
3128 		klip->li_crypto_enabled = lsp->ls_crypto_enabled;
3129 		mutex_exit(&lofi_lock);
3130 
3131 		lofi_copy_devpath(klip);
3132 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
3133 		free_lofi_ioctl(klip);
3134 		return (error);
3135 	case LOFI_GET_MINOR:
3136 		mutex_enter(&lofi_lock);
3137 		error = file_to_lofi(klip->li_filename,
3138 		    klip->li_readonly, &lsp);
3139 		if (error != 0) {
3140 			mutex_exit(&lofi_lock);
3141 			free_lofi_ioctl(klip);
3142 			return (error);
3143 		}
3144 		klip->li_id = LOFI_MINOR2ID(getminor(lsp->ls_dev));
3145 
3146 		klip->li_readonly = lsp->ls_readonly;
3147 		klip->li_labeled = lsp->ls_cmlbhandle != NULL;
3148 		mutex_exit(&lofi_lock);
3149 
3150 		lofi_copy_devpath(klip);
3151 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
3152 
3153 		free_lofi_ioctl(klip);
3154 		return (error);
3155 	case LOFI_CHECK_COMPRESSED:
3156 		mutex_enter(&lofi_lock);
3157 		error = file_to_lofi(klip->li_filename,
3158 		    klip->li_readonly, &lsp);
3159 		if (error != 0) {
3160 			mutex_exit(&lofi_lock);
3161 			free_lofi_ioctl(klip);
3162 			return (error);
3163 		}
3164 
3165 		klip->li_id = LOFI_MINOR2ID(getminor(lsp->ls_dev));
3166 		(void) strlcpy(klip->li_algorithm, lsp->ls_comp_algorithm,
3167 		    sizeof (klip->li_algorithm));
3168 
3169 		mutex_exit(&lofi_lock);
3170 		error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag);
3171 		free_lofi_ioctl(klip);
3172 		return (error);
3173 	default:
3174 		free_lofi_ioctl(klip);
3175 		return (EINVAL);
3176 	}
3177 }
3178 
3179 static int
3180 uscsi_is_inquiry(intptr_t arg, int flag, union scsi_cdb *cdb,
3181     struct uscsi_cmd *uscmd)
3182 {
3183 	int rval;
3184 
3185 #ifdef	_MULTI_DATAMODEL
3186 	switch (ddi_model_convert_from(flag & FMODELS)) {
3187 	case DDI_MODEL_ILP32: {
3188 		struct uscsi_cmd32 ucmd32;
3189 
3190 		if (ddi_copyin((void *)arg, &ucmd32, sizeof (ucmd32), flag)) {
3191 			rval = EFAULT;
3192 			goto err;
3193 		}
3194 		uscsi_cmd32touscsi_cmd((&ucmd32), uscmd);
3195 		break;
3196 	}
3197 	case DDI_MODEL_NONE:
3198 		if (ddi_copyin((void *)arg, uscmd, sizeof (*uscmd), flag)) {
3199 			rval = EFAULT;
3200 			goto err;
3201 		}
3202 		break;
3203 	default:
3204 		rval = EFAULT;
3205 		goto err;
3206 	}
3207 #else
3208 	if (ddi_copyin((void *)arg, uscmd, sizeof (*uscmd), flag)) {
3209 		rval = EFAULT;
3210 		goto err;
3211 	}
3212 #endif	/* _MULTI_DATAMODEL */
3213 	if (ddi_copyin(uscmd->uscsi_cdb, cdb, uscmd->uscsi_cdblen, flag)) {
3214 		rval = EFAULT;
3215 		goto err;
3216 	}
3217 	if (cdb->scc_cmd == SCMD_INQUIRY) {
3218 		return (0);
3219 	}
3220 err:
3221 	return (rval);
3222 }
3223 
3224 static int
3225 lofi_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *credp,
3226     int *rvalp)
3227 {
3228 	int	error;
3229 	enum dkio_state dkstate;
3230 	struct lofi_state *lsp;
3231 	int	id;
3232 
3233 	id = LOFI_MINOR2ID(getminor(dev));
3234 
3235 	/* lofi ioctls only apply to the master device */
3236 	if (id == 0) {
3237 		struct lofi_ioctl *lip = (struct lofi_ioctl *)arg;
3238 
3239 		/*
3240 		 * the query command only need read-access - i.e., normal
3241 		 * users are allowed to do those on the ctl device as
3242 		 * long as they can open it read-only.
3243 		 */
3244 		switch (cmd) {
3245 		case LOFI_MAP_FILE:
3246 			if ((flag & FWRITE) == 0)
3247 				return (EPERM);
3248 			return (lofi_map_file(dev, lip, 1, rvalp, credp, flag));
3249 		case LOFI_MAP_FILE_MINOR:
3250 			if ((flag & FWRITE) == 0)
3251 				return (EPERM);
3252 			return (lofi_map_file(dev, lip, 0, rvalp, credp, flag));
3253 		case LOFI_UNMAP_FILE:
3254 			if ((flag & FWRITE) == 0)
3255 				return (EPERM);
3256 			return (lofi_unmap_file(lip, 1, credp, flag));
3257 		case LOFI_UNMAP_FILE_MINOR:
3258 			if ((flag & FWRITE) == 0)
3259 				return (EPERM);
3260 			return (lofi_unmap_file(lip, 0, credp, flag));
3261 		case LOFI_GET_FILENAME:
3262 			return (lofi_get_info(dev, lip, LOFI_GET_FILENAME,
3263 			    credp, flag));
3264 		case LOFI_GET_MINOR:
3265 			return (lofi_get_info(dev, lip, LOFI_GET_MINOR,
3266 			    credp, flag));
3267 
3268 		/*
3269 		 * This API made limited sense when this value was fixed
3270 		 * at LOFI_MAX_FILES.  However, its use to iterate
3271 		 * across all possible devices in lofiadm means we don't
3272 		 * want to return L_MAXMIN, but the highest
3273 		 * *allocated* id.
3274 		 */
3275 		case LOFI_GET_MAXMINOR:
3276 			id = 0;
3277 
3278 			mutex_enter(&lofi_lock);
3279 
3280 			for (lsp = list_head(&lofi_list); lsp != NULL;
3281 			    lsp = list_next(&lofi_list, lsp)) {
3282 				int i;
3283 				if (lofi_access(lsp) != 0)
3284 					continue;
3285 
3286 				i = ddi_get_instance(lsp->ls_dip);
3287 				if (i > id)
3288 					id = i;
3289 			}
3290 
3291 			mutex_exit(&lofi_lock);
3292 
3293 			error = ddi_copyout(&id, &lip->li_id,
3294 			    sizeof (id), flag);
3295 			if (error)
3296 				return (EFAULT);
3297 			return (0);
3298 
3299 		case LOFI_CHECK_COMPRESSED:
3300 			return (lofi_get_info(dev, lip, LOFI_CHECK_COMPRESSED,
3301 			    credp, flag));
3302 		default:
3303 			return (EINVAL);
3304 		}
3305 	}
3306 
3307 	mutex_enter(&lofi_lock);
3308 	lsp = ddi_get_soft_state(lofi_statep, id);
3309 	if (lsp == NULL || lsp->ls_vp_closereq) {
3310 		mutex_exit(&lofi_lock);
3311 		return (ENXIO);
3312 	}
3313 	mutex_exit(&lofi_lock);
3314 
3315 	if (ddi_prop_exists(DDI_DEV_T_ANY, lsp->ls_dip, DDI_PROP_DONTPASS,
3316 	    "labeled") == 1) {
3317 		error = cmlb_ioctl(lsp->ls_cmlbhandle, dev, cmd, arg, flag,
3318 		    credp, rvalp, 0);
3319 		if (error != ENOTTY)
3320 			return (error);
3321 	}
3322 
3323 	/*
3324 	 * We explicitly allow DKIOCSTATE, but all other ioctls should fail with
3325 	 * EIO as if the device was no longer present.
3326 	 */
3327 	if (lsp->ls_vp == NULL && cmd != DKIOCSTATE)
3328 		return (EIO);
3329 
3330 	/* these are for faking out utilities like newfs */
3331 	switch (cmd) {
3332 	case DKIOCGMEDIAINFO:
3333 	case DKIOCGMEDIAINFOEXT: {
3334 		struct dk_minfo_ext media_info;
3335 		int shift = lsp->ls_lbshift;
3336 		int size;
3337 
3338 		if (cmd == DKIOCGMEDIAINFOEXT) {
3339 			media_info.dki_pbsize = 1U << lsp->ls_pbshift;
3340 			size = sizeof (struct dk_minfo_ext);
3341 		} else {
3342 			size = sizeof (struct dk_minfo);
3343 		}
3344 
3345 		media_info.dki_media_type = DK_FIXED_DISK;
3346 		media_info.dki_lbsize = 1U << shift;
3347 		media_info.dki_capacity =
3348 		    (lsp->ls_vp_size - lsp->ls_crypto_offset) >> shift;
3349 
3350 		if (ddi_copyout(&media_info, (void *)arg, size, flag))
3351 			return (EFAULT);
3352 		return (0);
3353 	}
3354 	case DKIOCREMOVABLE: {
3355 		int i = 0;
3356 		if (ddi_copyout(&i, (caddr_t)arg, sizeof (int), flag))
3357 			return (EFAULT);
3358 		return (0);
3359 	}
3360 
3361 	case DKIOCGVTOC: {
3362 		struct vtoc vt;
3363 		fake_disk_vtoc(lsp, &vt);
3364 
3365 		switch (ddi_model_convert_from(flag & FMODELS)) {
3366 		case DDI_MODEL_ILP32: {
3367 			struct vtoc32 vtoc32;
3368 
3369 			vtoctovtoc32(vt, vtoc32);
3370 			if (ddi_copyout(&vtoc32, (void *)arg,
3371 			    sizeof (struct vtoc32), flag))
3372 				return (EFAULT);
3373 			break;
3374 			}
3375 
3376 		case DDI_MODEL_NONE:
3377 			if (ddi_copyout(&vt, (void *)arg,
3378 			    sizeof (struct vtoc), flag))
3379 				return (EFAULT);
3380 			break;
3381 		}
3382 		return (0);
3383 	}
3384 	case DKIOCINFO: {
3385 		struct dk_cinfo ci;
3386 		fake_disk_info(dev, &ci);
3387 		if (ddi_copyout(&ci, (void *)arg, sizeof (ci), flag))
3388 			return (EFAULT);
3389 		return (0);
3390 	}
3391 	case DKIOCG_VIRTGEOM:
3392 	case DKIOCG_PHYGEOM:
3393 	case DKIOCGGEOM:
3394 		error = ddi_copyout(&lsp->ls_dkg, (void *)arg,
3395 		    sizeof (struct dk_geom), flag);
3396 		if (error)
3397 			return (EFAULT);
3398 		return (0);
3399 	case DKIOCSTATE:
3400 		/*
3401 		 * Normally, lofi devices are always in the INSERTED state.  If
3402 		 * a device is forcefully unmapped, then the device transitions
3403 		 * to the DKIO_DEV_GONE state.
3404 		 */
3405 		if (ddi_copyin((void *)arg, &dkstate, sizeof (dkstate),
3406 		    flag) != 0)
3407 			return (EFAULT);
3408 
3409 		mutex_enter(&lsp->ls_vp_lock);
3410 		lsp->ls_vp_iocount++;
3411 		while (((dkstate == DKIO_INSERTED && lsp->ls_vp != NULL) ||
3412 		    (dkstate == DKIO_DEV_GONE && lsp->ls_vp == NULL)) &&
3413 		    !lsp->ls_vp_closereq) {
3414 			/*
3415 			 * By virtue of having the device open, we know that
3416 			 * 'lsp' will remain valid when we return.
3417 			 */
3418 			if (!cv_wait_sig(&lsp->ls_vp_cv,
3419 			    &lsp->ls_vp_lock)) {
3420 				lsp->ls_vp_iocount--;
3421 				cv_broadcast(&lsp->ls_vp_cv);
3422 				mutex_exit(&lsp->ls_vp_lock);
3423 				return (EINTR);
3424 			}
3425 		}
3426 
3427 		dkstate = (!lsp->ls_vp_closereq && lsp->ls_vp != NULL ?
3428 		    DKIO_INSERTED : DKIO_DEV_GONE);
3429 		lsp->ls_vp_iocount--;
3430 		cv_broadcast(&lsp->ls_vp_cv);
3431 		mutex_exit(&lsp->ls_vp_lock);
3432 
3433 		if (ddi_copyout(&dkstate, (void *)arg,
3434 		    sizeof (dkstate), flag) != 0)
3435 			return (EFAULT);
3436 		return (0);
3437 	case USCSICMD: {
3438 		struct uscsi_cmd uscmd;
3439 		union scsi_cdb cdb;
3440 
3441 		if (uscsi_is_inquiry(arg, flag, &cdb, &uscmd) == 0) {
3442 			struct scsi_inquiry inq = {0};
3443 
3444 			lofi_create_inquiry(lsp, &inq);
3445 			if (ddi_copyout(&inq, uscmd.uscsi_bufaddr,
3446 			    uscmd.uscsi_buflen, flag) != 0)
3447 				return (EFAULT);
3448 			return (0);
3449 		} else if (cdb.scc_cmd == SCMD_READ_CAPACITY) {
3450 			struct scsi_capacity capacity;
3451 
3452 			capacity.capacity =
3453 			    BE_32((lsp->ls_vp_size - lsp->ls_crypto_offset) >>
3454 			    lsp->ls_lbshift);
3455 			capacity.lbasize = BE_32(1 << lsp->ls_lbshift);
3456 			if (ddi_copyout(&capacity, uscmd.uscsi_bufaddr,
3457 			    uscmd.uscsi_buflen, flag) != 0)
3458 				return (EFAULT);
3459 			return (0);
3460 		}
3461 
3462 		uscmd.uscsi_rqstatus = 0xff;
3463 #ifdef	_MULTI_DATAMODEL
3464 		switch (ddi_model_convert_from(flag & FMODELS)) {
3465 		case DDI_MODEL_ILP32: {
3466 			struct uscsi_cmd32 ucmd32;
3467 			uscsi_cmdtouscsi_cmd32((&uscmd), (&ucmd32));
3468 			if (ddi_copyout(&ucmd32, (void *)arg, sizeof (ucmd32),
3469 			    flag) != 0)
3470 				return (EFAULT);
3471 			break;
3472 		}
3473 		case DDI_MODEL_NONE:
3474 			if (ddi_copyout(&uscmd, (void *)arg, sizeof (uscmd),
3475 			    flag) != 0)
3476 				return (EFAULT);
3477 			break;
3478 		default:
3479 			return (EFAULT);
3480 		}
3481 #else
3482 		if (ddi_copyout(&uscmd, (void *)arg, sizeof (uscmd), flag) != 0)
3483 			return (EFAULT);
3484 #endif	/* _MULTI_DATAMODEL */
3485 		return (0);
3486 	}
3487 	default:
3488 #ifdef DEBUG
3489 		cmn_err(CE_WARN, "lofi_ioctl: %d is not implemented\n", cmd);
3490 #endif	/* DEBUG */
3491 		return (ENOTTY);
3492 	}
3493 }
3494 
3495 static int
3496 lofi_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
3497     char *name, caddr_t valuep, int *lengthp)
3498 {
3499 	struct lofi_state *lsp;
3500 
3501 	lsp = ddi_get_soft_state(lofi_statep, ddi_get_instance(dip));
3502 	if (lsp == NULL) {
3503 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
3504 		    name, valuep, lengthp));
3505 	}
3506 
3507 	return (cmlb_prop_op(lsp->ls_cmlbhandle, dev, dip, prop_op, mod_flags,
3508 	    name, valuep, lengthp, LOFI_PART(getminor(dev)), NULL));
3509 }
3510 
3511 static struct cb_ops lofi_cb_ops = {
3512 	lofi_open,		/* open */
3513 	lofi_close,		/* close */
3514 	lofi_strategy,		/* strategy */
3515 	nodev,			/* print */
3516 	nodev,			/* dump */
3517 	lofi_read,		/* read */
3518 	lofi_write,		/* write */
3519 	lofi_ioctl,		/* ioctl */
3520 	nodev,			/* devmap */
3521 	nodev,			/* mmap */
3522 	nodev,			/* segmap */
3523 	nochpoll,		/* poll */
3524 	lofi_prop_op,		/* prop_op */
3525 	0,			/* streamtab  */
3526 	D_64BIT | D_NEW | D_MP,	/* Driver compatibility flag */
3527 	CB_REV,
3528 	lofi_aread,
3529 	lofi_awrite
3530 };
3531 
3532 static struct dev_ops lofi_ops = {
3533 	DEVO_REV,		/* devo_rev, */
3534 	0,			/* refcnt  */
3535 	lofi_info,		/* info */
3536 	nulldev,		/* identify */
3537 	nulldev,		/* probe */
3538 	lofi_attach,		/* attach */
3539 	lofi_detach,		/* detach */
3540 	nodev,			/* reset */
3541 	&lofi_cb_ops,		/* driver operations */
3542 	NULL,			/* no bus operations */
3543 	NULL,			/* power */
3544 	ddi_quiesce_not_needed,	/* quiesce */
3545 };
3546 
3547 static struct modldrv modldrv = {
3548 	&mod_driverops,
3549 	"loopback file driver",
3550 	&lofi_ops,
3551 };
3552 
3553 static struct modlinkage modlinkage = {
3554 	MODREV_1,
3555 	&modldrv,
3556 	NULL
3557 };
3558 
3559 int
3560 _init(void)
3561 {
3562 	int error;
3563 
3564 	list_create(&lofi_list, sizeof (struct lofi_state),
3565 	    offsetof(struct lofi_state, ls_list));
3566 
3567 	error = ddi_soft_state_init((void **)&lofi_statep,
3568 	    sizeof (struct lofi_state), 0);
3569 	if (error) {
3570 		list_destroy(&lofi_list);
3571 		return (error);
3572 	}
3573 
3574 	/*
3575 	 * The minor number is stored as id << LOFI_CMLB_SHIFT as
3576 	 * we need to reserve space for cmlb minor numbers.
3577 	 * This will leave out 4096 id values on 32bit kernel, which should
3578 	 * still suffice.
3579 	 */
3580 	lofi_id = id_space_create("lofi_id", 1,
3581 	    (1 << (L_BITSMINOR - LOFI_CMLB_SHIFT)));
3582 
3583 	if (lofi_id == NULL) {
3584 		ddi_soft_state_fini((void **)&lofi_statep);
3585 		list_destroy(&lofi_list);
3586 		return (DDI_FAILURE);
3587 	}
3588 
3589 	mutex_init(&lofi_lock, NULL, MUTEX_DRIVER, NULL);
3590 	mutex_init(&lofi_chan_lock, NULL, MUTEX_DRIVER, NULL);
3591 	cv_init(&lofi_chan_cv, NULL, CV_DRIVER, NULL);
3592 	error = nvlist_alloc(&lofi_devlink_cache, NV_UNIQUE_NAME, KM_SLEEP);
3593 
3594 	if (error == 0)
3595 		error = mod_install(&modlinkage);
3596 	if (error) {
3597 		id_space_destroy(lofi_id);
3598 		if (lofi_devlink_cache != NULL)
3599 			nvlist_free(lofi_devlink_cache);
3600 		mutex_destroy(&lofi_chan_lock);
3601 		cv_destroy(&lofi_chan_cv);
3602 		mutex_destroy(&lofi_lock);
3603 		ddi_soft_state_fini((void **)&lofi_statep);
3604 		list_destroy(&lofi_list);
3605 	}
3606 
3607 	return (error);
3608 }
3609 
3610 int
3611 _fini(void)
3612 {
3613 	int	error;
3614 
3615 	mutex_enter(&lofi_lock);
3616 
3617 	if (!list_is_empty(&lofi_list)) {
3618 		mutex_exit(&lofi_lock);
3619 		return (EBUSY);
3620 	}
3621 
3622 	mutex_exit(&lofi_lock);
3623 
3624 	error = mod_remove(&modlinkage);
3625 	if (error)
3626 		return (error);
3627 
3628 	mutex_enter(&lofi_chan_lock);
3629 	nvlist_free(lofi_devlink_cache);
3630 	lofi_devlink_cache = NULL;
3631 	mutex_exit(&lofi_chan_lock);
3632 
3633 	mutex_destroy(&lofi_chan_lock);
3634 	cv_destroy(&lofi_chan_cv);
3635 	mutex_destroy(&lofi_lock);
3636 	id_space_destroy(lofi_id);
3637 	ddi_soft_state_fini((void **)&lofi_statep);
3638 	list_destroy(&lofi_list);
3639 
3640 	return (error);
3641 }
3642 
3643 int
3644 _info(struct modinfo *modinfop)
3645 {
3646 	return (mod_info(&modlinkage, modinfop));
3647 }
3648