xref: /titanic_52/usr/src/uts/common/io/cmlb.c (revision 39b361b2ebefcef5612a54ae5cbd2179e19be296)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * This module provides support for labeling operations for target
29  * drivers.
30  */
31 
32 #include <sys/scsi/scsi.h>
33 #include <sys/sunddi.h>
34 #include <sys/dklabel.h>
35 #include <sys/dkio.h>
36 #include <sys/vtoc.h>
37 #include <sys/dktp/fdisk.h>
38 #include <sys/vtrace.h>
39 #include <sys/efi_partition.h>
40 #include <sys/cmlb.h>
41 #include <sys/cmlb_impl.h>
42 #include <sys/ddi_impldefs.h>
43 
44 /*
45  * Driver minor node structure and data table
46  */
47 struct driver_minor_data {
48 	char	*name;
49 	minor_t	minor;
50 	int	type;
51 };
52 
53 static struct driver_minor_data dk_minor_data[] = {
54 	{"a", 0, S_IFBLK},
55 	{"b", 1, S_IFBLK},
56 	{"c", 2, S_IFBLK},
57 	{"d", 3, S_IFBLK},
58 	{"e", 4, S_IFBLK},
59 	{"f", 5, S_IFBLK},
60 	{"g", 6, S_IFBLK},
61 	{"h", 7, S_IFBLK},
62 #if defined(_SUNOS_VTOC_16)
63 	{"i", 8, S_IFBLK},
64 	{"j", 9, S_IFBLK},
65 	{"k", 10, S_IFBLK},
66 	{"l", 11, S_IFBLK},
67 	{"m", 12, S_IFBLK},
68 	{"n", 13, S_IFBLK},
69 	{"o", 14, S_IFBLK},
70 	{"p", 15, S_IFBLK},
71 #endif			/* defined(_SUNOS_VTOC_16) */
72 #if defined(_FIRMWARE_NEEDS_FDISK)
73 	{"q", 16, S_IFBLK},
74 	{"r", 17, S_IFBLK},
75 	{"s", 18, S_IFBLK},
76 	{"t", 19, S_IFBLK},
77 	{"u", 20, S_IFBLK},
78 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
79 	{"a,raw", 0, S_IFCHR},
80 	{"b,raw", 1, S_IFCHR},
81 	{"c,raw", 2, S_IFCHR},
82 	{"d,raw", 3, S_IFCHR},
83 	{"e,raw", 4, S_IFCHR},
84 	{"f,raw", 5, S_IFCHR},
85 	{"g,raw", 6, S_IFCHR},
86 	{"h,raw", 7, S_IFCHR},
87 #if defined(_SUNOS_VTOC_16)
88 	{"i,raw", 8, S_IFCHR},
89 	{"j,raw", 9, S_IFCHR},
90 	{"k,raw", 10, S_IFCHR},
91 	{"l,raw", 11, S_IFCHR},
92 	{"m,raw", 12, S_IFCHR},
93 	{"n,raw", 13, S_IFCHR},
94 	{"o,raw", 14, S_IFCHR},
95 	{"p,raw", 15, S_IFCHR},
96 #endif			/* defined(_SUNOS_VTOC_16) */
97 #if defined(_FIRMWARE_NEEDS_FDISK)
98 	{"q,raw", 16, S_IFCHR},
99 	{"r,raw", 17, S_IFCHR},
100 	{"s,raw", 18, S_IFCHR},
101 	{"t,raw", 19, S_IFCHR},
102 	{"u,raw", 20, S_IFCHR},
103 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
104 	{0}
105 };
106 
107 static struct driver_minor_data dk_minor_data_efi[] = {
108 	{"a", 0, S_IFBLK},
109 	{"b", 1, S_IFBLK},
110 	{"c", 2, S_IFBLK},
111 	{"d", 3, S_IFBLK},
112 	{"e", 4, S_IFBLK},
113 	{"f", 5, S_IFBLK},
114 	{"g", 6, S_IFBLK},
115 	{"wd", 7, S_IFBLK},
116 #if defined(_FIRMWARE_NEEDS_FDISK)
117 	{"q", 16, S_IFBLK},
118 	{"r", 17, S_IFBLK},
119 	{"s", 18, S_IFBLK},
120 	{"t", 19, S_IFBLK},
121 	{"u", 20, S_IFBLK},
122 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
123 	{"a,raw", 0, S_IFCHR},
124 	{"b,raw", 1, S_IFCHR},
125 	{"c,raw", 2, S_IFCHR},
126 	{"d,raw", 3, S_IFCHR},
127 	{"e,raw", 4, S_IFCHR},
128 	{"f,raw", 5, S_IFCHR},
129 	{"g,raw", 6, S_IFCHR},
130 	{"wd,raw", 7, S_IFCHR},
131 #if defined(_FIRMWARE_NEEDS_FDISK)
132 	{"q,raw", 16, S_IFCHR},
133 	{"r,raw", 17, S_IFCHR},
134 	{"s,raw", 18, S_IFCHR},
135 	{"t,raw", 19, S_IFCHR},
136 	{"u,raw", 20, S_IFCHR},
137 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
138 	{0}
139 };
140 
141 /*
142  * Declare the dynamic properties implemented in prop_op(9E) implementation
143  * that we want to have show up in a di_init(3DEVINFO) device tree snapshot
144  * of drivers that call cmlb_attach().
145  */
146 static i_ddi_prop_dyn_t cmlb_prop_dyn[] = {
147 	{"Nblocks",		DDI_PROP_TYPE_INT64,	S_IFBLK},
148 	{"Size",		DDI_PROP_TYPE_INT64,	S_IFCHR},
149 	{"device-nblocks",	DDI_PROP_TYPE_INT64},
150 	{"device-blksize",	DDI_PROP_TYPE_INT},
151 	{NULL}
152 };
153 
154 /*
155  * External kernel interfaces
156  */
157 extern struct mod_ops mod_miscops;
158 
159 extern int ddi_create_internal_pathname(dev_info_t *dip, char *name,
160     int spec_type, minor_t minor_num);
161 
162 /*
163  * Global buffer and mutex for debug logging
164  */
165 static char	cmlb_log_buffer[1024];
166 static kmutex_t	cmlb_log_mutex;
167 
168 
169 struct cmlb_lun *cmlb_debug_cl = NULL;
170 uint_t cmlb_level_mask = 0x0;
171 
172 int cmlb_rot_delay = 4;	/* default rotational delay */
173 
174 static struct modlmisc modlmisc = {
175 	&mod_miscops,   /* Type of module */
176 	"Common Labeling module"
177 };
178 
179 static struct modlinkage modlinkage = {
180 	MODREV_1, (void *)&modlmisc, NULL
181 };
182 
183 /* Local function prototypes */
184 static dev_t cmlb_make_device(struct cmlb_lun *cl);
185 static int cmlb_validate_geometry(struct cmlb_lun *cl, int forcerevalid,
186     int flags, void *tg_cookie);
187 static void cmlb_resync_geom_caches(struct cmlb_lun *cl, diskaddr_t capacity,
188     void *tg_cookie);
189 static int cmlb_read_fdisk(struct cmlb_lun *cl, diskaddr_t capacity,
190     void *tg_cookie);
191 static void cmlb_swap_efi_gpt(efi_gpt_t *e);
192 static void cmlb_swap_efi_gpe(int nparts, efi_gpe_t *p);
193 static int cmlb_validate_efi(efi_gpt_t *labp);
194 static int cmlb_use_efi(struct cmlb_lun *cl, diskaddr_t capacity, int flags,
195     void *tg_cookie);
196 static void cmlb_build_default_label(struct cmlb_lun *cl, void *tg_cookie);
197 static int  cmlb_uselabel(struct cmlb_lun *cl,  struct dk_label *l, int flags);
198 #if defined(_SUNOS_VTOC_8)
199 static void cmlb_build_user_vtoc(struct cmlb_lun *cl, struct vtoc *user_vtoc);
200 #endif
201 static int cmlb_build_label_vtoc(struct cmlb_lun *cl, struct vtoc *user_vtoc);
202 static int cmlb_write_label(struct cmlb_lun *cl, void *tg_cookie);
203 static int cmlb_set_vtoc(struct cmlb_lun *cl, struct dk_label *dkl,
204     void *tg_cookie);
205 static void cmlb_clear_efi(struct cmlb_lun *cl, void *tg_cookie);
206 static void cmlb_clear_vtoc(struct cmlb_lun *cl, void *tg_cookie);
207 static void cmlb_setup_default_geometry(struct cmlb_lun *cl, void *tg_cookie);
208 static int cmlb_create_minor_nodes(struct cmlb_lun *cl);
209 static int cmlb_check_update_blockcount(struct cmlb_lun *cl, void *tg_cookie);
210 static int cmlb_check_efi_mbr(uchar_t *buf, int *is_mbr);
211 
212 #if defined(__i386) || defined(__amd64)
213 static int cmlb_update_fdisk_and_vtoc(struct cmlb_lun *cl, void *tg_cookie);
214 #endif
215 
216 #if defined(_FIRMWARE_NEEDS_FDISK)
217 static int  cmlb_has_max_chs_vals(struct ipart *fdp);
218 #endif
219 
220 #if defined(_SUNOS_VTOC_16)
221 static void cmlb_convert_geometry(diskaddr_t capacity, struct dk_geom *cl_g);
222 #endif
223 
224 static int cmlb_dkio_get_geometry(struct cmlb_lun *cl, caddr_t arg, int flag,
225     void *tg_cookie);
226 static int cmlb_dkio_set_geometry(struct cmlb_lun *cl, caddr_t arg, int flag);
227 static int cmlb_dkio_get_partition(struct cmlb_lun *cl, caddr_t arg, int flag,
228     void *tg_cookie);
229 static int cmlb_dkio_set_partition(struct cmlb_lun *cl, caddr_t arg, int flag);
230 static int cmlb_dkio_get_efi(struct cmlb_lun *cl, caddr_t arg, int flag,
231     void *tg_cookie);
232 static int cmlb_dkio_set_efi(struct cmlb_lun *cl, dev_t dev, caddr_t arg,
233     int flag, void *tg_cookie);
234 static int cmlb_dkio_get_vtoc(struct cmlb_lun *cl, caddr_t arg, int flag,
235     void *tg_cookie);
236 static int cmlb_dkio_get_extvtoc(struct cmlb_lun *cl, caddr_t arg, int flag,
237     void *tg_cookie);
238 static int cmlb_dkio_set_vtoc(struct cmlb_lun *cl, dev_t dev, caddr_t arg,
239     int flag, void *tg_cookie);
240 static int cmlb_dkio_set_extvtoc(struct cmlb_lun *cl, dev_t dev, caddr_t arg,
241     int flag, void *tg_cookie);
242 static int cmlb_dkio_get_mboot(struct cmlb_lun *cl, caddr_t arg, int flag,
243     void *tg_cookie);
244 static int cmlb_dkio_set_mboot(struct cmlb_lun *cl, caddr_t arg, int flag,
245     void *tg_cookie);
246 static int cmlb_dkio_partition(struct cmlb_lun *cl, caddr_t arg, int flag,
247     void *tg_cookie);
248 
249 #if defined(__i386) || defined(__amd64)
250 static int cmlb_dkio_get_virtgeom(struct cmlb_lun *cl, caddr_t arg, int flag);
251 static int cmlb_dkio_get_phygeom(struct cmlb_lun *cl, caddr_t  arg, int flag);
252 static int cmlb_dkio_partinfo(struct cmlb_lun *cl, dev_t dev, caddr_t arg,
253     int flag);
254 static int cmlb_dkio_extpartinfo(struct cmlb_lun *cl, dev_t dev, caddr_t arg,
255     int flag);
256 #endif
257 
258 static void cmlb_dbg(uint_t comp, struct cmlb_lun *cl, const char *fmt, ...);
259 static void cmlb_v_log(dev_info_t *dev, char *label, uint_t level,
260     const char *fmt, va_list ap);
261 static void cmlb_log(dev_info_t *dev, char *label, uint_t level,
262     const char *fmt, ...);
263 
264 int
265 _init(void)
266 {
267 	mutex_init(&cmlb_log_mutex, NULL, MUTEX_DRIVER, NULL);
268 	return (mod_install(&modlinkage));
269 }
270 
271 int
272 _info(struct modinfo *modinfop)
273 {
274 	return (mod_info(&modlinkage, modinfop));
275 }
276 
277 int
278 _fini(void)
279 {
280 	int err;
281 
282 	if ((err = mod_remove(&modlinkage)) != 0) {
283 		return (err);
284 	}
285 
286 	mutex_destroy(&cmlb_log_mutex);
287 	return (err);
288 }
289 
290 /*
291  * cmlb_dbg is used for debugging to log additional info
292  * Level of output is controlled via cmlb_level_mask setting.
293  */
294 static void
295 cmlb_dbg(uint_t comp, struct cmlb_lun *cl, const char *fmt, ...)
296 {
297 	va_list		ap;
298 	dev_info_t	*dev;
299 	uint_t		level_mask = 0;
300 
301 	ASSERT(cl != NULL);
302 	dev = CMLB_DEVINFO(cl);
303 	ASSERT(dev != NULL);
304 	/*
305 	 * Filter messages based on the global component and level masks,
306 	 * also print if cl matches the value of cmlb_debug_cl, or if
307 	 * cmlb_debug_cl is set to NULL.
308 	 */
309 	if (comp & CMLB_TRACE)
310 		level_mask |= CMLB_LOGMASK_TRACE;
311 
312 	if (comp & CMLB_INFO)
313 		level_mask |= CMLB_LOGMASK_INFO;
314 
315 	if (comp & CMLB_ERROR)
316 		level_mask |= CMLB_LOGMASK_ERROR;
317 
318 	if ((cmlb_level_mask & level_mask) &&
319 	    ((cmlb_debug_cl == NULL) || (cmlb_debug_cl == cl))) {
320 		va_start(ap, fmt);
321 		cmlb_v_log(dev, CMLB_LABEL(cl), CE_CONT, fmt, ap);
322 		va_end(ap);
323 	}
324 }
325 
326 /*
327  * cmlb_log is basically a duplicate of scsi_log. It is redefined here
328  * so that this module does not depend on scsi module.
329  */
330 static void
331 cmlb_log(dev_info_t *dev, char *label, uint_t level, const char *fmt, ...)
332 {
333 	va_list		ap;
334 
335 	va_start(ap, fmt);
336 	cmlb_v_log(dev, label, level, fmt, ap);
337 	va_end(ap);
338 }
339 
340 static void
341 cmlb_v_log(dev_info_t *dev, char *label, uint_t level, const char *fmt,
342     va_list ap)
343 {
344 	static char 	name[256];
345 	int 		log_only = 0;
346 	int 		boot_only = 0;
347 	int 		console_only = 0;
348 
349 	mutex_enter(&cmlb_log_mutex);
350 
351 	if (dev) {
352 		if (level == CE_PANIC || level == CE_WARN ||
353 		    level == CE_NOTE) {
354 			(void) sprintf(name, "%s (%s%d):\n",
355 			    ddi_pathname(dev, cmlb_log_buffer),
356 			    label, ddi_get_instance(dev));
357 		} else {
358 			name[0] = '\0';
359 		}
360 	} else {
361 		(void) sprintf(name, "%s:", label);
362 	}
363 
364 	(void) vsprintf(cmlb_log_buffer, fmt, ap);
365 
366 	switch (cmlb_log_buffer[0]) {
367 	case '!':
368 		log_only = 1;
369 		break;
370 	case '?':
371 		boot_only = 1;
372 		break;
373 	case '^':
374 		console_only = 1;
375 		break;
376 	}
377 
378 	switch (level) {
379 	case CE_NOTE:
380 		level = CE_CONT;
381 		/* FALLTHROUGH */
382 	case CE_CONT:
383 	case CE_WARN:
384 	case CE_PANIC:
385 		if (boot_only) {
386 			cmn_err(level, "?%s\t%s", name, &cmlb_log_buffer[1]);
387 		} else if (console_only) {
388 			cmn_err(level, "^%s\t%s", name, &cmlb_log_buffer[1]);
389 		} else if (log_only) {
390 			cmn_err(level, "!%s\t%s", name, &cmlb_log_buffer[1]);
391 		} else {
392 			cmn_err(level, "%s\t%s", name, cmlb_log_buffer);
393 		}
394 		break;
395 	case CE_IGNORE:
396 		break;
397 	default:
398 		cmn_err(CE_CONT, "^DEBUG: %s\t%s", name, cmlb_log_buffer);
399 		break;
400 	}
401 	mutex_exit(&cmlb_log_mutex);
402 }
403 
404 
405 /*
406  * cmlb_alloc_handle:
407  *
408  *	Allocates a handle.
409  *
410  * Arguments:
411  *	cmlbhandlep	pointer to handle
412  *
413  * Notes:
414  *	Allocates a handle and stores the allocated handle in the area
415  *	pointed to by cmlbhandlep
416  *
417  * Context:
418  *	Kernel thread only (can sleep).
419  */
420 void
421 cmlb_alloc_handle(cmlb_handle_t *cmlbhandlep)
422 {
423 	struct cmlb_lun 	*cl;
424 
425 	cl = kmem_zalloc(sizeof (struct cmlb_lun), KM_SLEEP);
426 	ASSERT(cmlbhandlep != NULL);
427 
428 	cl->cl_state = CMLB_INITED;
429 	cl->cl_def_labeltype = CMLB_LABEL_UNDEF;
430 	mutex_init(CMLB_MUTEX(cl), NULL, MUTEX_DRIVER, NULL);
431 
432 	*cmlbhandlep = (cmlb_handle_t)(cl);
433 }
434 
435 /*
436  * cmlb_free_handle
437  *
438  *	Frees handle.
439  *
440  * Arguments:
441  *	cmlbhandlep	pointer to handle
442  */
443 void
444 cmlb_free_handle(cmlb_handle_t *cmlbhandlep)
445 {
446 	struct cmlb_lun 	*cl;
447 
448 	cl = (struct cmlb_lun *)*cmlbhandlep;
449 	if (cl != NULL) {
450 		mutex_destroy(CMLB_MUTEX(cl));
451 		kmem_free(cl, sizeof (struct cmlb_lun));
452 	}
453 
454 }
455 
456 /*
457  * cmlb_attach:
458  *
459  *	Attach handle to device, create minor nodes for device.
460  *
461  * Arguments:
462  * 	devi		pointer to device's dev_info structure.
463  * 	tgopsp		pointer to array of functions cmlb can use to callback
464  *			to target driver.
465  *
466  *	device_type	Peripheral device type as defined in
467  *			scsi/generic/inquiry.h
468  *
469  *	is_removable	whether or not device is removable.
470  *			0 non-removable, 1 removable.
471  *
472  *	is_hotpluggable	whether or not device is hotpluggable.
473  *			0 non-hotpluggable, 1 hotpluggable.
474  *
475  *	node_type	minor node type (as used by ddi_create_minor_node)
476  *
477  *	alter_behavior
478  *			bit flags:
479  *
480  *			CMLB_CREATE_ALTSLICE_VTOC_16_DTYPE_DIRECT: create
481  *			an alternate slice for the default label, if
482  *			device type is DTYPE_DIRECT an architectures default
483  *			label type is VTOC16.
484  *			Otherwise alternate slice will no be created.
485  *
486  *
487  *			CMLB_FAKE_GEOM_LABEL_IOCTLS_VTOC8: report a default
488  *			geometry and label for DKIOCGGEOM and DKIOCGVTOC
489  *			on architecture with VTOC8 label types.
490  *
491  * 			CMLB_OFF_BY_ONE: do the workaround for legacy off-by-
492  *                      one bug in obtaining capacity (in sd):
493  *			SCSI READ_CAPACITY command returns the LBA number of the
494  *			last logical block, but sd once treated this number as
495  *			disks' capacity on x86 platform. And LBAs are addressed
496  *			based 0. So the last block was lost on x86 platform.
497  *
498  *			Now, we remove this workaround. In order for present sd
499  *			driver to work with disks which are labeled/partitioned
500  *			via previous sd, we add workaround as follows:
501  *
502  *			1) Locate backup EFI label: cmlb searches the next to
503  *			   last
504  *			   block for backup EFI label. If fails, it will
505  *			   turn to the last block for backup EFI label;
506  *
507  *			2) Clear backup EFI label: cmlb first search the last
508  *			   block for backup EFI label, and will search the
509  *			   next to last block only if failed for the last
510  *			   block.
511  *
512  *			3) Calculate geometry:refer to cmlb_convert_geometry()
513  *			   If capacity increasing by 1 causes disks' capacity
514  *			   to cross over the limits in geometry calculation,
515  *			   geometry info will change. This will raise an issue:
516  *			   In case that primary VTOC label is destroyed, format
517  *			   commandline can restore it via backup VTOC labels.
518  *			   And format locates backup VTOC labels by use of
519  *			   geometry. So changing geometry will
520  *			   prevent format from finding backup VTOC labels. To
521  *			   eliminate this side effect for compatibility,
522  *			   sd uses (capacity -1) to calculate geometry;
523  *
524  *			4) 1TB disks: some important data structures use
525  *			   32-bit signed long/int (for example, daddr_t),
526  *			   so that sd doesn't support a disk with capacity
527  *			   larger than 1TB on 32-bit platform. However,
528  *			   for exactly 1TB disk, it was treated as (1T - 512)B
529  *			   in the past, and could have valid Solaris
530  *			   partitions. To workaround this, if an exactly 1TB
531  *			   disk has Solaris fdisk partition, it will be allowed
532  *			   to work with sd.
533  *
534  *
535  *
536  *			CMLB_FAKE_LABEL_ONE_PARTITION: create s0 and s2 covering
537  *			the entire disk, if there is no valid partition info.
538  *			If there is a valid Solaris partition, s0 and s2 will
539  *			only cover the entire Solaris partition.
540  *
541  *
542  *	cmlbhandle	cmlb handle associated with device
543  *
544  *	tg_cookie	cookie from target driver to be passed back to target
545  *			driver when we call back to it through tg_ops.
546  *
547  * Notes:
548  *	Assumes a default label based on capacity for non-removable devices.
549  *	If capacity > 1TB, EFI is assumed otherwise VTOC (default VTOC
550  *	for the architecture).
551  *
552  *	For removable devices, default label type is assumed to be VTOC
553  *	type. Create minor nodes based on a default label type.
554  *	Label on the media is not validated.
555  *	minor number consists of:
556  *		if _SUNOS_VTOC_8 is defined
557  *			lowest 3 bits is taken as partition number
558  *			the rest is instance number
559  *		if _SUNOS_VTOC_16 is defined
560  *			lowest 6 bits is taken as partition number
561  *			the rest is instance number
562  *
563  *
564  * Return values:
565  *	0 	Success
566  * 	ENXIO 	creating minor nodes failed.
567  *	EINVAL  invalid arg, unsupported tg_ops version
568  */
569 int
570 cmlb_attach(dev_info_t *devi, cmlb_tg_ops_t *tgopsp, int device_type,
571     int is_removable, int is_hotpluggable, char *node_type,
572     int alter_behavior, cmlb_handle_t cmlbhandle, void *tg_cookie)
573 {
574 
575 	struct cmlb_lun	*cl = (struct cmlb_lun *)cmlbhandle;
576 	diskaddr_t	cap;
577 	int		status;
578 
579 	if (tgopsp->tg_version < TG_DK_OPS_VERSION_1)
580 		return (EINVAL);
581 
582 	mutex_enter(CMLB_MUTEX(cl));
583 
584 	CMLB_DEVINFO(cl) = devi;
585 	cl->cmlb_tg_ops = tgopsp;
586 	cl->cl_device_type = device_type;
587 	cl->cl_is_removable = is_removable;
588 	cl->cl_is_hotpluggable = is_hotpluggable;
589 	cl->cl_node_type = node_type;
590 	cl->cl_sys_blocksize = DEV_BSIZE;
591 	cl->cl_f_geometry_is_valid = FALSE;
592 	cl->cl_def_labeltype = CMLB_LABEL_VTOC;
593 	cl->cl_alter_behavior = alter_behavior;
594 	cl->cl_reserved = -1;
595 	cl->cl_msglog_flag |= CMLB_ALLOW_2TB_WARN;
596 
597 	if (is_removable == 0) {
598 		mutex_exit(CMLB_MUTEX(cl));
599 		status = DK_TG_GETCAP(cl, &cap, tg_cookie);
600 		mutex_enter(CMLB_MUTEX(cl));
601 		if (status == 0 && cap > CMLB_EXTVTOC_LIMIT) {
602 			/* set default EFI if > 2TB */
603 			cl->cl_def_labeltype = CMLB_LABEL_EFI;
604 		}
605 	}
606 
607 	/* create minor nodes based on default label type */
608 	cl->cl_last_labeltype = CMLB_LABEL_UNDEF;
609 	cl->cl_cur_labeltype = CMLB_LABEL_UNDEF;
610 
611 	if (cmlb_create_minor_nodes(cl) != 0) {
612 		mutex_exit(CMLB_MUTEX(cl));
613 		return (ENXIO);
614 	}
615 
616 	/* Define the dynamic properties for devinfo spapshots. */
617 	i_ddi_prop_dyn_driver_set(CMLB_DEVINFO(cl), cmlb_prop_dyn);
618 
619 	cl->cl_state = CMLB_ATTACHED;
620 
621 	mutex_exit(CMLB_MUTEX(cl));
622 	return (0);
623 }
624 
625 /*
626  * cmlb_detach:
627  *
628  * Invalidate in-core labeling data and remove all minor nodes for
629  * the device associate with handle.
630  *
631  * Arguments:
632  *	cmlbhandle	cmlb handle associated with device.
633  *
634  *	tg_cookie	cookie from target driver to be passed back to target
635  *			driver when we call back to it through tg_ops.
636  *
637  */
638 /*ARGSUSED1*/
639 void
640 cmlb_detach(cmlb_handle_t cmlbhandle, void *tg_cookie)
641 {
642 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
643 
644 	mutex_enter(CMLB_MUTEX(cl));
645 	cl->cl_def_labeltype = CMLB_LABEL_UNDEF;
646 	cl->cl_f_geometry_is_valid = FALSE;
647 	ddi_remove_minor_node(CMLB_DEVINFO(cl), NULL);
648 	i_ddi_prop_dyn_driver_set(CMLB_DEVINFO(cl), NULL);
649 	cl->cl_state = CMLB_INITED;
650 	mutex_exit(CMLB_MUTEX(cl));
651 }
652 
653 /*
654  * cmlb_validate:
655  *
656  *	Validates label.
657  *
658  * Arguments
659  *	cmlbhandle	cmlb handle associated with device.
660  *
661  *	flags		operation flags. used for verbosity control
662  *
663  *	tg_cookie	cookie from target driver to be passed back to target
664  *			driver when we call back to it through tg_ops.
665  *
666  *
667  * Notes:
668  *	If new label type is different from the current, adjust minor nodes
669  *	accordingly.
670  *
671  * Return values:
672  *	0		success
673  *			Note: having fdisk but no solaris partition is assumed
674  *			success.
675  *
676  *	ENOMEM		memory allocation failed
677  *	EIO		i/o errors during read or get capacity
678  * 	EACCESS		reservation conflicts
679  * 	EINVAL		label was corrupt, or no default label was assumed
680  *	ENXIO		invalid handle
681  */
682 int
683 cmlb_validate(cmlb_handle_t cmlbhandle, int flags, void *tg_cookie)
684 {
685 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
686 	int 		rval;
687 	int  		ret = 0;
688 
689 	/*
690 	 * Temp work-around checking cl for NULL since there is a bug
691 	 * in sd_detach calling this routine from taskq_dispatch
692 	 * inited function.
693 	 */
694 	if (cl == NULL)
695 		return (ENXIO);
696 
697 	mutex_enter(CMLB_MUTEX(cl));
698 	if (cl->cl_state < CMLB_ATTACHED) {
699 		mutex_exit(CMLB_MUTEX(cl));
700 		return (ENXIO);
701 	}
702 
703 	rval = cmlb_validate_geometry((struct cmlb_lun *)cmlbhandle, 1,
704 	    flags, tg_cookie);
705 
706 	if (rval == ENOTSUP) {
707 		if (cl->cl_f_geometry_is_valid == TRUE) {
708 			cl->cl_cur_labeltype = CMLB_LABEL_EFI;
709 			ret = 0;
710 		} else {
711 			ret = EINVAL;
712 		}
713 	} else {
714 		ret = rval;
715 		if (ret == 0)
716 			cl->cl_cur_labeltype = CMLB_LABEL_VTOC;
717 	}
718 
719 	if (ret == 0)
720 		(void) cmlb_create_minor_nodes(cl);
721 
722 	mutex_exit(CMLB_MUTEX(cl));
723 	return (ret);
724 }
725 
726 /*
727  * cmlb_invalidate:
728  *	Invalidate in core label data
729  *
730  * Arguments:
731  *	cmlbhandle	cmlb handle associated with device.
732  *	tg_cookie	cookie from target driver to be passed back to target
733  *			driver when we call back to it through tg_ops.
734  */
735 /*ARGSUSED1*/
736 void
737 cmlb_invalidate(cmlb_handle_t cmlbhandle, void *tg_cookie)
738 {
739 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
740 
741 	if (cl == NULL)
742 		return;
743 
744 	mutex_enter(CMLB_MUTEX(cl));
745 	cl->cl_f_geometry_is_valid = FALSE;
746 	mutex_exit(CMLB_MUTEX(cl));
747 }
748 
749 /*
750  * cmlb_is_valid
751  * 	Get status on whether the incore label/geom data is valid
752  *
753  * Arguments:
754  *	cmlbhandle      cmlb handle associated with device.
755  *
756  * Return values:
757  *	TRUE if incore label/geom data is valid.
758  *	FALSE otherwise.
759  *
760  */
761 
762 
763 int
764 cmlb_is_valid(cmlb_handle_t cmlbhandle)
765 {
766 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
767 
768 	if (cmlbhandle == NULL)
769 		return (FALSE);
770 
771 	return (cl->cl_f_geometry_is_valid);
772 
773 }
774 
775 
776 
777 /*
778  * cmlb_close:
779  *
780  * Close the device, revert to a default label minor node for the device,
781  * if it is removable.
782  *
783  * Arguments:
784  *	cmlbhandle	cmlb handle associated with device.
785  *
786  *	tg_cookie	cookie from target driver to be passed back to target
787  *			driver when we call back to it through tg_ops.
788  * Return values:
789  *	0	Success
790  * 	ENXIO	Re-creating minor node failed.
791  */
792 /*ARGSUSED1*/
793 int
794 cmlb_close(cmlb_handle_t cmlbhandle, void *tg_cookie)
795 {
796 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
797 
798 	mutex_enter(CMLB_MUTEX(cl));
799 	cl->cl_f_geometry_is_valid = FALSE;
800 
801 	/* revert to default minor node for this device */
802 	if (ISREMOVABLE(cl)) {
803 		cl->cl_cur_labeltype = CMLB_LABEL_UNDEF;
804 		(void) cmlb_create_minor_nodes(cl);
805 	}
806 
807 	mutex_exit(CMLB_MUTEX(cl));
808 	return (0);
809 }
810 
811 /*
812  * cmlb_get_devid_block:
813  *	 get the block number where device id is stored.
814  *
815  * Arguments:
816  *	cmlbhandle	cmlb handle associated with device.
817  *	devidblockp	pointer to block number.
818  *	tg_cookie	cookie from target driver to be passed back to target
819  *			driver when we call back to it through tg_ops.
820  *
821  * Notes:
822  *	It stores the block number of device id in the area pointed to
823  *	by devidblockp.
824  * 	with the block number of device id.
825  *
826  * Return values:
827  *	0	success
828  *	EINVAL 	device id does not apply to current label type.
829  */
830 /*ARGSUSED2*/
831 int
832 cmlb_get_devid_block(cmlb_handle_t cmlbhandle, diskaddr_t *devidblockp,
833     void *tg_cookie)
834 {
835 	daddr_t			spc, blk, head, cyl;
836 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
837 
838 	mutex_enter(CMLB_MUTEX(cl));
839 	if (cl->cl_state < CMLB_ATTACHED) {
840 		mutex_exit(CMLB_MUTEX(cl));
841 		return (EINVAL);
842 	}
843 
844 	if ((cl->cl_f_geometry_is_valid == FALSE) ||
845 	    (cl->cl_solaris_size < DK_LABEL_LOC)) {
846 		mutex_exit(CMLB_MUTEX(cl));
847 		return (EINVAL);
848 	}
849 
850 	if (cl->cl_cur_labeltype == CMLB_LABEL_EFI) {
851 		if (cl->cl_reserved != -1) {
852 			blk = cl->cl_map[cl->cl_reserved].dkl_cylno;
853 		} else {
854 			mutex_exit(CMLB_MUTEX(cl));
855 			return (EINVAL);
856 		}
857 	} else {
858 		/* if the disk is unlabeled, don't write a devid to it */
859 		if (cl->cl_label_from_media != CMLB_LABEL_VTOC) {
860 			mutex_exit(CMLB_MUTEX(cl));
861 			return (EINVAL);
862 		}
863 
864 		/* this geometry doesn't allow us to write a devid */
865 		if (cl->cl_g.dkg_acyl < 2) {
866 			mutex_exit(CMLB_MUTEX(cl));
867 			return (EINVAL);
868 		}
869 
870 		/*
871 		 * Subtract 2 guarantees that the next to last cylinder
872 		 * is used
873 		 */
874 		cyl  = cl->cl_g.dkg_ncyl  + cl->cl_g.dkg_acyl - 2;
875 		spc  = cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect;
876 		head = cl->cl_g.dkg_nhead - 1;
877 		blk  = cl->cl_solaris_offset +
878 		    (cyl * (spc - cl->cl_g.dkg_apc)) +
879 		    (head * cl->cl_g.dkg_nsect) + 1;
880 	}
881 
882 	*devidblockp = blk;
883 	mutex_exit(CMLB_MUTEX(cl));
884 	return (0);
885 }
886 
887 /*
888  * cmlb_partinfo:
889  *	Get partition info for specified partition number.
890  *
891  * Arguments:
892  *	cmlbhandle	cmlb handle associated with device.
893  *	part		partition number
894  *	nblocksp	pointer to number of blocks
895  *	startblockp	pointer to starting block
896  *	partnamep	pointer to name of partition
897  *	tagp		pointer to tag info
898  *	tg_cookie	cookie from target driver to be passed back to target
899  *			driver when we call back to it through tg_ops.
900  *
901  *
902  * Notes:
903  *	If in-core label is not valid, this functions tries to revalidate
904  *	the label. If label is valid, it stores the total number of blocks
905  *	in this partition in the area pointed to by nblocksp, starting
906  *	block number in area pointed to by startblockp,  pointer to partition
907  *	name in area pointed to by partnamep, and tag value in area
908  *	pointed by tagp.
909  *	For EFI labels, tag value will be set to 0.
910  *
911  *	For all nblocksp, startblockp and partnamep, tagp, a value of NULL
912  *	indicates the corresponding info is not requested.
913  *
914  *
915  * Return values:
916  *	0	success
917  *	EINVAL  no valid label or requested partition number is invalid.
918  *
919  */
920 int
921 cmlb_partinfo(cmlb_handle_t cmlbhandle, int part, diskaddr_t *nblocksp,
922     diskaddr_t *startblockp, char **partnamep, uint16_t *tagp, void *tg_cookie)
923 {
924 
925 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
926 	int rval;
927 
928 	ASSERT(cl != NULL);
929 	mutex_enter(CMLB_MUTEX(cl));
930 	if (cl->cl_state < CMLB_ATTACHED) {
931 		mutex_exit(CMLB_MUTEX(cl));
932 		return (EINVAL);
933 	}
934 
935 	if (part  < 0 || part >= MAXPART) {
936 		rval = EINVAL;
937 	} else {
938 		if (cl->cl_f_geometry_is_valid == FALSE)
939 			(void) cmlb_validate_geometry((struct cmlb_lun *)cl, 0,
940 			    0, tg_cookie);
941 
942 #if defined(_SUNOS_VTOC_16)
943 		if (((cl->cl_f_geometry_is_valid == FALSE) ||
944 		    (part < NDKMAP && cl->cl_solaris_size == 0)) &&
945 		    (part != P0_RAW_DISK)) {
946 #else
947 		if ((cl->cl_f_geometry_is_valid == FALSE) ||
948 		    (part < NDKMAP && cl->cl_solaris_size == 0)) {
949 #endif
950 			rval = EINVAL;
951 		} else {
952 			if (startblockp != NULL)
953 				*startblockp = (diskaddr_t)cl->cl_offset[part];
954 
955 			if (nblocksp != NULL)
956 				*nblocksp = (diskaddr_t)
957 				    cl->cl_map[part].dkl_nblk;
958 
959 			if (tagp != NULL)
960 				if (cl->cl_cur_labeltype == CMLB_LABEL_EFI)
961 					*tagp = V_UNASSIGNED;
962 				else
963 					*tagp = cl->cl_vtoc.v_part[part].p_tag;
964 			rval = 0;
965 		}
966 
967 		/* consistent with behavior of sd for getting minor name */
968 		if (partnamep != NULL)
969 			*partnamep = dk_minor_data[part].name;
970 
971 	}
972 
973 	mutex_exit(CMLB_MUTEX(cl));
974 	return (rval);
975 }
976 
977 /*
978  * cmlb_efi_label_capacity:
979  *	Get capacity stored in EFI disk label.
980  *
981  * Arguments:
982  *	cmlbhandle	cmlb handle associated with device.
983  *	capacity	pointer to capacity stored in EFI disk label.
984  *	tg_cookie	cookie from target driver to be passed back to target
985  *			driver when we call back to it through tg_ops.
986  *
987  *
988  * Notes:
989  *	If in-core label is not valid, this functions tries to revalidate
990  *	the label. If label is valid and is an EFI label, it stores the capacity
991  *      in disk label in the area pointed to by capacity.
992  *
993  *
994  * Return values:
995  *	0	success
996  *	EINVAL  no valid EFI label or capacity is NULL.
997  *
998  */
999 int
1000 cmlb_efi_label_capacity(cmlb_handle_t cmlbhandle, diskaddr_t *capacity,
1001     void *tg_cookie)
1002 {
1003 	struct cmlb_lun *cl = (struct cmlb_lun *)cmlbhandle;
1004 	int rval;
1005 
1006 	ASSERT(cl != NULL);
1007 	mutex_enter(CMLB_MUTEX(cl));
1008 	if (cl->cl_state < CMLB_ATTACHED) {
1009 		mutex_exit(CMLB_MUTEX(cl));
1010 		return (EINVAL);
1011 	}
1012 
1013 	if (cl->cl_f_geometry_is_valid == FALSE)
1014 		(void) cmlb_validate_geometry((struct cmlb_lun *)cl, 0,
1015 		    0, tg_cookie);
1016 
1017 	if ((cl->cl_f_geometry_is_valid == FALSE) || (capacity == NULL) ||
1018 	    (cl->cl_cur_labeltype != CMLB_LABEL_EFI)) {
1019 		rval = EINVAL;
1020 	} else {
1021 		*capacity = (diskaddr_t)cl->cl_map[WD_NODE].dkl_nblk;
1022 		rval = 0;
1023 	}
1024 
1025 	mutex_exit(CMLB_MUTEX(cl));
1026 	return (rval);
1027 }
1028 
1029 /* Caller should make sure Test Unit Ready succeeds before calling this. */
1030 /*ARGSUSED*/
1031 int
1032 cmlb_ioctl(cmlb_handle_t cmlbhandle, dev_t dev, int cmd, intptr_t arg,
1033     int flag, cred_t *cred_p, int *rval_p, void *tg_cookie)
1034 {
1035 
1036 	int err;
1037 	struct cmlb_lun *cl;
1038 
1039 	cl = (struct cmlb_lun *)cmlbhandle;
1040 
1041 	ASSERT(cl != NULL);
1042 
1043 	mutex_enter(CMLB_MUTEX(cl));
1044 	if (cl->cl_state < CMLB_ATTACHED) {
1045 		mutex_exit(CMLB_MUTEX(cl));
1046 		return (EIO);
1047 	}
1048 
1049 	switch (cmd) {
1050 		case DKIOCSEXTVTOC:
1051 		case DKIOCSGEOM:
1052 		case DKIOCSETEFI:
1053 		case DKIOCSMBOOT:
1054 			break;
1055 		case DKIOCSVTOC:
1056 #if defined(__i386) || defined(__amd64)
1057 		case DKIOCPARTINFO:
1058 #endif
1059 			if (cl->cl_blockcount > CMLB_OLDVTOC_LIMIT) {
1060 				mutex_exit(CMLB_MUTEX(cl));
1061 				return (EOVERFLOW);
1062 			}
1063 			break;
1064 		default:
1065 			(void) cmlb_validate_geometry(cl, 1, CMLB_SILENT,
1066 			    tg_cookie);
1067 
1068 			switch (cmd) {
1069 			case DKIOCGVTOC:
1070 			case DKIOCGAPART:
1071 			case DKIOCSAPART:
1072 
1073 				if (cl->cl_label_from_media == CMLB_LABEL_EFI) {
1074 					/* GPT label on disk */
1075 					mutex_exit(CMLB_MUTEX(cl));
1076 					return (ENOTSUP);
1077 				} else if
1078 				    (cl->cl_blockcount > CMLB_OLDVTOC_LIMIT) {
1079 					mutex_exit(CMLB_MUTEX(cl));
1080 					return (EOVERFLOW);
1081 				}
1082 				break;
1083 
1084 			case DKIOCGGEOM:
1085 				if (cl->cl_label_from_media == CMLB_LABEL_EFI) {
1086 					/* GPT label on disk */
1087 					mutex_exit(CMLB_MUTEX(cl));
1088 					return (ENOTSUP);
1089 				}
1090 				break;
1091 			default:
1092 				break;
1093 			}
1094 	}
1095 
1096 	mutex_exit(CMLB_MUTEX(cl));
1097 
1098 	switch (cmd) {
1099 	case DKIOCGGEOM:
1100 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGGEOM\n");
1101 		err = cmlb_dkio_get_geometry(cl, (caddr_t)arg, flag, tg_cookie);
1102 		break;
1103 
1104 	case DKIOCSGEOM:
1105 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSGEOM\n");
1106 		err = cmlb_dkio_set_geometry(cl, (caddr_t)arg, flag);
1107 		break;
1108 
1109 	case DKIOCGAPART:
1110 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGAPART\n");
1111 		err = cmlb_dkio_get_partition(cl, (caddr_t)arg,
1112 		    flag, tg_cookie);
1113 		break;
1114 
1115 	case DKIOCSAPART:
1116 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSAPART\n");
1117 		err = cmlb_dkio_set_partition(cl, (caddr_t)arg, flag);
1118 		break;
1119 
1120 	case DKIOCGVTOC:
1121 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGVTOC\n");
1122 		err = cmlb_dkio_get_vtoc(cl, (caddr_t)arg, flag, tg_cookie);
1123 		break;
1124 
1125 	case DKIOCGEXTVTOC:
1126 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGVTOC\n");
1127 		err = cmlb_dkio_get_extvtoc(cl, (caddr_t)arg, flag, tg_cookie);
1128 		break;
1129 
1130 	case DKIOCGETEFI:
1131 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGETEFI\n");
1132 		err = cmlb_dkio_get_efi(cl, (caddr_t)arg, flag, tg_cookie);
1133 		break;
1134 
1135 	case DKIOCPARTITION:
1136 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCPARTITION\n");
1137 		err = cmlb_dkio_partition(cl, (caddr_t)arg, flag, tg_cookie);
1138 		break;
1139 
1140 	case DKIOCSVTOC:
1141 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSVTOC\n");
1142 		err = cmlb_dkio_set_vtoc(cl, dev, (caddr_t)arg, flag,
1143 		    tg_cookie);
1144 		break;
1145 
1146 	case DKIOCSEXTVTOC:
1147 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSVTOC\n");
1148 		err = cmlb_dkio_set_extvtoc(cl, dev, (caddr_t)arg, flag,
1149 		    tg_cookie);
1150 		break;
1151 
1152 	case DKIOCSETEFI:
1153 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSETEFI\n");
1154 		err = cmlb_dkio_set_efi(cl, dev, (caddr_t)arg, flag, tg_cookie);
1155 		break;
1156 
1157 	case DKIOCGMBOOT:
1158 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCGMBOOT\n");
1159 		err = cmlb_dkio_get_mboot(cl, (caddr_t)arg, flag, tg_cookie);
1160 		break;
1161 
1162 	case DKIOCSMBOOT:
1163 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCSMBOOT\n");
1164 		err = cmlb_dkio_set_mboot(cl, (caddr_t)arg, flag, tg_cookie);
1165 		break;
1166 	case DKIOCG_PHYGEOM:
1167 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCG_PHYGEOM\n");
1168 #if defined(__i386) || defined(__amd64)
1169 		err = cmlb_dkio_get_phygeom(cl, (caddr_t)arg, flag);
1170 #else
1171 		err = ENOTTY;
1172 #endif
1173 		break;
1174 	case DKIOCG_VIRTGEOM:
1175 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCG_VIRTGEOM\n");
1176 #if defined(__i386) || defined(__amd64)
1177 		err = cmlb_dkio_get_virtgeom(cl, (caddr_t)arg, flag);
1178 #else
1179 		err = ENOTTY;
1180 #endif
1181 		break;
1182 	case DKIOCPARTINFO:
1183 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCPARTINFO");
1184 #if defined(__i386) || defined(__amd64)
1185 		err = cmlb_dkio_partinfo(cl, dev, (caddr_t)arg, flag);
1186 #else
1187 		err = ENOTTY;
1188 #endif
1189 		break;
1190 	case DKIOCEXTPARTINFO:
1191 		cmlb_dbg(CMLB_TRACE, cl, "DKIOCPARTINFO");
1192 #if defined(__i386) || defined(__amd64)
1193 		err = cmlb_dkio_extpartinfo(cl, dev, (caddr_t)arg, flag);
1194 #else
1195 		err = ENOTTY;
1196 #endif
1197 		break;
1198 
1199 	default:
1200 		err = ENOTTY;
1201 
1202 	}
1203 
1204 	/*
1205 	 * An ioctl that succeeds and changed ('set') size(9P) information
1206 	 * needs to invalidate the cached devinfo snapshot to avoid having
1207 	 * old information being returned in a snapshots.
1208 	 *
1209 	 * NB: When available, call ddi_change_minor_node() to clear
1210 	 * SSIZEVALID in specfs vnodes via spec_size_invalidate().
1211 	 */
1212 	if (err == 0) {
1213 		switch (cmd) {
1214 		case DKIOCSGEOM:
1215 		case DKIOCSAPART:
1216 		case DKIOCSVTOC:
1217 		case DKIOCSEXTVTOC:
1218 		case DKIOCSETEFI:
1219 			i_ddi_prop_dyn_cache_invalidate(CMLB_DEVINFO(cl),
1220 			    i_ddi_prop_dyn_driver_get(CMLB_DEVINFO(cl)));
1221 		}
1222 	}
1223 	return (err);
1224 }
1225 
1226 dev_t
1227 cmlb_make_device(struct cmlb_lun *cl)
1228 {
1229 	return (makedevice(ddi_name_to_major(ddi_get_name(CMLB_DEVINFO(cl))),
1230 	    ddi_get_instance(CMLB_DEVINFO(cl)) << CMLBUNIT_SHIFT));
1231 }
1232 
1233 /*
1234  * Function: cmlb_check_update_blockcount
1235  *
1236  * Description: If current capacity value is invalid, obtains the
1237  *		current capacity from target driver.
1238  *
1239  * Return Code: 0	success
1240  *		EIO	failure
1241  */
1242 static int
1243 cmlb_check_update_blockcount(struct cmlb_lun *cl, void *tg_cookie)
1244 {
1245 	int status;
1246 	diskaddr_t capacity;
1247 	uint32_t lbasize;
1248 
1249 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1250 
1251 	if (cl->cl_f_geometry_is_valid == FALSE)  {
1252 		mutex_exit(CMLB_MUTEX(cl));
1253 		status = DK_TG_GETCAP(cl, &capacity, tg_cookie);
1254 		if (status != 0) {
1255 			mutex_enter(CMLB_MUTEX(cl));
1256 			return (EIO);
1257 		}
1258 
1259 		status = DK_TG_GETBLOCKSIZE(cl, &lbasize, tg_cookie);
1260 		mutex_enter(CMLB_MUTEX(cl));
1261 		if (status != 0)
1262 			return (EIO);
1263 
1264 		if ((capacity != 0) && (lbasize != 0)) {
1265 			cl->cl_blockcount = capacity;
1266 			cl->cl_tgt_blocksize = lbasize;
1267 			return (0);
1268 		} else
1269 			return (EIO);
1270 	} else
1271 		return (0);
1272 }
1273 
1274 static int
1275 cmlb_create_minor(dev_info_t *dip, char *name, int spec_type,
1276     minor_t minor_num, char *node_type, int flag, boolean_t internal)
1277 {
1278 	if (internal)
1279 		return (ddi_create_internal_pathname(dip,
1280 		    name, spec_type, minor_num));
1281 	else
1282 		return (ddi_create_minor_node(dip,
1283 		    name, spec_type, minor_num, node_type, flag));
1284 }
1285 
1286 /*
1287  *    Function: cmlb_create_minor_nodes
1288  *
1289  * Description: Create or adjust the minor device nodes for the instance.
1290  * 		Minor nodes are created based on default label type,
1291  *		current label type and last label type we created
1292  *		minor nodes based on.
1293  *
1294  *
1295  *   Arguments: cl - driver soft state (unit) structure
1296  *
1297  * Return Code: 0 success
1298  *		ENXIO	failure.
1299  *
1300  *     Context: Kernel thread context
1301  */
1302 static int
1303 cmlb_create_minor_nodes(struct cmlb_lun *cl)
1304 {
1305 	struct driver_minor_data	*dmdp;
1306 	int				instance;
1307 	char				name[48];
1308 	cmlb_label_t			newlabeltype;
1309 	boolean_t			internal;
1310 
1311 	ASSERT(cl != NULL);
1312 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1313 
1314 	internal = ((cl->cl_alter_behavior & (CMLB_INTERNAL_MINOR_NODES)) != 0);
1315 
1316 	/* check the most common case */
1317 	if (cl->cl_cur_labeltype != CMLB_LABEL_UNDEF &&
1318 	    cl->cl_last_labeltype == cl->cl_cur_labeltype) {
1319 		/* do nothing */
1320 		return (0);
1321 	}
1322 
1323 	if (cl->cl_def_labeltype == CMLB_LABEL_UNDEF) {
1324 		/* we should never get here */
1325 		return (ENXIO);
1326 	}
1327 
1328 	if (cl->cl_last_labeltype == CMLB_LABEL_UNDEF) {
1329 		/* first time during attach */
1330 		newlabeltype = cl->cl_def_labeltype;
1331 
1332 		instance = ddi_get_instance(CMLB_DEVINFO(cl));
1333 
1334 		/* Create all the minor nodes for this target. */
1335 		dmdp = (newlabeltype == CMLB_LABEL_EFI) ? dk_minor_data_efi :
1336 		    dk_minor_data;
1337 		while (dmdp->name != NULL) {
1338 
1339 			(void) sprintf(name, "%s", dmdp->name);
1340 
1341 			if (cmlb_create_minor(CMLB_DEVINFO(cl), name,
1342 			    dmdp->type,
1343 			    (instance << CMLBUNIT_SHIFT) | dmdp->minor,
1344 			    cl->cl_node_type, NULL, internal) == DDI_FAILURE) {
1345 				/*
1346 				 * Clean up any nodes that may have been
1347 				 * created, in case this fails in the middle
1348 				 * of the loop.
1349 				 */
1350 				ddi_remove_minor_node(CMLB_DEVINFO(cl), NULL);
1351 				return (ENXIO);
1352 			}
1353 			dmdp++;
1354 		}
1355 		cl->cl_last_labeltype = newlabeltype;
1356 		return (0);
1357 	}
1358 
1359 	/* Not first time  */
1360 	if (cl->cl_cur_labeltype == CMLB_LABEL_UNDEF) {
1361 		if (cl->cl_last_labeltype != cl->cl_def_labeltype) {
1362 			/* close time, revert to default. */
1363 			newlabeltype = cl->cl_def_labeltype;
1364 		} else {
1365 			/*
1366 			 * do nothing since the type for which we last created
1367 			 * nodes matches the default
1368 			 */
1369 			return (0);
1370 		}
1371 	} else {
1372 		if (cl->cl_cur_labeltype != cl->cl_last_labeltype) {
1373 			/* We are not closing, use current label type */
1374 			newlabeltype = cl->cl_cur_labeltype;
1375 		} else {
1376 			/*
1377 			 * do nothing since the type for which we last created
1378 			 * nodes matches the current label type
1379 			 */
1380 			return (0);
1381 		}
1382 	}
1383 
1384 	instance = ddi_get_instance(CMLB_DEVINFO(cl));
1385 
1386 	/*
1387 	 * Currently we only fix up the s7 node when we are switching
1388 	 * label types from or to EFI. This is consistent with
1389 	 * current behavior of sd.
1390 	 */
1391 	if (newlabeltype == CMLB_LABEL_EFI &&
1392 	    cl->cl_last_labeltype != CMLB_LABEL_EFI) {
1393 		/* from vtoc to EFI */
1394 		ddi_remove_minor_node(CMLB_DEVINFO(cl), "h");
1395 		ddi_remove_minor_node(CMLB_DEVINFO(cl), "h,raw");
1396 		(void) cmlb_create_minor(CMLB_DEVINFO(cl), "wd",
1397 		    S_IFBLK, (instance << CMLBUNIT_SHIFT) | WD_NODE,
1398 		    cl->cl_node_type, NULL, internal);
1399 		(void) cmlb_create_minor(CMLB_DEVINFO(cl), "wd,raw",
1400 		    S_IFCHR, (instance << CMLBUNIT_SHIFT) | WD_NODE,
1401 		    cl->cl_node_type, NULL, internal);
1402 	} else {
1403 		/* from efi to vtoc */
1404 		ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd");
1405 		ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd,raw");
1406 		(void) cmlb_create_minor(CMLB_DEVINFO(cl), "h",
1407 		    S_IFBLK, (instance << CMLBUNIT_SHIFT) | WD_NODE,
1408 		    cl->cl_node_type, NULL, internal);
1409 		(void) cmlb_create_minor(CMLB_DEVINFO(cl), "h,raw",
1410 		    S_IFCHR, (instance << CMLBUNIT_SHIFT) | WD_NODE,
1411 		    cl->cl_node_type, NULL, internal);
1412 	}
1413 
1414 	cl->cl_last_labeltype = newlabeltype;
1415 	return (0);
1416 }
1417 
1418 /*
1419  *    Function: cmlb_validate_geometry
1420  *
1421  * Description: Read the label from the disk (if present). Update the unit's
1422  *		geometry and vtoc information from the data in the label.
1423  *		Verify that the label is valid.
1424  *
1425  *   Arguments:
1426  *	cl		driver soft state (unit) structure
1427  *
1428  *	forcerevalid	force revalidation even if we are already valid.
1429  *	flags		operation flags from target driver. Used for verbosity
1430  *			control	at this time.
1431  *	tg_cookie	cookie from target driver to be passed back to target
1432  *			driver when we call back to it through tg_ops.
1433  *
1434  * Return Code: 0 - Successful completion
1435  *		EINVAL  - Invalid value in cl->cl_tgt_blocksize or
1436  *			  cl->cl_blockcount; or label on disk is corrupted
1437  *			  or unreadable.
1438  *		EACCES  - Reservation conflict at the device.
1439  *		ENOMEM  - Resource allocation error
1440  *		ENOTSUP - geometry not applicable
1441  *
1442  *     Context: Kernel thread only (can sleep).
1443  */
1444 static int
1445 cmlb_validate_geometry(struct cmlb_lun *cl, int forcerevalid, int flags,
1446     void *tg_cookie)
1447 {
1448 	int		label_error = 0;
1449 	diskaddr_t	capacity;
1450 	int		count;
1451 
1452 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1453 
1454 	if ((cl->cl_f_geometry_is_valid == TRUE) && (forcerevalid == 0)) {
1455 		if (cl->cl_cur_labeltype == CMLB_LABEL_EFI)
1456 			return (ENOTSUP);
1457 		return (0);
1458 	}
1459 
1460 	if (cmlb_check_update_blockcount(cl, tg_cookie) != 0)
1461 		return (EIO);
1462 
1463 	capacity = cl->cl_blockcount;
1464 
1465 #if defined(_SUNOS_VTOC_16)
1466 	/*
1467 	 * Set up the "whole disk" fdisk partition; this should always
1468 	 * exist, regardless of whether the disk contains an fdisk table
1469 	 * or vtoc.
1470 	 */
1471 	cl->cl_map[P0_RAW_DISK].dkl_cylno = 0;
1472 	cl->cl_offset[P0_RAW_DISK] = 0;
1473 	/*
1474 	 * note if capacity > int32_max(1TB) we are in 64bit environment
1475 	 * so no truncation happens
1476 	 */
1477 	cl->cl_map[P0_RAW_DISK].dkl_nblk  = capacity;
1478 #endif
1479 	/*
1480 	 * Refresh the logical and physical geometry caches.
1481 	 * (data from MODE SENSE format/rigid disk geometry pages,
1482 	 * and scsi_ifgetcap("geometry").
1483 	 */
1484 	cmlb_resync_geom_caches(cl, capacity, tg_cookie);
1485 
1486 	cl->cl_label_from_media = CMLB_LABEL_UNDEF;
1487 	label_error = cmlb_use_efi(cl, capacity, flags, tg_cookie);
1488 	if (label_error == 0) {
1489 
1490 		/* found a valid EFI label */
1491 		cmlb_dbg(CMLB_TRACE, cl,
1492 		    "cmlb_validate_geometry: found EFI label\n");
1493 		/*
1494 		 * solaris_size and geometry_is_valid are set in
1495 		 * cmlb_use_efi
1496 		 */
1497 		return (ENOTSUP);
1498 	}
1499 
1500 	/* NO EFI label found */
1501 
1502 	if (capacity > CMLB_EXTVTOC_LIMIT) {
1503 		if (label_error == ESRCH) {
1504 			/*
1505 			 * they've configured a LUN over 2TB, but used
1506 			 * format.dat to restrict format's view of the
1507 			 * capacity to be under 2TB in some earlier Solaris
1508 			 * release.
1509 			 */
1510 			/* i.e > 2TB with a VTOC < 2TB */
1511 			if (!(flags & CMLB_SILENT) &&
1512 			    (cl->cl_msglog_flag & CMLB_ALLOW_2TB_WARN)) {
1513 
1514 				cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl),
1515 				    CE_NOTE, "!Disk (%s%d) is limited to 2 TB "
1516 				    "due to VTOC label. To use the full "
1517 				    "capacity of the disk, use format(1M) to "
1518 				    "relabel the disk with EFI/GPT label.\n",
1519 				    CMLB_LABEL(cl),
1520 				    ddi_get_instance(CMLB_DEVINFO(cl)));
1521 
1522 				cl->cl_msglog_flag &= ~CMLB_ALLOW_2TB_WARN;
1523 			}
1524 		} else {
1525 				return (ENOTSUP);
1526 		}
1527 	}
1528 
1529 	label_error = 0;
1530 
1531 	/*
1532 	 * at this point it is either labeled with a VTOC or it is
1533 	 * under 1TB (<= 1TB actually for off-by-1)
1534 	 */
1535 
1536 	/*
1537 	 * Only DIRECT ACCESS devices will have Scl labels.
1538 	 * CD's supposedly have a Scl label, too
1539 	 */
1540 	if (cl->cl_device_type == DTYPE_DIRECT || ISREMOVABLE(cl)) {
1541 		struct	dk_label *dkl;
1542 		offset_t label_addr;
1543 		int	rval;
1544 		size_t	buffer_size;
1545 
1546 		/*
1547 		 * Note: This will set up cl->cl_solaris_size and
1548 		 * cl->cl_solaris_offset.
1549 		 */
1550 		rval = cmlb_read_fdisk(cl, capacity, tg_cookie);
1551 		if ((rval != 0) && !ISCD(cl)) {
1552 			ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1553 			return (rval);
1554 		}
1555 
1556 		if (cl->cl_solaris_size <= DK_LABEL_LOC) {
1557 			/*
1558 			 * Found fdisk table but no Solaris partition entry,
1559 			 * so don't call cmlb_uselabel() and don't create
1560 			 * a default label.
1561 			 */
1562 			label_error = 0;
1563 			cl->cl_f_geometry_is_valid = TRUE;
1564 			goto no_solaris_partition;
1565 		}
1566 
1567 		label_addr = (daddr_t)(cl->cl_solaris_offset + DK_LABEL_LOC);
1568 
1569 		buffer_size = sizeof (struct dk_label);
1570 
1571 		cmlb_dbg(CMLB_TRACE, cl, "cmlb_validate_geometry: "
1572 		    "label_addr: 0x%x allocation size: 0x%x\n",
1573 		    label_addr, buffer_size);
1574 
1575 		if ((dkl = kmem_zalloc(buffer_size, KM_NOSLEEP)) == NULL)
1576 			return (ENOMEM);
1577 
1578 		mutex_exit(CMLB_MUTEX(cl));
1579 		rval = DK_TG_READ(cl, dkl, label_addr, buffer_size, tg_cookie);
1580 		mutex_enter(CMLB_MUTEX(cl));
1581 
1582 		switch (rval) {
1583 		case 0:
1584 			/*
1585 			 * cmlb_uselabel will establish that the geometry
1586 			 * is valid.
1587 			 */
1588 			if (cmlb_uselabel(cl,
1589 			    (struct dk_label *)(uintptr_t)dkl, flags) !=
1590 			    CMLB_LABEL_IS_VALID) {
1591 				label_error = EINVAL;
1592 			} else
1593 				cl->cl_label_from_media = CMLB_LABEL_VTOC;
1594 			break;
1595 		case EACCES:
1596 			label_error = EACCES;
1597 			break;
1598 		default:
1599 			label_error = EINVAL;
1600 			break;
1601 		}
1602 
1603 		kmem_free(dkl, buffer_size);
1604 	}
1605 
1606 	/*
1607 	 * If a valid label was not found, AND if no reservation conflict
1608 	 * was detected, then go ahead and create a default label (4069506).
1609 	 *
1610 	 * Note: currently, for VTOC_8 devices, the default label is created
1611 	 * for removables and hotpluggables only.  For VTOC_16 devices, the
1612 	 * default label will be created for all devices.
1613 	 * (see cmlb_build_default_label)
1614 	 */
1615 #if defined(_SUNOS_VTOC_8)
1616 	if ((ISREMOVABLE(cl) || ISHOTPLUGGABLE(cl)) &&
1617 	    (label_error != EACCES)) {
1618 #elif defined(_SUNOS_VTOC_16)
1619 	if (label_error != EACCES) {
1620 #endif
1621 		if (cl->cl_f_geometry_is_valid == FALSE) {
1622 			cmlb_build_default_label(cl, tg_cookie);
1623 		}
1624 		label_error = 0;
1625 	}
1626 
1627 no_solaris_partition:
1628 
1629 #if defined(_SUNOS_VTOC_16)
1630 	/*
1631 	 * If we have valid geometry, set up the remaining fdisk partitions.
1632 	 * Note that dkl_cylno is not used for the fdisk map entries, so
1633 	 * we set it to an entirely bogus value.
1634 	 */
1635 	for (count = 0; count < FD_NUMPART; count++) {
1636 		cl->cl_map[FDISK_P1 + count].dkl_cylno = UINT16_MAX;
1637 		cl->cl_map[FDISK_P1 + count].dkl_nblk =
1638 		    cl->cl_fmap[count].fmap_nblk;
1639 
1640 		cl->cl_offset[FDISK_P1 + count] =
1641 		    cl->cl_fmap[count].fmap_start;
1642 	}
1643 #endif
1644 
1645 	for (count = 0; count < NDKMAP; count++) {
1646 #if defined(_SUNOS_VTOC_8)
1647 		struct dk_map *lp  = &cl->cl_map[count];
1648 		cl->cl_offset[count] =
1649 		    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect * lp->dkl_cylno;
1650 #elif defined(_SUNOS_VTOC_16)
1651 		struct dkl_partition *vp = &cl->cl_vtoc.v_part[count];
1652 
1653 		cl->cl_offset[count] = vp->p_start + cl->cl_solaris_offset;
1654 #else
1655 #error "No VTOC format defined."
1656 #endif
1657 	}
1658 
1659 	return (label_error);
1660 }
1661 
1662 #if defined(_SUNOS_VTOC_16)
1663 /*
1664  *    Function: cmlb_convert_geometry
1665  *
1666  * Description: Convert physical geometry into a dk_geom structure. In
1667  *		other words, make sure we don't wrap 16-bit values.
1668  *		e.g. converting from geom_cache to dk_geom
1669  *
1670  *     Context: Kernel thread only
1671  */
1672 static void
1673 cmlb_convert_geometry(diskaddr_t capacity, struct dk_geom *cl_g)
1674 {
1675 
1676 	/* Unlabeled SCSI floppy device */
1677 	if (capacity <= 0x1000) {
1678 		cl_g->dkg_nhead = 2;
1679 		cl_g->dkg_ncyl = 80;
1680 		cl_g->dkg_nsect = capacity / (cl_g->dkg_nhead * cl_g->dkg_ncyl);
1681 		return;
1682 	}
1683 
1684 	/*
1685 	 * For all devices we calculate cylinders using the heads and sectors
1686 	 * we assign based on capacity of the device.  The algorithm is
1687 	 * designed to be compatible with the way other operating systems
1688 	 * lay out fdisk tables for X86 and to insure that the cylinders never
1689 	 * exceed 65535 to prevent problems with X86 ioctls that report
1690 	 * geometry.
1691 	 * For some smaller disk sizes we report geometry that matches those
1692 	 * used by X86 BIOS usage. For larger disks, we use SPT that are
1693 	 * multiples of 63, since other OSes that are not limited to 16-bits
1694 	 * for cylinders stop at 63 SPT we make do by using multiples of 63 SPT.
1695 	 *
1696 	 * The following table (in order) illustrates some end result
1697 	 * calculations:
1698 	 *
1699 	 * Maximum number of blocks 		nhead	nsect
1700 	 *
1701 	 * 2097152 (1GB)			64	32
1702 	 * 16777216 (8GB)			128	32
1703 	 * 1052819775 (502.02GB)		255  	63
1704 	 * 2105639550 (0.98TB)			255	126
1705 	 * 3158459325 (1.47TB)			255  	189
1706 	 * 4211279100 (1.96TB)			255  	252
1707 	 * 5264098875 (2.45TB)			255  	315
1708 	 * ...
1709 	 */
1710 
1711 	if (capacity <= 0x200000) {
1712 		cl_g->dkg_nhead = 64;
1713 		cl_g->dkg_nsect = 32;
1714 	} else if (capacity <= 0x01000000) {
1715 		cl_g->dkg_nhead = 128;
1716 		cl_g->dkg_nsect = 32;
1717 	} else {
1718 		cl_g->dkg_nhead = 255;
1719 
1720 		/* make nsect be smallest multiple of 63 */
1721 		cl_g->dkg_nsect = ((capacity +
1722 		    (UINT16_MAX * 255 * 63) - 1) /
1723 		    (UINT16_MAX * 255 * 63)) * 63;
1724 
1725 		if (cl_g->dkg_nsect == 0)
1726 			cl_g->dkg_nsect = (UINT16_MAX / 63) * 63;
1727 	}
1728 
1729 }
1730 #endif
1731 
1732 /*
1733  *    Function: cmlb_resync_geom_caches
1734  *
1735  * Description: (Re)initialize both geometry caches: the virtual geometry
1736  *            information is extracted from the HBA (the "geometry"
1737  *            capability), and the physical geometry cache data is
1738  *            generated by issuing MODE SENSE commands.
1739  *
1740  *   Arguments:
1741  *	cl 		driver soft state (unit) structure
1742  *	capacity	disk capacity in #blocks
1743  *	tg_cookie	cookie from target driver to be passed back to target
1744  *			driver when we call back to it through tg_ops.
1745  *
1746  *     Context: Kernel thread only (can sleep).
1747  */
1748 static void
1749 cmlb_resync_geom_caches(struct cmlb_lun *cl, diskaddr_t capacity,
1750     void *tg_cookie)
1751 {
1752 	struct	cmlb_geom 	pgeom;
1753 	struct	cmlb_geom	lgeom;
1754 	struct 	cmlb_geom	*pgeomp = &pgeom;
1755 	unsigned short 		nhead;
1756 	unsigned short 		nsect;
1757 	int 			spc;
1758 	int			ret;
1759 
1760 	ASSERT(cl != NULL);
1761 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1762 
1763 	/*
1764 	 * Ask the controller for its logical geometry.
1765 	 * Note: if the HBA does not support scsi_ifgetcap("geometry"),
1766 	 * then the lgeom cache will be invalid.
1767 	 */
1768 	mutex_exit(CMLB_MUTEX(cl));
1769 	bzero(&lgeom, sizeof (struct cmlb_geom));
1770 	ret = DK_TG_GETVIRTGEOM(cl, &lgeom, tg_cookie);
1771 	mutex_enter(CMLB_MUTEX(cl));
1772 
1773 	bcopy(&lgeom, &cl->cl_lgeom, sizeof (cl->cl_lgeom));
1774 
1775 	/*
1776 	 * Initialize the pgeom cache from lgeom, so that if MODE SENSE
1777 	 * doesn't work, DKIOCG_PHYSGEOM can return reasonable values.
1778 	 */
1779 	if (ret != 0 || cl->cl_lgeom.g_nsect == 0 ||
1780 	    cl->cl_lgeom.g_nhead == 0) {
1781 		/*
1782 		 * Note: Perhaps this needs to be more adaptive? The rationale
1783 		 * is that, if there's no HBA geometry from the HBA driver, any
1784 		 * guess is good, since this is the physical geometry. If MODE
1785 		 * SENSE fails this gives a max cylinder size for non-LBA access
1786 		 */
1787 		nhead = 255;
1788 		nsect = 63;
1789 	} else {
1790 		nhead = cl->cl_lgeom.g_nhead;
1791 		nsect = cl->cl_lgeom.g_nsect;
1792 	}
1793 
1794 	if (ISCD(cl)) {
1795 		pgeomp->g_nhead = 1;
1796 		pgeomp->g_nsect = nsect * nhead;
1797 	} else {
1798 		pgeomp->g_nhead = nhead;
1799 		pgeomp->g_nsect = nsect;
1800 	}
1801 
1802 	spc = pgeomp->g_nhead * pgeomp->g_nsect;
1803 	pgeomp->g_capacity = capacity;
1804 	pgeomp->g_ncyl = pgeomp->g_capacity / spc;
1805 	pgeomp->g_acyl = 0;
1806 
1807 	/*
1808 	 * Retrieve fresh geometry data from the hardware, stash it
1809 	 * here temporarily before we rebuild the incore label.
1810 	 *
1811 	 * We want to use the MODE SENSE commands to derive the
1812 	 * physical geometry of the device, but if either command
1813 	 * fails, the logical geometry is used as the fallback for
1814 	 * disk label geometry.
1815 	 */
1816 
1817 	mutex_exit(CMLB_MUTEX(cl));
1818 	(void) DK_TG_GETPHYGEOM(cl, pgeomp, tg_cookie);
1819 	mutex_enter(CMLB_MUTEX(cl));
1820 
1821 	/*
1822 	 * Now update the real copy while holding the mutex. This
1823 	 * way the global copy is never in an inconsistent state.
1824 	 */
1825 	bcopy(pgeomp, &cl->cl_pgeom,  sizeof (cl->cl_pgeom));
1826 
1827 	cmlb_dbg(CMLB_INFO, cl, "cmlb_resync_geom_caches: "
1828 	    "(cached from lgeom)\n");
1829 	cmlb_dbg(CMLB_INFO,  cl,
1830 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
1831 	    cl->cl_pgeom.g_ncyl, cl->cl_pgeom.g_acyl,
1832 	    cl->cl_pgeom.g_nhead, cl->cl_pgeom.g_nsect);
1833 	cmlb_dbg(CMLB_INFO,  cl, "   lbasize: %d; capacity: %ld; "
1834 	    "intrlv: %d; rpm: %d\n", cl->cl_pgeom.g_secsize,
1835 	    cl->cl_pgeom.g_capacity, cl->cl_pgeom.g_intrlv,
1836 	    cl->cl_pgeom.g_rpm);
1837 }
1838 
1839 
1840 /*
1841  *    Function: cmlb_read_fdisk
1842  *
1843  * Description: utility routine to read the fdisk table.
1844  *
1845  *   Arguments:
1846  *	cl		driver soft state (unit) structure
1847  *	capacity	disk capacity in #blocks
1848  *	tg_cookie	cookie from target driver to be passed back to target
1849  *			driver when we call back to it through tg_ops.
1850  *
1851  * Return Code: 0 for success (includes not reading for no_fdisk_present case
1852  *		errnos from tg_rw if failed to read the first block.
1853  *
1854  *     Context: Kernel thread only (can sleep).
1855  */
1856 /*ARGSUSED*/
1857 static int
1858 cmlb_read_fdisk(struct cmlb_lun *cl, diskaddr_t capacity, void *tg_cookie)
1859 {
1860 #if defined(_NO_FDISK_PRESENT)
1861 
1862 	cl->cl_solaris_offset = 0;
1863 	cl->cl_solaris_size = capacity;
1864 	bzero(cl->cl_fmap, sizeof (struct fmap) * FD_NUMPART);
1865 	return (0);
1866 
1867 #elif defined(_FIRMWARE_NEEDS_FDISK)
1868 
1869 	struct ipart	*fdp;
1870 	struct mboot	*mbp;
1871 	struct ipart	fdisk[FD_NUMPART];
1872 	int		i;
1873 	char		sigbuf[2];
1874 	caddr_t		bufp;
1875 	int		uidx;
1876 	int 		rval;
1877 	int		lba = 0;
1878 	uint_t		solaris_offset;	/* offset to solaris part. */
1879 	daddr_t		solaris_size;	/* size of solaris partition */
1880 	uint32_t	blocksize;
1881 
1882 	ASSERT(cl != NULL);
1883 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
1884 
1885 	/*
1886 	 * Start off assuming no fdisk table
1887 	 */
1888 	solaris_offset = 0;
1889 	solaris_size   = capacity;
1890 
1891 	blocksize = cl->cl_tgt_blocksize;
1892 
1893 	bufp = kmem_zalloc(blocksize, KM_SLEEP);
1894 
1895 	mutex_exit(CMLB_MUTEX(cl));
1896 	rval = DK_TG_READ(cl, bufp, 0, blocksize, tg_cookie);
1897 	mutex_enter(CMLB_MUTEX(cl));
1898 
1899 	if (rval != 0) {
1900 		cmlb_dbg(CMLB_ERROR,  cl,
1901 		    "cmlb_read_fdisk: fdisk read err\n");
1902 		bzero(cl->cl_fmap, sizeof (struct fmap) * FD_NUMPART);
1903 		goto done;
1904 	}
1905 
1906 	mbp = (struct mboot *)bufp;
1907 
1908 	/*
1909 	 * The fdisk table does not begin on a 4-byte boundary within the
1910 	 * master boot record, so we copy it to an aligned structure to avoid
1911 	 * alignment exceptions on some processors.
1912 	 */
1913 	bcopy(&mbp->parts[0], fdisk, sizeof (fdisk));
1914 
1915 	/*
1916 	 * Check for lba support before verifying sig; sig might not be
1917 	 * there, say on a blank disk, but the max_chs mark may still
1918 	 * be present.
1919 	 *
1920 	 * Note: LBA support and BEFs are an x86-only concept but this
1921 	 * code should work OK on SPARC as well.
1922 	 */
1923 
1924 	/*
1925 	 * First, check for lba-access-ok on root node (or prom root node)
1926 	 * if present there, don't need to search fdisk table.
1927 	 */
1928 	if (ddi_getprop(DDI_DEV_T_ANY, ddi_root_node(), 0,
1929 	    "lba-access-ok", 0) != 0) {
1930 		/* All drives do LBA; don't search fdisk table */
1931 		lba = 1;
1932 	} else {
1933 		/* Okay, look for mark in fdisk table */
1934 		for (fdp = fdisk, i = 0; i < FD_NUMPART; i++, fdp++) {
1935 			/* accumulate "lba" value from all partitions */
1936 			lba = (lba || cmlb_has_max_chs_vals(fdp));
1937 		}
1938 	}
1939 
1940 	if (lba != 0) {
1941 		dev_t dev = cmlb_make_device(cl);
1942 
1943 		if (ddi_getprop(dev, CMLB_DEVINFO(cl), DDI_PROP_DONTPASS,
1944 		    "lba-access-ok", 0) == 0) {
1945 			/* not found; create it */
1946 			if (ddi_prop_create(dev, CMLB_DEVINFO(cl), 0,
1947 			    "lba-access-ok", (caddr_t)NULL, 0) !=
1948 			    DDI_PROP_SUCCESS) {
1949 				cmlb_dbg(CMLB_ERROR,  cl,
1950 				    "cmlb_read_fdisk: Can't create lba "
1951 				    "property for instance %d\n",
1952 				    ddi_get_instance(CMLB_DEVINFO(cl)));
1953 			}
1954 		}
1955 	}
1956 
1957 	bcopy(&mbp->signature, sigbuf, sizeof (sigbuf));
1958 
1959 	/*
1960 	 * Endian-independent signature check
1961 	 */
1962 	if (((sigbuf[1] & 0xFF) != ((MBB_MAGIC >> 8) & 0xFF)) ||
1963 	    (sigbuf[0] != (MBB_MAGIC & 0xFF))) {
1964 		cmlb_dbg(CMLB_ERROR,  cl,
1965 		    "cmlb_read_fdisk: no fdisk\n");
1966 		bzero(cl->cl_fmap, sizeof (struct fmap) * FD_NUMPART);
1967 		goto done;
1968 	}
1969 
1970 #ifdef CMLBDEBUG
1971 	if (cmlb_level_mask & CMLB_LOGMASK_INFO) {
1972 		fdp = fdisk;
1973 		cmlb_dbg(CMLB_INFO,  cl, "cmlb_read_fdisk:\n");
1974 		cmlb_dbg(CMLB_INFO,  cl, "         relsect    "
1975 		    "numsect         sysid       bootid\n");
1976 		for (i = 0; i < FD_NUMPART; i++, fdp++) {
1977 			cmlb_dbg(CMLB_INFO,  cl,
1978 			    "    %d:  %8d   %8d     0x%08x     0x%08x\n",
1979 			    i, fdp->relsect, fdp->numsect,
1980 			    fdp->systid, fdp->bootid);
1981 		}
1982 	}
1983 #endif
1984 
1985 	/*
1986 	 * Try to find the unix partition
1987 	 */
1988 	uidx = -1;
1989 	solaris_offset = 0;
1990 	solaris_size   = 0;
1991 
1992 	for (fdp = fdisk, i = 0; i < FD_NUMPART; i++, fdp++) {
1993 		uint32_t relsect;
1994 		uint32_t numsect;
1995 
1996 		if (fdp->numsect == 0) {
1997 			cl->cl_fmap[i].fmap_start = 0;
1998 			cl->cl_fmap[i].fmap_nblk  = 0;
1999 			continue;
2000 		}
2001 
2002 		/*
2003 		 * Data in the fdisk table is little-endian.
2004 		 */
2005 		relsect = LE_32(fdp->relsect);
2006 		numsect = LE_32(fdp->numsect);
2007 
2008 		cl->cl_fmap[i].fmap_start = relsect;
2009 		cl->cl_fmap[i].fmap_nblk  = numsect;
2010 
2011 		if (fdp->systid != SUNIXOS &&
2012 		    fdp->systid != SUNIXOS2 &&
2013 		    fdp->systid != EFI_PMBR) {
2014 			continue;
2015 		}
2016 
2017 		/*
2018 		 * use the last active solaris partition id found
2019 		 * (there should only be 1 active partition id)
2020 		 *
2021 		 * if there are no active solaris partition id
2022 		 * then use the first inactive solaris partition id
2023 		 */
2024 		if ((uidx == -1) || (fdp->bootid == ACTIVE)) {
2025 			uidx = i;
2026 			solaris_offset = relsect;
2027 			solaris_size   = numsect;
2028 		}
2029 	}
2030 
2031 	cmlb_dbg(CMLB_INFO,  cl, "fdisk 0x%x 0x%lx",
2032 	    cl->cl_solaris_offset, cl->cl_solaris_size);
2033 done:
2034 
2035 	/*
2036 	 * Clear the VTOC info, only if the Solaris partition entry
2037 	 * has moved, changed size, been deleted, or if the size of
2038 	 * the partition is too small to even fit the label sector.
2039 	 */
2040 	if ((cl->cl_solaris_offset != solaris_offset) ||
2041 	    (cl->cl_solaris_size != solaris_size) ||
2042 	    solaris_size <= DK_LABEL_LOC) {
2043 		cmlb_dbg(CMLB_INFO,  cl, "fdisk moved 0x%x 0x%lx",
2044 		    solaris_offset, solaris_size);
2045 		bzero(&cl->cl_g, sizeof (struct dk_geom));
2046 		bzero(&cl->cl_vtoc, sizeof (struct dk_vtoc));
2047 		bzero(&cl->cl_map, NDKMAP * (sizeof (struct dk_map)));
2048 		cl->cl_f_geometry_is_valid = FALSE;
2049 	}
2050 	cl->cl_solaris_offset = solaris_offset;
2051 	cl->cl_solaris_size = solaris_size;
2052 	kmem_free(bufp, blocksize);
2053 	return (rval);
2054 
2055 #else	/* #elif defined(_FIRMWARE_NEEDS_FDISK) */
2056 #error "fdisk table presence undetermined for this platform."
2057 #endif	/* #if defined(_NO_FDISK_PRESENT) */
2058 }
2059 
2060 static void
2061 cmlb_swap_efi_gpt(efi_gpt_t *e)
2062 {
2063 	_NOTE(ASSUMING_PROTECTED(*e))
2064 	e->efi_gpt_Signature = LE_64(e->efi_gpt_Signature);
2065 	e->efi_gpt_Revision = LE_32(e->efi_gpt_Revision);
2066 	e->efi_gpt_HeaderSize = LE_32(e->efi_gpt_HeaderSize);
2067 	e->efi_gpt_HeaderCRC32 = LE_32(e->efi_gpt_HeaderCRC32);
2068 	e->efi_gpt_MyLBA = LE_64(e->efi_gpt_MyLBA);
2069 	e->efi_gpt_AlternateLBA = LE_64(e->efi_gpt_AlternateLBA);
2070 	e->efi_gpt_FirstUsableLBA = LE_64(e->efi_gpt_FirstUsableLBA);
2071 	e->efi_gpt_LastUsableLBA = LE_64(e->efi_gpt_LastUsableLBA);
2072 	UUID_LE_CONVERT(e->efi_gpt_DiskGUID, e->efi_gpt_DiskGUID);
2073 	e->efi_gpt_PartitionEntryLBA = LE_64(e->efi_gpt_PartitionEntryLBA);
2074 	e->efi_gpt_NumberOfPartitionEntries =
2075 	    LE_32(e->efi_gpt_NumberOfPartitionEntries);
2076 	e->efi_gpt_SizeOfPartitionEntry =
2077 	    LE_32(e->efi_gpt_SizeOfPartitionEntry);
2078 	e->efi_gpt_PartitionEntryArrayCRC32 =
2079 	    LE_32(e->efi_gpt_PartitionEntryArrayCRC32);
2080 }
2081 
2082 static void
2083 cmlb_swap_efi_gpe(int nparts, efi_gpe_t *p)
2084 {
2085 	int i;
2086 
2087 	_NOTE(ASSUMING_PROTECTED(*p))
2088 	for (i = 0; i < nparts; i++) {
2089 		UUID_LE_CONVERT(p[i].efi_gpe_PartitionTypeGUID,
2090 		    p[i].efi_gpe_PartitionTypeGUID);
2091 		p[i].efi_gpe_StartingLBA = LE_64(p[i].efi_gpe_StartingLBA);
2092 		p[i].efi_gpe_EndingLBA = LE_64(p[i].efi_gpe_EndingLBA);
2093 		/* PartitionAttrs */
2094 	}
2095 }
2096 
2097 static int
2098 cmlb_validate_efi(efi_gpt_t *labp)
2099 {
2100 	if (labp->efi_gpt_Signature != EFI_SIGNATURE)
2101 		return (EINVAL);
2102 	/* at least 96 bytes in this version of the spec. */
2103 	if (sizeof (efi_gpt_t) - sizeof (labp->efi_gpt_Reserved2) >
2104 	    labp->efi_gpt_HeaderSize)
2105 		return (EINVAL);
2106 	/* this should be 128 bytes */
2107 	if (labp->efi_gpt_SizeOfPartitionEntry != sizeof (efi_gpe_t))
2108 		return (EINVAL);
2109 	return (0);
2110 }
2111 
2112 /*
2113  * This function returns FALSE if there is a valid MBR signature and no
2114  * partition table entries of type EFI_PMBR (0xEE). Otherwise it returns TRUE.
2115  *
2116  * The EFI spec (1.10 and later) requires having a Protective MBR (PMBR) to
2117  * recognize the disk as GPT partitioned. However, some other OS creates an MBR
2118  * where a PMBR entry is not the only one. Also, if the first block has been
2119  * corrupted, currently best attempt to allow data access would be to try to
2120  * check for GPT headers. Hence in case of more than one partition entry, but
2121  * at least one EFI_PMBR partition type or no valid magic number, the function
2122  * returns TRUE to continue with looking for GPT header.
2123  */
2124 
2125 static int
2126 cmlb_check_efi_mbr(uchar_t *buf, int *is_mbr)
2127 {
2128 	struct ipart	*fdp;
2129 	struct mboot	*mbp = (struct mboot *)buf;
2130 	struct ipart	fdisk[FD_NUMPART];
2131 	int		i;
2132 
2133 	if (is_mbr != NULL)
2134 		*is_mbr = TRUE;
2135 
2136 	if (LE_16(mbp->signature) != MBB_MAGIC) {
2137 		if (is_mbr != NULL)
2138 			is_mbr = FALSE;
2139 		return (TRUE);
2140 	}
2141 
2142 	bcopy(&mbp->parts[0], fdisk, sizeof (fdisk));
2143 
2144 	for (fdp = fdisk, i = 0; i < FD_NUMPART; i++, fdp++) {
2145 		if (fdp->systid == EFI_PMBR)
2146 			return (TRUE);
2147 	}
2148 
2149 	return (FALSE);
2150 }
2151 
2152 static int
2153 cmlb_use_efi(struct cmlb_lun *cl, diskaddr_t capacity, int flags,
2154     void *tg_cookie)
2155 {
2156 	int		i;
2157 	int		rval = 0;
2158 	efi_gpe_t	*partitions;
2159 	uchar_t		*buf;
2160 	uint_t		lbasize;	/* is really how much to read */
2161 	diskaddr_t	cap = 0;
2162 	uint_t		nparts;
2163 	diskaddr_t	gpe_lba;
2164 	diskaddr_t	alternate_lba;
2165 	int		iofailed = 0;
2166 	struct uuid	uuid_type_reserved = EFI_RESERVED;
2167 #if defined(_FIRMWARE_NEEDS_FDISK)
2168 		int 		is_mbr;
2169 #endif
2170 
2171 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
2172 
2173 	if (cl->cl_tgt_blocksize != cl->cl_sys_blocksize) {
2174 		rval = EINVAL;
2175 		goto done_err1;
2176 	}
2177 
2178 
2179 	lbasize = cl->cl_sys_blocksize;
2180 
2181 	cl->cl_reserved = -1;
2182 	mutex_exit(CMLB_MUTEX(cl));
2183 
2184 	buf = kmem_zalloc(EFI_MIN_ARRAY_SIZE, KM_SLEEP);
2185 
2186 	rval = DK_TG_READ(cl, buf,  0, lbasize, tg_cookie);
2187 	if (rval) {
2188 		iofailed = 1;
2189 		goto done_err;
2190 	}
2191 	if (((struct dk_label *)buf)->dkl_magic == DKL_MAGIC) {
2192 		/* not ours */
2193 		rval = ESRCH;
2194 		goto done_err;
2195 	}
2196 
2197 #if defined(_FIRMWARE_NEEDS_FDISK)
2198 	if (cmlb_check_efi_mbr(buf, &is_mbr) == FALSE) {
2199 		if (is_mbr == TRUE)
2200 			rval = ESRCH;
2201 		else
2202 			rval = EINVAL;
2203 		goto done_err;
2204 	}
2205 #else
2206 	if (cmlb_check_efi_mbr(buf, NULL) == FALSE) {
2207 		rval = EINVAL;
2208 		goto done_err;
2209 	}
2210 
2211 #endif
2212 
2213 	rval = DK_TG_READ(cl, buf, 1, lbasize, tg_cookie);
2214 	if (rval) {
2215 		iofailed = 1;
2216 		goto done_err;
2217 	}
2218 	cmlb_swap_efi_gpt((efi_gpt_t *)buf);
2219 
2220 	if ((rval = cmlb_validate_efi((efi_gpt_t *)buf)) != 0) {
2221 		/*
2222 		 * Couldn't read the primary, try the backup.  Our
2223 		 * capacity at this point could be based on CHS, so
2224 		 * check what the device reports.
2225 		 */
2226 		rval = DK_TG_GETCAP(cl, &cap, tg_cookie);
2227 		if (rval) {
2228 			iofailed = 1;
2229 			goto done_err;
2230 		}
2231 
2232 		/*
2233 		 * CMLB_OFF_BY_ONE case, we check the next to last block first
2234 		 * for backup GPT header, otherwise check the last block.
2235 		 */
2236 
2237 		if ((rval = DK_TG_READ(cl, buf,
2238 		    cap - ((cl->cl_alter_behavior & CMLB_OFF_BY_ONE) ? 2 : 1),
2239 		    lbasize, tg_cookie))
2240 		    != 0) {
2241 			iofailed = 1;
2242 			goto done_err;
2243 		}
2244 		cmlb_swap_efi_gpt((efi_gpt_t *)buf);
2245 
2246 		if ((rval = cmlb_validate_efi((efi_gpt_t *)buf)) != 0) {
2247 
2248 			if (!(cl->cl_alter_behavior & CMLB_OFF_BY_ONE))
2249 				goto done_err;
2250 			if ((rval = DK_TG_READ(cl, buf, cap - 1, lbasize,
2251 			    tg_cookie)) != 0)
2252 				goto done_err;
2253 			cmlb_swap_efi_gpt((efi_gpt_t *)buf);
2254 			if ((rval = cmlb_validate_efi((efi_gpt_t *)buf)) != 0)
2255 				goto done_err;
2256 		}
2257 		if (!(flags & CMLB_SILENT))
2258 			cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl), CE_WARN,
2259 			    "primary label corrupt; using backup\n");
2260 	}
2261 
2262 	nparts = ((efi_gpt_t *)buf)->efi_gpt_NumberOfPartitionEntries;
2263 	gpe_lba = ((efi_gpt_t *)buf)->efi_gpt_PartitionEntryLBA;
2264 	alternate_lba = ((efi_gpt_t *)buf)->efi_gpt_AlternateLBA;
2265 
2266 	rval = DK_TG_READ(cl, buf, gpe_lba, EFI_MIN_ARRAY_SIZE, tg_cookie);
2267 	if (rval) {
2268 		iofailed = 1;
2269 		goto done_err;
2270 	}
2271 	partitions = (efi_gpe_t *)buf;
2272 
2273 	if (nparts > MAXPART) {
2274 		nparts = MAXPART;
2275 	}
2276 	cmlb_swap_efi_gpe(nparts, partitions);
2277 
2278 	mutex_enter(CMLB_MUTEX(cl));
2279 
2280 	/* Fill in partition table. */
2281 	for (i = 0; i < nparts; i++) {
2282 		if (partitions->efi_gpe_StartingLBA != 0 ||
2283 		    partitions->efi_gpe_EndingLBA != 0) {
2284 			cl->cl_map[i].dkl_cylno =
2285 			    partitions->efi_gpe_StartingLBA;
2286 			cl->cl_map[i].dkl_nblk =
2287 			    partitions->efi_gpe_EndingLBA -
2288 			    partitions->efi_gpe_StartingLBA + 1;
2289 			cl->cl_offset[i] =
2290 			    partitions->efi_gpe_StartingLBA;
2291 		}
2292 
2293 		if (cl->cl_reserved == -1) {
2294 			if (bcmp(&partitions->efi_gpe_PartitionTypeGUID,
2295 			    &uuid_type_reserved, sizeof (struct uuid)) == 0) {
2296 				cl->cl_reserved = i;
2297 			}
2298 		}
2299 		if (i == WD_NODE) {
2300 			/*
2301 			 * minor number 7 corresponds to the whole disk
2302 			 * if the disk capacity is expanded after disk is
2303 			 * labeled, minor number 7 represents the capacity
2304 			 * indicated by the disk label.
2305 			 */
2306 			cl->cl_map[i].dkl_cylno = 0;
2307 			if (alternate_lba == 1) {
2308 				/*
2309 				 * We are using backup label. Since we can
2310 				 * find a valid label at the end of disk,
2311 				 * the disk capacity is not expanded.
2312 				 */
2313 				cl->cl_map[i].dkl_nblk = capacity;
2314 			} else {
2315 				cl->cl_map[i].dkl_nblk = alternate_lba + 1;
2316 			}
2317 			cl->cl_offset[i] = 0;
2318 		}
2319 		partitions++;
2320 	}
2321 	cl->cl_solaris_offset = 0;
2322 	cl->cl_solaris_size = capacity;
2323 	cl->cl_label_from_media = CMLB_LABEL_EFI;
2324 	cl->cl_f_geometry_is_valid = TRUE;
2325 
2326 	/* clear the vtoc label */
2327 	bzero(&cl->cl_vtoc, sizeof (struct dk_vtoc));
2328 
2329 	kmem_free(buf, EFI_MIN_ARRAY_SIZE);
2330 	return (0);
2331 
2332 done_err:
2333 	kmem_free(buf, EFI_MIN_ARRAY_SIZE);
2334 	mutex_enter(CMLB_MUTEX(cl));
2335 done_err1:
2336 	/*
2337 	 * if we didn't find something that could look like a VTOC
2338 	 * and the disk is over 1TB, we know there isn't a valid label.
2339 	 * Otherwise let cmlb_uselabel decide what to do.  We only
2340 	 * want to invalidate this if we're certain the label isn't
2341 	 * valid because cmlb_prop_op will now fail, which in turn
2342 	 * causes things like opens and stats on the partition to fail.
2343 	 */
2344 	if ((capacity > CMLB_EXTVTOC_LIMIT) && (rval != ESRCH) && !iofailed) {
2345 		cl->cl_f_geometry_is_valid = FALSE;
2346 	}
2347 	return (rval);
2348 }
2349 
2350 
2351 /*
2352  *    Function: cmlb_uselabel
2353  *
2354  * Description: Validate the disk label and update the relevant data (geometry,
2355  *		partition, vtoc, and capacity data) in the cmlb_lun struct.
2356  *		Marks the geometry of the unit as being valid.
2357  *
2358  *   Arguments: cl: unit struct.
2359  *		dk_label: disk label
2360  *
2361  * Return Code: CMLB_LABEL_IS_VALID: Label read from disk is OK; geometry,
2362  *		partition, vtoc, and capacity data are good.
2363  *
2364  *		CMLB_LABEL_IS_INVALID: Magic number or checksum error in the
2365  *		label; or computed capacity does not jibe with capacity
2366  *		reported from the READ CAPACITY command.
2367  *
2368  *     Context: Kernel thread only (can sleep).
2369  */
2370 static int
2371 cmlb_uselabel(struct cmlb_lun *cl, struct dk_label *labp, int flags)
2372 {
2373 	short		*sp;
2374 	short		sum;
2375 	short		count;
2376 	int		label_error = CMLB_LABEL_IS_VALID;
2377 	int		i;
2378 	diskaddr_t	label_capacity;
2379 	uint32_t	part_end;
2380 	diskaddr_t	track_capacity;
2381 #if defined(_SUNOS_VTOC_16)
2382 	struct	dkl_partition	*vpartp;
2383 #endif
2384 	ASSERT(cl != NULL);
2385 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
2386 
2387 	/* Validate the magic number of the label. */
2388 	if (labp->dkl_magic != DKL_MAGIC) {
2389 #if defined(__sparc)
2390 		if (!ISREMOVABLE(cl) && !ISHOTPLUGGABLE(cl)) {
2391 			if (!(flags & CMLB_SILENT))
2392 				cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl),
2393 				    CE_WARN,
2394 				    "Corrupt label; wrong magic number\n");
2395 		}
2396 #endif
2397 		return (CMLB_LABEL_IS_INVALID);
2398 	}
2399 
2400 	/* Validate the checksum of the label. */
2401 	sp  = (short *)labp;
2402 	sum = 0;
2403 	count = sizeof (struct dk_label) / sizeof (short);
2404 	while (count--)	 {
2405 		sum ^= *sp++;
2406 	}
2407 
2408 	if (sum != 0) {
2409 #if defined(_SUNOS_VTOC_16)
2410 		if (!ISCD(cl)) {
2411 #elif defined(_SUNOS_VTOC_8)
2412 		if (!ISREMOVABLE(cl) && !ISHOTPLUGGABLE(cl)) {
2413 #endif
2414 			if (!(flags & CMLB_SILENT))
2415 				cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl),
2416 				    CE_WARN,
2417 				    "Corrupt label - label checksum failed\n");
2418 		}
2419 		return (CMLB_LABEL_IS_INVALID);
2420 	}
2421 
2422 
2423 	/*
2424 	 * Fill in geometry structure with data from label.
2425 	 */
2426 	bzero(&cl->cl_g, sizeof (struct dk_geom));
2427 	cl->cl_g.dkg_ncyl   = labp->dkl_ncyl;
2428 	cl->cl_g.dkg_acyl   = labp->dkl_acyl;
2429 	cl->cl_g.dkg_bcyl   = 0;
2430 	cl->cl_g.dkg_nhead  = labp->dkl_nhead;
2431 	cl->cl_g.dkg_nsect  = labp->dkl_nsect;
2432 	cl->cl_g.dkg_intrlv = labp->dkl_intrlv;
2433 
2434 #if defined(_SUNOS_VTOC_8)
2435 	cl->cl_g.dkg_gap1   = labp->dkl_gap1;
2436 	cl->cl_g.dkg_gap2   = labp->dkl_gap2;
2437 	cl->cl_g.dkg_bhead  = labp->dkl_bhead;
2438 #endif
2439 #if defined(_SUNOS_VTOC_16)
2440 	cl->cl_dkg_skew = labp->dkl_skew;
2441 #endif
2442 
2443 #if defined(__i386) || defined(__amd64)
2444 	cl->cl_g.dkg_apc = labp->dkl_apc;
2445 #endif
2446 
2447 	/*
2448 	 * Currently we rely on the values in the label being accurate. If
2449 	 * dkl_rpm or dkl_pcly are zero in the label, use a default value.
2450 	 *
2451 	 * Note: In the future a MODE SENSE may be used to retrieve this data,
2452 	 * although this command is optional in SCSI-2.
2453 	 */
2454 	cl->cl_g.dkg_rpm  = (labp->dkl_rpm  != 0) ? labp->dkl_rpm  : 3600;
2455 	cl->cl_g.dkg_pcyl = (labp->dkl_pcyl != 0) ? labp->dkl_pcyl :
2456 	    (cl->cl_g.dkg_ncyl + cl->cl_g.dkg_acyl);
2457 
2458 	/*
2459 	 * The Read and Write reinstruct values may not be valid
2460 	 * for older disks.
2461 	 */
2462 	cl->cl_g.dkg_read_reinstruct  = labp->dkl_read_reinstruct;
2463 	cl->cl_g.dkg_write_reinstruct = labp->dkl_write_reinstruct;
2464 
2465 	/* Fill in partition table. */
2466 #if defined(_SUNOS_VTOC_8)
2467 	for (i = 0; i < NDKMAP; i++) {
2468 		cl->cl_map[i].dkl_cylno = labp->dkl_map[i].dkl_cylno;
2469 		cl->cl_map[i].dkl_nblk  = labp->dkl_map[i].dkl_nblk;
2470 	}
2471 #endif
2472 #if  defined(_SUNOS_VTOC_16)
2473 	vpartp		= labp->dkl_vtoc.v_part;
2474 	track_capacity	= labp->dkl_nhead * labp->dkl_nsect;
2475 
2476 	/* Prevent divide by zero */
2477 	if (track_capacity == 0) {
2478 		if (!(flags & CMLB_SILENT))
2479 			cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl), CE_WARN,
2480 			    "Corrupt label - zero nhead or nsect value\n");
2481 
2482 		return (CMLB_LABEL_IS_INVALID);
2483 	}
2484 
2485 	for (i = 0; i < NDKMAP; i++, vpartp++) {
2486 		cl->cl_map[i].dkl_cylno = vpartp->p_start / track_capacity;
2487 		cl->cl_map[i].dkl_nblk  = vpartp->p_size;
2488 	}
2489 #endif
2490 
2491 	/* Fill in VTOC Structure. */
2492 	bcopy(&labp->dkl_vtoc, &cl->cl_vtoc, sizeof (struct dk_vtoc));
2493 #if defined(_SUNOS_VTOC_8)
2494 	/*
2495 	 * The 8-slice vtoc does not include the ascii label; save it into
2496 	 * the device's soft state structure here.
2497 	 */
2498 	bcopy(labp->dkl_asciilabel, cl->cl_asciilabel, LEN_DKL_ASCII);
2499 #endif
2500 
2501 	/* Now look for a valid capacity. */
2502 	track_capacity	= (cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect);
2503 	label_capacity	= (cl->cl_g.dkg_ncyl  * track_capacity);
2504 
2505 	if (cl->cl_g.dkg_acyl) {
2506 #if defined(__i386) || defined(__amd64)
2507 		/* we may have > 1 alts cylinder */
2508 		label_capacity += (track_capacity * cl->cl_g.dkg_acyl);
2509 #else
2510 		label_capacity += track_capacity;
2511 #endif
2512 	}
2513 
2514 	/*
2515 	 * Force check here to ensure the computed capacity is valid.
2516 	 * If capacity is zero, it indicates an invalid label and
2517 	 * we should abort updating the relevant data then.
2518 	 */
2519 	if (label_capacity == 0) {
2520 		if (!(flags & CMLB_SILENT))
2521 			cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl), CE_WARN,
2522 			    "Corrupt label - no valid capacity could be "
2523 			    "retrieved\n");
2524 
2525 		return (CMLB_LABEL_IS_INVALID);
2526 	}
2527 
2528 	/* Mark the geometry as valid. */
2529 	cl->cl_f_geometry_is_valid = TRUE;
2530 
2531 	/*
2532 	 * if we got invalidated when mutex exit and entered again,
2533 	 * if blockcount different than when we came in, need to
2534 	 * retry from beginning of cmlb_validate_geometry.
2535 	 * revisit this on next phase of utilizing this for
2536 	 * sd.
2537 	 */
2538 
2539 	if (label_capacity <= cl->cl_blockcount) {
2540 #if defined(_SUNOS_VTOC_8)
2541 		/*
2542 		 * We can't let this happen on drives that are subdivided
2543 		 * into logical disks (i.e., that have an fdisk table).
2544 		 * The cl_blockcount field should always hold the full media
2545 		 * size in sectors, period.  This code would overwrite
2546 		 * cl_blockcount with the size of the Solaris fdisk partition.
2547 		 */
2548 		cmlb_dbg(CMLB_ERROR,  cl,
2549 		    "cmlb_uselabel: Label %d blocks; Drive %d blocks\n",
2550 		    label_capacity, cl->cl_blockcount);
2551 		cl->cl_solaris_size = label_capacity;
2552 
2553 #endif	/* defined(_SUNOS_VTOC_8) */
2554 		goto done;
2555 	}
2556 
2557 	if (ISCD(cl)) {
2558 		/* For CDROMs, we trust that the data in the label is OK. */
2559 #if defined(_SUNOS_VTOC_8)
2560 		for (i = 0; i < NDKMAP; i++) {
2561 			part_end = labp->dkl_nhead * labp->dkl_nsect *
2562 			    labp->dkl_map[i].dkl_cylno +
2563 			    labp->dkl_map[i].dkl_nblk  - 1;
2564 
2565 			if ((labp->dkl_map[i].dkl_nblk) &&
2566 			    (part_end > cl->cl_blockcount)) {
2567 				cl->cl_f_geometry_is_valid = FALSE;
2568 				break;
2569 			}
2570 		}
2571 #endif
2572 #if defined(_SUNOS_VTOC_16)
2573 		vpartp = &(labp->dkl_vtoc.v_part[0]);
2574 		for (i = 0; i < NDKMAP; i++, vpartp++) {
2575 			part_end = vpartp->p_start + vpartp->p_size;
2576 			if ((vpartp->p_size > 0) &&
2577 			    (part_end > cl->cl_blockcount)) {
2578 				cl->cl_f_geometry_is_valid = FALSE;
2579 				break;
2580 			}
2581 		}
2582 #endif
2583 	} else {
2584 		/* label_capacity > cl->cl_blockcount */
2585 		if (!(flags & CMLB_SILENT)) {
2586 			cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl), CE_WARN,
2587 			    "Corrupt label - bad geometry\n");
2588 			cmlb_log(CMLB_DEVINFO(cl), CMLB_LABEL(cl), CE_CONT,
2589 			    "Label says %llu blocks; Drive says %llu blocks\n",
2590 			    label_capacity, cl->cl_blockcount);
2591 		}
2592 		cl->cl_f_geometry_is_valid = FALSE;
2593 		label_error = CMLB_LABEL_IS_INVALID;
2594 	}
2595 
2596 done:
2597 
2598 	cmlb_dbg(CMLB_INFO,  cl, "cmlb_uselabel: (label geometry)\n");
2599 	cmlb_dbg(CMLB_INFO,  cl,
2600 	    "   ncyl: %d; acyl: %d; nhead: %d; nsect: %d\n",
2601 	    cl->cl_g.dkg_ncyl,  cl->cl_g.dkg_acyl,
2602 	    cl->cl_g.dkg_nhead, cl->cl_g.dkg_nsect);
2603 
2604 	cmlb_dbg(CMLB_INFO,  cl,
2605 	    "   label_capacity: %d; intrlv: %d; rpm: %d\n",
2606 	    cl->cl_blockcount, cl->cl_g.dkg_intrlv, cl->cl_g.dkg_rpm);
2607 	cmlb_dbg(CMLB_INFO,  cl, "   wrt_reinstr: %d; rd_reinstr: %d\n",
2608 	    cl->cl_g.dkg_write_reinstruct, cl->cl_g.dkg_read_reinstruct);
2609 
2610 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
2611 
2612 	return (label_error);
2613 }
2614 
2615 
2616 /*
2617  *    Function: cmlb_build_default_label
2618  *
2619  * Description: Generate a default label for those devices that do not have
2620  *		one, e.g., new media, removable cartridges, etc..
2621  *
2622  *     Context: Kernel thread only
2623  */
2624 /*ARGSUSED*/
2625 static void
2626 cmlb_build_default_label(struct cmlb_lun *cl, void *tg_cookie)
2627 {
2628 #if defined(_SUNOS_VTOC_16)
2629 	uint_t	phys_spc;
2630 	uint_t	disksize;
2631 	struct  dk_geom cl_g;
2632 	diskaddr_t capacity;
2633 #endif
2634 
2635 	ASSERT(cl != NULL);
2636 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
2637 
2638 #if defined(_SUNOS_VTOC_8)
2639 	/*
2640 	 * Note: This is a legacy check for non-removable devices on VTOC_8
2641 	 * only. This may be a valid check for VTOC_16 as well.
2642 	 * Once we understand why there is this difference between SPARC and
2643 	 * x86 platform, we could remove this legacy check.
2644 	 */
2645 	if (!ISREMOVABLE(cl) && !ISHOTPLUGGABLE(cl)) {
2646 		return;
2647 	}
2648 #endif
2649 
2650 	bzero(&cl->cl_g, sizeof (struct dk_geom));
2651 	bzero(&cl->cl_vtoc, sizeof (struct dk_vtoc));
2652 	bzero(&cl->cl_map, NDKMAP * (sizeof (struct dk_map)));
2653 
2654 #if defined(_SUNOS_VTOC_8)
2655 
2656 	/*
2657 	 * It's a REMOVABLE media, therefore no label (on sparc, anyway).
2658 	 * But it is still necessary to set up various geometry information,
2659 	 * and we are doing this here.
2660 	 */
2661 
2662 	/*
2663 	 * For the rpm, we use the minimum for the disk.  For the head, cyl,
2664 	 * and number of sector per track, if the capacity <= 1GB, head = 64,
2665 	 * sect = 32.  else head = 255, sect 63 Note: the capacity should be
2666 	 * equal to C*H*S values.  This will cause some truncation of size due
2667 	 * to round off errors. For CD-ROMs, this truncation can have adverse
2668 	 * side effects, so returning ncyl and nhead as 1. The nsect will
2669 	 * overflow for most of CD-ROMs as nsect is of type ushort. (4190569)
2670 	 */
2671 	cl->cl_solaris_size = cl->cl_blockcount;
2672 	if (ISCD(cl)) {
2673 		tg_attribute_t tgattribute;
2674 		int is_writable;
2675 		/*
2676 		 * Preserve the old behavior for non-writable
2677 		 * medias. Since dkg_nsect is a ushort, it
2678 		 * will lose bits as cdroms have more than
2679 		 * 65536 sectors. So if we recalculate
2680 		 * capacity, it will become much shorter.
2681 		 * But the dkg_* information is not
2682 		 * used for CDROMs so it is OK. But for
2683 		 * Writable CDs we need this information
2684 		 * to be valid (for newfs say). So we
2685 		 * make nsect and nhead > 1 that way
2686 		 * nsect can still stay within ushort limit
2687 		 * without losing any bits.
2688 		 */
2689 
2690 		bzero(&tgattribute, sizeof (tg_attribute_t));
2691 
2692 		mutex_exit(CMLB_MUTEX(cl));
2693 		is_writable =
2694 		    (DK_TG_GETATTRIBUTE(cl, &tgattribute, tg_cookie) == 0) ?
2695 		    tgattribute.media_is_writable : 1;
2696 		mutex_enter(CMLB_MUTEX(cl));
2697 
2698 		if (is_writable) {
2699 			cl->cl_g.dkg_nhead = 64;
2700 			cl->cl_g.dkg_nsect = 32;
2701 			cl->cl_g.dkg_ncyl = cl->cl_blockcount / (64 * 32);
2702 			cl->cl_solaris_size = (diskaddr_t)cl->cl_g.dkg_ncyl *
2703 			    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect;
2704 		} else {
2705 			cl->cl_g.dkg_ncyl  = 1;
2706 			cl->cl_g.dkg_nhead = 1;
2707 			cl->cl_g.dkg_nsect = cl->cl_blockcount;
2708 		}
2709 	} else {
2710 		if (cl->cl_blockcount <= 0x1000) {
2711 			/* unlabeled SCSI floppy device */
2712 			cl->cl_g.dkg_nhead = 2;
2713 			cl->cl_g.dkg_ncyl = 80;
2714 			cl->cl_g.dkg_nsect = cl->cl_blockcount / (2 * 80);
2715 		} else if (cl->cl_blockcount <= 0x200000) {
2716 			cl->cl_g.dkg_nhead = 64;
2717 			cl->cl_g.dkg_nsect = 32;
2718 			cl->cl_g.dkg_ncyl  = cl->cl_blockcount / (64 * 32);
2719 		} else {
2720 			cl->cl_g.dkg_nhead = 255;
2721 
2722 			cl->cl_g.dkg_nsect = ((cl->cl_blockcount +
2723 			    (UINT16_MAX * 255 * 63) - 1) /
2724 			    (UINT16_MAX * 255 * 63)) * 63;
2725 
2726 			if (cl->cl_g.dkg_nsect == 0)
2727 				cl->cl_g.dkg_nsect = (UINT16_MAX / 63) * 63;
2728 
2729 			cl->cl_g.dkg_ncyl = cl->cl_blockcount /
2730 			    (255 * cl->cl_g.dkg_nsect);
2731 		}
2732 
2733 		cl->cl_solaris_size =
2734 		    (diskaddr_t)cl->cl_g.dkg_ncyl * cl->cl_g.dkg_nhead *
2735 		    cl->cl_g.dkg_nsect;
2736 
2737 	}
2738 
2739 	cl->cl_g.dkg_acyl	= 0;
2740 	cl->cl_g.dkg_bcyl	= 0;
2741 	cl->cl_g.dkg_rpm	= 200;
2742 	cl->cl_asciilabel[0]	= '\0';
2743 	cl->cl_g.dkg_pcyl	= cl->cl_g.dkg_ncyl;
2744 
2745 	cl->cl_map[0].dkl_cylno = 0;
2746 	cl->cl_map[0].dkl_nblk  = cl->cl_solaris_size;
2747 
2748 	cl->cl_map[2].dkl_cylno = 0;
2749 	cl->cl_map[2].dkl_nblk  = cl->cl_solaris_size;
2750 
2751 #elif defined(_SUNOS_VTOC_16)
2752 
2753 	if (cl->cl_solaris_size == 0) {
2754 		/*
2755 		 * Got fdisk table but no solaris entry therefore
2756 		 * don't create a default label
2757 		 */
2758 		cl->cl_f_geometry_is_valid = TRUE;
2759 		return;
2760 	}
2761 
2762 	/*
2763 	 * For CDs we continue to use the physical geometry to calculate
2764 	 * number of cylinders. All other devices must convert the
2765 	 * physical geometry (cmlb_geom) to values that will fit
2766 	 * in a dk_geom structure.
2767 	 */
2768 	if (ISCD(cl)) {
2769 		phys_spc = cl->cl_pgeom.g_nhead * cl->cl_pgeom.g_nsect;
2770 	} else {
2771 		/* Convert physical geometry to disk geometry */
2772 		bzero(&cl_g, sizeof (struct dk_geom));
2773 
2774 		/*
2775 		 * Refer to comments related to off-by-1 at the
2776 		 * header of this file.
2777 		 * Before calculating geometry, capacity should be
2778 		 * decreased by 1.
2779 		 */
2780 
2781 		if (cl->cl_alter_behavior & CMLB_OFF_BY_ONE)
2782 			capacity = cl->cl_blockcount - 1;
2783 		else
2784 			capacity = cl->cl_blockcount;
2785 
2786 
2787 		cmlb_convert_geometry(capacity, &cl_g);
2788 		bcopy(&cl_g, &cl->cl_g, sizeof (cl->cl_g));
2789 		phys_spc = cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect;
2790 	}
2791 
2792 	ASSERT(phys_spc != 0);
2793 	cl->cl_g.dkg_pcyl = cl->cl_solaris_size / phys_spc;
2794 	if (cl->cl_alter_behavior & CMLB_FAKE_LABEL_ONE_PARTITION) {
2795 		/* disable devid */
2796 		cl->cl_g.dkg_ncyl = cl->cl_g.dkg_pcyl;
2797 		disksize = cl->cl_solaris_size;
2798 	} else {
2799 		cl->cl_g.dkg_acyl = DK_ACYL;
2800 		cl->cl_g.dkg_ncyl = cl->cl_g.dkg_pcyl - DK_ACYL;
2801 		disksize = cl->cl_g.dkg_ncyl * phys_spc;
2802 	}
2803 
2804 	if (ISCD(cl)) {
2805 		/*
2806 		 * CD's don't use the "heads * sectors * cyls"-type of
2807 		 * geometry, but instead use the entire capacity of the media.
2808 		 */
2809 		disksize = cl->cl_solaris_size;
2810 		cl->cl_g.dkg_nhead = 1;
2811 		cl->cl_g.dkg_nsect = 1;
2812 		cl->cl_g.dkg_rpm =
2813 		    (cl->cl_pgeom.g_rpm == 0) ? 200 : cl->cl_pgeom.g_rpm;
2814 
2815 		cl->cl_vtoc.v_part[0].p_start = 0;
2816 		cl->cl_vtoc.v_part[0].p_size  = disksize;
2817 		cl->cl_vtoc.v_part[0].p_tag   = V_BACKUP;
2818 		cl->cl_vtoc.v_part[0].p_flag  = V_UNMNT;
2819 
2820 		cl->cl_map[0].dkl_cylno = 0;
2821 		cl->cl_map[0].dkl_nblk  = disksize;
2822 		cl->cl_offset[0] = 0;
2823 
2824 	} else {
2825 		/*
2826 		 * Hard disks and removable media cartridges
2827 		 */
2828 		cl->cl_g.dkg_rpm =
2829 		    (cl->cl_pgeom.g_rpm == 0) ? 3600: cl->cl_pgeom.g_rpm;
2830 		cl->cl_vtoc.v_sectorsz = cl->cl_sys_blocksize;
2831 
2832 		/* Add boot slice */
2833 		cl->cl_vtoc.v_part[8].p_start = 0;
2834 		cl->cl_vtoc.v_part[8].p_size  = phys_spc;
2835 		cl->cl_vtoc.v_part[8].p_tag   = V_BOOT;
2836 		cl->cl_vtoc.v_part[8].p_flag  = V_UNMNT;
2837 
2838 		cl->cl_map[8].dkl_cylno = 0;
2839 		cl->cl_map[8].dkl_nblk  = phys_spc;
2840 		cl->cl_offset[8] = 0;
2841 
2842 		if ((cl->cl_alter_behavior &
2843 		    CMLB_CREATE_ALTSLICE_VTOC_16_DTYPE_DIRECT) &&
2844 		    cl->cl_device_type == DTYPE_DIRECT) {
2845 			cl->cl_vtoc.v_part[9].p_start = phys_spc;
2846 			cl->cl_vtoc.v_part[9].p_size  = 2 * phys_spc;
2847 			cl->cl_vtoc.v_part[9].p_tag   = V_ALTSCTR;
2848 			cl->cl_vtoc.v_part[9].p_flag  = 0;
2849 
2850 			cl->cl_map[9].dkl_cylno = 1;
2851 			cl->cl_map[9].dkl_nblk  = 2 * phys_spc;
2852 			cl->cl_offset[9] = phys_spc;
2853 		}
2854 	}
2855 
2856 	cl->cl_g.dkg_apc = 0;
2857 	cl->cl_vtoc.v_nparts = V_NUMPAR;
2858 	cl->cl_vtoc.v_version = V_VERSION;
2859 
2860 	/* Add backup slice */
2861 	cl->cl_vtoc.v_part[2].p_start = 0;
2862 	cl->cl_vtoc.v_part[2].p_size  = disksize;
2863 	cl->cl_vtoc.v_part[2].p_tag   = V_BACKUP;
2864 	cl->cl_vtoc.v_part[2].p_flag  = V_UNMNT;
2865 
2866 	cl->cl_map[2].dkl_cylno = 0;
2867 	cl->cl_map[2].dkl_nblk  = disksize;
2868 	cl->cl_offset[2] = 0;
2869 
2870 	/*
2871 	 * single slice (s0) covering the entire disk
2872 	 */
2873 	if (cl->cl_alter_behavior & CMLB_FAKE_LABEL_ONE_PARTITION) {
2874 		cl->cl_vtoc.v_part[0].p_start = 0;
2875 		cl->cl_vtoc.v_part[0].p_tag   = V_UNASSIGNED;
2876 		cl->cl_vtoc.v_part[0].p_flag  = 0;
2877 		cl->cl_vtoc.v_part[0].p_size  = disksize;
2878 		cl->cl_map[0].dkl_cylno = 0;
2879 		cl->cl_map[0].dkl_nblk  = disksize;
2880 		cl->cl_offset[0] = 0;
2881 	}
2882 
2883 	(void) sprintf(cl->cl_vtoc.v_asciilabel, "DEFAULT cyl %d alt %d"
2884 	    " hd %d sec %d", cl->cl_g.dkg_ncyl, cl->cl_g.dkg_acyl,
2885 	    cl->cl_g.dkg_nhead, cl->cl_g.dkg_nsect);
2886 
2887 #else
2888 #error "No VTOC format defined."
2889 #endif
2890 
2891 	cl->cl_g.dkg_read_reinstruct  = 0;
2892 	cl->cl_g.dkg_write_reinstruct = 0;
2893 
2894 	cl->cl_g.dkg_intrlv = 1;
2895 
2896 	cl->cl_vtoc.v_sanity  = VTOC_SANE;
2897 
2898 	cl->cl_f_geometry_is_valid = TRUE;
2899 	cl->cl_label_from_media = CMLB_LABEL_UNDEF;
2900 
2901 	cmlb_dbg(CMLB_INFO,  cl,
2902 	    "cmlb_build_default_label: Default label created: "
2903 	    "cyl: %d\tacyl: %d\tnhead: %d\tnsect: %d\tcap: %d\n",
2904 	    cl->cl_g.dkg_ncyl, cl->cl_g.dkg_acyl, cl->cl_g.dkg_nhead,
2905 	    cl->cl_g.dkg_nsect, cl->cl_blockcount);
2906 }
2907 
2908 
2909 #if defined(_FIRMWARE_NEEDS_FDISK)
2910 /*
2911  * Max CHS values, as they are encoded into bytes, for 1022/254/63
2912  */
2913 #define	LBA_MAX_SECT	(63 | ((1022 & 0x300) >> 2))
2914 #define	LBA_MAX_CYL	(1022 & 0xFF)
2915 #define	LBA_MAX_HEAD	(254)
2916 
2917 
2918 /*
2919  *    Function: cmlb_has_max_chs_vals
2920  *
2921  * Description: Return TRUE if Cylinder-Head-Sector values are all at maximum.
2922  *
2923  *   Arguments: fdp - ptr to CHS info
2924  *
2925  * Return Code: True or false
2926  *
2927  *     Context: Any.
2928  */
2929 static int
2930 cmlb_has_max_chs_vals(struct ipart *fdp)
2931 {
2932 	return ((fdp->begcyl  == LBA_MAX_CYL)	&&
2933 	    (fdp->beghead == LBA_MAX_HEAD)	&&
2934 	    (fdp->begsect == LBA_MAX_SECT)	&&
2935 	    (fdp->endcyl  == LBA_MAX_CYL)	&&
2936 	    (fdp->endhead == LBA_MAX_HEAD)	&&
2937 	    (fdp->endsect == LBA_MAX_SECT));
2938 }
2939 #endif
2940 
2941 /*
2942  *    Function: cmlb_dkio_get_geometry
2943  *
2944  * Description: This routine is the driver entry point for handling user
2945  *		requests to get the device geometry (DKIOCGGEOM).
2946  *
2947  *   Arguments:
2948  *	arg		pointer to user provided dk_geom structure specifying
2949  *			the controller's notion of the current geometry.
2950  *
2951  *	flag 		this argument is a pass through to ddi_copyxxx()
2952  *			directly from the mode argument of ioctl().
2953  *
2954  *	tg_cookie	cookie from target driver to be passed back to target
2955  *			driver when we call back to it through tg_ops.
2956  *
2957  * Return Code: 0
2958  *		EFAULT
2959  *		ENXIO
2960  *		EIO
2961  */
2962 static int
2963 cmlb_dkio_get_geometry(struct cmlb_lun *cl, caddr_t arg, int flag,
2964     void *tg_cookie)
2965 {
2966 	struct dk_geom	*tmp_geom = NULL;
2967 	int		rval = 0;
2968 
2969 	/*
2970 	 * cmlb_validate_geometry does not spin a disk up
2971 	 * if it was spcl down. We need to make sure it
2972 	 * is ready.
2973 	 */
2974 	mutex_enter(CMLB_MUTEX(cl));
2975 	rval = cmlb_validate_geometry(cl, 1, 0, tg_cookie);
2976 #if defined(_SUNOS_VTOC_8)
2977 	if (rval == EINVAL &&
2978 	    cl->cl_alter_behavior & CMLB_FAKE_GEOM_LABEL_IOCTLS_VTOC8) {
2979 		/*
2980 		 * This is to return a default label geometry even when we
2981 		 * do not really assume a default label for the device.
2982 		 * dad driver utilizes this.
2983 		 */
2984 		if (cl->cl_blockcount <= CMLB_OLDVTOC_LIMIT) {
2985 			cmlb_setup_default_geometry(cl, tg_cookie);
2986 			rval = 0;
2987 		}
2988 	}
2989 #endif
2990 	if (rval) {
2991 		mutex_exit(CMLB_MUTEX(cl));
2992 		return (rval);
2993 	}
2994 
2995 #if defined(__i386) || defined(__amd64)
2996 	if (cl->cl_solaris_size == 0) {
2997 		mutex_exit(CMLB_MUTEX(cl));
2998 		return (EIO);
2999 	}
3000 #endif
3001 
3002 	/*
3003 	 * Make a local copy of the soft state geometry to avoid some potential
3004 	 * race conditions associated with holding the mutex and updating the
3005 	 * write_reinstruct value
3006 	 */
3007 	tmp_geom = kmem_zalloc(sizeof (struct dk_geom), KM_SLEEP);
3008 	bcopy(&cl->cl_g, tmp_geom, sizeof (struct dk_geom));
3009 
3010 	if (tmp_geom->dkg_write_reinstruct == 0) {
3011 		tmp_geom->dkg_write_reinstruct =
3012 		    (int)((int)(tmp_geom->dkg_nsect * tmp_geom->dkg_rpm *
3013 		    cmlb_rot_delay) / (int)60000);
3014 	}
3015 	mutex_exit(CMLB_MUTEX(cl));
3016 
3017 	rval = ddi_copyout(tmp_geom, (void *)arg, sizeof (struct dk_geom),
3018 	    flag);
3019 	if (rval != 0) {
3020 		rval = EFAULT;
3021 	}
3022 
3023 	kmem_free(tmp_geom, sizeof (struct dk_geom));
3024 	return (rval);
3025 
3026 }
3027 
3028 
3029 /*
3030  *    Function: cmlb_dkio_set_geometry
3031  *
3032  * Description: This routine is the driver entry point for handling user
3033  *		requests to set the device geometry (DKIOCSGEOM). The actual
3034  *		device geometry is not updated, just the driver "notion" of it.
3035  *
3036  *   Arguments:
3037  *	arg		pointer to user provided dk_geom structure used to set
3038  *			the controller's notion of the current geometry.
3039  *
3040  *	flag 		this argument is a pass through to ddi_copyxxx()
3041  *			directly from the mode argument of ioctl().
3042  *
3043  *	tg_cookie	cookie from target driver to be passed back to target
3044  *			driver when we call back to it through tg_ops.
3045  *
3046  * Return Code: 0
3047  *		EFAULT
3048  *		ENXIO
3049  *		EIO
3050  */
3051 static int
3052 cmlb_dkio_set_geometry(struct cmlb_lun *cl, caddr_t arg, int flag)
3053 {
3054 	struct dk_geom	*tmp_geom;
3055 	struct dk_map	*lp;
3056 	int		rval = 0;
3057 	int		i;
3058 
3059 
3060 #if defined(__i386) || defined(__amd64)
3061 	if (cl->cl_solaris_size == 0) {
3062 		return (EIO);
3063 	}
3064 #endif
3065 	/*
3066 	 * We need to copy the user specified geometry into local
3067 	 * storage and then update the softstate. We don't want to hold
3068 	 * the mutex and copyin directly from the user to the soft state
3069 	 */
3070 	tmp_geom = (struct dk_geom *)
3071 	    kmem_zalloc(sizeof (struct dk_geom), KM_SLEEP);
3072 	rval = ddi_copyin(arg, tmp_geom, sizeof (struct dk_geom), flag);
3073 	if (rval != 0) {
3074 		kmem_free(tmp_geom, sizeof (struct dk_geom));
3075 		return (EFAULT);
3076 	}
3077 
3078 	mutex_enter(CMLB_MUTEX(cl));
3079 	bcopy(tmp_geom, &cl->cl_g, sizeof (struct dk_geom));
3080 	for (i = 0; i < NDKMAP; i++) {
3081 		lp  = &cl->cl_map[i];
3082 		cl->cl_offset[i] =
3083 		    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect * lp->dkl_cylno;
3084 #if defined(__i386) || defined(__amd64)
3085 		cl->cl_offset[i] += cl->cl_solaris_offset;
3086 #endif
3087 	}
3088 	cl->cl_f_geometry_is_valid = FALSE;
3089 	mutex_exit(CMLB_MUTEX(cl));
3090 	kmem_free(tmp_geom, sizeof (struct dk_geom));
3091 
3092 	return (rval);
3093 }
3094 
3095 /*
3096  *    Function: cmlb_dkio_get_partition
3097  *
3098  * Description: This routine is the driver entry point for handling user
3099  *		requests to get the partition table (DKIOCGAPART).
3100  *
3101  *   Arguments:
3102  *	arg		pointer to user provided dk_allmap structure specifying
3103  *			the controller's notion of the current partition table.
3104  *
3105  *	flag		this argument is a pass through to ddi_copyxxx()
3106  *			directly from the mode argument of ioctl().
3107  *
3108  *	tg_cookie	cookie from target driver to be passed back to target
3109  *			driver when we call back to it through tg_ops.
3110  *
3111  * Return Code: 0
3112  *		EFAULT
3113  *		ENXIO
3114  *		EIO
3115  */
3116 static int
3117 cmlb_dkio_get_partition(struct cmlb_lun *cl, caddr_t arg, int flag,
3118     void *tg_cookie)
3119 {
3120 	int		rval = 0;
3121 	int		size;
3122 
3123 	/*
3124 	 * Make sure the geometry is valid before getting the partition
3125 	 * information.
3126 	 */
3127 	mutex_enter(CMLB_MUTEX(cl));
3128 	if ((rval = cmlb_validate_geometry(cl, 1, 0, tg_cookie)) != 0) {
3129 		mutex_exit(CMLB_MUTEX(cl));
3130 		return (rval);
3131 	}
3132 	mutex_exit(CMLB_MUTEX(cl));
3133 
3134 #if defined(__i386) || defined(__amd64)
3135 	if (cl->cl_solaris_size == 0) {
3136 		return (EIO);
3137 	}
3138 #endif
3139 
3140 #ifdef _MULTI_DATAMODEL
3141 	switch (ddi_model_convert_from(flag & FMODELS)) {
3142 	case DDI_MODEL_ILP32: {
3143 		struct dk_map32 dk_map32[NDKMAP];
3144 		int		i;
3145 
3146 		for (i = 0; i < NDKMAP; i++) {
3147 			dk_map32[i].dkl_cylno = cl->cl_map[i].dkl_cylno;
3148 			dk_map32[i].dkl_nblk  = cl->cl_map[i].dkl_nblk;
3149 		}
3150 		size = NDKMAP * sizeof (struct dk_map32);
3151 		rval = ddi_copyout(dk_map32, (void *)arg, size, flag);
3152 		if (rval != 0) {
3153 			rval = EFAULT;
3154 		}
3155 		break;
3156 	}
3157 	case DDI_MODEL_NONE:
3158 		size = NDKMAP * sizeof (struct dk_map);
3159 		rval = ddi_copyout(cl->cl_map, (void *)arg, size, flag);
3160 		if (rval != 0) {
3161 			rval = EFAULT;
3162 		}
3163 		break;
3164 	}
3165 #else /* ! _MULTI_DATAMODEL */
3166 	size = NDKMAP * sizeof (struct dk_map);
3167 	rval = ddi_copyout(cl->cl_map, (void *)arg, size, flag);
3168 	if (rval != 0) {
3169 		rval = EFAULT;
3170 	}
3171 #endif /* _MULTI_DATAMODEL */
3172 	return (rval);
3173 }
3174 
3175 /*
3176  *    Function: cmlb_dkio_set_partition
3177  *
3178  * Description: This routine is the driver entry point for handling user
3179  *		requests to set the partition table (DKIOCSAPART). The actual
3180  *		device partition is not updated.
3181  *
3182  *   Arguments:
3183  *		arg  - pointer to user provided dk_allmap structure used to set
3184  *			the controller's notion of the partition table.
3185  *		flag - this argument is a pass through to ddi_copyxxx()
3186  *		       directly from the mode argument of ioctl().
3187  *
3188  * Return Code: 0
3189  *		EINVAL
3190  *		EFAULT
3191  *		ENXIO
3192  *		EIO
3193  */
3194 static int
3195 cmlb_dkio_set_partition(struct cmlb_lun *cl, caddr_t arg, int flag)
3196 {
3197 	struct dk_map	dk_map[NDKMAP];
3198 	struct dk_map	*lp;
3199 	int		rval = 0;
3200 	int		size;
3201 	int		i;
3202 #if defined(_SUNOS_VTOC_16)
3203 	struct dkl_partition	*vp;
3204 #endif
3205 
3206 	/*
3207 	 * Set the map for all logical partitions.  We lock
3208 	 * the priority just to make sure an interrupt doesn't
3209 	 * come in while the map is half updated.
3210 	 */
3211 	_NOTE(DATA_READABLE_WITHOUT_LOCK(cmlb_lun::cl_solaris_size))
3212 	mutex_enter(CMLB_MUTEX(cl));
3213 
3214 	if (cl->cl_blockcount > CMLB_OLDVTOC_LIMIT) {
3215 		mutex_exit(CMLB_MUTEX(cl));
3216 		return (ENOTSUP);
3217 	}
3218 	mutex_exit(CMLB_MUTEX(cl));
3219 	if (cl->cl_solaris_size == 0) {
3220 		return (EIO);
3221 	}
3222 
3223 #ifdef _MULTI_DATAMODEL
3224 	switch (ddi_model_convert_from(flag & FMODELS)) {
3225 	case DDI_MODEL_ILP32: {
3226 		struct dk_map32 dk_map32[NDKMAP];
3227 
3228 		size = NDKMAP * sizeof (struct dk_map32);
3229 		rval = ddi_copyin((void *)arg, dk_map32, size, flag);
3230 		if (rval != 0) {
3231 			return (EFAULT);
3232 		}
3233 		for (i = 0; i < NDKMAP; i++) {
3234 			dk_map[i].dkl_cylno = dk_map32[i].dkl_cylno;
3235 			dk_map[i].dkl_nblk  = dk_map32[i].dkl_nblk;
3236 		}
3237 		break;
3238 	}
3239 	case DDI_MODEL_NONE:
3240 		size = NDKMAP * sizeof (struct dk_map);
3241 		rval = ddi_copyin((void *)arg, dk_map, size, flag);
3242 		if (rval != 0) {
3243 			return (EFAULT);
3244 		}
3245 		break;
3246 	}
3247 #else /* ! _MULTI_DATAMODEL */
3248 	size = NDKMAP * sizeof (struct dk_map);
3249 	rval = ddi_copyin((void *)arg, dk_map, size, flag);
3250 	if (rval != 0) {
3251 		return (EFAULT);
3252 	}
3253 #endif /* _MULTI_DATAMODEL */
3254 
3255 	mutex_enter(CMLB_MUTEX(cl));
3256 	/* Note: The size used in this bcopy is set based upon the data model */
3257 	bcopy(dk_map, cl->cl_map, size);
3258 #if defined(_SUNOS_VTOC_16)
3259 	vp = (struct dkl_partition *)&(cl->cl_vtoc);
3260 #endif	/* defined(_SUNOS_VTOC_16) */
3261 	for (i = 0; i < NDKMAP; i++) {
3262 		lp  = &cl->cl_map[i];
3263 		cl->cl_offset[i] =
3264 		    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect * lp->dkl_cylno;
3265 #if defined(_SUNOS_VTOC_16)
3266 		vp->p_start = cl->cl_offset[i];
3267 		vp->p_size = lp->dkl_nblk;
3268 		vp++;
3269 #endif	/* defined(_SUNOS_VTOC_16) */
3270 #if defined(__i386) || defined(__amd64)
3271 		cl->cl_offset[i] += cl->cl_solaris_offset;
3272 #endif
3273 	}
3274 	mutex_exit(CMLB_MUTEX(cl));
3275 	return (rval);
3276 }
3277 
3278 
3279 /*
3280  *    Function: cmlb_dkio_get_vtoc
3281  *
3282  * Description: This routine is the driver entry point for handling user
3283  *		requests to get the current volume table of contents
3284  *		(DKIOCGVTOC).
3285  *
3286  *   Arguments:
3287  *	arg		pointer to user provided vtoc structure specifying
3288  *			the current vtoc.
3289  *
3290  *	flag		this argument is a pass through to ddi_copyxxx()
3291  *			directly from the mode argument of ioctl().
3292  *
3293  *	tg_cookie	cookie from target driver to be passed back to target
3294  *			driver when we call back to it through tg_ops.
3295  *
3296  * Return Code: 0
3297  *		EFAULT
3298  *		ENXIO
3299  *		EIO
3300  */
3301 static int
3302 cmlb_dkio_get_vtoc(struct cmlb_lun *cl, caddr_t arg, int flag, void *tg_cookie)
3303 {
3304 #if defined(_SUNOS_VTOC_8)
3305 	struct vtoc	user_vtoc;
3306 #endif	/* defined(_SUNOS_VTOC_8) */
3307 	int		rval = 0;
3308 
3309 	mutex_enter(CMLB_MUTEX(cl));
3310 	if (cl->cl_blockcount > CMLB_OLDVTOC_LIMIT) {
3311 		mutex_exit(CMLB_MUTEX(cl));
3312 		return (EOVERFLOW);
3313 	}
3314 
3315 	rval = cmlb_validate_geometry(cl, 1, 0, tg_cookie);
3316 
3317 #if defined(_SUNOS_VTOC_8)
3318 	if (rval == EINVAL &&
3319 	    (cl->cl_alter_behavior & CMLB_FAKE_GEOM_LABEL_IOCTLS_VTOC8)) {
3320 		/*
3321 		 * This is to return a default label even when we do not
3322 		 * really assume a default label for the device.
3323 		 * dad driver utilizes this.
3324 		 */
3325 		if (cl->cl_blockcount <= CMLB_OLDVTOC_LIMIT) {
3326 			cmlb_setup_default_geometry(cl, tg_cookie);
3327 			rval = 0;
3328 		}
3329 	}
3330 #endif
3331 	if (rval) {
3332 		mutex_exit(CMLB_MUTEX(cl));
3333 		return (rval);
3334 	}
3335 
3336 #if defined(_SUNOS_VTOC_8)
3337 	cmlb_build_user_vtoc(cl, &user_vtoc);
3338 	mutex_exit(CMLB_MUTEX(cl));
3339 
3340 #ifdef _MULTI_DATAMODEL
3341 	switch (ddi_model_convert_from(flag & FMODELS)) {
3342 	case DDI_MODEL_ILP32: {
3343 		struct vtoc32 user_vtoc32;
3344 
3345 		vtoctovtoc32(user_vtoc, user_vtoc32);
3346 		if (ddi_copyout(&user_vtoc32, (void *)arg,
3347 		    sizeof (struct vtoc32), flag)) {
3348 			return (EFAULT);
3349 		}
3350 		break;
3351 	}
3352 
3353 	case DDI_MODEL_NONE:
3354 		if (ddi_copyout(&user_vtoc, (void *)arg,
3355 		    sizeof (struct vtoc), flag)) {
3356 			return (EFAULT);
3357 		}
3358 		break;
3359 	}
3360 #else /* ! _MULTI_DATAMODEL */
3361 	if (ddi_copyout(&user_vtoc, (void *)arg, sizeof (struct vtoc), flag)) {
3362 		return (EFAULT);
3363 	}
3364 #endif /* _MULTI_DATAMODEL */
3365 
3366 #elif defined(_SUNOS_VTOC_16)
3367 	mutex_exit(CMLB_MUTEX(cl));
3368 
3369 #ifdef _MULTI_DATAMODEL
3370 	/*
3371 	 * The cl_vtoc structure is a "struct dk_vtoc"  which is always
3372 	 * 32-bit to maintain compatibility with existing on-disk
3373 	 * structures.  Thus, we need to convert the structure when copying
3374 	 * it out to a datamodel-dependent "struct vtoc" in a 64-bit
3375 	 * program.  If the target is a 32-bit program, then no conversion
3376 	 * is necessary.
3377 	 */
3378 	/* LINTED: logical expression always true: op "||" */
3379 	ASSERT(sizeof (cl->cl_vtoc) == sizeof (struct vtoc32));
3380 	switch (ddi_model_convert_from(flag & FMODELS)) {
3381 	case DDI_MODEL_ILP32:
3382 		if (ddi_copyout(&(cl->cl_vtoc), (void *)arg,
3383 		    sizeof (cl->cl_vtoc), flag)) {
3384 			return (EFAULT);
3385 		}
3386 		break;
3387 
3388 	case DDI_MODEL_NONE: {
3389 		struct vtoc user_vtoc;
3390 
3391 		vtoc32tovtoc(cl->cl_vtoc, user_vtoc);
3392 		if (ddi_copyout(&user_vtoc, (void *)arg,
3393 		    sizeof (struct vtoc), flag)) {
3394 			return (EFAULT);
3395 		}
3396 		break;
3397 	}
3398 	}
3399 #else /* ! _MULTI_DATAMODEL */
3400 	if (ddi_copyout(&(cl->cl_vtoc), (void *)arg, sizeof (cl->cl_vtoc),
3401 	    flag)) {
3402 		return (EFAULT);
3403 	}
3404 #endif /* _MULTI_DATAMODEL */
3405 #else
3406 #error "No VTOC format defined."
3407 #endif
3408 
3409 	return (rval);
3410 }
3411 
3412 
3413 /*
3414  *    Function: cmlb_dkio_get_extvtoc
3415  */
3416 static int
3417 cmlb_dkio_get_extvtoc(struct cmlb_lun *cl, caddr_t arg, int flag,
3418     void *tg_cookie)
3419 {
3420 	struct extvtoc	ext_vtoc;
3421 #if defined(_SUNOS_VTOC_8)
3422 	struct vtoc	user_vtoc;
3423 #endif	/* defined(_SUNOS_VTOC_8) */
3424 	int		rval = 0;
3425 
3426 	bzero(&ext_vtoc, sizeof (struct extvtoc));
3427 	mutex_enter(CMLB_MUTEX(cl));
3428 	rval = cmlb_validate_geometry(cl, 1, 0, tg_cookie);
3429 
3430 #if defined(_SUNOS_VTOC_8)
3431 	if (rval == EINVAL &&
3432 	    (cl->cl_alter_behavior & CMLB_FAKE_GEOM_LABEL_IOCTLS_VTOC8)) {
3433 		/*
3434 		 * This is to return a default label even when we do not
3435 		 * really assume a default label for the device.
3436 		 * dad driver utilizes this.
3437 		 */
3438 		if (cl->cl_blockcount <= CMLB_OLDVTOC_LIMIT) {
3439 			cmlb_setup_default_geometry(cl, tg_cookie);
3440 			rval = 0;
3441 		}
3442 	}
3443 #endif
3444 	if (rval) {
3445 		mutex_exit(CMLB_MUTEX(cl));
3446 		return (rval);
3447 	}
3448 
3449 #if defined(_SUNOS_VTOC_8)
3450 	cmlb_build_user_vtoc(cl, &user_vtoc);
3451 	mutex_exit(CMLB_MUTEX(cl));
3452 
3453 	/*
3454 	 * Checking callers data model does not make much sense here
3455 	 * since extvtoc will always be equivalent to 64bit vtoc.
3456 	 * What is important is whether the kernel is in 32 or 64 bit
3457 	 */
3458 
3459 #ifdef _LP64
3460 		if (ddi_copyout(&user_vtoc, (void *)arg,
3461 		    sizeof (struct extvtoc), flag)) {
3462 			return (EFAULT);
3463 		}
3464 #else
3465 		vtoc32tovtoc(user_vtoc, ext_vtoc);
3466 		if (ddi_copyout(&ext_vtoc, (void *)arg,
3467 		    sizeof (struct extvtoc), flag)) {
3468 			return (EFAULT);
3469 		}
3470 #endif
3471 
3472 #elif defined(_SUNOS_VTOC_16)
3473 	mutex_exit(CMLB_MUTEX(cl));
3474 
3475 	/*
3476 	 * The cl_vtoc structure is a "struct dk_vtoc"  which is always
3477 	 * 32-bit to maintain compatibility with existing on-disk
3478 	 * structures.  Thus, we need to convert the structure when copying
3479 	 * it out to extvtoc
3480 	 */
3481 	vtoc32tovtoc(cl->cl_vtoc, ext_vtoc);
3482 
3483 	if (ddi_copyout(&ext_vtoc, (void *)arg, sizeof (struct extvtoc), flag))
3484 		return (EFAULT);
3485 #else
3486 #error "No VTOC format defined."
3487 #endif
3488 
3489 	return (rval);
3490 }
3491 static int
3492 cmlb_dkio_get_efi(struct cmlb_lun *cl, caddr_t arg, int flag, void *tg_cookie)
3493 {
3494 	dk_efi_t	user_efi;
3495 	int		rval = 0;
3496 	void		*buffer;
3497 	diskaddr_t	tgt_lba;
3498 
3499 	if (ddi_copyin(arg, &user_efi, sizeof (dk_efi_t), flag))
3500 		return (EFAULT);
3501 
3502 	user_efi.dki_data = (void *)(uintptr_t)user_efi.dki_data_64;
3503 
3504 	tgt_lba = user_efi.dki_lba;
3505 
3506 	mutex_enter(CMLB_MUTEX(cl));
3507 	if ((cmlb_check_update_blockcount(cl, tg_cookie) != 0) ||
3508 	    (cl->cl_tgt_blocksize == 0)) {
3509 		mutex_exit(CMLB_MUTEX(cl));
3510 		return (EINVAL);
3511 	}
3512 	if (cl->cl_tgt_blocksize != cl->cl_sys_blocksize)
3513 		tgt_lba = tgt_lba * cl->cl_tgt_blocksize /
3514 		    cl->cl_sys_blocksize;
3515 	mutex_exit(CMLB_MUTEX(cl));
3516 
3517 	buffer = kmem_alloc(user_efi.dki_length, KM_SLEEP);
3518 	rval = DK_TG_READ(cl, buffer, tgt_lba, user_efi.dki_length, tg_cookie);
3519 	if (rval == 0 && ddi_copyout(buffer, user_efi.dki_data,
3520 	    user_efi.dki_length, flag) != 0)
3521 		rval = EFAULT;
3522 
3523 	kmem_free(buffer, user_efi.dki_length);
3524 	return (rval);
3525 }
3526 
3527 #if defined(_SUNOS_VTOC_8)
3528 /*
3529  *    Function: cmlb_build_user_vtoc
3530  *
3531  * Description: This routine populates a pass by reference variable with the
3532  *		current volume table of contents.
3533  *
3534  *   Arguments: cl - driver soft state (unit) structure
3535  *		user_vtoc - pointer to vtoc structure to be populated
3536  */
3537 static void
3538 cmlb_build_user_vtoc(struct cmlb_lun *cl, struct vtoc *user_vtoc)
3539 {
3540 	struct dk_map2		*lpart;
3541 	struct dk_map		*lmap;
3542 	struct partition	*vpart;
3543 	uint32_t		nblks;
3544 	int			i;
3545 
3546 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
3547 
3548 	/*
3549 	 * Return vtoc structure fields in the provided VTOC area, addressed
3550 	 * by *vtoc.
3551 	 */
3552 	bzero(user_vtoc, sizeof (struct vtoc));
3553 	user_vtoc->v_bootinfo[0] = cl->cl_vtoc.v_bootinfo[0];
3554 	user_vtoc->v_bootinfo[1] = cl->cl_vtoc.v_bootinfo[1];
3555 	user_vtoc->v_bootinfo[2] = cl->cl_vtoc.v_bootinfo[2];
3556 	user_vtoc->v_sanity	= VTOC_SANE;
3557 	user_vtoc->v_version	= cl->cl_vtoc.v_version;
3558 	bcopy(cl->cl_vtoc.v_volume, user_vtoc->v_volume, LEN_DKL_VVOL);
3559 	user_vtoc->v_sectorsz = cl->cl_sys_blocksize;
3560 	user_vtoc->v_nparts = cl->cl_vtoc.v_nparts;
3561 
3562 	for (i = 0; i < 10; i++)
3563 		user_vtoc->v_reserved[i] = cl->cl_vtoc.v_reserved[i];
3564 
3565 	/*
3566 	 * Convert partitioning information.
3567 	 *
3568 	 * Note the conversion from starting cylinder number
3569 	 * to starting sector number.
3570 	 */
3571 	lmap = cl->cl_map;
3572 	lpart = (struct dk_map2 *)cl->cl_vtoc.v_part;
3573 	vpart = user_vtoc->v_part;
3574 
3575 	nblks = cl->cl_g.dkg_nsect * cl->cl_g.dkg_nhead;
3576 
3577 	for (i = 0; i < V_NUMPAR; i++) {
3578 		vpart->p_tag	= lpart->p_tag;
3579 		vpart->p_flag	= lpart->p_flag;
3580 		vpart->p_start	= lmap->dkl_cylno * nblks;
3581 		vpart->p_size	= lmap->dkl_nblk;
3582 		lmap++;
3583 		lpart++;
3584 		vpart++;
3585 
3586 		/* (4364927) */
3587 		user_vtoc->timestamp[i] = (time_t)cl->cl_vtoc.v_timestamp[i];
3588 	}
3589 
3590 	bcopy(cl->cl_asciilabel, user_vtoc->v_asciilabel, LEN_DKL_ASCII);
3591 }
3592 #endif
3593 
3594 static int
3595 cmlb_dkio_partition(struct cmlb_lun *cl, caddr_t arg, int flag,
3596     void *tg_cookie)
3597 {
3598 	struct partition64	p64;
3599 	int			rval = 0;
3600 	uint_t			nparts;
3601 	efi_gpe_t		*partitions;
3602 	efi_gpt_t		*buffer;
3603 	diskaddr_t		gpe_lba;
3604 
3605 	if (ddi_copyin((const void *)arg, &p64,
3606 	    sizeof (struct partition64), flag)) {
3607 		return (EFAULT);
3608 	}
3609 
3610 	buffer = kmem_alloc(EFI_MIN_ARRAY_SIZE, KM_SLEEP);
3611 	rval = DK_TG_READ(cl, buffer, 1, DEV_BSIZE, tg_cookie);
3612 	if (rval != 0)
3613 		goto done_error;
3614 
3615 	cmlb_swap_efi_gpt(buffer);
3616 
3617 	if ((rval = cmlb_validate_efi(buffer)) != 0)
3618 		goto done_error;
3619 
3620 	nparts = buffer->efi_gpt_NumberOfPartitionEntries;
3621 	gpe_lba = buffer->efi_gpt_PartitionEntryLBA;
3622 	if (p64.p_partno > nparts) {
3623 		/* couldn't find it */
3624 		rval = ESRCH;
3625 		goto done_error;
3626 	}
3627 	/*
3628 	 * if we're dealing with a partition that's out of the normal
3629 	 * 16K block, adjust accordingly
3630 	 */
3631 	gpe_lba += p64.p_partno / sizeof (efi_gpe_t);
3632 	rval = DK_TG_READ(cl, buffer, gpe_lba, EFI_MIN_ARRAY_SIZE, tg_cookie);
3633 
3634 	if (rval) {
3635 		goto done_error;
3636 	}
3637 	partitions = (efi_gpe_t *)buffer;
3638 
3639 	cmlb_swap_efi_gpe(nparts, partitions);
3640 
3641 	partitions += p64.p_partno;
3642 	bcopy(&partitions->efi_gpe_PartitionTypeGUID, &p64.p_type,
3643 	    sizeof (struct uuid));
3644 	p64.p_start = partitions->efi_gpe_StartingLBA;
3645 	p64.p_size = partitions->efi_gpe_EndingLBA -
3646 	    p64.p_start + 1;
3647 
3648 	if (ddi_copyout(&p64, (void *)arg, sizeof (struct partition64), flag))
3649 		rval = EFAULT;
3650 
3651 done_error:
3652 	kmem_free(buffer, EFI_MIN_ARRAY_SIZE);
3653 	return (rval);
3654 }
3655 
3656 
3657 /*
3658  *    Function: cmlb_dkio_set_vtoc
3659  *
3660  * Description: This routine is the driver entry point for handling user
3661  *		requests to set the current volume table of contents
3662  *		(DKIOCSVTOC).
3663  *
3664  *   Arguments:
3665  *	dev		the device number
3666  *	arg		pointer to user provided vtoc structure used to set the
3667  *			current vtoc.
3668  *
3669  *	flag		this argument is a pass through to ddi_copyxxx()
3670  *			directly from the mode argument of ioctl().
3671  *
3672  *	tg_cookie	cookie from target driver to be passed back to target
3673  *			driver when we call back to it through tg_ops.
3674  *
3675  * Return Code: 0
3676  *		EFAULT
3677  *		ENXIO
3678  *		EINVAL
3679  *		ENOTSUP
3680  */
3681 static int
3682 cmlb_dkio_set_vtoc(struct cmlb_lun *cl, dev_t dev, caddr_t arg, int flag,
3683     void *tg_cookie)
3684 {
3685 	struct vtoc	user_vtoc;
3686 	int		rval = 0;
3687 	boolean_t	internal;
3688 
3689 	internal = ((cl->cl_alter_behavior & (CMLB_INTERNAL_MINOR_NODES)) != 0);
3690 
3691 #ifdef _MULTI_DATAMODEL
3692 	switch (ddi_model_convert_from(flag & FMODELS)) {
3693 	case DDI_MODEL_ILP32: {
3694 		struct vtoc32 user_vtoc32;
3695 
3696 		if (ddi_copyin((const void *)arg, &user_vtoc32,
3697 		    sizeof (struct vtoc32), flag)) {
3698 			return (EFAULT);
3699 		}
3700 		vtoc32tovtoc(user_vtoc32, user_vtoc);
3701 		break;
3702 	}
3703 
3704 	case DDI_MODEL_NONE:
3705 		if (ddi_copyin((const void *)arg, &user_vtoc,
3706 		    sizeof (struct vtoc), flag)) {
3707 			return (EFAULT);
3708 		}
3709 		break;
3710 	}
3711 #else /* ! _MULTI_DATAMODEL */
3712 	if (ddi_copyin((const void *)arg, &user_vtoc,
3713 	    sizeof (struct vtoc), flag)) {
3714 		return (EFAULT);
3715 	}
3716 #endif /* _MULTI_DATAMODEL */
3717 
3718 	mutex_enter(CMLB_MUTEX(cl));
3719 
3720 	if (cl->cl_blockcount > CMLB_OLDVTOC_LIMIT) {
3721 		mutex_exit(CMLB_MUTEX(cl));
3722 		return (EOVERFLOW);
3723 	}
3724 
3725 #if defined(__i386) || defined(__amd64)
3726 	if (cl->cl_tgt_blocksize != cl->cl_sys_blocksize) {
3727 		mutex_exit(CMLB_MUTEX(cl));
3728 		return (EINVAL);
3729 	}
3730 #endif
3731 
3732 	if (cl->cl_g.dkg_ncyl == 0) {
3733 		mutex_exit(CMLB_MUTEX(cl));
3734 		return (EINVAL);
3735 	}
3736 
3737 	mutex_exit(CMLB_MUTEX(cl));
3738 	cmlb_clear_efi(cl, tg_cookie);
3739 	ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd");
3740 	ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd,raw");
3741 	(void) cmlb_create_minor(CMLB_DEVINFO(cl), "h",
3742 	    S_IFBLK, (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
3743 	    cl->cl_node_type, NULL, internal);
3744 	(void) cmlb_create_minor(CMLB_DEVINFO(cl), "h,raw",
3745 	    S_IFCHR, (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
3746 	    cl->cl_node_type, NULL, internal);
3747 	mutex_enter(CMLB_MUTEX(cl));
3748 
3749 	if ((rval = cmlb_build_label_vtoc(cl, &user_vtoc)) == 0) {
3750 		if ((rval = cmlb_write_label(cl, tg_cookie)) == 0) {
3751 			if (cmlb_validate_geometry(cl, 1, 0, tg_cookie) != 0) {
3752 				cmlb_dbg(CMLB_ERROR, cl,
3753 				    "cmlb_dkio_set_vtoc: "
3754 				    "Failed validate geometry\n");
3755 			}
3756 			cl->cl_msglog_flag |= CMLB_ALLOW_2TB_WARN;
3757 		}
3758 	}
3759 	mutex_exit(CMLB_MUTEX(cl));
3760 	return (rval);
3761 }
3762 
3763 /*
3764  *    Function: cmlb_dkio_set_extvtoc
3765  */
3766 static int
3767 cmlb_dkio_set_extvtoc(struct cmlb_lun *cl, dev_t dev, caddr_t arg, int flag,
3768     void *tg_cookie)
3769 {
3770 	int		rval = 0;
3771 	struct vtoc	user_vtoc;
3772 
3773 	/*
3774 	 * Checking callers data model does not make much sense here
3775 	 * since extvtoc will always be equivalent to 64bit vtoc.
3776 	 * What is important is whether the kernel is in 32 or 64 bit
3777 	 */
3778 
3779 #ifdef _LP64
3780 	if (ddi_copyin((const void *)arg, &user_vtoc,
3781 		    sizeof (struct extvtoc), flag)) {
3782 			return (EFAULT);
3783 	}
3784 #else
3785 	struct	extvtoc	user_extvtoc;
3786 	if (ddi_copyin((const void *)arg, &user_extvtoc,
3787 		    sizeof (struct extvtoc), flag)) {
3788 			return (EFAULT);
3789 	}
3790 
3791 	vtoctovtoc32(user_extvtoc, user_vtoc);
3792 #endif
3793 
3794 	mutex_enter(CMLB_MUTEX(cl));
3795 #if defined(__i386) || defined(__amd64)
3796 	if (cl->cl_tgt_blocksize != cl->cl_sys_blocksize) {
3797 		mutex_exit(CMLB_MUTEX(cl));
3798 		return (EINVAL);
3799 	}
3800 #endif
3801 
3802 	if (cl->cl_g.dkg_ncyl == 0) {
3803 		mutex_exit(CMLB_MUTEX(cl));
3804 		return (EINVAL);
3805 	}
3806 
3807 	mutex_exit(CMLB_MUTEX(cl));
3808 	cmlb_clear_efi(cl, tg_cookie);
3809 	ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd");
3810 	ddi_remove_minor_node(CMLB_DEVINFO(cl), "wd,raw");
3811 	(void) ddi_create_minor_node(CMLB_DEVINFO(cl), "h",
3812 	    S_IFBLK, (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
3813 	    cl->cl_node_type, NULL);
3814 	(void) ddi_create_minor_node(CMLB_DEVINFO(cl), "h,raw",
3815 	    S_IFCHR, (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
3816 	    cl->cl_node_type, NULL);
3817 	mutex_enter(CMLB_MUTEX(cl));
3818 
3819 	if ((rval = cmlb_build_label_vtoc(cl, &user_vtoc)) == 0) {
3820 		if ((rval = cmlb_write_label(cl, tg_cookie)) == 0) {
3821 			if (cmlb_validate_geometry(cl, 1, 0, tg_cookie) != 0) {
3822 				cmlb_dbg(CMLB_ERROR, cl,
3823 				    "cmlb_dkio_set_vtoc: "
3824 				    "Failed validate geometry\n");
3825 			}
3826 		}
3827 	}
3828 	mutex_exit(CMLB_MUTEX(cl));
3829 	return (rval);
3830 }
3831 
3832 /*
3833  *    Function: cmlb_build_label_vtoc
3834  *
3835  * Description: This routine updates the driver soft state current volume table
3836  *		of contents based on a user specified vtoc.
3837  *
3838  *   Arguments: cl - driver soft state (unit) structure
3839  *		user_vtoc - pointer to vtoc structure specifying vtoc to be used
3840  *			    to update the driver soft state.
3841  *
3842  * Return Code: 0
3843  *		EINVAL
3844  */
3845 static int
3846 cmlb_build_label_vtoc(struct cmlb_lun *cl, struct vtoc *user_vtoc)
3847 {
3848 	struct dk_map		*lmap;
3849 	struct partition	*vpart;
3850 	uint_t			nblks;
3851 #if defined(_SUNOS_VTOC_8)
3852 	int			ncyl;
3853 	struct dk_map2		*lpart;
3854 #endif	/* defined(_SUNOS_VTOC_8) */
3855 	int			i;
3856 
3857 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
3858 
3859 	/* Sanity-check the vtoc */
3860 	if (user_vtoc->v_sanity != VTOC_SANE ||
3861 	    user_vtoc->v_sectorsz != cl->cl_sys_blocksize ||
3862 	    user_vtoc->v_nparts != V_NUMPAR) {
3863 		cmlb_dbg(CMLB_INFO,  cl,
3864 		    "cmlb_build_label_vtoc: vtoc not valid\n");
3865 		return (EINVAL);
3866 	}
3867 
3868 	nblks = cl->cl_g.dkg_nsect * cl->cl_g.dkg_nhead;
3869 	if (nblks == 0) {
3870 		cmlb_dbg(CMLB_INFO,  cl,
3871 		    "cmlb_build_label_vtoc: geom nblks is 0\n");
3872 		return (EINVAL);
3873 	}
3874 
3875 #if defined(_SUNOS_VTOC_8)
3876 	vpart = user_vtoc->v_part;
3877 	for (i = 0; i < V_NUMPAR; i++) {
3878 		if (((unsigned)vpart->p_start % nblks) != 0) {
3879 			cmlb_dbg(CMLB_INFO,  cl,
3880 			    "cmlb_build_label_vtoc: p_start not multiply of"
3881 			    "nblks part %d p_start %d nblks %d\n", i,
3882 			    vpart->p_start, nblks);
3883 			return (EINVAL);
3884 		}
3885 		ncyl = (unsigned)vpart->p_start / nblks;
3886 		ncyl += (unsigned)vpart->p_size / nblks;
3887 		if (((unsigned)vpart->p_size % nblks) != 0) {
3888 			ncyl++;
3889 		}
3890 		if (ncyl > (int)cl->cl_g.dkg_ncyl) {
3891 			cmlb_dbg(CMLB_INFO,  cl,
3892 			    "cmlb_build_label_vtoc: ncyl %d  > dkg_ncyl %d"
3893 			    "p_size %ld p_start %ld nblks %d  part number %d"
3894 			    "tag %d\n",
3895 			    ncyl, cl->cl_g.dkg_ncyl, vpart->p_size,
3896 			    vpart->p_start, nblks,
3897 			    i, vpart->p_tag);
3898 
3899 			return (EINVAL);
3900 		}
3901 		vpart++;
3902 	}
3903 #endif	/* defined(_SUNOS_VTOC_8) */
3904 
3905 	/* Put appropriate vtoc structure fields into the disk label */
3906 #if defined(_SUNOS_VTOC_16)
3907 	/*
3908 	 * The vtoc is always a 32bit data structure to maintain the
3909 	 * on-disk format. Convert "in place" instead of doing bcopy.
3910 	 */
3911 	vtoctovtoc32((*user_vtoc), (*((struct vtoc32 *)&(cl->cl_vtoc))));
3912 
3913 	/*
3914 	 * in the 16-slice vtoc, starting sectors are expressed in
3915 	 * numbers *relative* to the start of the Solaris fdisk partition.
3916 	 */
3917 	lmap = cl->cl_map;
3918 	vpart = user_vtoc->v_part;
3919 
3920 	for (i = 0; i < (int)user_vtoc->v_nparts; i++, lmap++, vpart++) {
3921 		lmap->dkl_cylno = (unsigned)vpart->p_start / nblks;
3922 		lmap->dkl_nblk = (unsigned)vpart->p_size;
3923 	}
3924 
3925 #elif defined(_SUNOS_VTOC_8)
3926 
3927 	cl->cl_vtoc.v_bootinfo[0] = (uint32_t)user_vtoc->v_bootinfo[0];
3928 	cl->cl_vtoc.v_bootinfo[1] = (uint32_t)user_vtoc->v_bootinfo[1];
3929 	cl->cl_vtoc.v_bootinfo[2] = (uint32_t)user_vtoc->v_bootinfo[2];
3930 
3931 	cl->cl_vtoc.v_sanity = (uint32_t)user_vtoc->v_sanity;
3932 	cl->cl_vtoc.v_version = (uint32_t)user_vtoc->v_version;
3933 
3934 	bcopy(user_vtoc->v_volume, cl->cl_vtoc.v_volume, LEN_DKL_VVOL);
3935 
3936 	cl->cl_vtoc.v_nparts = user_vtoc->v_nparts;
3937 
3938 	for (i = 0; i < 10; i++)
3939 		cl->cl_vtoc.v_reserved[i] =  user_vtoc->v_reserved[i];
3940 
3941 	/*
3942 	 * Note the conversion from starting sector number
3943 	 * to starting cylinder number.
3944 	 * Return error if division results in a remainder.
3945 	 */
3946 	lmap = cl->cl_map;
3947 	lpart = cl->cl_vtoc.v_part;
3948 	vpart = user_vtoc->v_part;
3949 
3950 	for (i = 0; i < (int)user_vtoc->v_nparts; i++) {
3951 		lpart->p_tag  = vpart->p_tag;
3952 		lpart->p_flag = vpart->p_flag;
3953 		lmap->dkl_cylno = (unsigned)vpart->p_start / nblks;
3954 		lmap->dkl_nblk = (unsigned)vpart->p_size;
3955 
3956 		lmap++;
3957 		lpart++;
3958 		vpart++;
3959 
3960 		/* (4387723) */
3961 #ifdef _LP64
3962 		if (user_vtoc->timestamp[i] > TIME32_MAX) {
3963 			cl->cl_vtoc.v_timestamp[i] = TIME32_MAX;
3964 		} else {
3965 			cl->cl_vtoc.v_timestamp[i] = user_vtoc->timestamp[i];
3966 		}
3967 #else
3968 		cl->cl_vtoc.v_timestamp[i] = user_vtoc->timestamp[i];
3969 #endif
3970 	}
3971 
3972 	bcopy(user_vtoc->v_asciilabel, cl->cl_asciilabel, LEN_DKL_ASCII);
3973 #else
3974 #error "No VTOC format defined."
3975 #endif
3976 	return (0);
3977 }
3978 
3979 /*
3980  *    Function: cmlb_clear_efi
3981  *
3982  * Description: This routine clears all EFI labels.
3983  *
3984  *   Arguments:
3985  *	cl		 driver soft state (unit) structure
3986  *
3987  *	tg_cookie	cookie from target driver to be passed back to target
3988  *			driver when we call back to it through tg_ops.
3989  * Return Code: void
3990  */
3991 static void
3992 cmlb_clear_efi(struct cmlb_lun *cl, void *tg_cookie)
3993 {
3994 	efi_gpt_t	*gpt;
3995 	diskaddr_t	cap;
3996 	int		rval;
3997 
3998 	ASSERT(!mutex_owned(CMLB_MUTEX(cl)));
3999 
4000 	mutex_enter(CMLB_MUTEX(cl));
4001 	cl->cl_reserved = -1;
4002 	mutex_exit(CMLB_MUTEX(cl));
4003 
4004 	gpt = kmem_alloc(sizeof (efi_gpt_t), KM_SLEEP);
4005 
4006 	if (DK_TG_READ(cl, gpt, 1, DEV_BSIZE, tg_cookie) != 0) {
4007 		goto done;
4008 	}
4009 
4010 	cmlb_swap_efi_gpt(gpt);
4011 	rval = cmlb_validate_efi(gpt);
4012 	if (rval == 0) {
4013 		/* clear primary */
4014 		bzero(gpt, sizeof (efi_gpt_t));
4015 		if (rval = DK_TG_WRITE(cl, gpt, 1, EFI_LABEL_SIZE, tg_cookie)) {
4016 			cmlb_dbg(CMLB_INFO,  cl,
4017 			    "cmlb_clear_efi: clear primary label failed\n");
4018 		}
4019 	}
4020 	/* the backup */
4021 	rval = DK_TG_GETCAP(cl, &cap, tg_cookie);
4022 	if (rval) {
4023 		goto done;
4024 	}
4025 
4026 	if ((rval = DK_TG_READ(cl, gpt, cap - 1, EFI_LABEL_SIZE, tg_cookie))
4027 	    != 0) {
4028 		goto done;
4029 	}
4030 	cmlb_swap_efi_gpt(gpt);
4031 	rval = cmlb_validate_efi(gpt);
4032 	if (rval == 0) {
4033 		/* clear backup */
4034 		cmlb_dbg(CMLB_TRACE,  cl,
4035 		    "cmlb_clear_efi clear backup@%lu\n", cap - 1);
4036 		bzero(gpt, sizeof (efi_gpt_t));
4037 		if ((rval = DK_TG_WRITE(cl,  gpt, cap - 1, EFI_LABEL_SIZE,
4038 		    tg_cookie))) {
4039 			cmlb_dbg(CMLB_INFO,  cl,
4040 			    "cmlb_clear_efi: clear backup label failed\n");
4041 		}
4042 	} else {
4043 		/*
4044 		 * Refer to comments related to off-by-1 at the
4045 		 * header of this file
4046 		 */
4047 		if ((rval = DK_TG_READ(cl, gpt, cap - 2,
4048 		    EFI_LABEL_SIZE, tg_cookie)) != 0) {
4049 			goto done;
4050 		}
4051 		cmlb_swap_efi_gpt(gpt);
4052 		rval = cmlb_validate_efi(gpt);
4053 		if (rval == 0) {
4054 			/* clear legacy backup EFI label */
4055 			cmlb_dbg(CMLB_TRACE,  cl,
4056 			    "cmlb_clear_efi clear legacy backup@%lu\n",
4057 			    cap - 2);
4058 			bzero(gpt, sizeof (efi_gpt_t));
4059 			if ((rval = DK_TG_WRITE(cl,  gpt, cap - 2,
4060 			    EFI_LABEL_SIZE, tg_cookie))) {
4061 				cmlb_dbg(CMLB_INFO,  cl,
4062 				"cmlb_clear_efi: clear legacy backup label "
4063 				"failed\n");
4064 			}
4065 		}
4066 	}
4067 
4068 done:
4069 	kmem_free(gpt, sizeof (efi_gpt_t));
4070 }
4071 
4072 /*
4073  *    Function: cmlb_set_vtoc
4074  *
4075  * Description: This routine writes data to the appropriate positions
4076  *
4077  *   Arguments:
4078  *	cl		driver soft state (unit) structure
4079  *
4080  *	dkl		the data to be written
4081  *
4082  *	tg_cookie	cookie from target driver to be passed back to target
4083  *			driver when we call back to it through tg_ops.
4084  *
4085  * Return: void
4086  */
4087 static int
4088 cmlb_set_vtoc(struct cmlb_lun *cl, struct dk_label *dkl, void *tg_cookie)
4089 {
4090 	uint_t	label_addr;
4091 	int	sec;
4092 	diskaddr_t	blk;
4093 	int	head;
4094 	int	cyl;
4095 	int	rval;
4096 
4097 #if defined(__i386) || defined(__amd64)
4098 	label_addr = cl->cl_solaris_offset + DK_LABEL_LOC;
4099 #else
4100 	/* Write the primary label at block 0 of the solaris partition. */
4101 	label_addr = 0;
4102 #endif
4103 
4104 	rval = DK_TG_WRITE(cl, dkl, label_addr, cl->cl_sys_blocksize,
4105 	    tg_cookie);
4106 
4107 	if (rval != 0) {
4108 		return (rval);
4109 	}
4110 
4111 	/*
4112 	 * Calculate where the backup labels go.  They are always on
4113 	 * the last alternate cylinder, but some older drives put them
4114 	 * on head 2 instead of the last head.	They are always on the
4115 	 * first 5 odd sectors of the appropriate track.
4116 	 *
4117 	 * We have no choice at this point, but to believe that the
4118 	 * disk label is valid.	 Use the geometry of the disk
4119 	 * as described in the label.
4120 	 */
4121 	cyl  = dkl->dkl_ncyl  + dkl->dkl_acyl - 1;
4122 	head = dkl->dkl_nhead - 1;
4123 
4124 	/*
4125 	 * Write and verify the backup labels. Make sure we don't try to
4126 	 * write past the last cylinder.
4127 	 */
4128 	for (sec = 1; ((sec < 5 * 2 + 1) && (sec < dkl->dkl_nsect)); sec += 2) {
4129 		blk = (diskaddr_t)(
4130 		    (cyl * ((dkl->dkl_nhead * dkl->dkl_nsect) - dkl->dkl_apc)) +
4131 		    (head * dkl->dkl_nsect) + sec);
4132 #if defined(__i386) || defined(__amd64)
4133 		blk += cl->cl_solaris_offset;
4134 #endif
4135 		rval = DK_TG_WRITE(cl, dkl, blk, cl->cl_sys_blocksize,
4136 		    tg_cookie);
4137 		cmlb_dbg(CMLB_INFO,  cl,
4138 		"cmlb_set_vtoc: wrote backup label %llx\n", blk);
4139 		if (rval != 0) {
4140 			goto exit;
4141 		}
4142 	}
4143 exit:
4144 	return (rval);
4145 }
4146 
4147 /*
4148  *    Function: cmlb_clear_vtoc
4149  *
4150  * Description: This routine clears out the VTOC labels.
4151  *
4152  *   Arguments:
4153  *	cl		driver soft state (unit) structure
4154  *
4155  *	tg_cookie	cookie from target driver to be passed back to target
4156  *			driver when we call back to it through tg_ops.
4157  *
4158  * Return: void
4159  */
4160 static void
4161 cmlb_clear_vtoc(struct cmlb_lun *cl, void *tg_cookie)
4162 {
4163 	struct dk_label		*dkl;
4164 
4165 	mutex_exit(CMLB_MUTEX(cl));
4166 	dkl = kmem_zalloc(sizeof (struct dk_label), KM_SLEEP);
4167 	mutex_enter(CMLB_MUTEX(cl));
4168 	/*
4169 	 * cmlb_set_vtoc uses these fields in order to figure out
4170 	 * where to overwrite the backup labels
4171 	 */
4172 	dkl->dkl_apc    = cl->cl_g.dkg_apc;
4173 	dkl->dkl_ncyl   = cl->cl_g.dkg_ncyl;
4174 	dkl->dkl_acyl   = cl->cl_g.dkg_acyl;
4175 	dkl->dkl_nhead  = cl->cl_g.dkg_nhead;
4176 	dkl->dkl_nsect  = cl->cl_g.dkg_nsect;
4177 	mutex_exit(CMLB_MUTEX(cl));
4178 	(void) cmlb_set_vtoc(cl, dkl, tg_cookie);
4179 	kmem_free(dkl, sizeof (struct dk_label));
4180 
4181 	mutex_enter(CMLB_MUTEX(cl));
4182 }
4183 
4184 /*
4185  *    Function: cmlb_write_label
4186  *
4187  * Description: This routine will validate and write the driver soft state vtoc
4188  *		contents to the device.
4189  *
4190  *   Arguments:
4191  *	cl		cmlb handle
4192  *
4193  *	tg_cookie	cookie from target driver to be passed back to target
4194  *			driver when we call back to it through tg_ops.
4195  *
4196  *
4197  * Return Code: the code returned by cmlb_send_scsi_cmd()
4198  *		0
4199  *		EINVAL
4200  *		ENXIO
4201  *		ENOMEM
4202  */
4203 static int
4204 cmlb_write_label(struct cmlb_lun *cl, void *tg_cookie)
4205 {
4206 	struct dk_label	*dkl;
4207 	short		sum;
4208 	short		*sp;
4209 	int		i;
4210 	int		rval;
4211 
4212 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4213 	mutex_exit(CMLB_MUTEX(cl));
4214 	dkl = kmem_zalloc(sizeof (struct dk_label), KM_SLEEP);
4215 	mutex_enter(CMLB_MUTEX(cl));
4216 
4217 	bcopy(&cl->cl_vtoc, &dkl->dkl_vtoc, sizeof (struct dk_vtoc));
4218 	dkl->dkl_rpm	= cl->cl_g.dkg_rpm;
4219 	dkl->dkl_pcyl	= cl->cl_g.dkg_pcyl;
4220 	dkl->dkl_apc	= cl->cl_g.dkg_apc;
4221 	dkl->dkl_intrlv = cl->cl_g.dkg_intrlv;
4222 	dkl->dkl_ncyl	= cl->cl_g.dkg_ncyl;
4223 	dkl->dkl_acyl	= cl->cl_g.dkg_acyl;
4224 	dkl->dkl_nhead	= cl->cl_g.dkg_nhead;
4225 	dkl->dkl_nsect	= cl->cl_g.dkg_nsect;
4226 
4227 #if defined(_SUNOS_VTOC_8)
4228 	dkl->dkl_obs1	= cl->cl_g.dkg_obs1;
4229 	dkl->dkl_obs2	= cl->cl_g.dkg_obs2;
4230 	dkl->dkl_obs3	= cl->cl_g.dkg_obs3;
4231 	for (i = 0; i < NDKMAP; i++) {
4232 		dkl->dkl_map[i].dkl_cylno = cl->cl_map[i].dkl_cylno;
4233 		dkl->dkl_map[i].dkl_nblk  = cl->cl_map[i].dkl_nblk;
4234 	}
4235 	bcopy(cl->cl_asciilabel, dkl->dkl_asciilabel, LEN_DKL_ASCII);
4236 #elif defined(_SUNOS_VTOC_16)
4237 	dkl->dkl_skew	= cl->cl_dkg_skew;
4238 #else
4239 #error "No VTOC format defined."
4240 #endif
4241 
4242 	dkl->dkl_magic			= DKL_MAGIC;
4243 	dkl->dkl_write_reinstruct	= cl->cl_g.dkg_write_reinstruct;
4244 	dkl->dkl_read_reinstruct	= cl->cl_g.dkg_read_reinstruct;
4245 
4246 	/* Construct checksum for the new disk label */
4247 	sum = 0;
4248 	sp = (short *)dkl;
4249 	i = sizeof (struct dk_label) / sizeof (short);
4250 	while (i--) {
4251 		sum ^= *sp++;
4252 	}
4253 	dkl->dkl_cksum = sum;
4254 
4255 	mutex_exit(CMLB_MUTEX(cl));
4256 
4257 	rval = cmlb_set_vtoc(cl, dkl, tg_cookie);
4258 exit:
4259 	kmem_free(dkl, sizeof (struct dk_label));
4260 	mutex_enter(CMLB_MUTEX(cl));
4261 	return (rval);
4262 }
4263 
4264 static int
4265 cmlb_dkio_set_efi(struct cmlb_lun *cl, dev_t dev, caddr_t arg, int flag,
4266     void *tg_cookie)
4267 {
4268 	dk_efi_t	user_efi;
4269 	int		rval = 0;
4270 	void		*buffer;
4271 	diskaddr_t	tgt_lba;
4272 	boolean_t	internal;
4273 
4274 	if (ddi_copyin(arg, &user_efi, sizeof (dk_efi_t), flag))
4275 		return (EFAULT);
4276 
4277 	internal = ((cl->cl_alter_behavior & (CMLB_INTERNAL_MINOR_NODES)) != 0);
4278 
4279 	user_efi.dki_data = (void *)(uintptr_t)user_efi.dki_data_64;
4280 
4281 	buffer = kmem_alloc(user_efi.dki_length, KM_SLEEP);
4282 	if (ddi_copyin(user_efi.dki_data, buffer, user_efi.dki_length, flag)) {
4283 		rval = EFAULT;
4284 	} else {
4285 		/*
4286 		 * let's clear the vtoc labels and clear the softstate
4287 		 * vtoc.
4288 		 */
4289 		mutex_enter(CMLB_MUTEX(cl));
4290 		if (cl->cl_vtoc.v_sanity == VTOC_SANE) {
4291 			cmlb_dbg(CMLB_TRACE,  cl,
4292 			    "cmlb_dkio_set_efi: CLEAR VTOC\n");
4293 			if (cl->cl_label_from_media == CMLB_LABEL_VTOC)
4294 				cmlb_clear_vtoc(cl, tg_cookie);
4295 			bzero(&cl->cl_vtoc, sizeof (struct dk_vtoc));
4296 			mutex_exit(CMLB_MUTEX(cl));
4297 			ddi_remove_minor_node(CMLB_DEVINFO(cl), "h");
4298 			ddi_remove_minor_node(CMLB_DEVINFO(cl), "h,raw");
4299 			(void) cmlb_create_minor(CMLB_DEVINFO(cl), "wd",
4300 			    S_IFBLK,
4301 			    (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
4302 			    cl->cl_node_type, NULL, internal);
4303 			(void) cmlb_create_minor(CMLB_DEVINFO(cl), "wd,raw",
4304 			    S_IFCHR,
4305 			    (CMLBUNIT(dev) << CMLBUNIT_SHIFT) | WD_NODE,
4306 			    cl->cl_node_type, NULL, internal);
4307 		} else
4308 			mutex_exit(CMLB_MUTEX(cl));
4309 
4310 		tgt_lba = user_efi.dki_lba;
4311 
4312 		mutex_enter(CMLB_MUTEX(cl));
4313 		if ((cmlb_check_update_blockcount(cl, tg_cookie) != 0) ||
4314 		    (cl->cl_tgt_blocksize == 0)) {
4315 			kmem_free(buffer, user_efi.dki_length);
4316 			mutex_exit(CMLB_MUTEX(cl));
4317 			return (EINVAL);
4318 		}
4319 		if (cl->cl_tgt_blocksize != cl->cl_sys_blocksize)
4320 			tgt_lba = tgt_lba *
4321 			    cl->cl_tgt_blocksize / cl->cl_sys_blocksize;
4322 
4323 		mutex_exit(CMLB_MUTEX(cl));
4324 		rval = DK_TG_WRITE(cl, buffer, tgt_lba, user_efi.dki_length,
4325 		    tg_cookie);
4326 
4327 		if (rval == 0) {
4328 			mutex_enter(CMLB_MUTEX(cl));
4329 			cl->cl_f_geometry_is_valid = FALSE;
4330 			mutex_exit(CMLB_MUTEX(cl));
4331 		}
4332 	}
4333 	kmem_free(buffer, user_efi.dki_length);
4334 	return (rval);
4335 }
4336 
4337 /*
4338  *    Function: cmlb_dkio_get_mboot
4339  *
4340  * Description: This routine is the driver entry point for handling user
4341  *		requests to get the current device mboot (DKIOCGMBOOT)
4342  *
4343  *   Arguments:
4344  *	arg		pointer to user provided mboot structure specifying
4345  *			the current mboot.
4346  *
4347  *	flag		this argument is a pass through to ddi_copyxxx()
4348  *			directly from the mode argument of ioctl().
4349  *
4350  *	tg_cookie	cookie from target driver to be passed back to target
4351  *			driver when we call back to it through tg_ops.
4352  *
4353  * Return Code: 0
4354  *		EINVAL
4355  *		EFAULT
4356  *		ENXIO
4357  */
4358 static int
4359 cmlb_dkio_get_mboot(struct cmlb_lun *cl, caddr_t arg, int flag, void *tg_cookie)
4360 {
4361 	struct mboot	*mboot;
4362 	int		rval;
4363 	size_t		buffer_size;
4364 
4365 
4366 #if defined(_SUNOS_VTOC_8)
4367 	if ((!ISREMOVABLE(cl) && !ISHOTPLUGGABLE(cl)) || (arg == NULL)) {
4368 #elif defined(_SUNOS_VTOC_16)
4369 	if (arg == NULL) {
4370 #endif
4371 		return (EINVAL);
4372 	}
4373 
4374 	/*
4375 	 * Read the mboot block, located at absolute block 0 on the target.
4376 	 */
4377 	buffer_size = sizeof (struct mboot);
4378 
4379 	cmlb_dbg(CMLB_TRACE,  cl,
4380 	    "cmlb_dkio_get_mboot: allocation size: 0x%x\n", buffer_size);
4381 
4382 	mboot = kmem_zalloc(buffer_size, KM_SLEEP);
4383 	if ((rval = DK_TG_READ(cl, mboot, 0, buffer_size, tg_cookie)) == 0) {
4384 		if (ddi_copyout(mboot, (void *)arg,
4385 		    sizeof (struct mboot), flag) != 0) {
4386 			rval = EFAULT;
4387 		}
4388 	}
4389 	kmem_free(mboot, buffer_size);
4390 	return (rval);
4391 }
4392 
4393 
4394 /*
4395  *    Function: cmlb_dkio_set_mboot
4396  *
4397  * Description: This routine is the driver entry point for handling user
4398  *		requests to validate and set the device master boot
4399  *		(DKIOCSMBOOT).
4400  *
4401  *   Arguments:
4402  *	arg		pointer to user provided mboot structure used to set the
4403  *			master boot.
4404  *
4405  *	flag		this argument is a pass through to ddi_copyxxx()
4406  *			directly from the mode argument of ioctl().
4407  *
4408  *	tg_cookie	cookie from target driver to be passed back to target
4409  *			driver when we call back to it through tg_ops.
4410  *
4411  * Return Code: 0
4412  *		EINVAL
4413  *		EFAULT
4414  *		ENXIO
4415  */
4416 static int
4417 cmlb_dkio_set_mboot(struct cmlb_lun *cl, caddr_t arg, int flag, void *tg_cookie)
4418 {
4419 	struct mboot	*mboot = NULL;
4420 	int		rval;
4421 	ushort_t	magic;
4422 
4423 
4424 	ASSERT(!mutex_owned(CMLB_MUTEX(cl)));
4425 
4426 #if defined(_SUNOS_VTOC_8)
4427 	if (!ISREMOVABLE(cl) && !ISHOTPLUGGABLE(cl)) {
4428 		return (EINVAL);
4429 	}
4430 #endif
4431 
4432 	if (arg == NULL) {
4433 		return (EINVAL);
4434 	}
4435 
4436 	mboot = kmem_zalloc(sizeof (struct mboot), KM_SLEEP);
4437 
4438 	if (ddi_copyin((const void *)arg, mboot,
4439 	    sizeof (struct mboot), flag) != 0) {
4440 		kmem_free(mboot, (size_t)(sizeof (struct mboot)));
4441 		return (EFAULT);
4442 	}
4443 
4444 	/* Is this really a master boot record? */
4445 	magic = LE_16(mboot->signature);
4446 	if (magic != MBB_MAGIC) {
4447 		kmem_free(mboot, (size_t)(sizeof (struct mboot)));
4448 		return (EINVAL);
4449 	}
4450 
4451 	rval = DK_TG_WRITE(cl, mboot, 0, cl->cl_sys_blocksize, tg_cookie);
4452 
4453 	mutex_enter(CMLB_MUTEX(cl));
4454 #if defined(__i386) || defined(__amd64)
4455 	if (rval == 0) {
4456 		/*
4457 		 * mboot has been written successfully.
4458 		 * update the fdisk and vtoc tables in memory
4459 		 */
4460 		rval = cmlb_update_fdisk_and_vtoc(cl, tg_cookie);
4461 		if ((cl->cl_f_geometry_is_valid == FALSE) || (rval != 0)) {
4462 			mutex_exit(CMLB_MUTEX(cl));
4463 			kmem_free(mboot, (size_t)(sizeof (struct mboot)));
4464 			return (rval);
4465 		}
4466 	}
4467 
4468 #ifdef __lock_lint
4469 	cmlb_setup_default_geometry(cl, tg_cookie);
4470 #endif
4471 
4472 #else
4473 	if (rval == 0) {
4474 		/*
4475 		 * mboot has been written successfully.
4476 		 * set up the default geometry and VTOC
4477 		 */
4478 		if (cl->cl_blockcount <= CMLB_EXTVTOC_LIMIT)
4479 			cmlb_setup_default_geometry(cl, tg_cookie);
4480 	}
4481 #endif
4482 	cl->cl_msglog_flag |= CMLB_ALLOW_2TB_WARN;
4483 	mutex_exit(CMLB_MUTEX(cl));
4484 	kmem_free(mboot, (size_t)(sizeof (struct mboot)));
4485 	return (rval);
4486 }
4487 
4488 
4489 /*
4490  *    Function: cmlb_setup_default_geometry
4491  *
4492  * Description: This local utility routine sets the default geometry as part of
4493  *		setting the device mboot.
4494  *
4495  *   Arguments:
4496  *	cl		driver soft state (unit) structure
4497  *
4498  *	tg_cookie	cookie from target driver to be passed back to target
4499  *			driver when we call back to it through tg_ops.
4500  *
4501  *
4502  * Note: This may be redundant with cmlb_build_default_label.
4503  */
4504 static void
4505 cmlb_setup_default_geometry(struct cmlb_lun *cl, void *tg_cookie)
4506 {
4507 	struct cmlb_geom	pgeom;
4508 	struct cmlb_geom	*pgeomp = &pgeom;
4509 	int			ret;
4510 	int			geom_base_cap = 1;
4511 
4512 
4513 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4514 
4515 	/* zero out the soft state geometry and partition table. */
4516 	bzero(&cl->cl_g, sizeof (struct dk_geom));
4517 	bzero(&cl->cl_vtoc, sizeof (struct dk_vtoc));
4518 	bzero(cl->cl_map, NDKMAP * (sizeof (struct dk_map)));
4519 
4520 	/*
4521 	 * For the rpm, we use the minimum for the disk.
4522 	 * For the head, cyl and number of sector per track,
4523 	 * if the capacity <= 1GB, head = 64, sect = 32.
4524 	 * else head = 255, sect 63
4525 	 * Note: the capacity should be equal to C*H*S values.
4526 	 * This will cause some truncation of size due to
4527 	 * round off errors. For CD-ROMs, this truncation can
4528 	 * have adverse side effects, so returning ncyl and
4529 	 * nhead as 1. The nsect will overflow for most of
4530 	 * CD-ROMs as nsect is of type ushort.
4531 	 */
4532 	if (cl->cl_alter_behavior & CMLB_FAKE_GEOM_LABEL_IOCTLS_VTOC8) {
4533 		/*
4534 		 * newfs currently can not handle 255 ntracks for SPARC
4535 		 * so get the geometry from target driver instead of coming up
4536 		 * with one based on capacity.
4537 		 */
4538 		mutex_exit(CMLB_MUTEX(cl));
4539 		ret = DK_TG_GETPHYGEOM(cl, pgeomp, tg_cookie);
4540 		mutex_enter(CMLB_MUTEX(cl));
4541 
4542 		if (ret  == 0) {
4543 			geom_base_cap = 0;
4544 		} else {
4545 			cmlb_dbg(CMLB_ERROR,  cl,
4546 			    "cmlb_setup_default_geometry: "
4547 			    "tg_getphygeom failed %d\n", ret);
4548 
4549 			/* do default setting, geometry based on capacity */
4550 		}
4551 	}
4552 
4553 	if (geom_base_cap) {
4554 		if (ISCD(cl)) {
4555 			cl->cl_g.dkg_ncyl = 1;
4556 			cl->cl_g.dkg_nhead = 1;
4557 			cl->cl_g.dkg_nsect = cl->cl_blockcount;
4558 		} else if (cl->cl_blockcount <= 0x1000) {
4559 			/* Needed for unlabeled SCSI floppies. */
4560 			cl->cl_g.dkg_nhead = 2;
4561 			cl->cl_g.dkg_ncyl = 80;
4562 			cl->cl_g.dkg_pcyl = 80;
4563 			cl->cl_g.dkg_nsect = cl->cl_blockcount / (2 * 80);
4564 		} else if (cl->cl_blockcount <= 0x200000) {
4565 			cl->cl_g.dkg_nhead = 64;
4566 			cl->cl_g.dkg_nsect = 32;
4567 			cl->cl_g.dkg_ncyl = cl->cl_blockcount / (64 * 32);
4568 		} else {
4569 			cl->cl_g.dkg_nhead = 255;
4570 
4571 			cl->cl_g.dkg_nsect = ((cl->cl_blockcount +
4572 			    (UINT16_MAX * 255 * 63) - 1) /
4573 			    (UINT16_MAX * 255 * 63)) * 63;
4574 
4575 			if (cl->cl_g.dkg_nsect == 0)
4576 				cl->cl_g.dkg_nsect = (UINT16_MAX / 63) * 63;
4577 
4578 			cl->cl_g.dkg_ncyl = cl->cl_blockcount /
4579 			    (255 * cl->cl_g.dkg_nsect);
4580 		}
4581 
4582 		cl->cl_g.dkg_acyl = 0;
4583 		cl->cl_g.dkg_bcyl = 0;
4584 		cl->cl_g.dkg_intrlv = 1;
4585 		cl->cl_g.dkg_rpm = 200;
4586 		if (cl->cl_g.dkg_pcyl == 0)
4587 			cl->cl_g.dkg_pcyl = cl->cl_g.dkg_ncyl +
4588 			    cl->cl_g.dkg_acyl;
4589 	} else {
4590 		cl->cl_g.dkg_ncyl = (short)pgeomp->g_ncyl;
4591 		cl->cl_g.dkg_acyl = pgeomp->g_acyl;
4592 		cl->cl_g.dkg_nhead = pgeomp->g_nhead;
4593 		cl->cl_g.dkg_nsect = pgeomp->g_nsect;
4594 		cl->cl_g.dkg_intrlv = pgeomp->g_intrlv;
4595 		cl->cl_g.dkg_rpm = pgeomp->g_rpm;
4596 		cl->cl_g.dkg_pcyl = cl->cl_g.dkg_ncyl + cl->cl_g.dkg_acyl;
4597 	}
4598 
4599 	cl->cl_g.dkg_read_reinstruct = 0;
4600 	cl->cl_g.dkg_write_reinstruct = 0;
4601 	cl->cl_solaris_size = cl->cl_g.dkg_ncyl *
4602 	    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect;
4603 
4604 	cl->cl_map['a'-'a'].dkl_cylno = 0;
4605 	cl->cl_map['a'-'a'].dkl_nblk = cl->cl_solaris_size;
4606 
4607 	cl->cl_map['c'-'a'].dkl_cylno = 0;
4608 	cl->cl_map['c'-'a'].dkl_nblk = cl->cl_solaris_size;
4609 
4610 	cl->cl_vtoc.v_part[2].p_tag   = V_BACKUP;
4611 	cl->cl_vtoc.v_part[2].p_flag  = V_UNMNT;
4612 	cl->cl_vtoc.v_nparts = V_NUMPAR;
4613 	cl->cl_vtoc.v_version = V_VERSION;
4614 	(void) sprintf((char *)cl->cl_asciilabel, "DEFAULT cyl %d alt %d"
4615 	    " hd %d sec %d", cl->cl_g.dkg_ncyl, cl->cl_g.dkg_acyl,
4616 	    cl->cl_g.dkg_nhead, cl->cl_g.dkg_nsect);
4617 
4618 	cl->cl_f_geometry_is_valid = FALSE;
4619 }
4620 
4621 
4622 #if defined(__i386) || defined(__amd64)
4623 /*
4624  *    Function: cmlb_update_fdisk_and_vtoc
4625  *
4626  * Description: This local utility routine updates the device fdisk and vtoc
4627  *		as part of setting the device mboot.
4628  *
4629  *   Arguments:
4630  *	cl		driver soft state (unit) structure
4631  *
4632  *	tg_cookie	cookie from target driver to be passed back to target
4633  *			driver when we call back to it through tg_ops.
4634  *
4635  *
4636  * Return Code: 0 for success or errno-type return code.
4637  *
4638  *    Note:x86: This looks like a duplicate of cmlb_validate_geometry(), but
4639  *		these did exist separately in x86 sd.c.
4640  */
4641 static int
4642 cmlb_update_fdisk_and_vtoc(struct cmlb_lun *cl, void *tg_cookie)
4643 {
4644 	int		count;
4645 	int		label_rc = 0;
4646 	int		fdisk_rval;
4647 	diskaddr_t	capacity;
4648 
4649 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4650 
4651 	if (cmlb_check_update_blockcount(cl, tg_cookie) != 0)
4652 		return (EINVAL);
4653 
4654 #if defined(_SUNOS_VTOC_16)
4655 	/*
4656 	 * Set up the "whole disk" fdisk partition; this should always
4657 	 * exist, regardless of whether the disk contains an fdisk table
4658 	 * or vtoc.
4659 	 */
4660 	cl->cl_map[P0_RAW_DISK].dkl_cylno = 0;
4661 	cl->cl_map[P0_RAW_DISK].dkl_nblk = cl->cl_blockcount;
4662 #endif	/* defined(_SUNOS_VTOC_16) */
4663 
4664 	/*
4665 	 * copy the lbasize and capacity so that if they're
4666 	 * reset while we're not holding the CMLB_MUTEX(cl), we will
4667 	 * continue to use valid values after the CMLB_MUTEX(cl) is
4668 	 * reacquired.
4669 	 */
4670 	capacity = cl->cl_blockcount;
4671 
4672 	/*
4673 	 * refresh the logical and physical geometry caches.
4674 	 * (data from mode sense format/rigid disk geometry pages,
4675 	 * and scsi_ifgetcap("geometry").
4676 	 */
4677 	cmlb_resync_geom_caches(cl, capacity, tg_cookie);
4678 
4679 	/*
4680 	 * Only DIRECT ACCESS devices will have Scl labels.
4681 	 * CD's supposedly have a Scl label, too
4682 	 */
4683 	if (cl->cl_device_type == DTYPE_DIRECT || ISREMOVABLE(cl)) {
4684 		fdisk_rval = cmlb_read_fdisk(cl, capacity, tg_cookie);
4685 		if (fdisk_rval != 0) {
4686 			ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4687 			return (fdisk_rval);
4688 		}
4689 
4690 		if (cl->cl_solaris_size <= DK_LABEL_LOC) {
4691 			/*
4692 			 * Found fdisk table but no Solaris partition entry,
4693 			 * so don't call cmlb_uselabel() and don't create
4694 			 * a default label.
4695 			 */
4696 			label_rc = 0;
4697 			cl->cl_f_geometry_is_valid = TRUE;
4698 			goto no_solaris_partition;
4699 		}
4700 	} else if (capacity < 0) {
4701 		ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4702 		return (EINVAL);
4703 	}
4704 
4705 	/*
4706 	 * For Removable media We reach here if we have found a
4707 	 * SOLARIS PARTITION.
4708 	 * If cl_f_geometry_is_valid is FALSE it indicates that the SOLARIS
4709 	 * PARTITION has changed from the previous one, hence we will setup a
4710 	 * default VTOC in this case.
4711 	 */
4712 	if (cl->cl_f_geometry_is_valid == FALSE) {
4713 		/* if we get here it is writable */
4714 		/* we are called from SMBOOT, and after a write of fdisk */
4715 		cmlb_build_default_label(cl, tg_cookie);
4716 		label_rc = 0;
4717 	}
4718 
4719 no_solaris_partition:
4720 
4721 #if defined(_SUNOS_VTOC_16)
4722 	/*
4723 	 * If we have valid geometry, set up the remaining fdisk partitions.
4724 	 * Note that dkl_cylno is not used for the fdisk map entries, so
4725 	 * we set it to an entirely bogus value.
4726 	 */
4727 	for (count = 0; count < FD_NUMPART; count++) {
4728 		cl->cl_map[FDISK_P1 + count].dkl_cylno = UINT32_MAX;
4729 		cl->cl_map[FDISK_P1 + count].dkl_nblk =
4730 		    cl->cl_fmap[count].fmap_nblk;
4731 		cl->cl_offset[FDISK_P1 + count] =
4732 		    cl->cl_fmap[count].fmap_start;
4733 	}
4734 #endif
4735 
4736 	for (count = 0; count < NDKMAP; count++) {
4737 #if defined(_SUNOS_VTOC_8)
4738 		struct dk_map *lp  = &cl->cl_map[count];
4739 		cl->cl_offset[count] =
4740 		    cl->cl_g.dkg_nhead * cl->cl_g.dkg_nsect * lp->dkl_cylno;
4741 #elif defined(_SUNOS_VTOC_16)
4742 		struct dkl_partition *vp = &cl->cl_vtoc.v_part[count];
4743 		cl->cl_offset[count] = vp->p_start + cl->cl_solaris_offset;
4744 #else
4745 #error "No VTOC format defined."
4746 #endif
4747 	}
4748 
4749 	ASSERT(mutex_owned(CMLB_MUTEX(cl)));
4750 	return (label_rc);
4751 }
4752 #endif
4753 
4754 #if defined(__i386) || defined(__amd64)
4755 static int
4756 cmlb_dkio_get_virtgeom(struct cmlb_lun *cl, caddr_t arg, int flag)
4757 {
4758 	int err = 0;
4759 
4760 	/* Return the driver's notion of the media's logical geometry */
4761 	struct dk_geom	disk_geom;
4762 	struct dk_geom	*dkgp = &disk_geom;
4763 
4764 	mutex_enter(CMLB_MUTEX(cl));
4765 	/*
4766 	 * If there is no HBA geometry available, or
4767 	 * if the HBA returned us something that doesn't
4768 	 * really fit into an Int 13/function 8 geometry
4769 	 * result, just fail the ioctl.  See PSARC 1998/313.
4770 	 */
4771 	if (cl->cl_lgeom.g_nhead == 0 ||
4772 	    cl->cl_lgeom.g_nsect == 0 ||
4773 	    cl->cl_lgeom.g_ncyl > 1024) {
4774 		mutex_exit(CMLB_MUTEX(cl));
4775 		err = EINVAL;
4776 	} else {
4777 		dkgp->dkg_ncyl	= cl->cl_lgeom.g_ncyl;
4778 		dkgp->dkg_acyl	= cl->cl_lgeom.g_acyl;
4779 		dkgp->dkg_pcyl	= dkgp->dkg_ncyl + dkgp->dkg_acyl;
4780 		dkgp->dkg_nhead	= cl->cl_lgeom.g_nhead;
4781 		dkgp->dkg_nsect	= cl->cl_lgeom.g_nsect;
4782 
4783 		mutex_exit(CMLB_MUTEX(cl));
4784 		if (ddi_copyout(dkgp, (void *)arg,
4785 		    sizeof (struct dk_geom), flag)) {
4786 			err = EFAULT;
4787 		} else {
4788 			err = 0;
4789 		}
4790 	}
4791 	return (err);
4792 }
4793 #endif
4794 
4795 #if defined(__i386) || defined(__amd64)
4796 static int
4797 cmlb_dkio_get_phygeom(struct cmlb_lun *cl, caddr_t  arg, int flag)
4798 {
4799 	int err = 0;
4800 	diskaddr_t capacity;
4801 
4802 
4803 	/* Return the driver's notion of the media physical geometry */
4804 	struct dk_geom	disk_geom;
4805 	struct dk_geom	*dkgp = &disk_geom;
4806 
4807 	mutex_enter(CMLB_MUTEX(cl));
4808 
4809 	if (cl->cl_g.dkg_nhead != 0 &&
4810 	    cl->cl_g.dkg_nsect != 0) {
4811 		/*
4812 		 * We succeeded in getting a geometry, but
4813 		 * right now it is being reported as just the
4814 		 * Solaris fdisk partition, just like for
4815 		 * DKIOCGGEOM. We need to change that to be
4816 		 * correct for the entire disk now.
4817 		 */
4818 		bcopy(&cl->cl_g, dkgp, sizeof (*dkgp));
4819 		dkgp->dkg_acyl = 0;
4820 		dkgp->dkg_ncyl = cl->cl_blockcount /
4821 		    (dkgp->dkg_nhead * dkgp->dkg_nsect);
4822 	} else {
4823 		bzero(dkgp, sizeof (struct dk_geom));
4824 		/*
4825 		 * This disk does not have a Solaris VTOC
4826 		 * so we must present a physical geometry
4827 		 * that will remain consistent regardless
4828 		 * of how the disk is used. This will ensure
4829 		 * that the geometry does not change regardless
4830 		 * of the fdisk partition type (ie. EFI, FAT32,
4831 		 * Solaris, etc).
4832 		 */
4833 		if (ISCD(cl)) {
4834 			dkgp->dkg_nhead = cl->cl_pgeom.g_nhead;
4835 			dkgp->dkg_nsect = cl->cl_pgeom.g_nsect;
4836 			dkgp->dkg_ncyl = cl->cl_pgeom.g_ncyl;
4837 			dkgp->dkg_acyl = cl->cl_pgeom.g_acyl;
4838 		} else {
4839 			/*
4840 			 * Invalid cl_blockcount can generate invalid
4841 			 * dk_geom and may result in division by zero
4842 			 * system failure. Should make sure blockcount
4843 			 * is valid before using it here.
4844 			 */
4845 			if (cl->cl_blockcount == 0) {
4846 				mutex_exit(CMLB_MUTEX(cl));
4847 				err = EIO;
4848 				return (err);
4849 			}
4850 			/*
4851 			 * Refer to comments related to off-by-1 at the
4852 			 * header of this file
4853 			 */
4854 			if (cl->cl_alter_behavior & CMLB_OFF_BY_ONE)
4855 				capacity = cl->cl_blockcount - 1;
4856 			else
4857 				capacity = cl->cl_blockcount;
4858 
4859 			cmlb_convert_geometry(capacity, dkgp);
4860 			dkgp->dkg_acyl = 0;
4861 			dkgp->dkg_ncyl = capacity /
4862 			    (dkgp->dkg_nhead * dkgp->dkg_nsect);
4863 		}
4864 	}
4865 	dkgp->dkg_pcyl = dkgp->dkg_ncyl + dkgp->dkg_acyl;
4866 
4867 	mutex_exit(CMLB_MUTEX(cl));
4868 	if (ddi_copyout(dkgp, (void *)arg, sizeof (struct dk_geom), flag))
4869 		err = EFAULT;
4870 
4871 	return (err);
4872 }
4873 #endif
4874 
4875 #if defined(__i386) || defined(__amd64)
4876 static int
4877 cmlb_dkio_partinfo(struct cmlb_lun *cl, dev_t dev, caddr_t  arg, int flag)
4878 {
4879 	int err = 0;
4880 
4881 	/*
4882 	 * Return parameters describing the selected disk slice.
4883 	 * Note: this ioctl is for the intel platform only
4884 	 */
4885 	int part;
4886 
4887 	part = CMLBPART(dev);
4888 
4889 	mutex_enter(CMLB_MUTEX(cl));
4890 	/* don't check cl_solaris_size for pN */
4891 	if (part < P0_RAW_DISK && cl->cl_solaris_size == 0) {
4892 		err = EIO;
4893 		mutex_exit(CMLB_MUTEX(cl));
4894 	} else {
4895 		struct part_info p;
4896 
4897 		p.p_start = (daddr_t)cl->cl_offset[part];
4898 		p.p_length = (int)cl->cl_map[part].dkl_nblk;
4899 		mutex_exit(CMLB_MUTEX(cl));
4900 #ifdef _MULTI_DATAMODEL
4901 		switch (ddi_model_convert_from(flag & FMODELS)) {
4902 		case DDI_MODEL_ILP32:
4903 		{
4904 			struct part_info32 p32;
4905 
4906 			p32.p_start = (daddr32_t)p.p_start;
4907 			p32.p_length = p.p_length;
4908 			if (ddi_copyout(&p32, (void *)arg,
4909 			    sizeof (p32), flag))
4910 				err = EFAULT;
4911 			break;
4912 		}
4913 
4914 		case DDI_MODEL_NONE:
4915 		{
4916 			if (ddi_copyout(&p, (void *)arg, sizeof (p),
4917 			    flag))
4918 				err = EFAULT;
4919 			break;
4920 		}
4921 		}
4922 #else /* ! _MULTI_DATAMODEL */
4923 		if (ddi_copyout(&p, (void *)arg, sizeof (p), flag))
4924 			err = EFAULT;
4925 #endif /* _MULTI_DATAMODEL */
4926 	}
4927 	return (err);
4928 }
4929 static int
4930 cmlb_dkio_extpartinfo(struct cmlb_lun *cl, dev_t dev, caddr_t  arg, int flag)
4931 {
4932 	int err = 0;
4933 
4934 	/*
4935 	 * Return parameters describing the selected disk slice.
4936 	 * Note: this ioctl is for the intel platform only
4937 	 */
4938 	int part;
4939 
4940 	part = CMLBPART(dev);
4941 
4942 	mutex_enter(CMLB_MUTEX(cl));
4943 	/* don't check cl_solaris_size for pN */
4944 	if (part < P0_RAW_DISK && cl->cl_solaris_size == 0) {
4945 		err = EIO;
4946 		mutex_exit(CMLB_MUTEX(cl));
4947 	} else {
4948 		struct extpart_info p;
4949 
4950 		p.p_start = (diskaddr_t)cl->cl_offset[part];
4951 		p.p_length = (diskaddr_t)cl->cl_map[part].dkl_nblk;
4952 		mutex_exit(CMLB_MUTEX(cl));
4953 		if (ddi_copyout(&p, (void *)arg, sizeof (p), flag))
4954 			err = EFAULT;
4955 	}
4956 	return (err);
4957 }
4958 #endif
4959 
4960 int
4961 cmlb_prop_op(cmlb_handle_t cmlbhandle,
4962     dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
4963     char *name, caddr_t valuep, int *lengthp, int part, void *tg_cookie)
4964 {
4965 	struct cmlb_lun	*cl;
4966 	diskaddr_t	capacity;
4967 	uint32_t	lbasize;
4968 	enum		dp { DP_NBLOCKS, DP_BLKSIZE } dp;
4969 	int		callers_length;
4970 	caddr_t		buffer;
4971 	uint64_t	nblocks64;
4972 	uint_t		dblk;
4973 
4974 	/* Always fallback to ddi_prop_op... */
4975 	cl = (struct cmlb_lun *)cmlbhandle;
4976 	if (cl == NULL) {
4977 fallback:	return (ddi_prop_op(dev, dip, prop_op, mod_flags,
4978 		    name, valuep, lengthp));
4979 	}
4980 
4981 	/* Pick up capacity and blocksize information. */
4982 	capacity = cl->cl_blockcount;
4983 	if (capacity == 0)
4984 		goto fallback;
4985 	lbasize = cl->cl_tgt_blocksize;
4986 	if (lbasize == 0)
4987 		lbasize = DEV_BSIZE;	/* 0 -> DEV_BSIZE units */
4988 
4989 	/* Check for dynamic property of whole device. */
4990 	if (dev == DDI_DEV_T_ANY) {
4991 		/* Fallback to ddi_prop_op if we don't understand.  */
4992 		if (strcmp(name, "device-nblocks") == 0)
4993 			dp = DP_NBLOCKS;
4994 		else if (strcmp(name, "device-blksize") == 0)
4995 			dp = DP_BLKSIZE;
4996 		else
4997 			goto fallback;
4998 
4999 		/* get callers length, establish length of our dynamic prop */
5000 		callers_length = *lengthp;
5001 		if (dp == DP_NBLOCKS)
5002 			*lengthp = sizeof (uint64_t);
5003 		else if (dp == DP_BLKSIZE)
5004 			*lengthp = sizeof (uint32_t);
5005 
5006 		/* service request for the length of the property */
5007 		if (prop_op == PROP_LEN)
5008 			return (DDI_PROP_SUCCESS);
5009 
5010 		switch (prop_op) {
5011 		case PROP_LEN_AND_VAL_ALLOC:
5012 			if ((buffer = kmem_alloc(*lengthp,
5013 			    (mod_flags & DDI_PROP_CANSLEEP) ?
5014 			    KM_SLEEP : KM_NOSLEEP)) == NULL)
5015 				return (DDI_PROP_NO_MEMORY);
5016 			*(caddr_t *)valuep = buffer;	/* set callers buf */
5017 			break;
5018 
5019 		case PROP_LEN_AND_VAL_BUF:
5020 			/* the length of the prop and the request must match */
5021 			if (callers_length != *lengthp)
5022 				return (DDI_PROP_INVAL_ARG);
5023 			buffer = valuep;		/* get callers buf */
5024 			break;
5025 
5026 		default:
5027 			return (DDI_PROP_INVAL_ARG);
5028 		}
5029 
5030 		/* transfer the value into the buffer */
5031 		if (dp == DP_NBLOCKS)
5032 			*((uint64_t *)buffer) = capacity;
5033 		else if (dp == DP_BLKSIZE)
5034 			*((uint32_t *)buffer) = lbasize;
5035 
5036 		return (DDI_PROP_SUCCESS);
5037 	}
5038 
5039 	/*
5040 	 * Support dynamic size oriented properties of partition. Requests
5041 	 * issued under conditions where size is valid are passed to
5042 	 * ddi_prop_op_nblocks with the size information, otherwise the
5043 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
5044 	 */
5045 	if (!cmlb_is_valid(cmlbhandle))
5046 		goto fallback;
5047 
5048 	/* Get partition nblocks value. */
5049 	(void) cmlb_partinfo(cmlbhandle, part,
5050 	    (diskaddr_t *)&nblocks64, NULL, NULL, NULL, tg_cookie);
5051 
5052 	/*
5053 	 * Assume partition information is in DEV_BSIZE units, compute
5054 	 * divisor for size(9P) property representation.
5055 	 */
5056 	dblk = lbasize / DEV_BSIZE;
5057 
5058 	/* Now let ddi_prop_op_nblocks_blksize() handle the request. */
5059 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
5060 	    name, valuep, lengthp, nblocks64 / dblk, lbasize));
5061 }
5062