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