xref: /titanic_51/usr/src/uts/common/io/sata/impl/sata.c (revision 791a814c934fcd4deb13b26c1f116ff283272a0d)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 #include <sys/sata/sata_blacklist.h>
54 
55 /* Debug flags - defined in sata.h */
56 int	sata_debug_flags = 0;
57 int	sata_msg = 0;
58 
59 /*
60  * Flags enabling selected SATA HBA framework functionality
61  */
62 #define	SATA_ENABLE_QUEUING		1
63 #define	SATA_ENABLE_NCQ			2
64 #define	SATA_ENABLE_PROCESS_EVENTS	4
65 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
66 int sata_func_enable =
67 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
68 
69 /*
70  * Global variable setting default maximum queue depth (NCQ or TCQ)
71  * Note:minimum queue depth is 1
72  */
73 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
74 
75 /*
76  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
77  * initialization, using value from sata_max_queue_depth
78  * It is adjusted to minimum supported by the controller and by the device,
79  * if queueing is enabled.
80  */
81 static	int sata_current_max_qdepth;
82 
83 /*
84  * Global variable determining the default behavior after device hotpluggin.
85  * If non-zero, the hotplugged device is onlined (if possible) without explicit
86  * IOCTL request (AP_CONFIGURE).
87  * If zero, hotplugged device is identified, but not onlined.
88  * Enabling (AP_CONNECT) device port with an attached device does not result
89  * in device onlining regardless of the flag setting
90  */
91 int sata_auto_online = 0;
92 
93 #ifdef SATA_DEBUG
94 
95 #define	SATA_LOG_D(args)	sata_log args
96 uint64_t mbuf_count = 0;
97 uint64_t mbuffail_count = 0;
98 
99 sata_atapi_cmd_t sata_atapi_trace[64];
100 uint32_t sata_atapi_trace_index = 0;
101 int sata_atapi_trace_save = 1;
102 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
103 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
104     sata_save_atapi_trace(spx, count);
105 
106 #else
107 #define	SATA_LOG_D(args)	sata_trace_log args
108 #define	SATAATAPITRACE(spx, count)
109 #endif
110 
111 #if 0
112 static void
113 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
114 #endif
115 
116 #ifdef SATA_INJECT_FAULTS
117 
118 #define		SATA_INJECT_PKT_FAULT	1
119 uint32_t	sata_inject_fault = 0;
120 
121 uint32_t	sata_inject_fault_count = 0;
122 uint32_t	sata_inject_fault_pause_count = 0;
123 uint32_t	sata_fault_type = 0;
124 uint32_t	sata_fault_cmd = 0;
125 dev_info_t	*sata_fault_ctrl = NULL;
126 sata_device_t	sata_fault_device;
127 
128 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
129 
130 #endif
131 
132 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
133 
134 static char sata_rev_tag[] = {"1.44"};
135 
136 /*
137  * SATA cb_ops functions
138  */
139 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
140 static 	int sata_hba_close(dev_t, int, int, cred_t *);
141 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
142 
143 /*
144  * SCSA required entry points
145  */
146 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
147     scsi_hba_tran_t *, struct scsi_device *);
148 static	int sata_scsi_tgt_probe(struct scsi_device *,
149     int (*callback)(void));
150 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
151     scsi_hba_tran_t *, struct scsi_device *);
152 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
153 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
154 static 	int sata_scsi_reset(struct scsi_address *, int);
155 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
156 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
157 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
158     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
159     caddr_t);
160 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
161 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
162 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
163 
164 /*
165  * SATA HBA interface functions are defined in sata_hba.h header file
166  */
167 
168 /* Event processing functions */
169 static	void sata_event_daemon(void *);
170 static	void sata_event_thread_control(int);
171 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
172 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
173 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
174 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
175 static	void sata_process_port_failed_event(sata_hba_inst_t *,
176     sata_address_t *);
177 static	void sata_process_port_link_events(sata_hba_inst_t *,
178     sata_address_t *);
179 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
180     sata_address_t *);
181 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
182 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
183     sata_address_t *);
184 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
188 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
189 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
190     sata_address_t *);
191 static	void sata_process_device_autoonline(sata_hba_inst_t *,
192     sata_address_t *saddr);
193 
194 /*
195  * Local translation functions
196  */
197 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
198 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
199 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
200 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
201 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
202 static	int sata_txlt_read(sata_pkt_txlate_t *);
203 static	int sata_txlt_write(sata_pkt_txlate_t *);
204 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
205 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
206 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
207 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
208 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
209 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
210 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
211 
212 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
213 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
214 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
215 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
216 static	void sata_txlt_rw_completion(sata_pkt_t *);
217 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
218 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
219 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
220 static	struct scsi_extended_sense *sata_immediate_error_response(
221     sata_pkt_txlate_t *, int);
222 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
223 
224 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
225 static	void sata_txlt_atapi_completion(sata_pkt_t *);
226 
227 /*
228  * Local functions for ioctl
229  */
230 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
231 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
232     devctl_ap_state_t *);
233 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
234 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
235 static	dev_info_t *sata_devt_to_devinfo(dev_t);
236 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
237 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
238 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
239 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
240 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
241 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
242 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
243 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
244 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
245 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
246 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
247     sata_ioctl_data_t *, int mode);
248 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
249     sata_ioctl_data_t *, int mode);
250 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
251     sata_ioctl_data_t *, int mode);
252 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
253     sata_ioctl_data_t *, int mode);
254 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
255     sata_device_t *, sata_ioctl_data_t *, int mode);
256 
257 /*
258  * Local functions
259  */
260 static 	void sata_remove_hba_instance(dev_info_t *);
261 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
262 static 	void sata_probe_ports(sata_hba_inst_t *);
263 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
264 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
265 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
266 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
267 static	void sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
268 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
269 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
270 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
271     sata_drive_info_t *);
272 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
273     sata_address_t *);
274 static 	void sata_remove_target_node(sata_hba_inst_t *,
275     sata_address_t *);
276 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
277     struct scsi_address *, sata_device_t *);
278 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
279 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
280 static	void sata_pkt_free(sata_pkt_txlate_t *);
281 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
282     caddr_t, ddi_dma_attr_t *);
283 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
284 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
285 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
286     sata_device_t *);
287 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
288 static	void sata_reidentify_device(sata_pkt_txlate_t *);
289 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
290 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
291 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
292 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
293     ddi_dma_attr_t *);
294 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
295     sata_drive_info_t *);
296 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
297 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
298 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
299 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
300 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
301 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
302 static	int sata_set_drive_features(sata_hba_inst_t *,
303     sata_drive_info_t *, int flag);
304 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
305 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
306 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
307     uint8_t *);
308 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
309     struct scsi_inquiry *);
310 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
311 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
312 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
313 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
314 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
315 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
316     struct mode_cache_scsi3 *, int, int *, int *, int *);
317 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
318     struct mode_info_power_cond *, int, int *, int *, int *);
319 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
320     struct mode_info_excpt_page *, int, int *, int *, int *);
321 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
322     struct mode_acoustic_management *, int, int *, int *, int *);
323 
324 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
325 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
326     sata_hba_inst_t *);
327 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
328     sata_hba_inst_t *);
329 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
330     sata_hba_inst_t *);
331 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
332     sata_pkt_txlate_t *);
333 
334 static	void sata_set_arq_data(sata_pkt_t *);
335 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
336 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
337 static	uint8_t sata_get_standby_timer(uint8_t *timer);
338 
339 static	void sata_save_drive_settings(sata_drive_info_t *);
340 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
341 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
342 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
343 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
344 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
345     sata_drive_info_t *);
346 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
347     struct smart_data *);
348 static	int sata_smart_selftest_log(sata_hba_inst_t *,
349     sata_drive_info_t *,
350     struct smart_selftest_log *);
351 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
352     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
353 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
354     uint8_t *, uint8_t, uint8_t);
355 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
356     struct read_log_ext_directory *);
357 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
358 static	void sata_xlate_errors(sata_pkt_txlate_t *);
359 static	void sata_decode_device_error(sata_pkt_txlate_t *,
360     struct scsi_extended_sense *);
361 static	void sata_set_device_removed(dev_info_t *);
362 static	boolean_t sata_check_device_removed(dev_info_t *);
363 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
364 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
365     sata_drive_info_t *);
366 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
367     sata_drive_info_t *);
368 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
369 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
370 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
371 static  int sata_check_modser(char *, int);
372 
373 
374 
375 /*
376  * SATA Framework will ignore SATA HBA driver cb_ops structure and
377  * register following one with SCSA framework.
378  * Open & close are provided, so scsi framework will not use its own
379  */
380 static struct cb_ops sata_cb_ops = {
381 	sata_hba_open,			/* open */
382 	sata_hba_close,			/* close */
383 	nodev,				/* strategy */
384 	nodev,				/* print */
385 	nodev,				/* dump */
386 	nodev,				/* read */
387 	nodev,				/* write */
388 	sata_hba_ioctl,			/* ioctl */
389 	nodev,				/* devmap */
390 	nodev,				/* mmap */
391 	nodev,				/* segmap */
392 	nochpoll,			/* chpoll */
393 	ddi_prop_op,			/* cb_prop_op */
394 	0,				/* streamtab */
395 	D_NEW | D_MP,			/* cb_flag */
396 	CB_REV,				/* rev */
397 	nodev,				/* aread */
398 	nodev				/* awrite */
399 };
400 
401 
402 extern struct mod_ops mod_miscops;
403 extern uchar_t	scsi_cdb_size[];
404 
405 static struct modlmisc modlmisc = {
406 	&mod_miscops,			/* Type of module */
407 	"SATA Module"			/* module name */
408 };
409 
410 
411 static struct modlinkage modlinkage = {
412 	MODREV_1,
413 	(void *)&modlmisc,
414 	NULL
415 };
416 
417 /*
418  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
419  * i.e. when scsi_pkt has not timeout specified.
420  */
421 static int sata_default_pkt_time = 60;	/* 60 seconds */
422 
423 /*
424  * Intermediate buffer device access attributes - they are required,
425  * but not necessarily used.
426  */
427 static ddi_device_acc_attr_t sata_acc_attr = {
428 	DDI_DEVICE_ATTR_V0,
429 	DDI_STRUCTURE_LE_ACC,
430 	DDI_STRICTORDER_ACC
431 };
432 
433 
434 /*
435  * Mutexes protecting structures in multithreaded operations.
436  * Because events are relatively rare, a single global mutex protecting
437  * data structures should be sufficient. To increase performance, add
438  * separate mutex per each sata port and use global mutex only to protect
439  * common data structures.
440  */
441 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
442 static	kmutex_t sata_log_mutex;	/* protects log */
443 
444 static 	char sata_log_buf[256];
445 
446 /*
447  * sata trace debug
448  */
449 static	sata_trace_rbuf_t *sata_debug_rbuf;
450 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
451 static	void sata_trace_dmsg_free(void);
452 static	void sata_trace_rbuf_alloc(void);
453 static	void sata_trace_rbuf_free(void);
454 
455 int	dmsg_ring_size = DMSG_RING_SIZE;
456 
457 /* Default write cache setting for SATA hard disks */
458 int	sata_write_cache = 1;		/* enabled */
459 
460 /* Default write cache setting for SATA ATAPI CD/DVD */
461 int	sata_atapicdvd_write_cache = 1; /* enabled */
462 
463 /* Default write cache setting for SATA ATAPI tape */
464 int	sata_atapitape_write_cache = 1; /* enabled */
465 
466 /* Default write cache setting for SATA ATAPI disk */
467 int	sata_atapidisk_write_cache = 1;	/* enabled */
468 
469 /*
470  * Linked list of HBA instances
471  */
472 static 	sata_hba_inst_t *sata_hba_list = NULL;
473 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
474 /*
475  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
476  * structure and in sata soft state.
477  */
478 
479 /*
480  * Event daemon related variables
481  */
482 static 	kmutex_t sata_event_mutex;
483 static 	kcondvar_t sata_event_cv;
484 static 	kthread_t *sata_event_thread = NULL;
485 static 	int sata_event_thread_terminate = 0;
486 static 	int sata_event_pending = 0;
487 static 	int sata_event_thread_active = 0;
488 extern 	pri_t minclsyspri;
489 
490 /*
491  * NCQ error recovery command
492  */
493 static const sata_cmd_t sata_rle_cmd = {
494 	SATA_CMD_REV,
495 	NULL,
496 	{
497 		SATA_DIR_READ
498 	},
499 	ATA_ADDR_LBA48,
500 	0,
501 	0,
502 	0,
503 	0,
504 	0,
505 	1,
506 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
507 	0,
508 	0,
509 	0,
510 	SATAC_READ_LOG_EXT,
511 	0,
512 	0,
513 	0,
514 };
515 
516 /*
517  * ATAPI error recovery CDB
518  */
519 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
520 	SCMD_REQUEST_SENSE,
521 	0,			/* Only fixed RQ format is supported */
522 	0,
523 	0,
524 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
525 	0
526 };
527 
528 
529 /* Warlock directives */
530 
531 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
532 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
533 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
534 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
535 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
536 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
537 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
538 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
539 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
540 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
541 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
542 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
543 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
544 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
545     sata_hba_inst::satahba_scsi_tran))
546 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
547 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
548 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
549 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
550 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
551     sata_hba_inst::satahba_event_flags))
552 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
553     sata_cport_info::cport_devp))
554 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
555 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
556 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
557     sata_cport_info::cport_dev_type))
558 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
559 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
560     sata_cport_info::cport_state))
561 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
562 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
563     sata_pmport_info::pmport_state))
564 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
565 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
566     sata_pmport_info::pmport_dev_type))
567 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
568 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
569     sata_pmport_info::pmport_sata_drive))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
571     sata_pmport_info::pmport_tgtnode_clean))
572 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
573     sata_pmport_info::pmport_event_flags))
574 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
575 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
576 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
577 #ifdef SATA_DEBUG
578 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
579 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
580 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
581 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
582 #endif
583 
584 /* End of warlock directives */
585 
586 /* ************** loadable module configuration functions ************** */
587 
588 int
589 _init()
590 {
591 	int rval;
592 
593 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
594 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
595 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
596 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
597 	sata_trace_rbuf_alloc();
598 	if ((rval = mod_install(&modlinkage)) != 0) {
599 #ifdef SATA_DEBUG
600 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
601 #endif
602 		sata_trace_rbuf_free();
603 		mutex_destroy(&sata_log_mutex);
604 		cv_destroy(&sata_event_cv);
605 		mutex_destroy(&sata_event_mutex);
606 		mutex_destroy(&sata_mutex);
607 	}
608 	return (rval);
609 }
610 
611 int
612 _fini()
613 {
614 	int rval;
615 
616 	if ((rval = mod_remove(&modlinkage)) != 0)
617 		return (rval);
618 
619 	sata_trace_rbuf_free();
620 	mutex_destroy(&sata_log_mutex);
621 	cv_destroy(&sata_event_cv);
622 	mutex_destroy(&sata_event_mutex);
623 	mutex_destroy(&sata_mutex);
624 	return (rval);
625 }
626 
627 int
628 _info(struct modinfo *modinfop)
629 {
630 	return (mod_info(&modlinkage, modinfop));
631 }
632 
633 
634 
635 /* ********************* SATA HBA entry points ********************* */
636 
637 
638 /*
639  * Called by SATA HBA from _init().
640  * Registers HBA driver instance/sata framework pair with scsi framework, by
641  * calling scsi_hba_init().
642  *
643  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
644  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
645  * cb_ops pointer in SATA HBA driver dev_ops structure.
646  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
647  *
648  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
649  * driver.
650  */
651 int
652 sata_hba_init(struct modlinkage *modlp)
653 {
654 	int rval;
655 	struct dev_ops *hba_ops;
656 
657 	SATADBG1(SATA_DBG_HBA_IF, NULL,
658 	    "sata_hba_init: name %s \n",
659 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
660 	/*
661 	 * Fill-up cb_ops and dev_ops when necessary
662 	 */
663 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
664 	/*
665 	 * Provide pointer to SATA dev_ops
666 	 */
667 	hba_ops->devo_cb_ops = &sata_cb_ops;
668 
669 	/*
670 	 * Register SATA HBA with SCSI framework
671 	 */
672 	if ((rval = scsi_hba_init(modlp)) != 0) {
673 		SATADBG1(SATA_DBG_HBA_IF, NULL,
674 		    "sata_hba_init: scsi hba init failed\n", NULL);
675 		return (rval);
676 	}
677 
678 	return (0);
679 }
680 
681 
682 /* HBA attach stages */
683 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
684 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
685 #define	HBA_ATTACH_STAGE_SETUP		4
686 #define	HBA_ATTACH_STAGE_LINKED		8
687 
688 
689 /*
690  *
691  * Called from SATA HBA driver's attach routine to attach an instance of
692  * the HBA.
693  *
694  * For DDI_ATTACH command:
695  * sata_hba_inst structure is allocated here and initialized with pointers to
696  * SATA framework implementation of required scsi tran functions.
697  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
698  * to the soft structure (sata_hba_inst) allocated by SATA framework for
699  * SATA HBA instance related data.
700  * The scsi_tran's tran_hba_private field is used by SATA framework to
701  * store a pointer to per-HBA-instance of sata_hba_inst structure.
702  * The sata_hba_inst structure is cross-linked to scsi tran structure.
703  * Among other info, a pointer to sata_hba_tran structure is stored in
704  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
705  * linked together into the list, pointed to by sata_hba_list.
706  * On the first HBA instance attach the sata event thread is initialized.
707  * Attachment points are created for all SATA ports of the HBA being attached.
708  * All HBA instance's SATA ports are probed and type of plugged devices is
709  * determined. For each device of a supported type, a target node is created.
710  *
711  * DDI_SUCCESS is returned when attachment process is successful,
712  * DDI_FAILURE is returned otherwise.
713  *
714  * For DDI_RESUME command:
715  * Not implemented at this time (postponed until phase 2 of the development).
716  */
717 int
718 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
719     ddi_attach_cmd_t cmd)
720 {
721 	sata_hba_inst_t	*sata_hba_inst;
722 	scsi_hba_tran_t *scsi_tran = NULL;
723 	int hba_attach_state = 0;
724 	char taskq_name[MAXPATHLEN];
725 
726 	SATADBG3(SATA_DBG_HBA_IF, NULL,
727 	    "sata_hba_attach: node %s (%s%d)\n",
728 	    ddi_node_name(dip), ddi_driver_name(dip),
729 	    ddi_get_instance(dip));
730 
731 	if (cmd == DDI_RESUME) {
732 		/*
733 		 * Postponed until phase 2 of the development
734 		 */
735 		return (DDI_FAILURE);
736 	}
737 
738 	if (cmd != DDI_ATTACH) {
739 		return (DDI_FAILURE);
740 	}
741 
742 	/* cmd == DDI_ATTACH */
743 
744 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
745 		SATA_LOG_D((NULL, CE_WARN,
746 		    "sata_hba_attach: invalid sata_hba_tran"));
747 		return (DDI_FAILURE);
748 	}
749 	/*
750 	 * Allocate and initialize SCSI tran structure.
751 	 * SATA copy of tran_bus_config is provided to create port nodes.
752 	 */
753 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
754 	if (scsi_tran == NULL)
755 		return (DDI_FAILURE);
756 	/*
757 	 * Allocate soft structure for SATA HBA instance.
758 	 * There is a separate softstate for each HBA instance.
759 	 */
760 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
761 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
762 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
763 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
764 
765 	/*
766 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
767 	 * soft structure allocated by SATA framework for
768 	 * SATA HBA instance related data.
769 	 */
770 	scsi_tran->tran_hba_private	= sata_hba_inst;
771 	scsi_tran->tran_tgt_private	= NULL;
772 
773 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
774 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
775 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
776 
777 	scsi_tran->tran_start		= sata_scsi_start;
778 	scsi_tran->tran_reset		= sata_scsi_reset;
779 	scsi_tran->tran_abort		= sata_scsi_abort;
780 	scsi_tran->tran_getcap		= sata_scsi_getcap;
781 	scsi_tran->tran_setcap		= sata_scsi_setcap;
782 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
783 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
784 
785 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
786 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
787 
788 	scsi_tran->tran_reset_notify	= NULL;
789 	scsi_tran->tran_get_bus_addr	= NULL;
790 	scsi_tran->tran_quiesce		= NULL;
791 	scsi_tran->tran_unquiesce	= NULL;
792 	scsi_tran->tran_bus_reset	= NULL;
793 
794 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
795 	    scsi_tran, 0) != DDI_SUCCESS) {
796 #ifdef SATA_DEBUG
797 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
798 		    ddi_driver_name(dip), ddi_get_instance(dip));
799 #endif
800 		goto fail;
801 	}
802 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
803 
804 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
805 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
806 		    "sata", 1) != DDI_PROP_SUCCESS) {
807 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
808 			    "failed to create hba sata prop"));
809 			goto fail;
810 		}
811 	}
812 
813 	/*
814 	 * Save pointers in hba instance soft state.
815 	 */
816 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
817 	sata_hba_inst->satahba_tran = sata_tran;
818 	sata_hba_inst->satahba_dip = dip;
819 
820 	/*
821 	 * Create a task queue to handle emulated commands completion
822 	 * Use node name, dash, instance number as the queue name.
823 	 */
824 	taskq_name[0] = '\0';
825 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
826 	    sizeof (taskq_name));
827 	(void) snprintf(taskq_name + strlen(taskq_name),
828 	    sizeof (taskq_name) - strlen(taskq_name),
829 	    "-%d", DEVI(dip)->devi_instance);
830 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
831 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
832 	    TASKQ_DYNAMIC);
833 
834 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
835 
836 	/*
837 	 * Create events thread if not created yet.
838 	 */
839 	sata_event_thread_control(1);
840 
841 	/*
842 	 * Link this hba instance into the list.
843 	 */
844 	mutex_enter(&sata_mutex);
845 
846 	if (sata_hba_list == NULL) {
847 		/*
848 		 * The first instance of HBA is attached.
849 		 * Set current/active default maximum NCQ/TCQ queue depth for
850 		 * all SATA devices. It is done here and now, to eliminate the
851 		 * possibility of the dynamic, programatic modification of the
852 		 * queue depth via global (and public) sata_max_queue_depth
853 		 * variable (this would require special handling in HBA drivers)
854 		 */
855 		sata_current_max_qdepth = sata_max_queue_depth;
856 		if (sata_current_max_qdepth > 32)
857 			sata_current_max_qdepth = 32;
858 		else if (sata_current_max_qdepth < 1)
859 			sata_current_max_qdepth = 1;
860 	}
861 
862 	sata_hba_inst->satahba_next = NULL;
863 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
864 	if (sata_hba_list == NULL) {
865 		sata_hba_list = sata_hba_inst;
866 	}
867 	if (sata_hba_list_tail != NULL) {
868 		sata_hba_list_tail->satahba_next = sata_hba_inst;
869 	}
870 	sata_hba_list_tail = sata_hba_inst;
871 	mutex_exit(&sata_mutex);
872 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
873 
874 	/*
875 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
876 	 * SATA HBA driver should not use its own open/close entry points.
877 	 *
878 	 * Make sure that instance number doesn't overflow
879 	 * when forming minor numbers.
880 	 */
881 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
882 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
883 	    INST2DEVCTL(ddi_get_instance(dip)),
884 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
885 #ifdef SATA_DEBUG
886 		cmn_err(CE_WARN, "sata_hba_attach: "
887 		    "cannot create devctl minor node");
888 #endif
889 		goto fail;
890 	}
891 
892 
893 	/*
894 	 * Set-up kstats here, if necessary.
895 	 * (postponed until future phase of the development).
896 	 */
897 
898 	/*
899 	 * Indicate that HBA is attached. This will enable events processing
900 	 * for this HBA.
901 	 */
902 	sata_hba_inst->satahba_attached = 1;
903 	/*
904 	 * Probe controller ports. This operation will describe a current
905 	 * controller/port/multipliers/device configuration and will create
906 	 * attachment points.
907 	 * We may end-up with just a controller with no devices attached.
908 	 * For the ports with a supported device attached, device target nodes
909 	 * are created and devices are initialized.
910 	 */
911 	sata_probe_ports(sata_hba_inst);
912 
913 	return (DDI_SUCCESS);
914 
915 fail:
916 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
917 		(void) sata_remove_hba_instance(dip);
918 		if (sata_hba_list == NULL)
919 			sata_event_thread_control(0);
920 	}
921 
922 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
923 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
924 		taskq_destroy(sata_hba_inst->satahba_taskq);
925 	}
926 
927 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
928 		(void) scsi_hba_detach(dip);
929 
930 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
931 		mutex_destroy(&sata_hba_inst->satahba_mutex);
932 		kmem_free((void *)sata_hba_inst,
933 		    sizeof (struct sata_hba_inst));
934 		scsi_hba_tran_free(scsi_tran);
935 	}
936 
937 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
938 	    ddi_driver_name(dip), ddi_get_instance(dip));
939 
940 	return (DDI_FAILURE);
941 }
942 
943 
944 /*
945  * Called by SATA HBA from to detach an instance of the driver.
946  *
947  * For DDI_DETACH command:
948  * Free local structures allocated for SATA HBA instance during
949  * sata_hba_attach processing.
950  *
951  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
952  *
953  * For DDI_SUSPEND command:
954  * Not implemented at this time (postponed until phase 2 of the development)
955  * Returnd DDI_SUCCESS.
956  *
957  * When the last HBA instance is detached, the event daemon is terminated.
958  *
959  * NOTE: Port multiplier is supported.
960  */
961 int
962 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
963 {
964 	dev_info_t	*tdip;
965 	sata_hba_inst_t	*sata_hba_inst;
966 	scsi_hba_tran_t *scsi_hba_tran;
967 	sata_cport_info_t *cportinfo;
968 	sata_pmult_info_t *pminfo;
969 	sata_drive_info_t *sdinfo;
970 	sata_device_t	sdevice;
971 	int ncport, npmport;
972 
973 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
974 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
975 
976 	switch (cmd) {
977 	case DDI_DETACH:
978 
979 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
980 			return (DDI_FAILURE);
981 
982 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
983 		if (sata_hba_inst == NULL)
984 			return (DDI_FAILURE);
985 
986 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
987 			sata_hba_inst->satahba_attached = 1;
988 			return (DDI_FAILURE);
989 		}
990 
991 		/*
992 		 * Free all target nodes - at this point
993 		 * devices should be at least offlined
994 		 * otherwise scsi_hba_detach() should not be called.
995 		 */
996 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
997 		    ncport++) {
998 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
999 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1000 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1001 				if (sdinfo != NULL) {
1002 					tdip = sata_get_target_dip(dip,
1003 					    ncport, 0);
1004 					if (tdip != NULL) {
1005 						if (ndi_devi_offline(tdip,
1006 						    NDI_DEVI_REMOVE) !=
1007 						    NDI_SUCCESS) {
1008 							SATA_LOG_D((
1009 							    sata_hba_inst,
1010 							    CE_WARN,
1011 							    "sata_hba_detach: "
1012 							    "Target node not "
1013 							    "removed !"));
1014 							return (DDI_FAILURE);
1015 						}
1016 					}
1017 				}
1018 			} else { /* SATA_DTYPE_PMULT */
1019 				mutex_enter(&cportinfo->cport_mutex);
1020 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1021 
1022 				if (pminfo == NULL) {
1023 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1024 					    "sata_hba_detach: Port multiplier "
1025 					    "not ready yet!"));
1026 					mutex_exit(&cportinfo->cport_mutex);
1027 					return (DDI_FAILURE);
1028 				}
1029 
1030 				/*
1031 				 * Detach would fail if removal of any of the
1032 				 * target nodes is failed - albeit in that
1033 				 * case some of them may have been removed.
1034 				 */
1035 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1036 				    sata_hba_inst, ncport); npmport++) {
1037 					tdip = sata_get_target_dip(dip, ncport,
1038 					    npmport);
1039 					if (tdip != NULL) {
1040 						if (ndi_devi_offline(tdip,
1041 						    NDI_DEVI_REMOVE) !=
1042 						    NDI_SUCCESS) {
1043 							SATA_LOG_D((
1044 							    sata_hba_inst,
1045 							    CE_WARN,
1046 							    "sata_hba_detach: "
1047 							    "Target node not "
1048 							    "removed !"));
1049 							mutex_exit(&cportinfo->
1050 							    cport_mutex);
1051 							return (DDI_FAILURE);
1052 						}
1053 					}
1054 				}
1055 				mutex_exit(&cportinfo->cport_mutex);
1056 			}
1057 		}
1058 		/*
1059 		 * Disable sata event daemon processing for this HBA
1060 		 */
1061 		sata_hba_inst->satahba_attached = 0;
1062 
1063 		/*
1064 		 * Remove event daemon thread, if it is last HBA instance.
1065 		 */
1066 
1067 		mutex_enter(&sata_mutex);
1068 		if (sata_hba_list->satahba_next == NULL) {
1069 			mutex_exit(&sata_mutex);
1070 			sata_event_thread_control(0);
1071 			mutex_enter(&sata_mutex);
1072 		}
1073 		mutex_exit(&sata_mutex);
1074 
1075 		/* Remove this HBA instance from the HBA list */
1076 		sata_remove_hba_instance(dip);
1077 
1078 		/*
1079 		 * At this point there should be no target nodes attached.
1080 		 * Detach and destroy device and port info structures.
1081 		 */
1082 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1083 		    ncport++) {
1084 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1085 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1086 				sdinfo =
1087 				    cportinfo->cport_devp.cport_sata_drive;
1088 				if (sdinfo != NULL) {
1089 					/* Release device structure */
1090 					kmem_free(sdinfo,
1091 					    sizeof (sata_drive_info_t));
1092 				}
1093 				/* Release cport info */
1094 				mutex_destroy(&cportinfo->cport_mutex);
1095 				kmem_free(cportinfo,
1096 				    sizeof (sata_cport_info_t));
1097 			} else { /* SATA_DTYPE_PMULT */
1098 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1099 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1100 				sata_free_pmult(sata_hba_inst, &sdevice);
1101 			}
1102 		}
1103 
1104 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1105 
1106 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1107 
1108 		taskq_destroy(sata_hba_inst->satahba_taskq);
1109 
1110 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1111 		kmem_free((void *)sata_hba_inst,
1112 		    sizeof (struct sata_hba_inst));
1113 
1114 		return (DDI_SUCCESS);
1115 
1116 	case DDI_SUSPEND:
1117 		/*
1118 		 * Postponed until phase 2
1119 		 */
1120 		return (DDI_FAILURE);
1121 
1122 	default:
1123 		return (DDI_FAILURE);
1124 	}
1125 }
1126 
1127 
1128 /*
1129  * Called by an HBA drive from _fini() routine.
1130  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1131  */
1132 void
1133 sata_hba_fini(struct modlinkage *modlp)
1134 {
1135 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1136 	    "sata_hba_fini: name %s\n",
1137 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1138 
1139 	scsi_hba_fini(modlp);
1140 }
1141 
1142 
1143 /*
1144  * Default open and close routine for sata_hba framework.
1145  *
1146  */
1147 /*
1148  * Open devctl node.
1149  *
1150  * Returns:
1151  * 0 if node was open successfully, error code otherwise.
1152  *
1153  *
1154  */
1155 
1156 static int
1157 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1158 {
1159 #ifndef __lock_lint
1160 	_NOTE(ARGUNUSED(credp))
1161 #endif
1162 	int rv = 0;
1163 	dev_info_t *dip;
1164 	scsi_hba_tran_t *scsi_hba_tran;
1165 	sata_hba_inst_t	*sata_hba_inst;
1166 
1167 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1168 
1169 	if (otyp != OTYP_CHR)
1170 		return (EINVAL);
1171 
1172 	dip = sata_devt_to_devinfo(*devp);
1173 	if (dip == NULL)
1174 		return (ENXIO);
1175 
1176 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1177 		return (ENXIO);
1178 
1179 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1180 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1181 		return (ENXIO);
1182 
1183 	mutex_enter(&sata_mutex);
1184 	if (flags & FEXCL) {
1185 		if (sata_hba_inst->satahba_open_flag != 0) {
1186 			rv = EBUSY;
1187 		} else {
1188 			sata_hba_inst->satahba_open_flag =
1189 			    SATA_DEVCTL_EXOPENED;
1190 		}
1191 	} else {
1192 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1193 			rv = EBUSY;
1194 		} else {
1195 			sata_hba_inst->satahba_open_flag =
1196 			    SATA_DEVCTL_SOPENED;
1197 		}
1198 	}
1199 	mutex_exit(&sata_mutex);
1200 
1201 	return (rv);
1202 }
1203 
1204 
1205 /*
1206  * Close devctl node.
1207  * Returns:
1208  * 0 if node was closed successfully, error code otherwise.
1209  *
1210  */
1211 
1212 static int
1213 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1214 {
1215 #ifndef __lock_lint
1216 	_NOTE(ARGUNUSED(credp))
1217 	_NOTE(ARGUNUSED(flag))
1218 #endif
1219 	dev_info_t *dip;
1220 	scsi_hba_tran_t *scsi_hba_tran;
1221 	sata_hba_inst_t	*sata_hba_inst;
1222 
1223 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1224 
1225 	if (otyp != OTYP_CHR)
1226 		return (EINVAL);
1227 
1228 	dip = sata_devt_to_devinfo(dev);
1229 	if (dip == NULL)
1230 		return (ENXIO);
1231 
1232 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1233 		return (ENXIO);
1234 
1235 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1236 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1237 		return (ENXIO);
1238 
1239 	mutex_enter(&sata_mutex);
1240 	sata_hba_inst->satahba_open_flag = 0;
1241 	mutex_exit(&sata_mutex);
1242 	return (0);
1243 }
1244 
1245 
1246 
1247 /*
1248  * Standard IOCTL commands for SATA hotplugging.
1249  * Implemented DEVCTL_AP commands:
1250  * DEVCTL_AP_CONNECT
1251  * DEVCTL_AP_DISCONNECT
1252  * DEVCTL_AP_CONFIGURE
1253  * DEVCTL_UNCONFIGURE
1254  * DEVCTL_AP_CONTROL
1255  *
1256  * Commands passed to default ndi ioctl handler:
1257  * DEVCTL_DEVICE_GETSTATE
1258  * DEVCTL_DEVICE_ONLINE
1259  * DEVCTL_DEVICE_OFFLINE
1260  * DEVCTL_DEVICE_REMOVE
1261  * DEVCTL_DEVICE_INSERT
1262  * DEVCTL_BUS_GETSTATE
1263  *
1264  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1265  * if not.
1266  *
1267  * Returns:
1268  * 0 if successful,
1269  * error code if operation failed.
1270  *
1271  * Port Multiplier support is supported now.
1272  *
1273  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1274  */
1275 
1276 static int
1277 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1278     int *rvalp)
1279 {
1280 #ifndef __lock_lint
1281 	_NOTE(ARGUNUSED(credp))
1282 	_NOTE(ARGUNUSED(rvalp))
1283 #endif
1284 	int rv = 0;
1285 	int32_t	comp_port = -1;
1286 	dev_info_t *dip;
1287 	devctl_ap_state_t ap_state;
1288 	struct devctl_iocdata *dcp = NULL;
1289 	scsi_hba_tran_t *scsi_hba_tran;
1290 	sata_hba_inst_t *sata_hba_inst;
1291 	sata_device_t sata_device;
1292 	sata_cport_info_t *cportinfo;
1293 	int cport, pmport, qual;
1294 	int rval = SATA_SUCCESS;
1295 
1296 	dip = sata_devt_to_devinfo(dev);
1297 	if (dip == NULL)
1298 		return (ENXIO);
1299 
1300 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1301 		return (ENXIO);
1302 
1303 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1304 	if (sata_hba_inst == NULL)
1305 		return (ENXIO);
1306 
1307 	if (sata_hba_inst->satahba_tran == NULL)
1308 		return (ENXIO);
1309 
1310 	switch (cmd) {
1311 
1312 	case DEVCTL_DEVICE_GETSTATE:
1313 	case DEVCTL_DEVICE_ONLINE:
1314 	case DEVCTL_DEVICE_OFFLINE:
1315 	case DEVCTL_DEVICE_REMOVE:
1316 	case DEVCTL_BUS_GETSTATE:
1317 		/*
1318 		 * There may be more cases that we want to pass to default
1319 		 * handler rather than fail them.
1320 		 */
1321 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1322 	}
1323 
1324 	/* read devctl ioctl data */
1325 	if (cmd != DEVCTL_AP_CONTROL) {
1326 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1327 			return (EFAULT);
1328 
1329 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1330 		    -1) {
1331 			if (dcp)
1332 				ndi_dc_freehdl(dcp);
1333 			return (EINVAL);
1334 		}
1335 
1336 		/*
1337 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1338 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1339 		 */
1340 		cport = SCSI_TO_SATA_CPORT(comp_port);
1341 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1342 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1343 
1344 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1345 		    qual) != 0) {
1346 			ndi_dc_freehdl(dcp);
1347 			return (EINVAL);
1348 		}
1349 
1350 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1351 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1352 		    cport_mutex);
1353 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1354 			/*
1355 			 * Cannot process ioctl request now. Come back later.
1356 			 */
1357 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1358 			    cport_mutex);
1359 			ndi_dc_freehdl(dcp);
1360 			return (EBUSY);
1361 		}
1362 		/* Block event processing for this port */
1363 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1364 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1365 
1366 		sata_device.satadev_addr.cport = cport;
1367 		sata_device.satadev_addr.pmport = pmport;
1368 		sata_device.satadev_addr.qual = qual;
1369 		sata_device.satadev_rev = SATA_DEVICE_REV;
1370 	}
1371 
1372 	switch (cmd) {
1373 
1374 	case DEVCTL_AP_DISCONNECT:
1375 
1376 		/*
1377 		 * Normally, cfgadm sata plugin will try to offline
1378 		 * (unconfigure) device before this request. Nevertheless,
1379 		 * if a device is still configured, we need to
1380 		 * attempt to offline and unconfigure device first, and we will
1381 		 * deactivate the port regardless of the unconfigure
1382 		 * operation results.
1383 		 *
1384 		 */
1385 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1386 
1387 		break;
1388 
1389 	case DEVCTL_AP_UNCONFIGURE:
1390 
1391 		/*
1392 		 * The unconfigure operation uses generic nexus operation to
1393 		 * offline a device. It leaves a target device node attached.
1394 		 * and obviously sata_drive_info attached as well, because
1395 		 * from the hardware point of view nothing has changed.
1396 		 */
1397 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1398 		break;
1399 
1400 	case DEVCTL_AP_CONNECT:
1401 	{
1402 		/*
1403 		 * The sata cfgadm pluging will invoke this operation only if
1404 		 * port was found in the disconnect state (failed state
1405 		 * is also treated as the disconnected state).
1406 		 * If port activation is successful and a device is found
1407 		 * attached to the port, the initialization sequence is
1408 		 * executed to probe the port and attach
1409 		 * a device structure to a port structure. The device is not
1410 		 * set in configured state (system-wise) by this operation.
1411 		 */
1412 
1413 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1414 
1415 		break;
1416 	}
1417 
1418 	case DEVCTL_AP_CONFIGURE:
1419 	{
1420 		/*
1421 		 * A port may be in an active or shutdown state.
1422 		 * If port is in a failed state, operation is aborted.
1423 		 * If a port is in a shutdown state, sata_tran_port_activate()
1424 		 * is invoked prior to any other operation.
1425 		 *
1426 		 * Onlining the device involves creating a new target node.
1427 		 * If there is an old target node present (belonging to
1428 		 * previously removed device), the operation is aborted - the
1429 		 * old node has to be released and removed before configure
1430 		 * operation is attempted.
1431 		 */
1432 
1433 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1434 
1435 		break;
1436 	}
1437 
1438 	case DEVCTL_AP_GETSTATE:
1439 
1440 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1441 
1442 		ap_state.ap_last_change = (time_t)-1;
1443 		ap_state.ap_error_code = 0;
1444 		ap_state.ap_in_transition = 0;
1445 
1446 		/* Copy the return AP-state information to the user space */
1447 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1448 			rv = EFAULT;
1449 		}
1450 		break;
1451 
1452 	case DEVCTL_AP_CONTROL:
1453 	{
1454 		/*
1455 		 * Generic devctl for hardware specific functionality
1456 		 */
1457 		sata_ioctl_data_t	ioc;
1458 
1459 		ASSERT(dcp == NULL);
1460 
1461 		/* Copy in user ioctl data first */
1462 #ifdef _MULTI_DATAMODEL
1463 		if (ddi_model_convert_from(mode & FMODELS) ==
1464 		    DDI_MODEL_ILP32) {
1465 
1466 			sata_ioctl_data_32_t	ioc32;
1467 
1468 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1469 			    sizeof (ioc32), mode) != 0) {
1470 				rv = EFAULT;
1471 				break;
1472 			}
1473 			ioc.cmd 	= (uint_t)ioc32.cmd;
1474 			ioc.port	= (uint_t)ioc32.port;
1475 			ioc.get_size	= (uint_t)ioc32.get_size;
1476 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1477 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1478 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1479 		} else
1480 #endif /* _MULTI_DATAMODEL */
1481 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1482 		    mode) != 0) {
1483 			return (EFAULT);
1484 		}
1485 
1486 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1487 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1488 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1489 
1490 		/*
1491 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1492 		 * a 32-bit number.
1493 		 */
1494 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1495 			return (EINVAL);
1496 		}
1497 		/* validate address */
1498 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1499 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1500 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1501 
1502 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1503 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1504 		    cport, pmport, qual);
1505 
1506 		if (sata_validate_sata_address(sata_hba_inst, cport,
1507 		    pmport, qual) != 0)
1508 			return (EINVAL);
1509 
1510 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1511 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1512 		    cport_mutex);
1513 		/* Is the port locked by event processing daemon ? */
1514 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1515 			/*
1516 			 * Cannot process ioctl request now. Come back later
1517 			 */
1518 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1519 			    cport_mutex);
1520 			return (EBUSY);
1521 		}
1522 		/* Block event processing for this port */
1523 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1524 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1525 
1526 
1527 		sata_device.satadev_addr.cport = cport;
1528 		sata_device.satadev_addr.pmport = pmport;
1529 		sata_device.satadev_addr.qual = qual;
1530 		sata_device.satadev_rev = SATA_DEVICE_REV;
1531 
1532 		switch (ioc.cmd) {
1533 
1534 		case SATA_CFGA_RESET_PORT:
1535 			/*
1536 			 * There is no protection for configured device.
1537 			 */
1538 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1539 			break;
1540 
1541 		case SATA_CFGA_RESET_DEVICE:
1542 			/*
1543 			 * There is no protection for configured device.
1544 			 */
1545 			rv = sata_ioctl_reset_device(sata_hba_inst,
1546 			    &sata_device);
1547 			break;
1548 
1549 		case SATA_CFGA_RESET_ALL:
1550 			/*
1551 			 * There is no protection for configured devices.
1552 			 */
1553 			rv = sata_ioctl_reset_all(sata_hba_inst);
1554 			/*
1555 			 * We return here, because common return is for
1556 			 * a single port operation - we have already unlocked
1557 			 * all ports and no dc handle was allocated.
1558 			 */
1559 			return (rv);
1560 
1561 		case SATA_CFGA_PORT_DEACTIVATE:
1562 			/*
1563 			 * Arbitrarily unconfigure attached device, if any.
1564 			 * Even if the unconfigure fails, proceed with the
1565 			 * port deactivation.
1566 			 */
1567 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1568 
1569 			break;
1570 
1571 		case SATA_CFGA_PORT_ACTIVATE:
1572 
1573 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1574 			break;
1575 
1576 		case SATA_CFGA_PORT_SELF_TEST:
1577 
1578 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1579 			    &sata_device);
1580 			break;
1581 
1582 		case SATA_CFGA_GET_DEVICE_PATH:
1583 
1584 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1585 			    &sata_device, &ioc, mode);
1586 			break;
1587 
1588 		case SATA_CFGA_GET_AP_TYPE:
1589 
1590 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1591 			    &sata_device, &ioc, mode);
1592 			break;
1593 
1594 		case SATA_CFGA_GET_MODEL_INFO:
1595 
1596 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1597 			    &sata_device, &ioc, mode);
1598 			break;
1599 
1600 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1601 
1602 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1603 			    &sata_device, &ioc, mode);
1604 			break;
1605 
1606 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1607 
1608 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1609 			    &sata_device, &ioc, mode);
1610 			break;
1611 
1612 		default:
1613 			rv = EINVAL;
1614 			break;
1615 
1616 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1617 
1618 		break;
1619 	}
1620 
1621 	default:
1622 	{
1623 		/*
1624 		 * If we got here, we got an IOCTL that SATA HBA Framework
1625 		 * does not recognize. Pass ioctl to HBA driver, in case
1626 		 * it could process it.
1627 		 */
1628 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1629 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1630 
1631 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1632 		    "IOCTL 0x%2x not supported in SATA framework, "
1633 		    "passthrough to HBA", cmd);
1634 
1635 		if (sata_tran->sata_tran_ioctl == NULL) {
1636 			rv = EINVAL;
1637 			break;
1638 		}
1639 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1640 		if (rval != 0) {
1641 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1642 			    "IOCTL 0x%2x failed in HBA", cmd);
1643 			rv = rval;
1644 		}
1645 		break;
1646 	}
1647 
1648 	} /* End of main IOCTL switch */
1649 
1650 	if (dcp) {
1651 		ndi_dc_freehdl(dcp);
1652 	}
1653 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1654 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1655 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1656 
1657 	return (rv);
1658 }
1659 
1660 
1661 /*
1662  * Create error retrieval sata packet
1663  *
1664  * A sata packet is allocated and set-up to contain specified error retrieval
1665  * command and appropriate dma-able data buffer.
1666  * No association with any scsi packet is made and no callback routine is
1667  * specified.
1668  *
1669  * Returns a pointer to sata packet upon successfull packet creation.
1670  * Returns NULL, if packet cannot be created.
1671  */
1672 sata_pkt_t *
1673 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1674     int pkt_type)
1675 {
1676 	sata_hba_inst_t	*sata_hba_inst;
1677 	sata_pkt_txlate_t *spx;
1678 	sata_pkt_t *spkt;
1679 	sata_drive_info_t *sdinfo;
1680 
1681 	mutex_enter(&sata_mutex);
1682 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1683 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1684 		if (SATA_DIP(sata_hba_inst) == dip)
1685 			break;
1686 	}
1687 	mutex_exit(&sata_mutex);
1688 	ASSERT(sata_hba_inst != NULL);
1689 
1690 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1691 	if (sdinfo == NULL) {
1692 		sata_log(sata_hba_inst, CE_WARN,
1693 		    "sata: error recovery request for non-attached device at "
1694 		    "cport %d", sata_device->satadev_addr.cport);
1695 		return (NULL);
1696 	}
1697 
1698 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1699 	spx->txlt_sata_hba_inst = sata_hba_inst;
1700 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1701 	spkt = sata_pkt_alloc(spx, NULL);
1702 	if (spkt == NULL) {
1703 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1704 		return (NULL);
1705 	}
1706 	/* address is needed now */
1707 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1708 
1709 	switch (pkt_type) {
1710 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1711 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1712 			return (spkt);
1713 		break;
1714 
1715 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1716 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1717 			return (spkt);
1718 		break;
1719 
1720 	default:
1721 		break;
1722 	}
1723 
1724 	sata_pkt_free(spx);
1725 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1726 	return (NULL);
1727 
1728 }
1729 
1730 
1731 /*
1732  * Free error retrieval sata packet
1733  *
1734  * Free sata packet and any associated resources allocated previously by
1735  * sata_get_error_retrieval_pkt().
1736  *
1737  * Void return.
1738  */
1739 void
1740 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1741 {
1742 	sata_pkt_txlate_t *spx =
1743 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1744 
1745 	ASSERT(sata_pkt != NULL);
1746 
1747 	sata_free_local_buffer(spx);
1748 	sata_pkt_free(spx);
1749 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1750 
1751 }
1752 
1753 /*
1754  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1755  *
1756  * No association with any scsi packet is made and no callback routine is
1757  * specified.
1758  *
1759  * Returns a pointer to sata packet upon successfull packet creation.
1760  * Returns NULL, if packet cannot be created.
1761  *
1762  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1763  * only lower 32 bits are available currently.
1764  */
1765 sata_pkt_t *
1766 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1767     uint8_t regn, uint32_t regv, uint32_t type)
1768 {
1769 	sata_hba_inst_t	*sata_hba_inst;
1770 	sata_pkt_txlate_t *spx;
1771 	sata_pkt_t *spkt;
1772 	sata_cmd_t *scmd;
1773 
1774 	/* Only READ/WRITE commands are accepted. */
1775 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1776 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1777 
1778 	mutex_enter(&sata_mutex);
1779 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1780 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1781 		if (SATA_DIP(sata_hba_inst) == dip)
1782 			break;
1783 	}
1784 	mutex_exit(&sata_mutex);
1785 	ASSERT(sata_hba_inst != NULL);
1786 
1787 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1788 	spx->txlt_sata_hba_inst = sata_hba_inst;
1789 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1790 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1791 	if (spkt == NULL) {
1792 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1793 		return (NULL);
1794 	}
1795 
1796 	/*
1797 	 * NOTE: We need to send this command to the port multiplier,
1798 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1799 	 *
1800 	 * sata_device contains the address of actual target device, and the
1801 	 * pmport number in the command comes from the sata_device structure.
1802 	 */
1803 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1804 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1805 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1806 
1807 	/* Fill sata_pkt */
1808 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1809 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1810 	spkt->satapkt_time = 10; /* Timeout 10s */
1811 
1812 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1813 	scmd = &spkt->satapkt_cmd;
1814 	scmd->satacmd_features_reg = regn & 0xff;
1815 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1816 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1817 	scmd->satacmd_addr_type = 0;		/* N/A */
1818 
1819 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1820 
1821 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1822 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1823 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1824 		scmd->satacmd_flags.sata_special_regs = 1;
1825 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1826 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1827 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1828 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1829 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1830 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1831 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1832 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1833 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1834 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1835 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1836 	}
1837 
1838 	return (spkt);
1839 }
1840 
1841 /*
1842  * Free sata packet and any associated resources allocated previously by
1843  * sata_get_rdwr_pmult_pkt().
1844  *
1845  * Void return.
1846  */
1847 void
1848 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1849 {
1850 	sata_pkt_txlate_t *spx =
1851 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1852 
1853 	/* Free allocated resources */
1854 	sata_pkt_free(spx);
1855 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1856 }
1857 
1858 /*
1859  * Search a port multiplier in the blacklist and update the flags if a match
1860  * is found.
1861  *
1862  * Returns:
1863  * SATA_SUCCESS if any matched entry is found.
1864  * SATA_FAILURE if no matched entry is found.
1865  */
1866 int
1867 sata_check_pmult_blacklist(sata_device_t *sd)
1868 {
1869 	sata_pmult_bl_t *blp;
1870 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1871 		if (sd->satadev_gscr.gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1872 			continue;
1873 		if (sd->satadev_gscr.gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1874 			continue;
1875 		if (sd->satadev_gscr.gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1876 			continue;
1877 
1878 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1879 		sd->satadev_add_info = blp->bl_flags;
1880 		return (SATA_SUCCESS);
1881 	}
1882 	return (SATA_FAILURE);
1883 }
1884 
1885 /*
1886  * sata_name_child is for composing the name of the node
1887  * the format of the name is "target,0".
1888  */
1889 static int
1890 sata_name_child(dev_info_t *dip, char *name, int namelen)
1891 {
1892 	int target;
1893 
1894 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1895 	    DDI_PROP_DONTPASS, "target", -1);
1896 	if (target == -1)
1897 		return (DDI_FAILURE);
1898 	(void) snprintf(name, namelen, "%x,0", target);
1899 	return (DDI_SUCCESS);
1900 }
1901 
1902 
1903 
1904 /* ****************** SCSA required entry points *********************** */
1905 
1906 /*
1907  * Implementation of scsi tran_tgt_init.
1908  * sata_scsi_tgt_init() initializes scsi_device structure
1909  *
1910  * If successful, DDI_SUCCESS is returned.
1911  * DDI_FAILURE is returned if addressed device does not exist
1912  */
1913 
1914 static int
1915 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1916     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1917 {
1918 #ifndef __lock_lint
1919 	_NOTE(ARGUNUSED(hba_dip))
1920 	_NOTE(ARGUNUSED(tgt_dip))
1921 #endif
1922 	sata_device_t		sata_device;
1923 	sata_drive_info_t	*sdinfo;
1924 	struct sata_id		*sid;
1925 	sata_hba_inst_t		*sata_hba_inst;
1926 	char			model[SATA_ID_MODEL_LEN + 1];
1927 	char			fw[SATA_ID_FW_LEN + 1];
1928 	char			*vid, *pid;
1929 	int			i;
1930 
1931 	/*
1932 	 * Fail tran_tgt_init for .conf stub node
1933 	 */
1934 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1935 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1936 		ddi_set_name_addr(tgt_dip, NULL);
1937 		return (DDI_FAILURE);
1938 	}
1939 
1940 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1941 
1942 	/* Validate scsi device address */
1943 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1944 	    &sata_device) != 0)
1945 		return (DDI_FAILURE);
1946 
1947 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1948 	    sata_device.satadev_addr.cport)));
1949 
1950 	/* sata_device now contains a valid sata address */
1951 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1952 	if (sdinfo == NULL) {
1953 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1954 		    sata_device.satadev_addr.cport)));
1955 		return (DDI_FAILURE);
1956 	}
1957 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1958 	    sata_device.satadev_addr.cport)));
1959 
1960 	/*
1961 	 * Check if we need to create a legacy devid (i.e cmdk style) for
1962 	 * the target disks.
1963 	 *
1964 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
1965 	 * if we need to create cmdk-style devid for all the disk devices
1966 	 * attached to this controller. This property may have been set
1967 	 * from HBA driver's .conf file or by the HBA driver in its
1968 	 * attach(9F) function.
1969 	 */
1970 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1971 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1972 	    "use-cmdk-devid-format", 0) == 1)) {
1973 		/* register a legacy devid for this target node */
1974 		sata_target_devid_register(tgt_dip, sdinfo);
1975 	}
1976 
1977 
1978 	/*
1979 	 * 'Identify Device Data' does not always fit in standard SCSI
1980 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
1981 	 * of information.
1982 	 */
1983 	sid = &sdinfo->satadrv_id;
1984 #ifdef	_LITTLE_ENDIAN
1985 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
1986 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
1987 #else	/* _LITTLE_ENDIAN */
1988 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
1989 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
1990 #endif	/* _LITTLE_ENDIAN */
1991 	model[SATA_ID_MODEL_LEN] = 0;
1992 	fw[SATA_ID_FW_LEN] = 0;
1993 
1994 	/* split model into into vid/pid */
1995 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
1996 		if ((*pid == ' ') || (*pid == '\t'))
1997 			break;
1998 	if (i < SATA_ID_MODEL_LEN) {
1999 		vid = model;
2000 		*pid++ = 0;		/* terminate vid, establish pid */
2001 	} else {
2002 		vid = NULL;		/* vid will stay "ATA     " */
2003 		pid = model;		/* model is all pid */
2004 	}
2005 
2006 	if (vid)
2007 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2008 		    vid, strlen(vid));
2009 	if (pid)
2010 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2011 		    pid, strlen(pid));
2012 	(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2013 	    fw, strlen(fw));
2014 
2015 	return (DDI_SUCCESS);
2016 }
2017 
2018 /*
2019  * Implementation of scsi tran_tgt_probe.
2020  * Probe target, by calling default scsi routine scsi_hba_probe()
2021  */
2022 static int
2023 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2024 {
2025 	sata_hba_inst_t *sata_hba_inst =
2026 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2027 	int rval;
2028 	uint32_t pm_cap;
2029 
2030 	rval = scsi_hba_probe(sd, callback);
2031 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2032 	    SATA_CAP_LOG_SENSE;
2033 
2034 	if (rval == SCSIPROBE_EXISTS) {
2035 		/*
2036 		 * Set property "pm-capable" on the target device node, so that
2037 		 * the target driver will not try to fetch scsi cycle counters
2038 		 * before enabling device power-management.
2039 		 */
2040 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2041 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2042 			sata_log(sata_hba_inst, CE_WARN,
2043 			    "SATA device at port %d: "
2044 			    "will not be power-managed ",
2045 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2046 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2047 			    "failure updating pm-capable property"));
2048 		}
2049 	}
2050 	return (rval);
2051 }
2052 
2053 /*
2054  * Implementation of scsi tran_tgt_free.
2055  * Release all resources allocated for scsi_device
2056  */
2057 static void
2058 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2059     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2060 {
2061 #ifndef __lock_lint
2062 	_NOTE(ARGUNUSED(hba_dip))
2063 #endif
2064 	sata_device_t		sata_device;
2065 	sata_drive_info_t	*sdinfo;
2066 	sata_hba_inst_t		*sata_hba_inst;
2067 	ddi_devid_t		devid;
2068 
2069 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2070 
2071 	/* Validate scsi device address */
2072 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2073 	    &sata_device) != 0)
2074 		return;
2075 
2076 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2077 	    sata_device.satadev_addr.cport)));
2078 
2079 	/* sata_device now should contain a valid sata address */
2080 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2081 	if (sdinfo == NULL) {
2082 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2083 		    sata_device.satadev_addr.cport)));
2084 		return;
2085 	}
2086 	/*
2087 	 * We did not allocate any resources in sata_scsi_tgt_init()
2088 	 * other than few properties.
2089 	 * Free them.
2090 	 */
2091 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2092 	    sata_device.satadev_addr.cport)));
2093 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2094 
2095 	/*
2096 	 * If devid was previously created but not freed up from
2097 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2098 	 */
2099 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2100 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2101 	    "use-cmdk-devid-format", 0) == 1) &&
2102 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2103 		ddi_devid_unregister(tgt_dip);
2104 		ddi_devid_free(devid);
2105 	}
2106 }
2107 
2108 /*
2109  * Implementation of scsi tran_init_pkt
2110  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2111  *
2112  * It seems that we should always allocate pkt, even if the address is
2113  * for non-existing device - just use some default for dma_attr.
2114  * The reason is that there is no way to communicate this to a caller here.
2115  * Subsequent call to sata_scsi_start may fail appropriately.
2116  * Simply returning NULL does not seem to discourage a target driver...
2117  *
2118  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2119  */
2120 static struct scsi_pkt *
2121 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2122     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2123     int (*callback)(caddr_t), caddr_t arg)
2124 {
2125 	sata_hba_inst_t *sata_hba_inst =
2126 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2127 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2128 	sata_device_t sata_device;
2129 	sata_drive_info_t *sdinfo;
2130 	sata_pkt_txlate_t *spx;
2131 	ddi_dma_attr_t cur_dma_attr;
2132 	int rval;
2133 	boolean_t new_pkt = TRUE;
2134 
2135 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2136 
2137 	/*
2138 	 * We need to translate the address, even if it could be
2139 	 * a bogus one, for a non-existing device
2140 	 */
2141 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2142 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2143 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2144 	sata_device.satadev_rev = SATA_DEVICE_REV;
2145 
2146 	if (pkt == NULL) {
2147 		/*
2148 		 * Have to allocate a brand new scsi packet.
2149 		 * We need to operate with auto request sense enabled.
2150 		 */
2151 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2152 		    MAX(statuslen, sizeof (struct scsi_arq_status)),
2153 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2154 
2155 		if (pkt == NULL)
2156 			return (NULL);
2157 
2158 		/* Fill scsi packet structure */
2159 		pkt->pkt_comp		= (void (*)())NULL;
2160 		pkt->pkt_time		= 0;
2161 		pkt->pkt_resid		= 0;
2162 		pkt->pkt_statistics	= 0;
2163 		pkt->pkt_reason		= 0;
2164 
2165 		/*
2166 		 * pkt_hba_private will point to sata pkt txlate structure
2167 		 */
2168 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2169 		bzero(spx, sizeof (sata_pkt_txlate_t));
2170 
2171 		spx->txlt_scsi_pkt = pkt;
2172 		spx->txlt_sata_hba_inst = sata_hba_inst;
2173 
2174 		/* Allocate sata_pkt */
2175 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2176 		if (spx->txlt_sata_pkt == NULL) {
2177 			/* Could not allocate sata pkt */
2178 			scsi_hba_pkt_free(ap, pkt);
2179 			return (NULL);
2180 		}
2181 		/* Set sata address */
2182 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2183 		    sata_device.satadev_addr;
2184 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2185 		    sata_device.satadev_rev;
2186 
2187 		if ((bp == NULL) || (bp->b_bcount == 0))
2188 			return (pkt);
2189 
2190 		spx->txlt_total_residue = bp->b_bcount;
2191 	} else {
2192 		new_pkt = FALSE;
2193 		/*
2194 		 * Packet was preallocated/initialized by previous call
2195 		 */
2196 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2197 
2198 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2199 			return (pkt);
2200 		}
2201 
2202 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2203 	}
2204 
2205 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2206 
2207 	/*
2208 	 * We use an adjusted version of the dma_attr, to account
2209 	 * for device addressing limitations.
2210 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2211 	 * happen when a device is not yet configured.
2212 	 */
2213 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2214 	    sata_device.satadev_addr.cport)));
2215 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2216 	    &spx->txlt_sata_pkt->satapkt_device);
2217 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2218 	sata_adjust_dma_attr(sdinfo,
2219 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2220 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2221 	    sata_device.satadev_addr.cport)));
2222 	/*
2223 	 * Allocate necessary DMA resources for the packet's data buffer
2224 	 * NOTE:
2225 	 * In case of read/write commands, DMA resource allocation here is
2226 	 * based on the premise that the transfer length specified in
2227 	 * the read/write scsi cdb will match exactly DMA resources -
2228 	 * returning correct packet residue is crucial.
2229 	 */
2230 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2231 	    &cur_dma_attr)) != DDI_SUCCESS) {
2232 		/*
2233 		 * If a DMA allocation request fails with
2234 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2235 		 * bioerror(9F) with bp and an error code of EFAULT.
2236 		 * If a DMA allocation request fails with
2237 		 * DDI_DMA_TOOBIG, indicate the error by calling
2238 		 * bioerror(9F) with bp and an error code of EINVAL.
2239 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2240 		 * Request may be repeated later - there is no real error.
2241 		 */
2242 		switch (rval) {
2243 		case DDI_DMA_NORESOURCES:
2244 			bioerror(bp, 0);
2245 			break;
2246 		case DDI_DMA_NOMAPPING:
2247 		case DDI_DMA_BADATTR:
2248 			bioerror(bp, EFAULT);
2249 			break;
2250 		case DDI_DMA_TOOBIG:
2251 		default:
2252 			bioerror(bp, EINVAL);
2253 			break;
2254 		}
2255 		if (new_pkt == TRUE) {
2256 			/*
2257 			 * Since this is a new packet, we can clean-up
2258 			 * everything
2259 			 */
2260 			sata_scsi_destroy_pkt(ap, pkt);
2261 		} else {
2262 			/*
2263 			 * This is a re-used packet. It will be target driver's
2264 			 * responsibility to eventually destroy it (which
2265 			 * will free allocated resources).
2266 			 * Here, we just "complete" the request, leaving
2267 			 * allocated resources intact, so the request may
2268 			 * be retried.
2269 			 */
2270 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2271 			sata_pkt_free(spx);
2272 		}
2273 		return (NULL);
2274 	}
2275 	/* Set number of bytes that are not yet accounted for */
2276 	pkt->pkt_resid = spx->txlt_total_residue;
2277 	ASSERT(pkt->pkt_resid >= 0);
2278 
2279 	return (pkt);
2280 }
2281 
2282 /*
2283  * Implementation of scsi tran_start.
2284  * Translate scsi cmd into sata operation and return status.
2285  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2286  * are supported.
2287  * For SATA hard disks, supported scsi commands:
2288  * SCMD_INQUIRY
2289  * SCMD_TEST_UNIT_READY
2290  * SCMD_START_STOP
2291  * SCMD_READ_CAPACITY
2292  * SCMD_REQUEST_SENSE
2293  * SCMD_LOG_SENSE_G1
2294  * SCMD_LOG_SELECT_G1
2295  * SCMD_MODE_SENSE	(specific pages)
2296  * SCMD_MODE_SENSE_G1	(specific pages)
2297  * SCMD_MODE_SELECT	(specific pages)
2298  * SCMD_MODE_SELECT_G1	(specific pages)
2299  * SCMD_SYNCHRONIZE_CACHE
2300  * SCMD_SYNCHRONIZE_CACHE_G1
2301  * SCMD_READ
2302  * SCMD_READ_G1
2303  * SCMD_READ_G4
2304  * SCMD_READ_G5
2305  * SCMD_WRITE
2306  * SCMD_WRITE_BUFFER
2307  * SCMD_WRITE_G1
2308  * SCMD_WRITE_G4
2309  * SCMD_WRITE_G5
2310  * SCMD_SEEK		(noop)
2311  * SCMD_SDIAG
2312  *
2313  * All other commands are rejected as unsupported.
2314  *
2315  * Returns:
2316  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2317  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2318  * a callback could be scheduled.
2319  * TRAN_BADPKT if cmd was directed to invalid address.
2320  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2321  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2322  * was removed and there was no callback specified in scsi pkt.
2323  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2324  * framework was busy performing some other operation(s).
2325  *
2326  */
2327 static int
2328 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2329 {
2330 	sata_hba_inst_t *sata_hba_inst =
2331 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2332 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2333 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2334 	sata_drive_info_t *sdinfo;
2335 	struct buf *bp;
2336 	uint8_t cport, pmport;
2337 	boolean_t dev_gone = B_FALSE;
2338 	int rval;
2339 
2340 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2341 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2342 
2343 	ASSERT(spx != NULL &&
2344 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2345 
2346 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2347 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2348 
2349 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2350 
2351 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2352 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2353 		if (sdinfo == NULL ||
2354 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2355 		    cport_tgtnode_clean == B_FALSE ||
2356 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2357 			dev_gone = B_TRUE;
2358 		}
2359 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2360 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2361 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2362 		    cport) == NULL) {
2363 			dev_gone = B_TRUE;
2364 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2365 		    pmport) == NULL) {
2366 			dev_gone = B_TRUE;
2367 		} else {
2368 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2369 			    cport, pmport)));
2370 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2371 			if (sdinfo == NULL ||
2372 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2373 			    pmport_tgtnode_clean == B_FALSE ||
2374 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2375 				dev_gone = B_TRUE;
2376 			}
2377 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2378 			    cport, pmport)));
2379 		}
2380 	}
2381 
2382 	if (dev_gone == B_TRUE) {
2383 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2384 		pkt->pkt_reason = CMD_DEV_GONE;
2385 		/*
2386 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2387 		 * only in callback function (for normal requests) and
2388 		 * in the dump code path.
2389 		 * So, if the callback is available, we need to do
2390 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2391 		 */
2392 		if (pkt->pkt_comp != NULL) {
2393 			/* scsi callback required */
2394 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2395 			    (task_func_t *)pkt->pkt_comp,
2396 			    (void *)pkt, TQ_SLEEP) == NULL)
2397 				/* Scheduling the callback failed */
2398 				return (TRAN_BUSY);
2399 			return (TRAN_ACCEPT);
2400 		}
2401 		/* No callback available */
2402 		return (TRAN_FATAL_ERROR);
2403 	}
2404 
2405 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2406 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2407 		rval = sata_txlt_atapi(spx);
2408 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2409 		    "sata_scsi_start atapi: rval %d\n", rval);
2410 		return (rval);
2411 	}
2412 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2413 
2414 	/*
2415 	 * Checking for power state, if it was on
2416 	 * STOPPED state, then the drive is not capable
2417 	 * of processing media access command.  And
2418 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2419 	 * in the function for different power state.
2420 	 */
2421 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2422 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2423 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2424 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2425 		    SD_SCSI_ASC_LU_NOT_READY));
2426 	}
2427 
2428 	/* ATA Disk commands processing starts here */
2429 
2430 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2431 
2432 	switch (pkt->pkt_cdbp[0]) {
2433 
2434 	case SCMD_INQUIRY:
2435 		/* Mapped to identify device */
2436 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2437 			bp_mapin(bp);
2438 		rval = sata_txlt_inquiry(spx);
2439 		break;
2440 
2441 	case SCMD_TEST_UNIT_READY:
2442 		/*
2443 		 * SAT "SATA to ATA Translation" doc specifies translation
2444 		 * to ATA CHECK POWER MODE.
2445 		 */
2446 		rval = sata_txlt_test_unit_ready(spx);
2447 		break;
2448 
2449 	case SCMD_START_STOP:
2450 		/* Mapping depends on the command */
2451 		rval = sata_txlt_start_stop_unit(spx);
2452 		break;
2453 
2454 	case SCMD_READ_CAPACITY:
2455 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2456 			bp_mapin(bp);
2457 		rval = sata_txlt_read_capacity(spx);
2458 		break;
2459 
2460 	case SCMD_REQUEST_SENSE:
2461 		/*
2462 		 * Always No Sense, since we force ARQ
2463 		 */
2464 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2465 			bp_mapin(bp);
2466 		rval = sata_txlt_request_sense(spx);
2467 		break;
2468 
2469 	case SCMD_LOG_SENSE_G1:
2470 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2471 			bp_mapin(bp);
2472 		rval = sata_txlt_log_sense(spx);
2473 		break;
2474 
2475 	case SCMD_LOG_SELECT_G1:
2476 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2477 			bp_mapin(bp);
2478 		rval = sata_txlt_log_select(spx);
2479 		break;
2480 
2481 	case SCMD_MODE_SENSE:
2482 	case SCMD_MODE_SENSE_G1:
2483 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2484 			bp_mapin(bp);
2485 		rval = sata_txlt_mode_sense(spx);
2486 		break;
2487 
2488 
2489 	case SCMD_MODE_SELECT:
2490 	case SCMD_MODE_SELECT_G1:
2491 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2492 			bp_mapin(bp);
2493 		rval = sata_txlt_mode_select(spx);
2494 		break;
2495 
2496 	case SCMD_SYNCHRONIZE_CACHE:
2497 	case SCMD_SYNCHRONIZE_CACHE_G1:
2498 		rval = sata_txlt_synchronize_cache(spx);
2499 		break;
2500 
2501 	case SCMD_READ:
2502 	case SCMD_READ_G1:
2503 	case SCMD_READ_G4:
2504 	case SCMD_READ_G5:
2505 		rval = sata_txlt_read(spx);
2506 		break;
2507 	case SCMD_WRITE_BUFFER:
2508 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2509 			bp_mapin(bp);
2510 		rval = sata_txlt_write_buffer(spx);
2511 		break;
2512 
2513 	case SCMD_WRITE:
2514 	case SCMD_WRITE_G1:
2515 	case SCMD_WRITE_G4:
2516 	case SCMD_WRITE_G5:
2517 		rval = sata_txlt_write(spx);
2518 		break;
2519 
2520 	case SCMD_SEEK:
2521 		rval = sata_txlt_nodata_cmd_immediate(spx);
2522 		break;
2523 
2524 		/* Other cases will be filed later */
2525 		/* postponed until phase 2 of the development */
2526 	default:
2527 		rval = sata_txlt_invalid_command(spx);
2528 		break;
2529 	}
2530 
2531 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2532 	    "sata_scsi_start: rval %d\n", rval);
2533 
2534 	return (rval);
2535 }
2536 
2537 /*
2538  * Implementation of scsi tran_abort.
2539  * Abort specific pkt or all packets.
2540  *
2541  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2542  *
2543  * May be called from an interrupt level.
2544  */
2545 static int
2546 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2547 {
2548 	sata_hba_inst_t *sata_hba_inst =
2549 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2550 	sata_device_t	sata_device;
2551 	sata_pkt_t	*sata_pkt;
2552 
2553 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2554 	    "sata_scsi_abort: %s at target: 0x%x\n",
2555 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2556 
2557 	/* Validate address */
2558 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2559 		/* Invalid address */
2560 		return (0);
2561 
2562 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2563 	    sata_device.satadev_addr.cport)));
2564 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2565 		/* invalid address */
2566 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2567 		    sata_device.satadev_addr.cport)));
2568 		return (0);
2569 	}
2570 	if (scsi_pkt == NULL) {
2571 		/*
2572 		 * Abort all packets.
2573 		 * Although we do not have specific packet, we still need
2574 		 * dummy packet structure to pass device address to HBA.
2575 		 * Allocate one, without sleeping. Fail if pkt cannot be
2576 		 * allocated.
2577 		 */
2578 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2579 		if (sata_pkt == NULL) {
2580 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2581 			    sata_device.satadev_addr.cport)));
2582 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2583 			    "could not allocate sata_pkt"));
2584 			return (0);
2585 		}
2586 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2587 		sata_pkt->satapkt_device = sata_device;
2588 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2589 	} else {
2590 		if (scsi_pkt->pkt_ha_private == NULL) {
2591 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2592 			    sata_device.satadev_addr.cport)));
2593 			return (0); /* Bad scsi pkt */
2594 		}
2595 		/* extract pointer to sata pkt */
2596 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2597 		    txlt_sata_pkt;
2598 	}
2599 
2600 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2601 	    sata_device.satadev_addr.cport)));
2602 	/* Send abort request to HBA */
2603 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2604 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2605 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2606 	    SATA_SUCCESS) {
2607 		if (scsi_pkt == NULL)
2608 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2609 		/* Success */
2610 		return (1);
2611 	}
2612 	/* Else, something did not go right */
2613 	if (scsi_pkt == NULL)
2614 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2615 	/* Failure */
2616 	return (0);
2617 }
2618 
2619 
2620 /*
2621  * Implementation of scsi tran_reset.
2622  * RESET_ALL request is translated into port reset.
2623  * RESET_TARGET requests is translated into a device reset,
2624  * RESET_LUN request is accepted only for LUN 0 and translated into
2625  * device reset.
2626  * The target reset should cause all HBA active and queued packets to
2627  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2628  * the return. HBA should report reset event for the device.
2629  *
2630  * Returns 1 upon success, 0 upon failure.
2631  */
2632 static int
2633 sata_scsi_reset(struct scsi_address *ap, int level)
2634 {
2635 	sata_hba_inst_t	*sata_hba_inst =
2636 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2637 	sata_device_t	sata_device;
2638 	int		val;
2639 
2640 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2641 	    "sata_scsi_reset: level %d target: 0x%x\n",
2642 	    level, ap->a_target);
2643 
2644 	/* Validate address */
2645 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2646 	if (val == -1)
2647 		/* Invalid address */
2648 		return (0);
2649 
2650 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2651 	    sata_device.satadev_addr.cport)));
2652 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2653 		/* invalid address */
2654 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2655 		    sata_device.satadev_addr.cport)));
2656 		return (0);
2657 	}
2658 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2659 	    sata_device.satadev_addr.cport)));
2660 	if (level == RESET_ALL) {
2661 		/* port reset */
2662 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2663 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2664 		else
2665 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2666 
2667 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2668 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2669 			return (1);
2670 		else
2671 			return (0);
2672 
2673 	} else if (val == 0 &&
2674 	    (level == RESET_TARGET || level == RESET_LUN)) {
2675 		/* reset device (device attached) */
2676 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2677 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2678 			return (1);
2679 		else
2680 			return (0);
2681 	}
2682 	return (0);
2683 }
2684 
2685 
2686 /*
2687  * Implementation of scsi tran_getcap (get transport/device capabilities).
2688  * Supported capabilities for SATA hard disks:
2689  * auto-rqsense		(always supported)
2690  * tagged-qing		(supported if HBA supports it)
2691  * untagged-qing	(could be supported if disk supports it, but because
2692  *			 caching behavior allowing untagged queuing actually
2693  *			 results in reduced performance.  sd tries to throttle
2694  *			 back to only 3 outstanding commands, which may
2695  *			 work for real SCSI disks, but with read ahead
2696  *			 caching, having more than 1 outstanding command
2697  *			 results in cache thrashing.)
2698  * sector_size
2699  * dma_max
2700  * interconnect-type	(INTERCONNECT_SATA)
2701  *
2702  * Supported capabilities for ATAPI CD/DVD devices:
2703  * auto-rqsense		(always supported)
2704  * sector_size
2705  * dma_max
2706  * max-cdb-length
2707  * interconnect-type	(INTERCONNECT_SATA)
2708  *
2709  * Supported capabilities for ATAPI TAPE devices:
2710  * auto-rqsense		(always supported)
2711  * dma_max
2712  * max-cdb-length
2713  *
2714  * Supported capabilities for SATA ATAPI hard disks:
2715  * auto-rqsense		(always supported)
2716  * interconnect-type	(INTERCONNECT_SATA)
2717  * max-cdb-length
2718  *
2719  * Request for other capabilities is rejected as unsupported.
2720  *
2721  * Returns supported capability value, or -1 if capability is unsuppported or
2722  * the address is invalid - no device.
2723  */
2724 
2725 static int
2726 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2727 {
2728 
2729 	sata_hba_inst_t 	*sata_hba_inst =
2730 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2731 	sata_device_t		sata_device;
2732 	sata_drive_info_t	*sdinfo;
2733 	ddi_dma_attr_t		adj_dma_attr;
2734 	int 			rval;
2735 
2736 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2737 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2738 	    ap->a_target, cap);
2739 
2740 	/*
2741 	 * We want to process the capabilities on per port granularity.
2742 	 * So, we are specifically restricting ourselves to whom != 0
2743 	 * to exclude the controller wide handling.
2744 	 */
2745 	if (cap == NULL || whom == 0)
2746 		return (-1);
2747 
2748 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2749 		/* Invalid address */
2750 		return (-1);
2751 	}
2752 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2753 	    sata_device.satadev_addr.cport)));
2754 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2755 	    NULL) {
2756 		/* invalid address */
2757 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2758 		    sata_device.satadev_addr.cport)));
2759 		return (-1);
2760 	}
2761 
2762 	switch (scsi_hba_lookup_capstr(cap)) {
2763 	case SCSI_CAP_ARQ:
2764 		rval = 1;		/* ARQ supported, turned on */
2765 		break;
2766 
2767 	case SCSI_CAP_SECTOR_SIZE:
2768 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2769 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2770 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2771 			rval = SATA_ATAPI_SECTOR_SIZE;
2772 		else rval = -1;
2773 		break;
2774 
2775 	/*
2776 	 * untagged queuing cause a performance inversion because of
2777 	 * the way sd operates.  Because of this reason we do not
2778 	 * use it when available.
2779 	 */
2780 	case SCSI_CAP_UNTAGGED_QING:
2781 		if (sdinfo->satadrv_features_enabled &
2782 		    SATA_DEV_F_E_UNTAGGED_QING)
2783 			rval = 1;	/* Untagged queuing available */
2784 		else
2785 			rval = -1;	/* Untagged queuing not available */
2786 		break;
2787 
2788 	case SCSI_CAP_TAGGED_QING:
2789 		if ((sdinfo->satadrv_features_enabled &
2790 		    SATA_DEV_F_E_TAGGED_QING) &&
2791 		    (sdinfo->satadrv_max_queue_depth > 1))
2792 			rval = 1;	/* Tagged queuing available */
2793 		else
2794 			rval = -1;	/* Tagged queuing not available */
2795 		break;
2796 
2797 	case SCSI_CAP_DMA_MAX:
2798 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2799 		    &adj_dma_attr);
2800 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2801 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2802 		break;
2803 
2804 	case SCSI_CAP_INTERCONNECT_TYPE:
2805 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2806 		break;
2807 
2808 	case SCSI_CAP_CDB_LEN:
2809 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2810 			rval = sdinfo->satadrv_atapi_cdb_len;
2811 		else
2812 			rval = -1;
2813 		break;
2814 
2815 	default:
2816 		rval = -1;
2817 		break;
2818 	}
2819 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2820 	    sata_device.satadev_addr.cport)));
2821 	return (rval);
2822 }
2823 
2824 /*
2825  * Implementation of scsi tran_setcap
2826  *
2827  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2828  *
2829  */
2830 static int
2831 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2832 {
2833 	sata_hba_inst_t	*sata_hba_inst =
2834 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2835 	sata_device_t	sata_device;
2836 	sata_drive_info_t	*sdinfo;
2837 	int		rval;
2838 
2839 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2840 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2841 
2842 	/*
2843 	 * We want to process the capabilities on per port granularity.
2844 	 * So, we are specifically restricting ourselves to whom != 0
2845 	 * to exclude the controller wide handling.
2846 	 */
2847 	if (cap == NULL || whom == 0) {
2848 		return (-1);
2849 	}
2850 
2851 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2852 		/* Invalid address */
2853 		return (-1);
2854 	}
2855 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2856 	    sata_device.satadev_addr.cport)));
2857 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2858 	    &sata_device)) == NULL) {
2859 		/* invalid address */
2860 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2861 		    sata_device.satadev_addr.cport)));
2862 		return (-1);
2863 	}
2864 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2865 	    sata_device.satadev_addr.cport)));
2866 
2867 	switch (scsi_hba_lookup_capstr(cap)) {
2868 	case SCSI_CAP_ARQ:
2869 	case SCSI_CAP_SECTOR_SIZE:
2870 	case SCSI_CAP_DMA_MAX:
2871 	case SCSI_CAP_INTERCONNECT_TYPE:
2872 		rval = 0;
2873 		break;
2874 	case SCSI_CAP_UNTAGGED_QING:
2875 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2876 			rval = 1;
2877 			if (value == 1) {
2878 				sdinfo->satadrv_features_enabled |=
2879 				    SATA_DEV_F_E_UNTAGGED_QING;
2880 			} else if (value == 0) {
2881 				sdinfo->satadrv_features_enabled &=
2882 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2883 			} else {
2884 				rval = -1;
2885 			}
2886 		} else {
2887 			rval = 0;
2888 		}
2889 		break;
2890 	case SCSI_CAP_TAGGED_QING:
2891 		/* This can TCQ or NCQ */
2892 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2893 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2894 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2895 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2896 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2897 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2898 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2899 			rval = 1;
2900 			if (value == 1) {
2901 				sdinfo->satadrv_features_enabled |=
2902 				    SATA_DEV_F_E_TAGGED_QING;
2903 			} else if (value == 0) {
2904 				sdinfo->satadrv_features_enabled &=
2905 				    ~SATA_DEV_F_E_TAGGED_QING;
2906 			} else {
2907 				rval = -1;
2908 			}
2909 		} else {
2910 			rval = 0;
2911 		}
2912 		break;
2913 	default:
2914 		rval = -1;
2915 		break;
2916 	}
2917 	return (rval);
2918 }
2919 
2920 /*
2921  * Implementations of scsi tran_destroy_pkt.
2922  * Free resources allocated by sata_scsi_init_pkt()
2923  */
2924 static void
2925 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2926 {
2927 	sata_pkt_txlate_t *spx;
2928 
2929 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2930 
2931 	sata_common_free_dma_rsrcs(spx);
2932 
2933 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2934 	sata_pkt_free(spx);
2935 
2936 	scsi_hba_pkt_free(ap, pkt);
2937 }
2938 
2939 /*
2940  * Implementation of scsi tran_dmafree.
2941  * Free DMA resources allocated by sata_scsi_init_pkt()
2942  */
2943 
2944 static void
2945 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
2946 {
2947 #ifndef __lock_lint
2948 	_NOTE(ARGUNUSED(ap))
2949 #endif
2950 	sata_pkt_txlate_t *spx;
2951 
2952 	ASSERT(pkt != NULL);
2953 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2954 
2955 	sata_common_free_dma_rsrcs(spx);
2956 }
2957 
2958 /*
2959  * Implementation of scsi tran_sync_pkt.
2960  *
2961  * The assumption below is that pkt is unique - there is no need to check ap
2962  *
2963  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
2964  * into/from the real buffer.
2965  */
2966 static void
2967 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2968 {
2969 #ifndef __lock_lint
2970 	_NOTE(ARGUNUSED(ap))
2971 #endif
2972 	int rval;
2973 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2974 	struct buf *bp;
2975 	int direction;
2976 
2977 	ASSERT(spx != NULL);
2978 	if (spx->txlt_buf_dma_handle != NULL) {
2979 		direction = spx->txlt_sata_pkt->
2980 		    satapkt_cmd.satacmd_flags.sata_data_direction;
2981 		if (spx->txlt_sata_pkt != NULL &&
2982 		    direction != SATA_DIR_NODATA_XFER) {
2983 			if (spx->txlt_tmp_buf != NULL) {
2984 				/* Intermediate DMA buffer used */
2985 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2986 
2987 				if (direction & SATA_DIR_WRITE) {
2988 					bcopy(bp->b_un.b_addr,
2989 					    spx->txlt_tmp_buf, bp->b_bcount);
2990 				}
2991 			}
2992 			/* Sync the buffer for device or for CPU */
2993 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
2994 			    (direction & SATA_DIR_WRITE) ?
2995 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
2996 			ASSERT(rval == DDI_SUCCESS);
2997 			if (spx->txlt_tmp_buf != NULL &&
2998 			    !(direction & SATA_DIR_WRITE)) {
2999 				/* Intermediate DMA buffer used for read */
3000 				bcopy(spx->txlt_tmp_buf,
3001 				    bp->b_un.b_addr, bp->b_bcount);
3002 			}
3003 
3004 		}
3005 	}
3006 }
3007 
3008 
3009 
3010 /* *******************  SATA - SCSI Translation functions **************** */
3011 /*
3012  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3013  * translation.
3014  */
3015 
3016 /*
3017  * Checks if a device exists and can be access and translates common
3018  * scsi_pkt data to sata_pkt data.
3019  *
3020  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3021  * sata_pkt was set-up.
3022  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3023  * exist and pkt_comp callback was scheduled.
3024  * Returns other TRAN_XXXXX values when error occured and command should be
3025  * rejected with the returned TRAN_XXXXX value.
3026  *
3027  * This function should be called with port mutex held.
3028  */
3029 static int
3030 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason)
3031 {
3032 	sata_drive_info_t *sdinfo;
3033 	sata_device_t sata_device;
3034 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3035 		SATA_DIR_NODATA_XFER,
3036 		/* all other values to 0/FALSE */
3037 	};
3038 	/*
3039 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3040 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3041 	 * indicates that the scsi packet was not accepted (the reason will not
3042 	 * be checked by the scsi target driver).
3043 	 * To make debugging easier, we set pkt_reason to know value here.
3044 	 * It may be changed later when different completion reason is
3045 	 * determined.
3046 	 */
3047 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3048 	*reason = CMD_TRAN_ERR;
3049 
3050 	/* Validate address */
3051 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3052 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3053 
3054 	case -1:
3055 		/* Invalid address or invalid device type */
3056 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3057 		    "sata_scsi_start: reject command because "
3058 		    "dev type or address is invalid\n", NULL);
3059 		return (TRAN_BADPKT);
3060 	case 1:
3061 		/* valid address but no device - it has disappeared ? */
3062 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3063 		    "sata_scsi_start: reject command because "
3064 		    "device is gone\n", NULL);
3065 
3066 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3067 		*reason = CMD_DEV_GONE;
3068 		/*
3069 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3070 		 * only in callback function (for normal requests) and
3071 		 * in the dump code path.
3072 		 * So, if the callback is available, we need to do
3073 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3074 		 */
3075 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3076 			/* scsi callback required */
3077 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3078 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3079 			    (void *)spx->txlt_scsi_pkt,
3080 			    TQ_SLEEP) == NULL)
3081 				/* Scheduling the callback failed */
3082 				return (TRAN_BUSY);
3083 
3084 			return (TRAN_ACCEPT);
3085 		}
3086 		return (TRAN_FATAL_ERROR);
3087 	default:
3088 		/* all OK; pkt reason will be overwritten later */
3089 		break;
3090 	}
3091 	/*
3092 	 * If in an interrupt context, reject packet if it is to be
3093 	 * executed in polling mode
3094 	 */
3095 	if (servicing_interrupt() &&
3096 	    (spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3097 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3098 		    "sata_scsi_start: rejecting synchronous command because "
3099 		    "of interrupt context\n", NULL);
3100 		return (TRAN_BUSY);
3101 	}
3102 
3103 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3104 	    &spx->txlt_sata_pkt->satapkt_device);
3105 
3106 	/*
3107 	 * If device is in reset condition, reject the packet with
3108 	 * TRAN_BUSY, unless:
3109 	 * 1. system is panicking (dumping)
3110 	 * In such case only one thread is running and there is no way to
3111 	 * process reset.
3112 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3113 	 * Some cfgadm operations involve drive commands, so reset condition
3114 	 * needs to be ignored for IOCTL operations.
3115 	 */
3116 	if ((sdinfo->satadrv_event_flags &
3117 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3118 
3119 		if (!ddi_in_panic() &&
3120 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3121 		    sata_device.satadev_addr.cport) &
3122 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3123 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3124 			*reason = CMD_INCOMPLETE;
3125 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3126 			    "sata_scsi_start: rejecting command because "
3127 			    "of device reset state\n", NULL);
3128 			return (TRAN_BUSY);
3129 		}
3130 	}
3131 
3132 	/*
3133 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3134 	 * sata_scsi_pkt_init() because pkt init had to work also with
3135 	 * non-existing devices.
3136 	 * Now we know that the packet was set-up for a real device, so its
3137 	 * type is known.
3138 	 */
3139 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3140 
3141 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3142 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3143 	    sata_device.satadev_addr.cport)->cport_event_flags &
3144 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3145 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3146 		    sata_ignore_dev_reset = B_TRUE;
3147 	}
3148 	/*
3149 	 * At this point the generic translation routine determined that the
3150 	 * scsi packet should be accepted. Packet completion reason may be
3151 	 * changed later when a different completion reason is determined.
3152 	 */
3153 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3154 	*reason = CMD_CMPLT;
3155 
3156 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3157 		/* Synchronous execution */
3158 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3159 		    SATA_OPMODE_POLLING;
3160 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3161 		    sata_ignore_dev_reset = ddi_in_panic();
3162 	} else {
3163 		/* Asynchronous execution */
3164 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3165 		    SATA_OPMODE_INTERRUPTS;
3166 	}
3167 	/* Convert queuing information */
3168 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3169 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3170 		    B_TRUE;
3171 	else if (spx->txlt_scsi_pkt->pkt_flags &
3172 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3173 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3174 		    B_TRUE;
3175 
3176 	/* Always limit pkt time */
3177 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3178 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3179 	else
3180 		/* Pass on scsi_pkt time */
3181 		spx->txlt_sata_pkt->satapkt_time =
3182 		    spx->txlt_scsi_pkt->pkt_time;
3183 
3184 	return (TRAN_ACCEPT);
3185 }
3186 
3187 
3188 /*
3189  * Translate ATA Identify Device data to SCSI Inquiry data.
3190  * This function may be called only for ATA devices.
3191  * This function should not be called for ATAPI devices - they
3192  * respond directly to SCSI Inquiry command.
3193  *
3194  * SATA Identify Device data has to be valid in sata_drive_info.
3195  * Buffer has to accomodate the inquiry length (36 bytes).
3196  *
3197  * This function should be called with a port mutex held.
3198  */
3199 static	void
3200 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3201     sata_drive_info_t *sdinfo, uint8_t *buf)
3202 {
3203 
3204 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3205 	struct sata_id *sid = &sdinfo->satadrv_id;
3206 
3207 	/* Start with a nice clean slate */
3208 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3209 
3210 	/*
3211 	 * Rely on the dev_type for setting paripheral qualifier.
3212 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3213 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3214 	 * ATAPI Inquiry may provide more data to the target driver.
3215 	 */
3216 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3217 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3218 
3219 	/* CFA type device is not a removable media device */
3220 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3221 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3222 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3223 	inq->inq_iso = 0;	/* ISO version */
3224 	inq->inq_ecma = 0;	/* ECMA version */
3225 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3226 	inq->inq_aenc = 0;	/* Async event notification cap. */
3227 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3228 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3229 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3230 	inq->inq_len = 31;	/* Additional length */
3231 	inq->inq_dualp = 0;	/* dual port device - NO */
3232 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3233 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3234 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3235 				/*
3236 				 * Queuing support - controller has to
3237 				 * support some sort of command queuing.
3238 				 */
3239 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3240 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3241 	else
3242 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3243 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3244 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3245 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3246 
3247 #ifdef	_LITTLE_ENDIAN
3248 	/* Swap text fields to match SCSI format */
3249 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3250 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3251 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3252 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3253 	else
3254 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3255 #else	/* _LITTLE_ENDIAN */
3256 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3257 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3258 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3259 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3260 	else
3261 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3262 #endif	/* _LITTLE_ENDIAN */
3263 }
3264 
3265 
3266 /*
3267  * Scsi response set up for invalid command (command not supported)
3268  *
3269  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3270  */
3271 static int
3272 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3273 {
3274 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3275 	struct scsi_extended_sense *sense;
3276 
3277 	scsipkt->pkt_reason = CMD_CMPLT;
3278 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3279 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3280 
3281 	*scsipkt->pkt_scbp = STATUS_CHECK;
3282 
3283 	sense = sata_arq_sense(spx);
3284 	sense->es_key = KEY_ILLEGAL_REQUEST;
3285 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3286 
3287 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3288 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3289 
3290 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3291 	    scsipkt->pkt_comp != NULL)
3292 		/* scsi callback required */
3293 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3294 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3295 		    (void *)spx->txlt_scsi_pkt,
3296 		    TQ_SLEEP) == NULL)
3297 			/* Scheduling the callback failed */
3298 			return (TRAN_BUSY);
3299 	return (TRAN_ACCEPT);
3300 }
3301 
3302 /*
3303  * Scsi response set up for check condition with special sense key
3304  * and additional sense code.
3305  *
3306  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3307  */
3308 static int
3309 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3310 {
3311 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3312 	int cport = SATA_TXLT_CPORT(spx);
3313 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3314 	struct scsi_extended_sense *sense;
3315 
3316 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3317 	scsipkt->pkt_reason = CMD_CMPLT;
3318 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3319 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3320 
3321 	*scsipkt->pkt_scbp = STATUS_CHECK;
3322 
3323 	sense = sata_arq_sense(spx);
3324 	sense->es_key = key;
3325 	sense->es_add_code = code;
3326 
3327 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3328 
3329 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3330 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3331 
3332 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3333 		/* scsi callback required */
3334 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3335 		    (task_func_t *)scsi_hba_pkt_comp,
3336 		    (void *)spx->txlt_scsi_pkt,
3337 		    TQ_SLEEP) == NULL)
3338 			/* Scheduling the callback failed */
3339 			return (TRAN_BUSY);
3340 	return (TRAN_ACCEPT);
3341 }
3342 
3343 /*
3344  * Scsi response setup for
3345  * emulated non-data command that requires no action/return data
3346  *
3347  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3348  */
3349 static	int
3350 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3351 {
3352 	int rval;
3353 	int reason;
3354 
3355 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3356 
3357 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3358 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3359 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3360 		return (rval);
3361 	}
3362 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3363 
3364 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3365 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3366 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3367 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3368 
3369 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3370 	    "Scsi_pkt completion reason %x\n",
3371 	    spx->txlt_scsi_pkt->pkt_reason);
3372 
3373 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3374 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3375 		/* scsi callback required */
3376 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3377 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3378 		    (void *)spx->txlt_scsi_pkt,
3379 		    TQ_SLEEP) == NULL)
3380 			/* Scheduling the callback failed */
3381 			return (TRAN_BUSY);
3382 	return (TRAN_ACCEPT);
3383 }
3384 
3385 
3386 /*
3387  * SATA translate command: Inquiry / Identify Device
3388  * Use cached Identify Device data for now, rather than issuing actual
3389  * Device Identify cmd request. If device is detached and re-attached,
3390  * asynchronous event processing should fetch and refresh Identify Device
3391  * data.
3392  * Two VPD pages are supported now:
3393  * Vital Product Data page
3394  * Unit Serial Number page
3395  *
3396  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3397  */
3398 
3399 #define	EVPD			1	/* Extended Vital Product Data flag */
3400 #define	CMDDT			2	/* Command Support Data - Obsolete */
3401 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3402 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3403 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3404 
3405 static int
3406 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3407 {
3408 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3409 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3410 	sata_drive_info_t *sdinfo;
3411 	struct scsi_extended_sense *sense;
3412 	int count;
3413 	uint8_t *p;
3414 	int i, j;
3415 	uint8_t page_buf[0xff]; /* Max length */
3416 	int rval, reason;
3417 
3418 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3419 
3420 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3421 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3422 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3423 		return (rval);
3424 	}
3425 
3426 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3427 	    &spx->txlt_sata_pkt->satapkt_device);
3428 
3429 	ASSERT(sdinfo != NULL);
3430 
3431 	scsipkt->pkt_reason = CMD_CMPLT;
3432 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3433 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3434 
3435 	/* Reject not supported request */
3436 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3437 		*scsipkt->pkt_scbp = STATUS_CHECK;
3438 		sense = sata_arq_sense(spx);
3439 		sense->es_key = KEY_ILLEGAL_REQUEST;
3440 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3441 		goto done;
3442 	}
3443 
3444 	/* Valid Inquiry request */
3445 	*scsipkt->pkt_scbp = STATUS_GOOD;
3446 
3447 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3448 
3449 		/*
3450 		 * Because it is fully emulated command storing data
3451 		 * programatically in the specified buffer, release
3452 		 * preallocated DMA resources before storing data in the buffer,
3453 		 * so no unwanted DMA sync would take place.
3454 		 */
3455 		sata_scsi_dmafree(NULL, scsipkt);
3456 
3457 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3458 			/* Standard Inquiry Data request */
3459 			struct scsi_inquiry inq;
3460 			unsigned int bufsize;
3461 
3462 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3463 			    sdinfo, (uint8_t *)&inq);
3464 			/* Copy no more than requested */
3465 			count = MIN(bp->b_bcount,
3466 			    sizeof (struct scsi_inquiry));
3467 			bufsize = scsipkt->pkt_cdbp[4];
3468 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3469 			count = MIN(count, bufsize);
3470 			bcopy(&inq, bp->b_un.b_addr, count);
3471 
3472 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3473 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3474 			    bufsize - count : 0;
3475 		} else {
3476 			/*
3477 			 * peripheral_qualifier = 0;
3478 			 *
3479 			 * We are dealing only with HD and will be
3480 			 * dealing with CD/DVD devices soon
3481 			 */
3482 			uint8_t peripheral_device_type =
3483 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3484 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3485 
3486 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3487 			case INQUIRY_SUP_VPD_PAGE:
3488 				/*
3489 				 * Request for suported Vital Product Data
3490 				 * pages - assuming only 2 page codes
3491 				 * supported.
3492 				 */
3493 				page_buf[0] = peripheral_device_type;
3494 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3495 				page_buf[2] = 0;
3496 				page_buf[3] = 2; /* page length */
3497 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3498 				page_buf[5] = INQUIRY_USN_PAGE;
3499 				/* Copy no more than requested */
3500 				count = MIN(bp->b_bcount, 6);
3501 				bcopy(page_buf, bp->b_un.b_addr, count);
3502 				break;
3503 
3504 			case INQUIRY_USN_PAGE:
3505 				/*
3506 				 * Request for Unit Serial Number page.
3507 				 * Set-up the page.
3508 				 */
3509 				page_buf[0] = peripheral_device_type;
3510 				page_buf[1] = INQUIRY_USN_PAGE;
3511 				page_buf[2] = 0;
3512 				/* remaining page length */
3513 				page_buf[3] = SATA_ID_SERIAL_LEN;
3514 
3515 				/*
3516 				 * Copy serial number from Identify Device data
3517 				 * words into the inquiry page and swap bytes
3518 				 * when necessary.
3519 				 */
3520 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3521 #ifdef	_LITTLE_ENDIAN
3522 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3523 #else
3524 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3525 #endif
3526 				/*
3527 				 * Least significant character of the serial
3528 				 * number shall appear as the last byte,
3529 				 * according to SBC-3 spec.
3530 				 * Count trailing spaces to determine the
3531 				 * necessary shift length.
3532 				 */
3533 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3534 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3535 					if (*(p - j) != '\0' &&
3536 					    *(p - j) != '\040')
3537 						break;
3538 				}
3539 
3540 				/*
3541 				 * Shift SN string right, so that the last
3542 				 * non-blank character would appear in last
3543 				 * byte of SN field in the page.
3544 				 * 'j' is the shift length.
3545 				 */
3546 				for (i = 0;
3547 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3548 				    i++, p--)
3549 					*p = *(p - j);
3550 
3551 				/*
3552 				 * Add leading spaces - same number as the
3553 				 * shift size
3554 				 */
3555 				for (; j > 0; j--)
3556 					page_buf[4 + j - 1] = '\040';
3557 
3558 				count = MIN(bp->b_bcount,
3559 				    SATA_ID_SERIAL_LEN + 4);
3560 				bcopy(page_buf, bp->b_un.b_addr, count);
3561 				break;
3562 
3563 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3564 				/*
3565 				 * We may want to implement this page, when
3566 				 * identifiers are common for SATA devices
3567 				 * But not now.
3568 				 */
3569 				/*FALLTHROUGH*/
3570 
3571 			default:
3572 				/* Request for unsupported VPD page */
3573 				*scsipkt->pkt_scbp = STATUS_CHECK;
3574 				sense = sata_arq_sense(spx);
3575 				sense->es_key = KEY_ILLEGAL_REQUEST;
3576 				sense->es_add_code =
3577 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3578 				goto done;
3579 			}
3580 		}
3581 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3582 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3583 		    scsipkt->pkt_cdbp[4] - count : 0;
3584 	}
3585 done:
3586 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3587 
3588 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3589 	    "Scsi_pkt completion reason %x\n",
3590 	    scsipkt->pkt_reason);
3591 
3592 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3593 	    scsipkt->pkt_comp != NULL) {
3594 		/* scsi callback required */
3595 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3596 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3597 		    TQ_SLEEP) == NULL)
3598 			/* Scheduling the callback failed */
3599 			return (TRAN_BUSY);
3600 	}
3601 	return (TRAN_ACCEPT);
3602 }
3603 
3604 /*
3605  * SATA translate command: Request Sense.
3606  *
3607  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3608  * At the moment this is an emulated command (ATA version for SATA hard disks).
3609  * May be translated into Check Power Mode command in the future.
3610  *
3611  * Note: There is a mismatch between already implemented Informational
3612  * Exception Mode Select page 0x1C and this function.
3613  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3614  * NO SENSE and set additional sense code to the exception code - this is not
3615  * implemented here.
3616  */
3617 static int
3618 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3619 {
3620 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3621 	struct scsi_extended_sense sense;
3622 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3623 	sata_drive_info_t *sdinfo;
3624 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3625 	int rval, reason, power_state = 0;
3626 
3627 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3628 
3629 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3630 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3631 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3632 		return (rval);
3633 	}
3634 
3635 	scsipkt->pkt_reason = CMD_CMPLT;
3636 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3637 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3638 	*scsipkt->pkt_scbp = STATUS_GOOD;
3639 
3640 	/*
3641 	 * when CONTROL field's NACA bit == 1
3642 	 * return ILLEGAL_REQUEST
3643 	 */
3644 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3645 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3646 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3647 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3648 	}
3649 
3650 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3651 	    &spx->txlt_sata_pkt->satapkt_device);
3652 	ASSERT(sdinfo != NULL);
3653 
3654 	spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3655 
3656 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3657 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3658 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3659 	if (sata_hba_start(spx, &rval) != 0) {
3660 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3661 		return (rval);
3662 	} else {
3663 		if (scmd->satacmd_error_reg != 0) {
3664 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3665 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3666 			    SD_SCSI_ASC_NO_ADD_SENSE));
3667 		}
3668 	}
3669 
3670 	switch (scmd->satacmd_sec_count_lsb) {
3671 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3672 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3673 			power_state = SATA_POWER_STOPPED;
3674 		else {
3675 			power_state = SATA_POWER_STANDBY;
3676 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3677 		}
3678 		break;
3679 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3680 		power_state = SATA_POWER_IDLE;
3681 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3682 		break;
3683 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3684 	default:		  /* 0x40, 0x41 active mode */
3685 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3686 			power_state = SATA_POWER_IDLE;
3687 		else {
3688 			power_state = SATA_POWER_ACTIVE;
3689 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3690 		}
3691 		break;
3692 	}
3693 
3694 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3695 
3696 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3697 		/*
3698 		 * Because it is fully emulated command storing data
3699 		 * programatically in the specified buffer, release
3700 		 * preallocated DMA resources before storing data in the buffer,
3701 		 * so no unwanted DMA sync would take place.
3702 		 */
3703 		int count = MIN(bp->b_bcount,
3704 		    sizeof (struct scsi_extended_sense));
3705 		sata_scsi_dmafree(NULL, scsipkt);
3706 		bzero(&sense, sizeof (struct scsi_extended_sense));
3707 		sense.es_valid = 0;	/* Valid LBA */
3708 		sense.es_class = 7;	/* Response code 0x70 - current err */
3709 		sense.es_key = KEY_NO_SENSE;
3710 		sense.es_add_len = 6;	/* Additional length */
3711 		/* Copy no more than requested */
3712 		bcopy(&sense, bp->b_un.b_addr, count);
3713 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3714 		scsipkt->pkt_resid = 0;
3715 		switch (power_state) {
3716 		case SATA_POWER_IDLE:
3717 		case SATA_POWER_STANDBY:
3718 			sense.es_add_code =
3719 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3720 			break;
3721 		case SATA_POWER_STOPPED:
3722 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3723 			break;
3724 		case SATA_POWER_ACTIVE:
3725 		default:
3726 			break;
3727 		}
3728 	}
3729 
3730 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3731 	    "Scsi_pkt completion reason %x\n",
3732 	    scsipkt->pkt_reason);
3733 
3734 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3735 		/* scsi callback required */
3736 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3737 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3738 		    TQ_SLEEP) == NULL)
3739 			/* Scheduling the callback failed */
3740 			return (TRAN_BUSY);
3741 	return (TRAN_ACCEPT);
3742 }
3743 
3744 /*
3745  * SATA translate command: Test Unit Ready
3746  * At the moment this is an emulated command (ATA version for SATA hard disks).
3747  * May be translated into Check Power Mode command in the future
3748  *
3749  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3750  */
3751 static int
3752 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3753 {
3754 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3755 	struct scsi_extended_sense *sense;
3756 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3757 	sata_drive_info_t *sdinfo;
3758 	int power_state;
3759 	int rval, reason;
3760 
3761 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3762 
3763 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3764 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3765 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3766 		return (rval);
3767 	}
3768 
3769 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3770 	    &spx->txlt_sata_pkt->satapkt_device);
3771 	ASSERT(sdinfo != NULL);
3772 
3773 	spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3774 
3775 	/* send CHECK POWER MODE command */
3776 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3777 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3778 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3779 	if (sata_hba_start(spx, &rval) != 0) {
3780 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3781 		return (rval);
3782 	} else {
3783 		if (scmd->satacmd_error_reg != 0) {
3784 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3785 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3786 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3787 		}
3788 	}
3789 
3790 	power_state = scmd->satacmd_sec_count_lsb;
3791 
3792 	/*
3793 	 * return NOT READY when device in STOPPED mode
3794 	 */
3795 	if (power_state == SATA_PWRMODE_STANDBY &&
3796 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3797 		*scsipkt->pkt_scbp = STATUS_CHECK;
3798 		sense = sata_arq_sense(spx);
3799 		sense->es_key = KEY_NOT_READY;
3800 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3801 	} else {
3802 		/*
3803 		 * For other power mode, return GOOD status
3804 		 */
3805 		*scsipkt->pkt_scbp = STATUS_GOOD;
3806 	}
3807 
3808 	scsipkt->pkt_reason = CMD_CMPLT;
3809 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3810 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3811 
3812 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3813 
3814 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3815 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3816 
3817 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3818 		/* scsi callback required */
3819 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3820 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3821 		    TQ_SLEEP) == NULL)
3822 			/* Scheduling the callback failed */
3823 			return (TRAN_BUSY);
3824 
3825 	return (TRAN_ACCEPT);
3826 }
3827 
3828 /*
3829  * SATA translate command: Start Stop Unit
3830  * Translation depends on a command:
3831  *
3832  * Power condition bits will be supported
3833  * and the power level should be maintained by SATL,
3834  * When SATL received a command, it will check the
3835  * power level firstly, and return the status according
3836  * to SAT2 v2.6 and SAT-2 Standby Modifications
3837  *
3838  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3839  * -----------------------------------------------------------------------
3840  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3841  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3842  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3843  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3844  *
3845  *	Unload Media / NOT SUPPORTED YET
3846  *	Load Media / NOT SUPPROTED YET
3847  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3848  *
3849  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3850  * appropriate values in scsi_pkt fields.
3851  */
3852 static int
3853 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3854 {
3855 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3856 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3857 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3858 	int cport = SATA_TXLT_CPORT(spx);
3859 	int rval, reason;
3860 	sata_drive_info_t *sdinfo;
3861 	sata_id_t *sata_id;
3862 
3863 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3864 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3865 
3866 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3867 
3868 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3869 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3870 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3871 		return (rval);
3872 	}
3873 
3874 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
3875 		/* IMMED bit - not supported */
3876 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3877 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3878 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
3879 	}
3880 
3881 	spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3882 	spx->txlt_sata_pkt->satapkt_comp = NULL;
3883 
3884 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3885 	    &spx->txlt_sata_pkt->satapkt_device);
3886 	ASSERT(sdinfo != NULL);
3887 	sata_id = &sdinfo->satadrv_id;
3888 
3889 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
3890 	case 0:
3891 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
3892 			/* Load/Unload Media - invalid request */
3893 			goto err_out;
3894 		}
3895 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
3896 			/* Start Unit */
3897 			sata_build_read_verify_cmd(scmd, 1, 5);
3898 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3899 			/* Transfer command to HBA */
3900 			if (sata_hba_start(spx, &rval) != 0) {
3901 				/* Pkt not accepted for execution */
3902 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3903 				return (rval);
3904 			} else {
3905 				if (scmd->satacmd_error_reg != 0) {
3906 					goto err_out;
3907 				}
3908 			}
3909 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3910 		} else {
3911 			/* Stop Unit */
3912 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3913 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3914 			if (sata_hba_start(spx, &rval) != 0) {
3915 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3916 				return (rval);
3917 			} else {
3918 				if (scmd->satacmd_error_reg != 0) {
3919 					goto err_out;
3920 				}
3921 			}
3922 			/* ata standby immediate command */
3923 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
3924 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3925 			if (sata_hba_start(spx, &rval) != 0) {
3926 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3927 				return (rval);
3928 			} else {
3929 				if (scmd->satacmd_error_reg != 0) {
3930 					goto err_out;
3931 				}
3932 			}
3933 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
3934 		}
3935 		break;
3936 	case 0x1:
3937 		sata_build_generic_cmd(scmd, SATAC_IDLE);
3938 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3939 		if (sata_hba_start(spx, &rval) != 0) {
3940 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3941 			return (rval);
3942 		} else {
3943 			if (scmd->satacmd_error_reg != 0) {
3944 				goto err_out;
3945 			}
3946 		}
3947 		sata_build_read_verify_cmd(scmd, 1, 5);
3948 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3949 		/* Transfer command to HBA */
3950 		if (sata_hba_start(spx, &rval) != 0) {
3951 			/* Pkt not accepted for execution */
3952 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3953 			return (rval);
3954 		} else {
3955 			if (scmd->satacmd_error_reg != 0) {
3956 				goto err_out;
3957 			}
3958 		}
3959 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3960 		break;
3961 	case 0x2:
3962 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3963 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3964 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
3965 			if (sata_hba_start(spx, &rval) != 0) {
3966 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3967 				return (rval);
3968 			} else {
3969 				if (scmd->satacmd_error_reg != 0) {
3970 					goto err_out;
3971 				}
3972 			}
3973 		}
3974 		sata_build_generic_cmd(scmd, SATAC_IDLE);
3975 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3976 		if (sata_hba_start(spx, &rval) != 0) {
3977 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3978 			return (rval);
3979 		} else {
3980 			if (scmd->satacmd_error_reg != 0) {
3981 				goto err_out;
3982 			}
3983 		}
3984 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
3985 			/*
3986 			 *  POWER CONDITION MODIFIER bit set
3987 			 *  to 0x1 or larger it will be handled
3988 			 *  on the same way as bit = 0x1
3989 			 */
3990 			if (!(sata_id->ai_cmdset84 &
3991 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
3992 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3993 				break;
3994 			}
3995 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
3996 			scmd->satacmd_features_reg = 0x44;
3997 			scmd->satacmd_lba_low_lsb = 0x4c;
3998 			scmd->satacmd_lba_mid_lsb = 0x4e;
3999 			scmd->satacmd_lba_high_lsb = 0x55;
4000 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4001 			if (sata_hba_start(spx, &rval) != 0) {
4002 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4003 				return (rval);
4004 			} else {
4005 				if (scmd->satacmd_error_reg != 0) {
4006 					goto err_out;
4007 				}
4008 			}
4009 		}
4010 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4011 		break;
4012 	case 0x3:
4013 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4014 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4015 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4016 			if (sata_hba_start(spx, &rval) != 0) {
4017 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4018 				return (rval);
4019 			} else {
4020 				if (scmd->satacmd_error_reg != 0) {
4021 					goto err_out;
4022 				}
4023 			}
4024 		}
4025 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4026 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4027 		if (sata_hba_start(spx, &rval) != 0) {
4028 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4029 			return (rval);
4030 		} else {
4031 			if (scmd->satacmd_error_reg != 0) {
4032 				goto err_out;
4033 			}
4034 		}
4035 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4036 		break;
4037 	case 0x7:
4038 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4039 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4040 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4041 		if (sata_hba_start(spx, &rval) != 0) {
4042 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4043 			return (rval);
4044 		} else {
4045 			if (scmd->satacmd_error_reg != 0) {
4046 				goto err_out;
4047 			}
4048 		}
4049 		switch (scmd->satacmd_sec_count_lsb) {
4050 		case SATA_PWRMODE_STANDBY:
4051 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4052 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4053 			    sdinfo->satadrv_standby_timer);
4054 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4055 			if (sata_hba_start(spx, &rval) != 0) {
4056 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4057 				return (rval);
4058 			} else {
4059 				if (scmd->satacmd_error_reg != 0) {
4060 					goto err_out;
4061 				}
4062 			}
4063 			break;
4064 		case SATA_PWRMODE_IDLE:
4065 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4066 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4067 			    sdinfo->satadrv_standby_timer);
4068 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4069 			if (sata_hba_start(spx, &rval) != 0) {
4070 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4071 				return (rval);
4072 			} else {
4073 				if (scmd->satacmd_error_reg != 0) {
4074 					goto err_out;
4075 				}
4076 			}
4077 			break;
4078 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4079 		case SATA_PWRMODE_ACTIVE_SPINUP:
4080 		case SATA_PWRMODE_ACTIVE:
4081 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4082 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4083 			    sdinfo->satadrv_standby_timer);
4084 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4085 			if (sata_hba_start(spx, &rval) != 0) {
4086 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4087 				return (rval);
4088 			} else {
4089 				if (scmd->satacmd_error_reg != 0) {
4090 					goto err_out;
4091 				}
4092 			}
4093 			sata_build_read_verify_cmd(scmd, 1, 5);
4094 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4095 			if (sata_hba_start(spx, &rval) != 0) {
4096 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4097 				return (rval);
4098 			} else {
4099 				if (scmd->satacmd_error_reg != 0) {
4100 					goto err_out;
4101 				}
4102 			}
4103 			break;
4104 		default:
4105 			goto err_out;
4106 		}
4107 		break;
4108 	case 0xb:
4109 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4110 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4111 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4112 			return (sata_txlt_check_condition(spx,
4113 			    KEY_ILLEGAL_REQUEST,
4114 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4115 		}
4116 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4117 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4118 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4119 			if (sata_hba_start(spx, &rval) != 0) {
4120 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4121 				return (rval);
4122 			} else {
4123 				if (scmd->satacmd_error_reg != 0) {
4124 					goto err_out;
4125 				}
4126 			}
4127 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4128 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4129 			if (sata_hba_start(spx, &rval) != 0) {
4130 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4131 				return (rval);
4132 			} else {
4133 				if (scmd->satacmd_error_reg != 0) {
4134 					goto err_out;
4135 				}
4136 			}
4137 		}
4138 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4139 		break;
4140 	default:
4141 err_out:
4142 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4143 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4144 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4145 	}
4146 
4147 	/*
4148 	 * since it was synchronous commands,
4149 	 * a callback function will be called directely.
4150 	 */
4151 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4152 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4153 	    "synchronous execution status %x\n",
4154 	    spx->txlt_sata_pkt->satapkt_reason);
4155 
4156 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0) {
4157 		sata_set_arq_data(spx->txlt_sata_pkt);
4158 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4159 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
4160 		    TQ_SLEEP) == 0) {
4161 			return (TRAN_BUSY);
4162 		}
4163 	}
4164 	else
4165 
4166 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4167 
4168 	return (TRAN_ACCEPT);
4169 
4170 }
4171 
4172 /*
4173  * SATA translate command:  Read Capacity.
4174  * Emulated command for SATA disks.
4175  * Capacity is retrieved from cached Idenifty Device data.
4176  * Identify Device data shows effective disk capacity, not the native
4177  * capacity, which may be limitted by Set Max Address command.
4178  * This is ATA version for SATA hard disks.
4179  *
4180  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4181  */
4182 static int
4183 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4184 {
4185 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4186 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4187 	sata_drive_info_t *sdinfo;
4188 	uint64_t val;
4189 	uchar_t *rbuf;
4190 	int rval, reason;
4191 
4192 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4193 	    "sata_txlt_read_capacity: ", NULL);
4194 
4195 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4196 
4197 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4198 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4199 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4200 		return (rval);
4201 	}
4202 
4203 	scsipkt->pkt_reason = CMD_CMPLT;
4204 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4205 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4206 	*scsipkt->pkt_scbp = STATUS_GOOD;
4207 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4208 		/*
4209 		 * Because it is fully emulated command storing data
4210 		 * programatically in the specified buffer, release
4211 		 * preallocated DMA resources before storing data in the buffer,
4212 		 * so no unwanted DMA sync would take place.
4213 		 */
4214 		sata_scsi_dmafree(NULL, scsipkt);
4215 
4216 		sdinfo = sata_get_device_info(
4217 		    spx->txlt_sata_hba_inst,
4218 		    &spx->txlt_sata_pkt->satapkt_device);
4219 		/* Last logical block address */
4220 		val = sdinfo->satadrv_capacity - 1;
4221 		rbuf = (uchar_t *)bp->b_un.b_addr;
4222 		/* Need to swap endians to match scsi format */
4223 		rbuf[0] = (val >> 24) & 0xff;
4224 		rbuf[1] = (val >> 16) & 0xff;
4225 		rbuf[2] = (val >> 8) & 0xff;
4226 		rbuf[3] = val & 0xff;
4227 		/* block size - always 512 bytes, for now */
4228 		rbuf[4] = 0;
4229 		rbuf[5] = 0;
4230 		rbuf[6] = 0x02;
4231 		rbuf[7] = 0;
4232 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4233 		scsipkt->pkt_resid = 0;
4234 
4235 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4236 		    sdinfo->satadrv_capacity -1);
4237 	}
4238 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4239 	/*
4240 	 * If a callback was requested, do it now.
4241 	 */
4242 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4243 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4244 
4245 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4246 	    scsipkt->pkt_comp != NULL)
4247 		/* scsi callback required */
4248 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4249 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4250 		    TQ_SLEEP) == NULL)
4251 			/* Scheduling the callback failed */
4252 			return (TRAN_BUSY);
4253 
4254 	return (TRAN_ACCEPT);
4255 }
4256 
4257 /*
4258  * SATA translate command: Mode Sense.
4259  * Translated into appropriate SATA command or emulated.
4260  * Saved Values Page Control (03) are not supported.
4261  *
4262  * NOTE: only caching mode sense page is currently implemented.
4263  *
4264  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4265  */
4266 
4267 #define	LLBAA	0x10	/* Long LBA Accepted */
4268 
4269 static int
4270 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4271 {
4272 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4273 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4274 	sata_drive_info_t *sdinfo;
4275 	sata_id_t *sata_id;
4276 	struct scsi_extended_sense *sense;
4277 	int 		len, bdlen, count, alc_len;
4278 	int		pc;	/* Page Control code */
4279 	uint8_t		*buf;	/* mode sense buffer */
4280 	int		rval, reason;
4281 
4282 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4283 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4284 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4285 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4286 
4287 	buf = kmem_zalloc(1024, KM_SLEEP);
4288 
4289 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4290 
4291 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4292 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4293 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4294 		kmem_free(buf, 1024);
4295 		return (rval);
4296 	}
4297 
4298 	scsipkt->pkt_reason = CMD_CMPLT;
4299 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4300 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4301 
4302 	pc = scsipkt->pkt_cdbp[2] >> 6;
4303 
4304 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4305 		/*
4306 		 * Because it is fully emulated command storing data
4307 		 * programatically in the specified buffer, release
4308 		 * preallocated DMA resources before storing data in the buffer,
4309 		 * so no unwanted DMA sync would take place.
4310 		 */
4311 		sata_scsi_dmafree(NULL, scsipkt);
4312 
4313 		len = 0;
4314 		bdlen = 0;
4315 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4316 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4317 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4318 				bdlen = 16;
4319 			else
4320 				bdlen = 8;
4321 		}
4322 		/* Build mode parameter header */
4323 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4324 			/* 4-byte mode parameter header */
4325 			buf[len++] = 0;		/* mode data length */
4326 			buf[len++] = 0;		/* medium type */
4327 			buf[len++] = 0;		/* dev-specific param */
4328 			buf[len++] = bdlen;	/* Block Descriptor length */
4329 		} else {
4330 			/* 8-byte mode parameter header */
4331 			buf[len++] = 0;		/* mode data length */
4332 			buf[len++] = 0;
4333 			buf[len++] = 0;		/* medium type */
4334 			buf[len++] = 0;		/* dev-specific param */
4335 			if (bdlen == 16)
4336 				buf[len++] = 1;	/* long lba descriptor */
4337 			else
4338 				buf[len++] = 0;
4339 			buf[len++] = 0;
4340 			buf[len++] = 0;		/* Block Descriptor length */
4341 			buf[len++] = bdlen;
4342 		}
4343 
4344 		sdinfo = sata_get_device_info(
4345 		    spx->txlt_sata_hba_inst,
4346 		    &spx->txlt_sata_pkt->satapkt_device);
4347 
4348 		/* Build block descriptor only if not disabled (DBD) */
4349 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4350 			/* Block descriptor - direct-access device format */
4351 			if (bdlen == 8) {
4352 				/* build regular block descriptor */
4353 				buf[len++] =
4354 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4355 				buf[len++] =
4356 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4357 				buf[len++] =
4358 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4359 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4360 				buf[len++] = 0; /* density code */
4361 				buf[len++] = 0;
4362 				if (sdinfo->satadrv_type ==
4363 				    SATA_DTYPE_ATADISK)
4364 					buf[len++] = 2;
4365 				else
4366 					/* ATAPI */
4367 					buf[len++] = 8;
4368 				buf[len++] = 0;
4369 			} else if (bdlen == 16) {
4370 				/* Long LBA Accepted */
4371 				/* build long lba block descriptor */
4372 #ifndef __lock_lint
4373 				buf[len++] =
4374 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4375 				buf[len++] =
4376 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4377 				buf[len++] =
4378 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4379 				buf[len++] =
4380 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4381 #endif
4382 				buf[len++] =
4383 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4384 				buf[len++] =
4385 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4386 				buf[len++] =
4387 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4388 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4389 				buf[len++] = 0;
4390 				buf[len++] = 0; /* density code */
4391 				buf[len++] = 0;
4392 				buf[len++] = 0;
4393 				if (sdinfo->satadrv_type ==
4394 				    SATA_DTYPE_ATADISK)
4395 					buf[len++] = 2;
4396 				else
4397 					/* ATAPI */
4398 					buf[len++] = 8;
4399 				buf[len++] = 0;
4400 			}
4401 		}
4402 
4403 		sata_id = &sdinfo->satadrv_id;
4404 
4405 		/*
4406 		 * Add requested pages.
4407 		 * Page 3 and 4 are obsolete and we are not supporting them.
4408 		 * We deal now with:
4409 		 * caching (read/write cache control).
4410 		 * We should eventually deal with following mode pages:
4411 		 * error recovery  (0x01),
4412 		 * power condition (0x1a),
4413 		 * exception control page (enables SMART) (0x1c),
4414 		 * enclosure management (ses),
4415 		 * protocol-specific port mode (port control).
4416 		 */
4417 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4418 		case MODEPAGE_RW_ERRRECOV:
4419 			/* DAD_MODE_ERR_RECOV */
4420 			/* R/W recovery */
4421 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4422 			break;
4423 		case MODEPAGE_CACHING:
4424 			/* DAD_MODE_CACHE */
4425 			/* Reject not supported request for saved parameters */
4426 			if (pc == 3) {
4427 				*scsipkt->pkt_scbp = STATUS_CHECK;
4428 				sense = sata_arq_sense(spx);
4429 				sense->es_key = KEY_ILLEGAL_REQUEST;
4430 				sense->es_add_code =
4431 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4432 				goto done;
4433 			}
4434 
4435 			/* caching */
4436 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4437 			break;
4438 		case MODEPAGE_INFO_EXCPT:
4439 			/* exception cntrl */
4440 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4441 				len += sata_build_msense_page_1c(sdinfo, pc,
4442 				    buf+len);
4443 			}
4444 			else
4445 				goto err;
4446 			break;
4447 		case MODEPAGE_POWER_COND:
4448 			/* DAD_MODE_POWER_COND */
4449 			/* power condition */
4450 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4451 			break;
4452 
4453 		case MODEPAGE_ACOUSTIC_MANAG:
4454 			/* acoustic management */
4455 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4456 			break;
4457 		case MODEPAGE_ALLPAGES:
4458 			/* all pages */
4459 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4460 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4461 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4462 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4463 				len += sata_build_msense_page_1c(sdinfo, pc,
4464 				    buf+len);
4465 			}
4466 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4467 			break;
4468 		default:
4469 		err:
4470 			/* Invalid request */
4471 			*scsipkt->pkt_scbp = STATUS_CHECK;
4472 			sense = sata_arq_sense(spx);
4473 			sense->es_key = KEY_ILLEGAL_REQUEST;
4474 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4475 			goto done;
4476 		}
4477 
4478 		/* fix total mode data length */
4479 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4480 			/* 4-byte mode parameter header */
4481 			buf[0] = len - 1;	/* mode data length */
4482 		} else {
4483 			buf[0] = (len -2) >> 8;
4484 			buf[1] = (len -2) & 0xff;
4485 		}
4486 
4487 
4488 		/* Check allocation length */
4489 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4490 			alc_len = scsipkt->pkt_cdbp[4];
4491 		} else {
4492 			alc_len = scsipkt->pkt_cdbp[7];
4493 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4494 		}
4495 		/*
4496 		 * We do not check for possible parameters truncation
4497 		 * (alc_len < len) assuming that the target driver works
4498 		 * correctly. Just avoiding overrun.
4499 		 * Copy no more than requested and possible, buffer-wise.
4500 		 */
4501 		count = MIN(alc_len, len);
4502 		count = MIN(bp->b_bcount, count);
4503 		bcopy(buf, bp->b_un.b_addr, count);
4504 
4505 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4506 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4507 	}
4508 	*scsipkt->pkt_scbp = STATUS_GOOD;
4509 done:
4510 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4511 	(void) kmem_free(buf, 1024);
4512 
4513 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4514 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4515 
4516 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4517 	    scsipkt->pkt_comp != NULL)
4518 		/* scsi callback required */
4519 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4520 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4521 		    TQ_SLEEP) == NULL)
4522 			/* Scheduling the callback failed */
4523 			return (TRAN_BUSY);
4524 
4525 	return (TRAN_ACCEPT);
4526 }
4527 
4528 
4529 /*
4530  * SATA translate command: Mode Select.
4531  * Translated into appropriate SATA command or emulated.
4532  * Saving parameters is not supported.
4533  * Changing device capacity is not supported (although theoretically
4534  * possible by executing SET FEATURES/SET MAX ADDRESS)
4535  *
4536  * Assumption is that the target driver is working correctly.
4537  *
4538  * More than one SATA command may be executed to perform operations specified
4539  * by mode select pages. The first error terminates further execution.
4540  * Operations performed successully are not backed-up in such case.
4541  *
4542  * NOTE: Implemented pages:
4543  * - caching page
4544  * - informational exception page
4545  * - acoustic management page
4546  * - power condition page
4547  * Caching setup is remembered so it could be re-stored in case of
4548  * an unexpected device reset.
4549  *
4550  * Returns TRAN_XXXX.
4551  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4552  */
4553 
4554 static int
4555 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4556 {
4557 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4558 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4559 	struct scsi_extended_sense *sense;
4560 	int len, pagelen, count, pllen;
4561 	uint8_t *buf;	/* mode select buffer */
4562 	int rval, stat, reason;
4563 	uint_t nointr_flag;
4564 	int dmod = 0;
4565 
4566 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4567 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4568 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4569 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4570 
4571 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4572 
4573 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4574 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4575 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4576 		return (rval);
4577 	}
4578 	/*
4579 	 * If in interrupt context, reject this packet because it may result
4580 	 * in issuing a synchronous command to HBA.
4581 	 */
4582 	if (servicing_interrupt()) {
4583 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4584 		    "sata_txlt_mode_select: rejecting command because "
4585 		    "of interrupt context\n", NULL);
4586 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4587 		return (TRAN_BUSY);
4588 	}
4589 
4590 	rval = TRAN_ACCEPT;
4591 
4592 	scsipkt->pkt_reason = CMD_CMPLT;
4593 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4594 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4595 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4596 
4597 	/* Reject not supported request */
4598 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4599 		*scsipkt->pkt_scbp = STATUS_CHECK;
4600 		sense = sata_arq_sense(spx);
4601 		sense->es_key = KEY_ILLEGAL_REQUEST;
4602 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4603 		goto done;
4604 	}
4605 
4606 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4607 		pllen = scsipkt->pkt_cdbp[4];
4608 	} else {
4609 		pllen = scsipkt->pkt_cdbp[7];
4610 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4611 	}
4612 
4613 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4614 
4615 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4616 		buf = (uint8_t *)bp->b_un.b_addr;
4617 		count = MIN(bp->b_bcount, pllen);
4618 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4619 		scsipkt->pkt_resid = 0;
4620 		pllen = count;
4621 
4622 		/*
4623 		 * Check the header to skip the block descriptor(s) - we
4624 		 * do not support setting device capacity.
4625 		 * Existing macros do not recognize long LBA dscriptor,
4626 		 * hence manual calculation.
4627 		 */
4628 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4629 			/* 6-bytes CMD, 4 bytes header */
4630 			if (count <= 4)
4631 				goto done;		/* header only */
4632 			len = buf[3] + 4;
4633 		} else {
4634 			/* 10-bytes CMD, 8 bytes header */
4635 			if (count <= 8)
4636 				goto done;		/* header only */
4637 			len = buf[6];
4638 			len = (len << 8) + buf[7] + 8;
4639 		}
4640 		if (len >= count)
4641 			goto done;	/* header + descriptor(s) only */
4642 
4643 		pllen -= len;		/* remaining data length */
4644 
4645 		/*
4646 		 * We may be executing SATA command and want to execute it
4647 		 * in SYNCH mode, regardless of scsi_pkt setting.
4648 		 * Save scsi_pkt setting and indicate SYNCH mode
4649 		 */
4650 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4651 		    scsipkt->pkt_comp != NULL) {
4652 			scsipkt->pkt_flags |= FLAG_NOINTR;
4653 		}
4654 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4655 
4656 		/*
4657 		 * len is now the offset to a first mode select page
4658 		 * Process all pages
4659 		 */
4660 		while (pllen > 0) {
4661 			switch ((int)buf[len]) {
4662 			case MODEPAGE_CACHING:
4663 				/* No support for SP (saving) */
4664 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4665 					*scsipkt->pkt_scbp = STATUS_CHECK;
4666 					sense = sata_arq_sense(spx);
4667 					sense->es_key = KEY_ILLEGAL_REQUEST;
4668 					sense->es_add_code =
4669 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4670 					goto done;
4671 				}
4672 				stat = sata_mode_select_page_8(spx,
4673 				    (struct mode_cache_scsi3 *)&buf[len],
4674 				    pllen, &pagelen, &rval, &dmod);
4675 				/*
4676 				 * The pagelen value indicates the number of
4677 				 * parameter bytes already processed.
4678 				 * The rval is the return value from
4679 				 * sata_tran_start().
4680 				 * The stat indicates the overall status of
4681 				 * the operation(s).
4682 				 */
4683 				if (stat != SATA_SUCCESS)
4684 					/*
4685 					 * Page processing did not succeed -
4686 					 * all error info is already set-up,
4687 					 * just return
4688 					 */
4689 					pllen = 0; /* this breaks the loop */
4690 				else {
4691 					len += pagelen;
4692 					pllen -= pagelen;
4693 				}
4694 				break;
4695 
4696 			case MODEPAGE_INFO_EXCPT:
4697 				stat = sata_mode_select_page_1c(spx,
4698 				    (struct mode_info_excpt_page *)&buf[len],
4699 				    pllen, &pagelen, &rval, &dmod);
4700 				/*
4701 				 * The pagelen value indicates the number of
4702 				 * parameter bytes already processed.
4703 				 * The rval is the return value from
4704 				 * sata_tran_start().
4705 				 * The stat indicates the overall status of
4706 				 * the operation(s).
4707 				 */
4708 				if (stat != SATA_SUCCESS)
4709 					/*
4710 					 * Page processing did not succeed -
4711 					 * all error info is already set-up,
4712 					 * just return
4713 					 */
4714 					pllen = 0; /* this breaks the loop */
4715 				else {
4716 					len += pagelen;
4717 					pllen -= pagelen;
4718 				}
4719 				break;
4720 
4721 			case MODEPAGE_ACOUSTIC_MANAG:
4722 				stat = sata_mode_select_page_30(spx,
4723 				    (struct mode_acoustic_management *)
4724 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4725 				/*
4726 				 * The pagelen value indicates the number of
4727 				 * parameter bytes already processed.
4728 				 * The rval is the return value from
4729 				 * sata_tran_start().
4730 				 * The stat indicates the overall status of
4731 				 * the operation(s).
4732 				 */
4733 				if (stat != SATA_SUCCESS)
4734 					/*
4735 					 * Page processing did not succeed -
4736 					 * all error info is already set-up,
4737 					 * just return
4738 					 */
4739 					pllen = 0; /* this breaks the loop */
4740 				else {
4741 					len += pagelen;
4742 					pllen -= pagelen;
4743 				}
4744 
4745 				break;
4746 			case MODEPAGE_POWER_COND:
4747 				stat = sata_mode_select_page_1a(spx,
4748 				    (struct mode_info_power_cond *)&buf[len],
4749 				    pllen, &pagelen, &rval, &dmod);
4750 				/*
4751 				 * The pagelen value indicates the number of
4752 				 * parameter bytes already processed.
4753 				 * The rval is the return value from
4754 				 * sata_tran_start().
4755 				 * The stat indicates the overall status of
4756 				 * the operation(s).
4757 				 */
4758 				if (stat != SATA_SUCCESS)
4759 					/*
4760 					 * Page processing did not succeed -
4761 					 * all error info is already set-up,
4762 					 * just return
4763 					 */
4764 					pllen = 0; /* this breaks the loop */
4765 				else {
4766 					len += pagelen;
4767 					pllen -= pagelen;
4768 				}
4769 				break;
4770 			default:
4771 				*scsipkt->pkt_scbp = STATUS_CHECK;
4772 				sense = sata_arq_sense(spx);
4773 				sense->es_key = KEY_ILLEGAL_REQUEST;
4774 				sense->es_add_code =
4775 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4776 				goto done;
4777 			}
4778 		}
4779 	}
4780 done:
4781 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4782 	/*
4783 	 * If device parameters were modified, fetch and store the new
4784 	 * Identify Device data. Since port mutex could have been released
4785 	 * for accessing HBA driver, we need to re-check device existence.
4786 	 */
4787 	if (dmod != 0) {
4788 		sata_drive_info_t new_sdinfo, *sdinfo;
4789 		int rv = 0;
4790 
4791 		/*
4792 		 * Following statement has to be changed if this function is
4793 		 * used for devices other than SATA hard disks.
4794 		 */
4795 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4796 
4797 		new_sdinfo.satadrv_addr =
4798 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4799 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4800 		    &new_sdinfo);
4801 
4802 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4803 		/*
4804 		 * Since port mutex could have been released when
4805 		 * accessing HBA driver, we need to re-check that the
4806 		 * framework still holds the device info structure.
4807 		 */
4808 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4809 		    &spx->txlt_sata_pkt->satapkt_device);
4810 		if (sdinfo != NULL) {
4811 			/*
4812 			 * Device still has info structure in the
4813 			 * sata framework. Copy newly fetched info
4814 			 */
4815 			if (rv == 0) {
4816 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4817 				sata_save_drive_settings(sdinfo);
4818 			} else {
4819 				/*
4820 				 * Could not fetch new data - invalidate
4821 				 * sata_drive_info. That makes device
4822 				 * unusable.
4823 				 */
4824 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4825 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4826 			}
4827 		}
4828 		if (rv != 0 || sdinfo == NULL) {
4829 			/*
4830 			 * This changes the overall mode select completion
4831 			 * reason to a failed one !!!!!
4832 			 */
4833 			*scsipkt->pkt_scbp = STATUS_CHECK;
4834 			sense = sata_arq_sense(spx);
4835 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4836 			rval = TRAN_ACCEPT;
4837 		}
4838 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4839 	}
4840 	/* Restore the scsi pkt flags */
4841 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4842 	scsipkt->pkt_flags |= nointr_flag;
4843 
4844 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4845 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4846 
4847 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4848 	    scsipkt->pkt_comp != NULL)
4849 		/* scsi callback required */
4850 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4851 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4852 		    TQ_SLEEP) == NULL)
4853 			/* Scheduling the callback failed */
4854 			return (TRAN_BUSY);
4855 
4856 	return (rval);
4857 }
4858 
4859 
4860 
4861 /*
4862  * Translate command: Log Sense
4863  */
4864 static 	int
4865 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4866 {
4867 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4868 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4869 	sata_drive_info_t *sdinfo;
4870 	struct scsi_extended_sense *sense;
4871 	int 		len, count, alc_len;
4872 	int		pc;	/* Page Control code */
4873 	int		page_code;	/* Page code */
4874 	uint8_t		*buf;	/* log sense buffer */
4875 	int		rval, reason;
4876 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4877 
4878 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4879 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4880 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4881 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4882 
4883 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4884 
4885 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4886 
4887 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4888 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4889 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4890 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4891 		return (rval);
4892 	}
4893 	/*
4894 	 * If in interrupt context, reject this packet because it may result
4895 	 * in issuing a synchronous command to HBA.
4896 	 */
4897 	if (servicing_interrupt()) {
4898 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4899 		    "sata_log_sense: rejecting command because "
4900 		    "of interrupt context\n", NULL);
4901 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4902 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4903 		return (TRAN_BUSY);
4904 	}
4905 
4906 	scsipkt->pkt_reason = CMD_CMPLT;
4907 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4908 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4909 
4910 	pc = scsipkt->pkt_cdbp[2] >> 6;
4911 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4912 
4913 	/* Reject not supported request for all but cumulative values */
4914 	switch (pc) {
4915 	case PC_CUMULATIVE_VALUES:
4916 		break;
4917 	default:
4918 		*scsipkt->pkt_scbp = STATUS_CHECK;
4919 		sense = sata_arq_sense(spx);
4920 		sense->es_key = KEY_ILLEGAL_REQUEST;
4921 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4922 		goto done;
4923 	}
4924 
4925 	switch (page_code) {
4926 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4927 	case PAGE_CODE_SELF_TEST_RESULTS:
4928 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4929 	case PAGE_CODE_SMART_READ_DATA:
4930 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
4931 		break;
4932 	default:
4933 		*scsipkt->pkt_scbp = STATUS_CHECK;
4934 		sense = sata_arq_sense(spx);
4935 		sense->es_key = KEY_ILLEGAL_REQUEST;
4936 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4937 		goto done;
4938 	}
4939 
4940 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4941 		/*
4942 		 * Because log sense uses local buffers for data retrieval from
4943 		 * the devices and sets the data programatically in the
4944 		 * original specified buffer, release preallocated DMA
4945 		 * resources before storing data in the original buffer,
4946 		 * so no unwanted DMA sync would take place.
4947 		 */
4948 		sata_id_t *sata_id;
4949 
4950 		sata_scsi_dmafree(NULL, scsipkt);
4951 
4952 		len = 0;
4953 
4954 		/* Build log parameter header */
4955 		buf[len++] = page_code;	/* page code as in the CDB */
4956 		buf[len++] = 0;		/* reserved */
4957 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4958 		buf[len++] = 0;		/* (LSB) */
4959 
4960 		sdinfo = sata_get_device_info(
4961 		    spx->txlt_sata_hba_inst,
4962 		    &spx->txlt_sata_pkt->satapkt_device);
4963 
4964 		/*
4965 		 * Add requested pages.
4966 		 */
4967 		switch (page_code) {
4968 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4969 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4970 			break;
4971 		case PAGE_CODE_SELF_TEST_RESULTS:
4972 			sata_id = &sdinfo->satadrv_id;
4973 			if ((! (sata_id->ai_cmdset84 &
4974 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4975 			    (! (sata_id->ai_features87 &
4976 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4977 				*scsipkt->pkt_scbp = STATUS_CHECK;
4978 				sense = sata_arq_sense(spx);
4979 				sense->es_key = KEY_ILLEGAL_REQUEST;
4980 				sense->es_add_code =
4981 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4982 
4983 				goto done;
4984 			}
4985 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4986 			    spx->txlt_sata_hba_inst);
4987 			break;
4988 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4989 			sata_id = &sdinfo->satadrv_id;
4990 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4991 				*scsipkt->pkt_scbp = STATUS_CHECK;
4992 				sense = sata_arq_sense(spx);
4993 				sense->es_key = KEY_ILLEGAL_REQUEST;
4994 				sense->es_add_code =
4995 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4996 
4997 				goto done;
4998 			}
4999 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5000 				*scsipkt->pkt_scbp = STATUS_CHECK;
5001 				sense = sata_arq_sense(spx);
5002 				sense->es_key = KEY_ABORTED_COMMAND;
5003 				sense->es_add_code =
5004 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5005 				sense->es_qual_code =
5006 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5007 
5008 				goto done;
5009 			}
5010 
5011 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5012 			    spx->txlt_sata_hba_inst);
5013 			break;
5014 		case PAGE_CODE_SMART_READ_DATA:
5015 			sata_id = &sdinfo->satadrv_id;
5016 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5017 				*scsipkt->pkt_scbp = STATUS_CHECK;
5018 				sense = sata_arq_sense(spx);
5019 				sense->es_key = KEY_ILLEGAL_REQUEST;
5020 				sense->es_add_code =
5021 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5022 
5023 				goto done;
5024 			}
5025 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5026 				*scsipkt->pkt_scbp = STATUS_CHECK;
5027 				sense = sata_arq_sense(spx);
5028 				sense->es_key = KEY_ABORTED_COMMAND;
5029 				sense->es_add_code =
5030 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5031 				sense->es_qual_code =
5032 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5033 
5034 				goto done;
5035 			}
5036 
5037 			/* This page doesn't include a page header */
5038 			len = sata_build_lsense_page_30(sdinfo, buf,
5039 			    spx->txlt_sata_hba_inst);
5040 			goto no_header;
5041 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5042 			sata_id = &sdinfo->satadrv_id;
5043 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5044 				*scsipkt->pkt_scbp = STATUS_CHECK;
5045 				sense = sata_arq_sense(spx);
5046 				sense->es_key = KEY_ILLEGAL_REQUEST;
5047 				sense->es_add_code =
5048 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5049 
5050 				goto done;
5051 			}
5052 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5053 				*scsipkt->pkt_scbp = STATUS_CHECK;
5054 				sense = sata_arq_sense(spx);
5055 				sense->es_key = KEY_ABORTED_COMMAND;
5056 				sense->es_add_code =
5057 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5058 				sense->es_qual_code =
5059 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5060 
5061 				goto done;
5062 			}
5063 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5064 			goto no_header;
5065 		default:
5066 			/* Invalid request */
5067 			*scsipkt->pkt_scbp = STATUS_CHECK;
5068 			sense = sata_arq_sense(spx);
5069 			sense->es_key = KEY_ILLEGAL_REQUEST;
5070 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5071 			goto done;
5072 		}
5073 
5074 		/* set parameter log sense data length */
5075 		buf[2] = len >> 8;	/* log sense length (MSB) */
5076 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5077 
5078 		len += SCSI_LOG_PAGE_HDR_LEN;
5079 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5080 
5081 no_header:
5082 		/* Check allocation length */
5083 		alc_len = scsipkt->pkt_cdbp[7];
5084 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5085 
5086 		/*
5087 		 * We do not check for possible parameters truncation
5088 		 * (alc_len < len) assuming that the target driver works
5089 		 * correctly. Just avoiding overrun.
5090 		 * Copy no more than requested and possible, buffer-wise.
5091 		 */
5092 		count = MIN(alc_len, len);
5093 		count = MIN(bp->b_bcount, count);
5094 		bcopy(buf, bp->b_un.b_addr, count);
5095 
5096 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5097 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5098 	}
5099 	*scsipkt->pkt_scbp = STATUS_GOOD;
5100 done:
5101 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5102 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5103 
5104 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5105 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5106 
5107 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5108 	    scsipkt->pkt_comp != NULL)
5109 		/* scsi callback required */
5110 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5111 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5112 		    TQ_SLEEP) == NULL)
5113 			/* Scheduling the callback failed */
5114 			return (TRAN_BUSY);
5115 
5116 	return (TRAN_ACCEPT);
5117 }
5118 
5119 /*
5120  * Translate command: Log Select
5121  * Not implemented at this time - returns invalid command response.
5122  */
5123 static	int
5124 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5125 {
5126 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5127 	    "sata_txlt_log_select\n", NULL);
5128 
5129 	return (sata_txlt_invalid_command(spx));
5130 }
5131 
5132 
5133 /*
5134  * Translate command: Read (various types).
5135  * Translated into appropriate type of ATA READ command
5136  * for SATA hard disks.
5137  * Both the device capabilities and requested operation mode are
5138  * considered.
5139  *
5140  * Following scsi cdb fields are ignored:
5141  * rdprotect, dpo, fua, fua_nv, group_number.
5142  *
5143  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5144  * enable variable sata_func_enable), the capability of the controller and
5145  * capability of a device are checked and if both support queueing, read
5146  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5147  * command rather than plain READ_XXX command.
5148  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5149  * both the controller and device suport such functionality, the read
5150  * request will be translated to READ_FPDMA_QUEUED command.
5151  * In both cases the maximum queue depth is derived as minimum of:
5152  * HBA capability,device capability and sata_max_queue_depth variable setting.
5153  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5154  * used to pass max queue depth value, and the maximum possible queue depth
5155  * is 32.
5156  *
5157  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5158  * appropriate values in scsi_pkt fields.
5159  */
5160 static int
5161 sata_txlt_read(sata_pkt_txlate_t *spx)
5162 {
5163 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5164 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5165 	sata_drive_info_t *sdinfo;
5166 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5167 	int cport = SATA_TXLT_CPORT(spx);
5168 	uint16_t sec_count;
5169 	uint64_t lba;
5170 	int rval, reason;
5171 	int synch;
5172 
5173 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5174 
5175 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5176 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5177 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5178 		return (rval);
5179 	}
5180 
5181 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5182 	    &spx->txlt_sata_pkt->satapkt_device);
5183 
5184 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5185 	/*
5186 	 * Extract LBA and sector count from scsi CDB.
5187 	 */
5188 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5189 	case SCMD_READ:
5190 		/* 6-byte scsi read cmd : 0x08 */
5191 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5192 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5193 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5194 		sec_count = scsipkt->pkt_cdbp[4];
5195 		/* sec_count 0 will be interpreted as 256 by a device */
5196 		break;
5197 	case SCMD_READ_G1:
5198 		/* 10-bytes scsi read command : 0x28 */
5199 		lba = scsipkt->pkt_cdbp[2];
5200 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5201 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5202 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5203 		sec_count = scsipkt->pkt_cdbp[7];
5204 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5205 		break;
5206 	case SCMD_READ_G5:
5207 		/* 12-bytes scsi read command : 0xA8 */
5208 		lba = scsipkt->pkt_cdbp[2];
5209 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5210 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5211 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5212 		sec_count = scsipkt->pkt_cdbp[6];
5213 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5214 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5215 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5216 		break;
5217 	case SCMD_READ_G4:
5218 		/* 16-bytes scsi read command : 0x88 */
5219 		lba = scsipkt->pkt_cdbp[2];
5220 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5221 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5222 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5223 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5224 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5225 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5226 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5227 		sec_count = scsipkt->pkt_cdbp[10];
5228 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5229 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5230 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5231 		break;
5232 	default:
5233 		/* Unsupported command */
5234 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5235 		return (sata_txlt_invalid_command(spx));
5236 	}
5237 
5238 	/*
5239 	 * Check if specified address exceeds device capacity
5240 	 */
5241 	if ((lba >= sdinfo->satadrv_capacity) ||
5242 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5243 		/* LBA out of range */
5244 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5245 		return (sata_txlt_lba_out_of_range(spx));
5246 	}
5247 
5248 	/*
5249 	 * For zero-length transfer, emulate good completion of the command
5250 	 * (reasons for rejecting the command were already checked).
5251 	 * No DMA resources were allocated.
5252 	 */
5253 	if (spx->txlt_dma_cookie_list == NULL) {
5254 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5255 		return (sata_emul_rw_completion(spx));
5256 	}
5257 
5258 	/*
5259 	 * Build cmd block depending on the device capability and
5260 	 * requested operation mode.
5261 	 * Do not bother with non-dma mode - we are working only with
5262 	 * devices supporting DMA.
5263 	 */
5264 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5265 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5266 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5267 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5268 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5269 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5270 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5271 #ifndef __lock_lint
5272 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5273 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5274 		scmd->satacmd_lba_high_msb = lba >> 40;
5275 #endif
5276 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5277 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5278 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5279 	}
5280 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5281 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5282 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5283 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5284 	scmd->satacmd_features_reg = 0;
5285 	scmd->satacmd_status_reg = 0;
5286 	scmd->satacmd_error_reg = 0;
5287 
5288 	/*
5289 	 * Check if queueing commands should be used and switch
5290 	 * to appropriate command if possible
5291 	 */
5292 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5293 		boolean_t using_queuing;
5294 
5295 		/* Queuing supported by controller and device? */
5296 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5297 		    (sdinfo->satadrv_features_support &
5298 		    SATA_DEV_F_NCQ) &&
5299 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5300 		    SATA_CTLF_NCQ)) {
5301 			using_queuing = B_TRUE;
5302 
5303 			/* NCQ supported - use FPDMA READ */
5304 			scmd->satacmd_cmd_reg =
5305 			    SATAC_READ_FPDMA_QUEUED;
5306 			scmd->satacmd_features_reg_ext =
5307 			    scmd->satacmd_sec_count_msb;
5308 			scmd->satacmd_sec_count_msb = 0;
5309 		} else if ((sdinfo->satadrv_features_support &
5310 		    SATA_DEV_F_TCQ) &&
5311 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5312 		    SATA_CTLF_QCMD)) {
5313 			using_queuing = B_TRUE;
5314 
5315 			/* Legacy queueing */
5316 			if (sdinfo->satadrv_features_support &
5317 			    SATA_DEV_F_LBA48) {
5318 				scmd->satacmd_cmd_reg =
5319 				    SATAC_READ_DMA_QUEUED_EXT;
5320 				scmd->satacmd_features_reg_ext =
5321 				    scmd->satacmd_sec_count_msb;
5322 				scmd->satacmd_sec_count_msb = 0;
5323 			} else {
5324 				scmd->satacmd_cmd_reg =
5325 				    SATAC_READ_DMA_QUEUED;
5326 			}
5327 		} else	/* NCQ nor legacy queuing not supported */
5328 			using_queuing = B_FALSE;
5329 
5330 		/*
5331 		 * If queuing, the sector count goes in the features register
5332 		 * and the secount count will contain the tag.
5333 		 */
5334 		if (using_queuing) {
5335 			scmd->satacmd_features_reg =
5336 			    scmd->satacmd_sec_count_lsb;
5337 			scmd->satacmd_sec_count_lsb = 0;
5338 			scmd->satacmd_flags.sata_queued = B_TRUE;
5339 
5340 			/* Set-up maximum queue depth */
5341 			scmd->satacmd_flags.sata_max_queue_depth =
5342 			    sdinfo->satadrv_max_queue_depth - 1;
5343 		} else if (sdinfo->satadrv_features_enabled &
5344 		    SATA_DEV_F_E_UNTAGGED_QING) {
5345 			/*
5346 			 * Although NCQ/TCQ is not enabled, untagged queuing
5347 			 * may be still used.
5348 			 * Set-up the maximum untagged queue depth.
5349 			 * Use controller's queue depth from sata_hba_tran.
5350 			 * SATA HBA drivers may ignore this value and rely on
5351 			 * the internal limits.For drivers that do not
5352 			 * ignore untaged queue depth, limit the value to
5353 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5354 			 * largest value that can be passed via
5355 			 * satacmd_flags.sata_max_queue_depth.
5356 			 */
5357 			scmd->satacmd_flags.sata_max_queue_depth =
5358 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5359 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5360 
5361 		} else {
5362 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5363 		}
5364 	} else
5365 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5366 
5367 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5368 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5369 	    scmd->satacmd_cmd_reg, lba, sec_count);
5370 
5371 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5372 		/* Need callback function */
5373 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5374 		synch = FALSE;
5375 	} else
5376 		synch = TRUE;
5377 
5378 	/* Transfer command to HBA */
5379 	if (sata_hba_start(spx, &rval) != 0) {
5380 		/* Pkt not accepted for execution */
5381 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5382 		return (rval);
5383 	}
5384 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5385 	/*
5386 	 * If execution is non-synchronous,
5387 	 * a callback function will handle potential errors, translate
5388 	 * the response and will do a callback to a target driver.
5389 	 * If it was synchronous, check execution status using the same
5390 	 * framework callback.
5391 	 */
5392 	if (synch) {
5393 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5394 		    "synchronous execution status %x\n",
5395 		    spx->txlt_sata_pkt->satapkt_reason);
5396 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5397 	}
5398 	return (TRAN_ACCEPT);
5399 }
5400 
5401 
5402 /*
5403  * SATA translate command: Write (various types)
5404  * Translated into appropriate type of ATA WRITE command
5405  * for SATA hard disks.
5406  * Both the device capabilities and requested operation mode are
5407  * considered.
5408  *
5409  * Following scsi cdb fields are ignored:
5410  * rwprotect, dpo, fua, fua_nv, group_number.
5411  *
5412  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5413  * enable variable sata_func_enable), the capability of the controller and
5414  * capability of a device are checked and if both support queueing, write
5415  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5416  * command rather than plain WRITE_XXX command.
5417  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5418  * both the controller and device suport such functionality, the write
5419  * request will be translated to WRITE_FPDMA_QUEUED command.
5420  * In both cases the maximum queue depth is derived as minimum of:
5421  * HBA capability,device capability and sata_max_queue_depth variable setting.
5422  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5423  * used to pass max queue depth value, and the maximum possible queue depth
5424  * is 32.
5425  *
5426  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5427  * appropriate values in scsi_pkt fields.
5428  */
5429 static int
5430 sata_txlt_write(sata_pkt_txlate_t *spx)
5431 {
5432 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5433 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5434 	sata_drive_info_t *sdinfo;
5435 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5436 	int cport = SATA_TXLT_CPORT(spx);
5437 	uint16_t sec_count;
5438 	uint64_t lba;
5439 	int rval, reason;
5440 	int synch;
5441 
5442 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5443 
5444 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5445 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5446 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5447 		return (rval);
5448 	}
5449 
5450 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5451 	    &spx->txlt_sata_pkt->satapkt_device);
5452 
5453 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5454 	/*
5455 	 * Extract LBA and sector count from scsi CDB
5456 	 */
5457 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5458 	case SCMD_WRITE:
5459 		/* 6-byte scsi read cmd : 0x0A */
5460 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5461 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5462 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5463 		sec_count = scsipkt->pkt_cdbp[4];
5464 		/* sec_count 0 will be interpreted as 256 by a device */
5465 		break;
5466 	case SCMD_WRITE_G1:
5467 		/* 10-bytes scsi write command : 0x2A */
5468 		lba = scsipkt->pkt_cdbp[2];
5469 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5470 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5471 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5472 		sec_count = scsipkt->pkt_cdbp[7];
5473 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5474 		break;
5475 	case SCMD_WRITE_G5:
5476 		/* 12-bytes scsi read command : 0xAA */
5477 		lba = scsipkt->pkt_cdbp[2];
5478 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5479 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5480 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5481 		sec_count = scsipkt->pkt_cdbp[6];
5482 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5483 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5484 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5485 		break;
5486 	case SCMD_WRITE_G4:
5487 		/* 16-bytes scsi write command : 0x8A */
5488 		lba = scsipkt->pkt_cdbp[2];
5489 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5490 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5491 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5492 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5493 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5494 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5495 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5496 		sec_count = scsipkt->pkt_cdbp[10];
5497 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5498 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5499 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5500 		break;
5501 	default:
5502 		/* Unsupported command */
5503 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5504 		return (sata_txlt_invalid_command(spx));
5505 	}
5506 
5507 	/*
5508 	 * Check if specified address and length exceeds device capacity
5509 	 */
5510 	if ((lba >= sdinfo->satadrv_capacity) ||
5511 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5512 		/* LBA out of range */
5513 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5514 		return (sata_txlt_lba_out_of_range(spx));
5515 	}
5516 
5517 	/*
5518 	 * For zero-length transfer, emulate good completion of the command
5519 	 * (reasons for rejecting the command were already checked).
5520 	 * No DMA resources were allocated.
5521 	 */
5522 	if (spx->txlt_dma_cookie_list == NULL) {
5523 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5524 		return (sata_emul_rw_completion(spx));
5525 	}
5526 
5527 	/*
5528 	 * Build cmd block depending on the device capability and
5529 	 * requested operation mode.
5530 	 * Do not bother with non-dma mode- we are working only with
5531 	 * devices supporting DMA.
5532 	 */
5533 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5534 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5535 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5536 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5537 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5538 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5539 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5540 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5541 #ifndef __lock_lint
5542 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5543 		scmd->satacmd_lba_high_msb = lba >> 40;
5544 #endif
5545 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5546 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5547 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5548 	}
5549 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5550 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5551 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5552 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5553 	scmd->satacmd_features_reg = 0;
5554 	scmd->satacmd_status_reg = 0;
5555 	scmd->satacmd_error_reg = 0;
5556 
5557 	/*
5558 	 * Check if queueing commands should be used and switch
5559 	 * to appropriate command if possible
5560 	 */
5561 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5562 		boolean_t using_queuing;
5563 
5564 		/* Queuing supported by controller and device? */
5565 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5566 		    (sdinfo->satadrv_features_support &
5567 		    SATA_DEV_F_NCQ) &&
5568 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5569 		    SATA_CTLF_NCQ)) {
5570 			using_queuing = B_TRUE;
5571 
5572 			/* NCQ supported - use FPDMA WRITE */
5573 			scmd->satacmd_cmd_reg =
5574 			    SATAC_WRITE_FPDMA_QUEUED;
5575 			scmd->satacmd_features_reg_ext =
5576 			    scmd->satacmd_sec_count_msb;
5577 			scmd->satacmd_sec_count_msb = 0;
5578 		} else if ((sdinfo->satadrv_features_support &
5579 		    SATA_DEV_F_TCQ) &&
5580 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5581 		    SATA_CTLF_QCMD)) {
5582 			using_queuing = B_TRUE;
5583 
5584 			/* Legacy queueing */
5585 			if (sdinfo->satadrv_features_support &
5586 			    SATA_DEV_F_LBA48) {
5587 				scmd->satacmd_cmd_reg =
5588 				    SATAC_WRITE_DMA_QUEUED_EXT;
5589 				scmd->satacmd_features_reg_ext =
5590 				    scmd->satacmd_sec_count_msb;
5591 				scmd->satacmd_sec_count_msb = 0;
5592 			} else {
5593 				scmd->satacmd_cmd_reg =
5594 				    SATAC_WRITE_DMA_QUEUED;
5595 			}
5596 		} else	/*  NCQ nor legacy queuing not supported */
5597 			using_queuing = B_FALSE;
5598 
5599 		if (using_queuing) {
5600 			scmd->satacmd_features_reg =
5601 			    scmd->satacmd_sec_count_lsb;
5602 			scmd->satacmd_sec_count_lsb = 0;
5603 			scmd->satacmd_flags.sata_queued = B_TRUE;
5604 			/* Set-up maximum queue depth */
5605 			scmd->satacmd_flags.sata_max_queue_depth =
5606 			    sdinfo->satadrv_max_queue_depth - 1;
5607 		} else if (sdinfo->satadrv_features_enabled &
5608 		    SATA_DEV_F_E_UNTAGGED_QING) {
5609 			/*
5610 			 * Although NCQ/TCQ is not enabled, untagged queuing
5611 			 * may be still used.
5612 			 * Set-up the maximum untagged queue depth.
5613 			 * Use controller's queue depth from sata_hba_tran.
5614 			 * SATA HBA drivers may ignore this value and rely on
5615 			 * the internal limits. For drivera that do not
5616 			 * ignore untaged queue depth, limit the value to
5617 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5618 			 * largest value that can be passed via
5619 			 * satacmd_flags.sata_max_queue_depth.
5620 			 */
5621 			scmd->satacmd_flags.sata_max_queue_depth =
5622 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5623 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5624 
5625 		} else {
5626 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5627 		}
5628 	} else
5629 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5630 
5631 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5632 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5633 	    scmd->satacmd_cmd_reg, lba, sec_count);
5634 
5635 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5636 		/* Need callback function */
5637 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5638 		synch = FALSE;
5639 	} else
5640 		synch = TRUE;
5641 
5642 	/* Transfer command to HBA */
5643 	if (sata_hba_start(spx, &rval) != 0) {
5644 		/* Pkt not accepted for execution */
5645 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5646 		return (rval);
5647 	}
5648 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5649 
5650 	/*
5651 	 * If execution is non-synchronous,
5652 	 * a callback function will handle potential errors, translate
5653 	 * the response and will do a callback to a target driver.
5654 	 * If it was synchronous, check execution status using the same
5655 	 * framework callback.
5656 	 */
5657 	if (synch) {
5658 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5659 		    "synchronous execution status %x\n",
5660 		    spx->txlt_sata_pkt->satapkt_reason);
5661 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5662 	}
5663 	return (TRAN_ACCEPT);
5664 }
5665 
5666 
5667 /*
5668  * Implements SCSI SBC WRITE BUFFER command download microcode option
5669  */
5670 static int
5671 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
5672 {
5673 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
5674 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
5675 
5676 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
5677 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5678 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
5679 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5680 
5681 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5682 	struct scsi_extended_sense *sense;
5683 	int rval, mode, sector_count, reason;
5684 	int cport = SATA_TXLT_CPORT(spx);
5685 
5686 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
5687 
5688 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5689 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
5690 
5691 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5692 
5693 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason)) != TRAN_ACCEPT) {
5694 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5695 		return (rval);
5696 	}
5697 	/*
5698 	 * If in interrupt context, reject this packet because it would issue
5699 	 * a synchronous command to HBA.
5700 	 */
5701 	if (servicing_interrupt()) {
5702 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
5703 		    "sata_txlt_write_buffer: rejecting command because "
5704 		    "of interrupt context\n", NULL);
5705 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5706 		return (TRAN_BUSY);
5707 	}
5708 
5709 	/* Use synchronous mode */
5710 	spx->txlt_sata_pkt->satapkt_op_mode
5711 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
5712 
5713 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5714 
5715 	scsipkt->pkt_reason = CMD_CMPLT;
5716 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5717 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5718 
5719 	/*
5720 	 * The SCSI to ATA translation specification only calls
5721 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
5722 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
5723 	 * ATA 8 (draft) got rid of download microcode for temp
5724 	 * and it is even optional for ATA 7, so it may be aborted.
5725 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
5726 	 * it is not specified and the buffer offset for SCSI is a 16-bit
5727 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
5728 	 * sectors.  Thus the offset really doesn't buy us anything.
5729 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
5730 	 * is revised, this can be revisisted.
5731 	 */
5732 	/* Reject not supported request */
5733 	switch (mode) {
5734 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
5735 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
5736 		break;
5737 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
5738 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
5739 		break;
5740 	default:
5741 		goto bad_param;
5742 	}
5743 
5744 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5745 
5746 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
5747 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
5748 		goto bad_param;
5749 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
5750 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
5751 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
5752 	scmd->satacmd_lba_mid_lsb = 0;
5753 	scmd->satacmd_lba_high_lsb = 0;
5754 	scmd->satacmd_device_reg = 0;
5755 	spx->txlt_sata_pkt->satapkt_comp = NULL;
5756 	scmd->satacmd_addr_type = 0;
5757 
5758 	/* Transfer command to HBA */
5759 	if (sata_hba_start(spx, &rval) != 0) {
5760 		/* Pkt not accepted for execution */
5761 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5762 		return (rval);
5763 	}
5764 
5765 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5766 
5767 	/* Then we need synchronous check the status of the disk */
5768 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5769 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5770 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5771 		scsipkt->pkt_reason = CMD_CMPLT;
5772 
5773 		/* Download commmand succeed, so probe and identify device */
5774 		sata_reidentify_device(spx);
5775 	} else {
5776 		/* Something went wrong, microcode download command failed */
5777 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5778 		*scsipkt->pkt_scbp = STATUS_CHECK;
5779 		sense = sata_arq_sense(spx);
5780 		switch (sata_pkt->satapkt_reason) {
5781 		case SATA_PKT_PORT_ERROR:
5782 			/*
5783 			 * We have no device data. Assume no data transfered.
5784 			 */
5785 			sense->es_key = KEY_HARDWARE_ERROR;
5786 			break;
5787 
5788 		case SATA_PKT_DEV_ERROR:
5789 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5790 			    SATA_STATUS_ERR) {
5791 				/*
5792 				 * determine dev error reason from error
5793 				 * reg content
5794 				 */
5795 				sata_decode_device_error(spx, sense);
5796 				break;
5797 			}
5798 			/* No extended sense key - no info available */
5799 			break;
5800 
5801 		case SATA_PKT_TIMEOUT:
5802 			scsipkt->pkt_reason = CMD_TIMEOUT;
5803 			scsipkt->pkt_statistics |=
5804 			    STAT_TIMEOUT | STAT_DEV_RESET;
5805 			/* No extended sense key ? */
5806 			break;
5807 
5808 		case SATA_PKT_ABORTED:
5809 			scsipkt->pkt_reason = CMD_ABORTED;
5810 			scsipkt->pkt_statistics |= STAT_ABORTED;
5811 			/* No extended sense key ? */
5812 			break;
5813 
5814 		case SATA_PKT_RESET:
5815 			/* pkt aborted by an explicit reset from a host */
5816 			scsipkt->pkt_reason = CMD_RESET;
5817 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5818 			break;
5819 
5820 		default:
5821 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5822 			    "sata_txlt_nodata_cmd_completion: "
5823 			    "invalid packet completion reason %d",
5824 			    sata_pkt->satapkt_reason));
5825 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5826 			break;
5827 		}
5828 
5829 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5830 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5831 
5832 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5833 			/* scsi callback required */
5834 			scsi_hba_pkt_comp(scsipkt);
5835 	}
5836 	return (TRAN_ACCEPT);
5837 
5838 bad_param:
5839 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5840 	*scsipkt->pkt_scbp = STATUS_CHECK;
5841 	sense = sata_arq_sense(spx);
5842 	sense->es_key = KEY_ILLEGAL_REQUEST;
5843 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5844 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5845 	    scsipkt->pkt_comp != NULL) {
5846 		/* scsi callback required */
5847 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5848 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5849 		    TQ_SLEEP) == 0) {
5850 			/* Scheduling the callback failed */
5851 			rval = TRAN_BUSY;
5852 		}
5853 	}
5854 	return (rval);
5855 }
5856 
5857 /*
5858  * Re-identify device after doing a firmware download.
5859  */
5860 static void
5861 sata_reidentify_device(sata_pkt_txlate_t *spx)
5862 {
5863 #define	DOWNLOAD_WAIT_TIME_SECS	60
5864 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
5865 	int rval;
5866 	int retry_cnt;
5867 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5868 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5869 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
5870 	sata_drive_info_t *sdinfo;
5871 
5872 	/*
5873 	 * Before returning good status, probe device.
5874 	 * Device probing will get IDENTIFY DEVICE data, if possible.
5875 	 * The assumption is that the new microcode is applied by the
5876 	 * device. It is a caller responsibility to verify this.
5877 	 */
5878 	for (retry_cnt = 0;
5879 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
5880 	    retry_cnt++) {
5881 		rval = sata_probe_device(sata_hba_inst, &sata_device);
5882 
5883 		if (rval == SATA_SUCCESS) { /* Set default features */
5884 			sdinfo = sata_get_device_info(sata_hba_inst,
5885 			    &sata_device);
5886 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
5887 			    SATA_SUCCESS) {
5888 				/* retry */
5889 				rval = sata_initialize_device(sata_hba_inst,
5890 				    sdinfo);
5891 				if (rval == SATA_RETRY)
5892 					sata_log(sata_hba_inst, CE_WARN,
5893 					    "SATA device at port %d pmport %d -"
5894 					    " default device features could not"
5895 					    " be set. Device may not operate "
5896 					    "as expected.",
5897 					    sata_device.satadev_addr.cport,
5898 					    sata_device.satadev_addr.pmport);
5899 			}
5900 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5901 				scsi_hba_pkt_comp(scsipkt);
5902 			return;
5903 		} else if (rval == SATA_RETRY) {
5904 			delay(drv_usectohz(1000000 *
5905 			    DOWNLOAD_WAIT_INTERVAL_SECS));
5906 			continue;
5907 		} else	/* failed - no reason to retry */
5908 			break;
5909 	}
5910 
5911 	/*
5912 	 * Something went wrong, device probing failed.
5913 	 */
5914 	SATA_LOG_D((sata_hba_inst, CE_WARN,
5915 	    "Cannot probe device after downloading microcode\n"));
5916 
5917 	/* Reset device to force retrying the probe. */
5918 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
5919 	    (SATA_DIP(sata_hba_inst), &sata_device);
5920 
5921 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5922 		scsi_hba_pkt_comp(scsipkt);
5923 }
5924 
5925 
5926 /*
5927  * Translate command: Synchronize Cache.
5928  * Translates into Flush Cache command for SATA hard disks.
5929  *
5930  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5931  * appropriate values in scsi_pkt fields.
5932  */
5933 static 	int
5934 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5935 {
5936 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5937 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5938 	int cport = SATA_TXLT_CPORT(spx);
5939 	int rval, reason;
5940 	int synch;
5941 
5942 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5943 
5944 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5945 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5946 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5947 		return (rval);
5948 	}
5949 
5950 	scmd->satacmd_addr_type = 0;
5951 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5952 	scmd->satacmd_device_reg = 0;
5953 	scmd->satacmd_sec_count_lsb = 0;
5954 	scmd->satacmd_lba_low_lsb = 0;
5955 	scmd->satacmd_lba_mid_lsb = 0;
5956 	scmd->satacmd_lba_high_lsb = 0;
5957 	scmd->satacmd_features_reg = 0;
5958 	scmd->satacmd_status_reg = 0;
5959 	scmd->satacmd_error_reg = 0;
5960 
5961 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5962 	    "sata_txlt_synchronize_cache\n", NULL);
5963 
5964 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5965 		/* Need to set-up a callback function */
5966 		spx->txlt_sata_pkt->satapkt_comp =
5967 		    sata_txlt_nodata_cmd_completion;
5968 		synch = FALSE;
5969 	} else
5970 		synch = TRUE;
5971 
5972 	/* Transfer command to HBA */
5973 	if (sata_hba_start(spx, &rval) != 0) {
5974 		/* Pkt not accepted for execution */
5975 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5976 		return (rval);
5977 	}
5978 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5979 
5980 	/*
5981 	 * If execution non-synchronous, it had to be completed
5982 	 * a callback function will handle potential errors, translate
5983 	 * the response and will do a callback to a target driver.
5984 	 * If it was synchronous, check status, using the same
5985 	 * framework callback.
5986 	 */
5987 	if (synch) {
5988 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5989 		    "synchronous execution status %x\n",
5990 		    spx->txlt_sata_pkt->satapkt_reason);
5991 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5992 	}
5993 	return (TRAN_ACCEPT);
5994 }
5995 
5996 
5997 /*
5998  * Send pkt to SATA HBA driver
5999  *
6000  * This function may be called only if the operation is requested by scsi_pkt,
6001  * i.e. scsi_pkt is not NULL.
6002  *
6003  * This function has to be called with cport mutex held. It does release
6004  * the mutex when it calls HBA driver sata_tran_start function and
6005  * re-acquires it afterwards.
6006  *
6007  * If return value is 0, pkt was accepted, -1 otherwise
6008  * rval is set to appropriate sata_scsi_start return value.
6009  *
6010  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6011  * have called the sata_pkt callback function for this packet.
6012  *
6013  * The scsi callback has to be performed by the caller of this routine.
6014  */
6015 static int
6016 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6017 {
6018 	int stat;
6019 	uint8_t cport = SATA_TXLT_CPORT(spx);
6020 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6021 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6022 	sata_drive_info_t *sdinfo;
6023 	sata_pmult_info_t *pminfo;
6024 	sata_pmport_info_t *pmportinfo = NULL;
6025 	sata_device_t *sata_device = NULL;
6026 	uint8_t cmd;
6027 	struct sata_cmd_flags cmd_flags;
6028 
6029 	ASSERT(spx->txlt_sata_pkt != NULL);
6030 
6031 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6032 
6033 	sdinfo = sata_get_device_info(sata_hba_inst,
6034 	    &spx->txlt_sata_pkt->satapkt_device);
6035 	ASSERT(sdinfo != NULL);
6036 
6037 	/* Clear device reset state? */
6038 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6039 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6040 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6041 
6042 		/*
6043 		 * Get the pmult_info of the its parent port multiplier, all
6044 		 * sub-devices share a common device reset flags on in
6045 		 * pmult_info.
6046 		 */
6047 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6048 		pmportinfo = pminfo->pmult_dev_port[pmport];
6049 		ASSERT(pminfo != NULL);
6050 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6051 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6052 			    sata_clear_dev_reset = B_TRUE;
6053 			pminfo->pmult_event_flags &=
6054 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6055 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6056 			    "sata_hba_start: clearing device reset state"
6057 			    "on pmult.\n", NULL);
6058 		}
6059 	} else {
6060 		if (sdinfo->satadrv_event_flags &
6061 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6062 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6063 			    sata_clear_dev_reset = B_TRUE;
6064 			sdinfo->satadrv_event_flags &=
6065 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6066 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6067 			    "sata_hba_start: clearing device reset state\n",
6068 			    NULL);
6069 		}
6070 	}
6071 
6072 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6073 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6074 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6075 
6076 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6077 
6078 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6079 	    "Sata cmd 0x%2x\n", cmd);
6080 
6081 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6082 	    spx->txlt_sata_pkt);
6083 
6084 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6085 	/*
6086 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6087 	 * with the sata callback, the sata_pkt could be already destroyed
6088 	 * by the time we check ther return status from the hba_start()
6089 	 * function, because sata_scsi_destroy_pkt() could have been already
6090 	 * called (perhaps in the interrupt context). So, in such case, there
6091 	 * should be no references to it. In other cases, sata_pkt still
6092 	 * exists.
6093 	 */
6094 	if (stat == SATA_TRAN_ACCEPTED) {
6095 		/*
6096 		 * pkt accepted for execution.
6097 		 * If it was executed synchronously, it is already completed
6098 		 * and pkt completion_reason indicates completion status.
6099 		 */
6100 		*rval = TRAN_ACCEPT;
6101 		return (0);
6102 	}
6103 
6104 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6105 	switch (stat) {
6106 	case SATA_TRAN_QUEUE_FULL:
6107 		/*
6108 		 * Controller detected queue full condition.
6109 		 */
6110 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6111 		    "sata_hba_start: queue full\n", NULL);
6112 
6113 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6114 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6115 
6116 		*rval = TRAN_BUSY;
6117 		break;
6118 
6119 	case SATA_TRAN_PORT_ERROR:
6120 		/*
6121 		 * Communication/link with device or general port error
6122 		 * detected before pkt execution begun.
6123 		 */
6124 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6125 		    SATA_ADDR_CPORT ||
6126 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6127 		    SATA_ADDR_DCPORT)
6128 			sata_log(sata_hba_inst, CE_CONT,
6129 			    "SATA port %d error",
6130 			    sata_device->satadev_addr.cport);
6131 		else
6132 			sata_log(sata_hba_inst, CE_CONT,
6133 			    "SATA port %d:%d error\n",
6134 			    sata_device->satadev_addr.cport,
6135 			    sata_device->satadev_addr.pmport);
6136 
6137 		/*
6138 		 * Update the port/device structure.
6139 		 * sata_pkt should be still valid. Since port error is
6140 		 * returned, sata_device content should reflect port
6141 		 * state - it means, that sata address have been changed,
6142 		 * because original packet's sata address refered to a device
6143 		 * attached to some port.
6144 		 */
6145 		if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6146 		    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6147 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6148 			mutex_enter(&pmportinfo->pmport_mutex);
6149 			sata_update_pmport_info(sata_hba_inst, sata_device);
6150 			mutex_exit(&pmportinfo->pmport_mutex);
6151 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6152 		} else {
6153 			sata_update_port_info(sata_hba_inst, sata_device);
6154 		}
6155 
6156 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6157 		*rval = TRAN_FATAL_ERROR;
6158 		break;
6159 
6160 	case SATA_TRAN_CMD_UNSUPPORTED:
6161 		/*
6162 		 * Command rejected by HBA as unsupported. It was HBA driver
6163 		 * that rejected the command, command was not sent to
6164 		 * an attached device.
6165 		 */
6166 		if ((sdinfo != NULL) &&
6167 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6168 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6169 			    "sat_hba_start: cmd 0x%2x rejected "
6170 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6171 
6172 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6173 		(void) sata_txlt_invalid_command(spx);
6174 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6175 
6176 		*rval = TRAN_ACCEPT;
6177 		break;
6178 
6179 	case SATA_TRAN_BUSY:
6180 		/*
6181 		 * Command rejected by HBA because other operation prevents
6182 		 * accepting the packet, or device is in RESET condition.
6183 		 */
6184 		if (sdinfo != NULL) {
6185 			sdinfo->satadrv_state =
6186 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6187 
6188 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6189 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6190 				    "sata_hba_start: cmd 0x%2x rejected "
6191 				    "because of device reset condition\n",
6192 				    cmd);
6193 			} else {
6194 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6195 				    "sata_hba_start: cmd 0x%2x rejected "
6196 				    "with SATA_TRAN_BUSY status\n",
6197 				    cmd);
6198 			}
6199 		}
6200 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6201 		*rval = TRAN_BUSY;
6202 		break;
6203 
6204 	default:
6205 		/* Unrecognized HBA response */
6206 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6207 		    "sata_hba_start: unrecognized HBA response "
6208 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6209 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6210 		*rval = TRAN_FATAL_ERROR;
6211 		break;
6212 	}
6213 
6214 	/*
6215 	 * If we got here, the packet was rejected.
6216 	 * Check if we need to remember reset state clearing request
6217 	 */
6218 	if (cmd_flags.sata_clear_dev_reset) {
6219 		/*
6220 		 * Check if device is still configured - it may have
6221 		 * disapeared from the configuration
6222 		 */
6223 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6224 		if (sdinfo != NULL) {
6225 			/*
6226 			 * Restore the flag that requests clearing of
6227 			 * the device reset state,
6228 			 * so the next sata packet may carry it to HBA.
6229 			 */
6230 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6231 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6232 				pminfo->pmult_event_flags |=
6233 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6234 			} else {
6235 				sdinfo->satadrv_event_flags |=
6236 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6237 			}
6238 		}
6239 	}
6240 	return (-1);
6241 }
6242 
6243 /*
6244  * Scsi response setup for invalid LBA
6245  *
6246  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6247  */
6248 static int
6249 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6250 {
6251 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6252 	struct scsi_extended_sense *sense;
6253 
6254 	scsipkt->pkt_reason = CMD_CMPLT;
6255 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6256 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6257 	*scsipkt->pkt_scbp = STATUS_CHECK;
6258 
6259 	*scsipkt->pkt_scbp = STATUS_CHECK;
6260 	sense = sata_arq_sense(spx);
6261 	sense->es_key = KEY_ILLEGAL_REQUEST;
6262 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6263 
6264 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6265 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6266 
6267 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6268 	    scsipkt->pkt_comp != NULL)
6269 		/* scsi callback required */
6270 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6271 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6272 		    TQ_SLEEP) == NULL)
6273 			/* Scheduling the callback failed */
6274 			return (TRAN_BUSY);
6275 	return (TRAN_ACCEPT);
6276 }
6277 
6278 
6279 /*
6280  * Analyze device status and error registers and translate them into
6281  * appropriate scsi sense codes.
6282  * NOTE: non-packet commands only for now
6283  */
6284 static void
6285 sata_decode_device_error(sata_pkt_txlate_t *spx,
6286     struct scsi_extended_sense *sense)
6287 {
6288 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6289 
6290 	ASSERT(sense != NULL);
6291 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6292 	    SATA_STATUS_ERR);
6293 
6294 
6295 	if (err_reg & SATA_ERROR_ICRC) {
6296 		sense->es_key = KEY_ABORTED_COMMAND;
6297 		sense->es_add_code = 0x08; /* Communication failure */
6298 		return;
6299 	}
6300 
6301 	if (err_reg & SATA_ERROR_UNC) {
6302 		sense->es_key = KEY_MEDIUM_ERROR;
6303 		/* Information bytes (LBA) need to be set by a caller */
6304 		return;
6305 	}
6306 
6307 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6308 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6309 		sense->es_key = KEY_UNIT_ATTENTION;
6310 		sense->es_add_code = 0x3a; /* No media present */
6311 		return;
6312 	}
6313 
6314 	if (err_reg & SATA_ERROR_IDNF) {
6315 		if (err_reg & SATA_ERROR_ABORT) {
6316 			sense->es_key = KEY_ABORTED_COMMAND;
6317 		} else {
6318 			sense->es_key = KEY_ILLEGAL_REQUEST;
6319 			sense->es_add_code = 0x21; /* LBA out of range */
6320 		}
6321 		return;
6322 	}
6323 
6324 	if (err_reg & SATA_ERROR_ABORT) {
6325 		ASSERT(spx->txlt_sata_pkt != NULL);
6326 		sense->es_key = KEY_ABORTED_COMMAND;
6327 		return;
6328 	}
6329 }
6330 
6331 /*
6332  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6333  */
6334 static void
6335 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6336 {
6337 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6338 
6339 	*lba = 0;
6340 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6341 		*lba = sata_cmd->satacmd_lba_high_msb;
6342 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6343 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6344 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6345 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6346 	}
6347 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6348 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6349 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6350 }
6351 
6352 /*
6353  * This is fixed sense format - if LBA exceeds the info field size,
6354  * no valid info will be returned (valid bit in extended sense will
6355  * be set to 0).
6356  */
6357 static struct scsi_extended_sense *
6358 sata_arq_sense(sata_pkt_txlate_t *spx)
6359 {
6360 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6361 	struct scsi_arq_status *arqs;
6362 	struct scsi_extended_sense *sense;
6363 
6364 	/* Fill ARQ sense data */
6365 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6366 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6367 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6368 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6369 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6370 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6371 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6372 	arqs->sts_rqpkt_resid = 0;
6373 	sense = &arqs->sts_sensedata;
6374 	bzero(sense, sizeof (struct scsi_extended_sense));
6375 	sata_fixed_sense_data_preset(sense);
6376 	return (sense);
6377 }
6378 
6379 
6380 /*
6381  * Emulated SATA Read/Write command completion for zero-length requests.
6382  * This request always succedes, so in synchronous mode it always returns
6383  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6384  * callback cannot be scheduled.
6385  */
6386 static int
6387 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6388 {
6389 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6390 
6391 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6392 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6393 	scsipkt->pkt_reason = CMD_CMPLT;
6394 	*scsipkt->pkt_scbp = STATUS_GOOD;
6395 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6396 		/* scsi callback required - have to schedule it */
6397 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6398 		    (task_func_t *)scsipkt->pkt_comp,
6399 		    (void *)scsipkt, TQ_SLEEP) == NULL)
6400 			/* Scheduling the callback failed */
6401 			return (TRAN_BUSY);
6402 	}
6403 	return (TRAN_ACCEPT);
6404 }
6405 
6406 
6407 /*
6408  * Translate completion status of SATA read/write commands into scsi response.
6409  * pkt completion_reason is checked to determine the completion status.
6410  * Do scsi callback if necessary.
6411  *
6412  * Note: this function may be called also for synchronously executed
6413  * commands.
6414  * This function may be used only if scsi_pkt is non-NULL.
6415  */
6416 static void
6417 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6418 {
6419 	sata_pkt_txlate_t *spx =
6420 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6421 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6422 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6423 	struct scsi_extended_sense *sense;
6424 	uint64_t lba;
6425 	struct buf *bp;
6426 	int rval;
6427 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6428 		/* Normal completion */
6429 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6430 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6431 		scsipkt->pkt_reason = CMD_CMPLT;
6432 		*scsipkt->pkt_scbp = STATUS_GOOD;
6433 		if (spx->txlt_tmp_buf != NULL) {
6434 			/* Temporary buffer was used */
6435 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6436 			if (bp->b_flags & B_READ) {
6437 				rval = ddi_dma_sync(
6438 				    spx->txlt_buf_dma_handle, 0, 0,
6439 				    DDI_DMA_SYNC_FORCPU);
6440 				ASSERT(rval == DDI_SUCCESS);
6441 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6442 				    bp->b_bcount);
6443 			}
6444 		}
6445 	} else {
6446 		/*
6447 		 * Something went wrong - analyze return
6448 		 */
6449 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6450 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6451 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6452 		*scsipkt->pkt_scbp = STATUS_CHECK;
6453 		sense = sata_arq_sense(spx);
6454 		ASSERT(sense != NULL);
6455 
6456 		/*
6457 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6458 		 * extract from device registers the failing LBA.
6459 		 */
6460 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6461 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6462 			    (scmd->satacmd_lba_mid_msb != 0 ||
6463 			    scmd->satacmd_lba_high_msb != 0)) {
6464 				/*
6465 				 * We have problem reporting this cmd LBA
6466 				 * in fixed sense data format, because of
6467 				 * the size of the scsi LBA fields.
6468 				 */
6469 				sense->es_valid = 0;
6470 			} else {
6471 				sata_extract_error_lba(spx, &lba);
6472 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6473 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6474 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6475 				sense->es_info_4 = lba & 0xFF;
6476 			}
6477 		} else {
6478 			/* Invalid extended sense info */
6479 			sense->es_valid = 0;
6480 		}
6481 
6482 		switch (sata_pkt->satapkt_reason) {
6483 		case SATA_PKT_PORT_ERROR:
6484 			/* We may want to handle DEV GONE state as well */
6485 			/*
6486 			 * We have no device data. Assume no data transfered.
6487 			 */
6488 			sense->es_key = KEY_HARDWARE_ERROR;
6489 			break;
6490 
6491 		case SATA_PKT_DEV_ERROR:
6492 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6493 			    SATA_STATUS_ERR) {
6494 				/*
6495 				 * determine dev error reason from error
6496 				 * reg content
6497 				 */
6498 				sata_decode_device_error(spx, sense);
6499 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6500 					switch (scmd->satacmd_cmd_reg) {
6501 					case SATAC_READ_DMA:
6502 					case SATAC_READ_DMA_EXT:
6503 					case SATAC_READ_DMA_QUEUED:
6504 					case SATAC_READ_DMA_QUEUED_EXT:
6505 					case SATAC_READ_FPDMA_QUEUED:
6506 						/* Unrecovered read error */
6507 						sense->es_add_code =
6508 						    SD_SCSI_ASC_UNREC_READ_ERR;
6509 						break;
6510 					case SATAC_WRITE_DMA:
6511 					case SATAC_WRITE_DMA_EXT:
6512 					case SATAC_WRITE_DMA_QUEUED:
6513 					case SATAC_WRITE_DMA_QUEUED_EXT:
6514 					case SATAC_WRITE_FPDMA_QUEUED:
6515 						/* Write error */
6516 						sense->es_add_code =
6517 						    SD_SCSI_ASC_WRITE_ERR;
6518 						break;
6519 					default:
6520 						/* Internal error */
6521 						SATA_LOG_D((
6522 						    spx->txlt_sata_hba_inst,
6523 						    CE_WARN,
6524 						    "sata_txlt_rw_completion :"
6525 						    "internal error - invalid "
6526 						    "command 0x%2x",
6527 						    scmd->satacmd_cmd_reg));
6528 						break;
6529 					}
6530 				}
6531 				break;
6532 			}
6533 			/* No extended sense key - no info available */
6534 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6535 			break;
6536 
6537 		case SATA_PKT_TIMEOUT:
6538 			scsipkt->pkt_reason = CMD_TIMEOUT;
6539 			scsipkt->pkt_statistics |=
6540 			    STAT_TIMEOUT | STAT_DEV_RESET;
6541 			sense->es_key = KEY_ABORTED_COMMAND;
6542 			break;
6543 
6544 		case SATA_PKT_ABORTED:
6545 			scsipkt->pkt_reason = CMD_ABORTED;
6546 			scsipkt->pkt_statistics |= STAT_ABORTED;
6547 			sense->es_key = KEY_ABORTED_COMMAND;
6548 			break;
6549 
6550 		case SATA_PKT_RESET:
6551 			scsipkt->pkt_reason = CMD_RESET;
6552 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6553 			sense->es_key = KEY_ABORTED_COMMAND;
6554 			break;
6555 
6556 		default:
6557 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6558 			    "sata_txlt_rw_completion: "
6559 			    "invalid packet completion reason"));
6560 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6561 			break;
6562 		}
6563 	}
6564 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6565 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6566 
6567 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6568 		/* scsi callback required */
6569 		scsi_hba_pkt_comp(scsipkt);
6570 }
6571 
6572 
6573 /*
6574  * Translate completion status of non-data commands (i.e. commands returning
6575  * no data).
6576  * pkt completion_reason is checked to determine the completion status.
6577  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6578  *
6579  * Note: this function may be called also for synchronously executed
6580  * commands.
6581  * This function may be used only if scsi_pkt is non-NULL.
6582  */
6583 
6584 static	void
6585 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6586 {
6587 	sata_pkt_txlate_t *spx =
6588 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6589 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6590 
6591 	sata_set_arq_data(sata_pkt);
6592 
6593 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6594 		/* scsi callback required */
6595 		scsi_hba_pkt_comp(scsipkt);
6596 }
6597 
6598 static	void
6599 sata_set_arq_data(sata_pkt_t *sata_pkt)
6600 {
6601 	sata_pkt_txlate_t *spx =
6602 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6603 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6604 	struct scsi_extended_sense *sense;
6605 
6606 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6607 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6608 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6609 		/* Normal completion */
6610 		scsipkt->pkt_reason = CMD_CMPLT;
6611 		*scsipkt->pkt_scbp = STATUS_GOOD;
6612 	} else {
6613 		/* Something went wrong */
6614 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6615 		*scsipkt->pkt_scbp = STATUS_CHECK;
6616 		sense = sata_arq_sense(spx);
6617 		switch (sata_pkt->satapkt_reason) {
6618 		case SATA_PKT_PORT_ERROR:
6619 			/*
6620 			 * We have no device data. Assume no data transfered.
6621 			 */
6622 			sense->es_key = KEY_HARDWARE_ERROR;
6623 			break;
6624 
6625 		case SATA_PKT_DEV_ERROR:
6626 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6627 			    SATA_STATUS_ERR) {
6628 				/*
6629 				 * determine dev error reason from error
6630 				 * reg content
6631 				 */
6632 				sata_decode_device_error(spx, sense);
6633 				break;
6634 			}
6635 			/* No extended sense key - no info available */
6636 			break;
6637 
6638 		case SATA_PKT_TIMEOUT:
6639 			scsipkt->pkt_reason = CMD_TIMEOUT;
6640 			scsipkt->pkt_statistics |=
6641 			    STAT_TIMEOUT | STAT_DEV_RESET;
6642 			/* No extended sense key ? */
6643 			break;
6644 
6645 		case SATA_PKT_ABORTED:
6646 			scsipkt->pkt_reason = CMD_ABORTED;
6647 			scsipkt->pkt_statistics |= STAT_ABORTED;
6648 			/* No extended sense key ? */
6649 			break;
6650 
6651 		case SATA_PKT_RESET:
6652 			/* pkt aborted by an explicit reset from a host */
6653 			scsipkt->pkt_reason = CMD_RESET;
6654 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6655 			break;
6656 
6657 		default:
6658 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6659 			    "sata_txlt_nodata_cmd_completion: "
6660 			    "invalid packet completion reason %d",
6661 			    sata_pkt->satapkt_reason));
6662 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6663 			break;
6664 		}
6665 
6666 	}
6667 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6668 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6669 }
6670 
6671 
6672 /*
6673  * Build Mode sense R/W recovery page
6674  * NOT IMPLEMENTED
6675  */
6676 
6677 static int
6678 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6679 {
6680 #ifndef __lock_lint
6681 	_NOTE(ARGUNUSED(sdinfo))
6682 	_NOTE(ARGUNUSED(pcntrl))
6683 	_NOTE(ARGUNUSED(buf))
6684 #endif
6685 	return (0);
6686 }
6687 
6688 /*
6689  * Build Mode sense caching page  -  scsi-3 implementation.
6690  * Page length distinguishes previous format from scsi-3 format.
6691  * buf must have space for 0x12 bytes.
6692  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
6693  *
6694  */
6695 static int
6696 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6697 {
6698 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
6699 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6700 
6701 	/*
6702 	 * Most of the fields are set to 0, being not supported and/or disabled
6703 	 */
6704 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
6705 
6706 	/* Saved paramters not supported */
6707 	if (pcntrl == 3)
6708 		return (0);
6709 	if (pcntrl == 0 || pcntrl == 2) {
6710 		/*
6711 		 * For now treat current and default parameters as same
6712 		 * That may have to change, if target driver will complain
6713 		 */
6714 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
6715 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6716 
6717 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
6718 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
6719 			page->dra = 1;		/* Read Ahead disabled */
6720 			page->rcd = 1;		/* Read Cache disabled */
6721 		}
6722 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
6723 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
6724 			page->wce = 1;		/* Write Cache enabled */
6725 	} else {
6726 		/* Changeable parameters */
6727 		page->mode_page.code = MODEPAGE_CACHING;
6728 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6729 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
6730 			page->dra = 1;
6731 			page->rcd = 1;
6732 		}
6733 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
6734 			page->wce = 1;
6735 	}
6736 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6737 	    sizeof (struct mode_page));
6738 }
6739 
6740 /*
6741  * Build Mode sense exception cntrl page
6742  */
6743 static int
6744 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6745 {
6746 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
6747 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6748 
6749 	/*
6750 	 * Most of the fields are set to 0, being not supported and/or disabled
6751 	 */
6752 	bzero(buf, PAGELENGTH_INFO_EXCPT);
6753 
6754 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
6755 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
6756 
6757 	/* Indicate that this is page is saveable */
6758 	page->mode_page.ps = 1;
6759 
6760 	/*
6761 	 * We will return the same data for default, current and saved page.
6762 	 * The only changeable bit is dexcpt and that bit is required
6763 	 * by the ATA specification to be preserved across power cycles.
6764 	 */
6765 	if (pcntrl != 1) {
6766 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
6767 		page->mrie = MRIE_ONLY_ON_REQUEST;
6768 	}
6769 	else
6770 		page->dexcpt = 1;	/* Only changeable parameter */
6771 
6772 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
6773 }
6774 
6775 
6776 static int
6777 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6778 {
6779 	struct mode_acoustic_management *page =
6780 	    (struct mode_acoustic_management *)buf;
6781 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6782 
6783 	/*
6784 	 * Most of the fields are set to 0, being not supported and/or disabled
6785 	 */
6786 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
6787 
6788 	switch (pcntrl) {
6789 	case P_CNTRL_DEFAULT:
6790 		/*  default paramters not supported */
6791 		return (0);
6792 
6793 	case P_CNTRL_CURRENT:
6794 	case P_CNTRL_SAVED:
6795 		/* Saved and current are supported and are identical */
6796 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6797 		page->mode_page.length =
6798 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6799 		page->mode_page.ps = 1;
6800 
6801 		/* Word 83 indicates if feature is supported */
6802 		/* If feature is not supported */
6803 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
6804 			page->acoustic_manag_enable =
6805 			    ACOUSTIC_DISABLED;
6806 		} else {
6807 			page->acoustic_manag_enable =
6808 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
6809 			    != 0);
6810 			/* Word 94 inidicates the value */
6811 #ifdef	_LITTLE_ENDIAN
6812 			page->acoustic_manag_level =
6813 			    (uchar_t)sata_id->ai_acoustic;
6814 			page->vendor_recommended_value =
6815 			    sata_id->ai_acoustic >> 8;
6816 #else
6817 			page->acoustic_manag_level =
6818 			    sata_id->ai_acoustic >> 8;
6819 			page->vendor_recommended_value =
6820 			    (uchar_t)sata_id->ai_acoustic;
6821 #endif
6822 		}
6823 		break;
6824 
6825 	case P_CNTRL_CHANGEABLE:
6826 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6827 		page->mode_page.length =
6828 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6829 		page->mode_page.ps = 1;
6830 
6831 		/* Word 83 indicates if the feature is supported */
6832 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
6833 			page->acoustic_manag_enable =
6834 			    ACOUSTIC_ENABLED;
6835 			page->acoustic_manag_level = 0xff;
6836 		}
6837 		break;
6838 	}
6839 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6840 	    sizeof (struct mode_page));
6841 }
6842 
6843 
6844 /*
6845  * Build Mode sense power condition page.
6846  */
6847 static int
6848 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6849 {
6850 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
6851 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6852 
6853 	/*
6854 	 * Most of the fields are set to 0, being not supported and/or disabled
6855 	 * power condition page length was 0x0a
6856 	 */
6857 	bzero(buf, sizeof (struct mode_info_power_cond));
6858 
6859 	if (pcntrl == P_CNTRL_DEFAULT) {
6860 		/*  default paramters not supported */
6861 		return (0);
6862 	}
6863 
6864 	page->mode_page.code = MODEPAGE_POWER_COND;
6865 	page->mode_page.length = sizeof (struct mode_info_power_cond);
6866 
6867 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
6868 		page->standby = 1;
6869 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
6870 		    sizeof (uchar_t) * 4);
6871 	}
6872 
6873 	return (sizeof (struct mode_info_power_cond));
6874 }
6875 
6876 /*
6877  * Process mode select caching page 8 (scsi3 format only).
6878  * Read Ahead (same as read cache) and Write Cache may be turned on and off
6879  * if these features are supported by the device. If these features are not
6880  * supported, the command will be terminated with STATUS_CHECK.
6881  * This function fails only if the SET FEATURE command sent to
6882  * the device fails. The page format is not varified, assuming that the
6883  * target driver operates correctly - if parameters length is too short,
6884  * we just drop the page.
6885  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
6886  * setting have to be changed.
6887  * SET FEATURE command is executed synchronously, i.e. we wait here until
6888  * it is completed, regardless of the scsi pkt directives.
6889  *
6890  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
6891  * changing DRA will change RCD.
6892  *
6893  * More than one SATA command may be executed to perform operations specified
6894  * by mode select pages. The first error terminates further execution.
6895  * Operations performed successully are not backed-up in such case.
6896  *
6897  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6898  * If operation resulted in changing device setup, dmod flag should be set to
6899  * one (1). If parameters were not changed, dmod flag should be set to 0.
6900  * Upon return, if operation required sending command to the device, the rval
6901  * should be set to the value returned by sata_hba_start. If operation
6902  * did not require device access, rval should be set to TRAN_ACCEPT.
6903  * The pagelen should be set to the length of the page.
6904  *
6905  * This function has to be called with a port mutex held.
6906  *
6907  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6908  */
6909 int
6910 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6911     int parmlen, int *pagelen, int *rval, int *dmod)
6912 {
6913 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6914 	sata_drive_info_t *sdinfo;
6915 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6916 	sata_id_t *sata_id;
6917 	struct scsi_extended_sense *sense;
6918 	int wce, dra;	/* Current settings */
6919 
6920 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6921 	    &spx->txlt_sata_pkt->satapkt_device);
6922 	sata_id = &sdinfo->satadrv_id;
6923 	*dmod = 0;
6924 
6925 	/* Verify parameters length. If too short, drop it */
6926 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6927 	    sizeof (struct mode_page)) > parmlen) {
6928 		*scsipkt->pkt_scbp = STATUS_CHECK;
6929 		sense = sata_arq_sense(spx);
6930 		sense->es_key = KEY_ILLEGAL_REQUEST;
6931 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6932 		*pagelen = parmlen;
6933 		*rval = TRAN_ACCEPT;
6934 		return (SATA_FAILURE);
6935 	}
6936 
6937 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6938 
6939 	/* Current setting of Read Ahead (and Read Cache) */
6940 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
6941 		dra = 0;	/* 0 == not disabled */
6942 	else
6943 		dra = 1;
6944 	/* Current setting of Write Cache */
6945 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
6946 		wce = 1;
6947 	else
6948 		wce = 0;
6949 
6950 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6951 		/* nothing to do */
6952 		*rval = TRAN_ACCEPT;
6953 		return (SATA_SUCCESS);
6954 	}
6955 
6956 	/*
6957 	 * Need to flip some setting
6958 	 * Set-up Internal SET FEATURES command(s)
6959 	 */
6960 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6961 	scmd->satacmd_addr_type = 0;
6962 	scmd->satacmd_device_reg = 0;
6963 	scmd->satacmd_status_reg = 0;
6964 	scmd->satacmd_error_reg = 0;
6965 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6966 	if (page->dra != dra || page->rcd != dra) {
6967 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
6968 			/* Need to flip read ahead setting */
6969 			if (dra == 0)
6970 				/* Disable read ahead / read cache */
6971 				scmd->satacmd_features_reg =
6972 				    SATAC_SF_DISABLE_READ_AHEAD;
6973 			else
6974 				/* Enable read ahead  / read cache */
6975 				scmd->satacmd_features_reg =
6976 				    SATAC_SF_ENABLE_READ_AHEAD;
6977 
6978 			/* Transfer command to HBA */
6979 			if (sata_hba_start(spx, rval) != 0)
6980 				/*
6981 				 * Pkt not accepted for execution.
6982 				 */
6983 				return (SATA_FAILURE);
6984 
6985 			*dmod = 1;
6986 
6987 			/* Now process return */
6988 			if (spx->txlt_sata_pkt->satapkt_reason !=
6989 			    SATA_PKT_COMPLETED) {
6990 				goto failure;	/* Terminate */
6991 			}
6992 		} else {
6993 			*scsipkt->pkt_scbp = STATUS_CHECK;
6994 			sense = sata_arq_sense(spx);
6995 			sense->es_key = KEY_ILLEGAL_REQUEST;
6996 			sense->es_add_code =
6997 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6998 			*pagelen = parmlen;
6999 			*rval = TRAN_ACCEPT;
7000 			return (SATA_FAILURE);
7001 		}
7002 	}
7003 
7004 	/* Note that the packet is not removed, so it could be re-used */
7005 	if (page->wce != wce) {
7006 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7007 			/* Need to flip Write Cache setting */
7008 			if (page->wce == 1)
7009 				/* Enable write cache */
7010 				scmd->satacmd_features_reg =
7011 				    SATAC_SF_ENABLE_WRITE_CACHE;
7012 			else
7013 				/* Disable write cache */
7014 				scmd->satacmd_features_reg =
7015 				    SATAC_SF_DISABLE_WRITE_CACHE;
7016 
7017 			/* Transfer command to HBA */
7018 			if (sata_hba_start(spx, rval) != 0)
7019 				/*
7020 				 * Pkt not accepted for execution.
7021 				 */
7022 				return (SATA_FAILURE);
7023 
7024 			*dmod = 1;
7025 
7026 			/* Now process return */
7027 			if (spx->txlt_sata_pkt->satapkt_reason !=
7028 			    SATA_PKT_COMPLETED) {
7029 				goto failure;
7030 			}
7031 		} else {
7032 			*scsipkt->pkt_scbp = STATUS_CHECK;
7033 			sense = sata_arq_sense(spx);
7034 			sense->es_key = KEY_ILLEGAL_REQUEST;
7035 			sense->es_add_code =
7036 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7037 			*pagelen = parmlen;
7038 			*rval = TRAN_ACCEPT;
7039 			return (SATA_FAILURE);
7040 		}
7041 	}
7042 	return (SATA_SUCCESS);
7043 
7044 failure:
7045 	sata_xlate_errors(spx);
7046 
7047 	return (SATA_FAILURE);
7048 }
7049 
7050 /*
7051  * Process mode select informational exceptions control page 0x1c
7052  *
7053  * The only changeable bit is dexcpt (disable exceptions).
7054  * MRIE (method of reporting informational exceptions) must be
7055  * "only on request".
7056  * This page applies to informational exceptions that report
7057  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7058  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7059  * Informational exception conditions occur as the result of background scan
7060  * errors, background self-test errors, or vendor specific events within a
7061  * logical unit. An informational exception condition may occur asynchronous
7062  * to any commands.
7063  *
7064  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7065  * If operation resulted in changing device setup, dmod flag should be set to
7066  * one (1). If parameters were not changed, dmod flag should be set to 0.
7067  * Upon return, if operation required sending command to the device, the rval
7068  * should be set to the value returned by sata_hba_start. If operation
7069  * did not require device access, rval should be set to TRAN_ACCEPT.
7070  * The pagelen should be set to the length of the page.
7071  *
7072  * This function has to be called with a port mutex held.
7073  *
7074  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7075  *
7076  * Cannot be called in the interrupt context.
7077  */
7078 static	int
7079 sata_mode_select_page_1c(
7080 	sata_pkt_txlate_t *spx,
7081 	struct mode_info_excpt_page *page,
7082 	int parmlen,
7083 	int *pagelen,
7084 	int *rval,
7085 	int *dmod)
7086 {
7087 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7088 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7089 	sata_drive_info_t *sdinfo;
7090 	sata_id_t *sata_id;
7091 	struct scsi_extended_sense *sense;
7092 
7093 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7094 	    &spx->txlt_sata_pkt->satapkt_device);
7095 	sata_id = &sdinfo->satadrv_id;
7096 
7097 	*dmod = 0;
7098 
7099 	/* Verify parameters length. If too short, drop it */
7100 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7101 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7102 		*scsipkt->pkt_scbp = STATUS_CHECK;
7103 		sense = sata_arq_sense(spx);
7104 		sense->es_key = KEY_ILLEGAL_REQUEST;
7105 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7106 		*pagelen = parmlen;
7107 		*rval = TRAN_ACCEPT;
7108 		return (SATA_FAILURE);
7109 	}
7110 
7111 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7112 
7113 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7114 		*scsipkt->pkt_scbp = STATUS_CHECK;
7115 		sense = sata_arq_sense(spx);
7116 		sense->es_key = KEY_ILLEGAL_REQUEST;
7117 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7118 		*pagelen = parmlen;
7119 		*rval = TRAN_ACCEPT;
7120 		return (SATA_FAILURE);
7121 	}
7122 
7123 	/* If already in the state requested, we are done */
7124 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7125 		/* nothing to do */
7126 		*rval = TRAN_ACCEPT;
7127 		return (SATA_SUCCESS);
7128 	}
7129 
7130 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7131 
7132 	/* Build SMART_ENABLE or SMART_DISABLE command */
7133 	scmd->satacmd_addr_type = 0;		/* N/A */
7134 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7135 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7136 	scmd->satacmd_features_reg = page->dexcpt ?
7137 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7138 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7139 	scmd->satacmd_cmd_reg = SATAC_SMART;
7140 
7141 	/* Transfer command to HBA */
7142 	if (sata_hba_start(spx, rval) != 0)
7143 		/*
7144 		 * Pkt not accepted for execution.
7145 		 */
7146 		return (SATA_FAILURE);
7147 
7148 	*dmod = 1;	/* At least may have been modified */
7149 
7150 	/* Now process return */
7151 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7152 		return (SATA_SUCCESS);
7153 
7154 	/* Packet did not complete successfully */
7155 	sata_xlate_errors(spx);
7156 
7157 	return (SATA_FAILURE);
7158 }
7159 
7160 /*
7161  * Process mode select acoustic management control page 0x30
7162  *
7163  *
7164  * This function has to be called with a port mutex held.
7165  *
7166  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7167  *
7168  * Cannot be called in the interrupt context.
7169  */
7170 int
7171 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7172     mode_acoustic_management *page, int parmlen, int *pagelen,
7173     int *rval, int *dmod)
7174 {
7175 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7176 	sata_drive_info_t *sdinfo;
7177 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7178 	sata_id_t *sata_id;
7179 	struct scsi_extended_sense *sense;
7180 
7181 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7182 	    &spx->txlt_sata_pkt->satapkt_device);
7183 	sata_id = &sdinfo->satadrv_id;
7184 	*dmod = 0;
7185 
7186 	/* If parmlen is too short or the feature is not supported, drop it */
7187 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7188 	    sizeof (struct mode_page)) > parmlen) ||
7189 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7190 		*scsipkt->pkt_scbp = STATUS_CHECK;
7191 		sense = sata_arq_sense(spx);
7192 		sense->es_key = KEY_ILLEGAL_REQUEST;
7193 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7194 		*pagelen = parmlen;
7195 		*rval = TRAN_ACCEPT;
7196 		return (SATA_FAILURE);
7197 	}
7198 
7199 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7200 	    sizeof (struct mode_page);
7201 
7202 	/*
7203 	 * We can enable and disable acoustice management and
7204 	 * set the acoustic management level.
7205 	 */
7206 
7207 	/*
7208 	 * Set-up Internal SET FEATURES command(s)
7209 	 */
7210 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7211 	scmd->satacmd_addr_type = 0;
7212 	scmd->satacmd_device_reg = 0;
7213 	scmd->satacmd_status_reg = 0;
7214 	scmd->satacmd_error_reg = 0;
7215 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7216 	if (page->acoustic_manag_enable) {
7217 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7218 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7219 	} else {	/* disabling acoustic management */
7220 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7221 	}
7222 
7223 	/* Transfer command to HBA */
7224 	if (sata_hba_start(spx, rval) != 0)
7225 		/*
7226 		 * Pkt not accepted for execution.
7227 		 */
7228 		return (SATA_FAILURE);
7229 
7230 	/* Now process return */
7231 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7232 		sata_xlate_errors(spx);
7233 		return (SATA_FAILURE);
7234 	}
7235 
7236 	*dmod = 1;
7237 
7238 	return (SATA_SUCCESS);
7239 }
7240 
7241 /*
7242  * Process mode select power condition page 0x1a
7243  *
7244  * This function has to be called with a port mutex held.
7245  *
7246  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7247  *
7248  * Cannot be called in the interrupt context.
7249  */
7250 int
7251 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7252     mode_info_power_cond *page, int parmlen, int *pagelen,
7253     int *rval, int *dmod)
7254 {
7255 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7256 	sata_drive_info_t *sdinfo;
7257 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7258 	sata_id_t *sata_id;
7259 	struct scsi_extended_sense *sense;
7260 	uint8_t ata_count;
7261 	int i, len;
7262 
7263 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7264 	    &spx->txlt_sata_pkt->satapkt_device);
7265 	sata_id = &sdinfo->satadrv_id;
7266 	*dmod = 0;
7267 
7268 	len = sizeof (struct mode_info_power_cond);
7269 	len += sizeof (struct mode_page);
7270 
7271 	/* If parmlen is too short or the feature is not supported, drop it */
7272 	if ((len < parmlen) || (page->idle == 1) ||
7273 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7274 		*scsipkt->pkt_scbp = STATUS_CHECK;
7275 		sense = sata_arq_sense(spx);
7276 		sense->es_key = KEY_ILLEGAL_REQUEST;
7277 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7278 		*pagelen = parmlen;
7279 		*rval = TRAN_ACCEPT;
7280 		return (SATA_FAILURE);
7281 	}
7282 
7283 	*pagelen = len;
7284 
7285 	/*
7286 	 * Set-up Internal STANDBY command(s)
7287 	 */
7288 	if (page->standby == 0)
7289 		goto out;
7290 
7291 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7292 
7293 	scmd->satacmd_addr_type = 0;
7294 	scmd->satacmd_sec_count_lsb = ata_count;
7295 	scmd->satacmd_lba_low_lsb = 0;
7296 	scmd->satacmd_lba_mid_lsb = 0;
7297 	scmd->satacmd_lba_high_lsb = 0;
7298 	scmd->satacmd_features_reg = 0;
7299 	scmd->satacmd_device_reg = 0;
7300 	scmd->satacmd_status_reg = 0;
7301 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7302 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7303 
7304 	/* Transfer command to HBA */
7305 	if (sata_hba_start(spx, rval) != 0) {
7306 		return (SATA_FAILURE);
7307 	} else {
7308 		if ((scmd->satacmd_error_reg != 0) ||
7309 		    (spx->txlt_sata_pkt->satapkt_reason !=
7310 		    SATA_PKT_COMPLETED)) {
7311 			sata_xlate_errors(spx);
7312 			return (SATA_FAILURE);
7313 		}
7314 	}
7315 
7316 	for (i = 0; i < 4; i++) {
7317 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7318 	}
7319 out:
7320 	*dmod = 1;
7321 	return (SATA_SUCCESS);
7322 }
7323 
7324 /*
7325  * sata_build_lsense_page0() is used to create the
7326  * SCSI LOG SENSE page 0 (supported log pages)
7327  *
7328  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7329  * (supported log pages, self-test results, informational exceptions
7330  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7331  *
7332  * Takes a sata_drive_info t * and the address of a buffer
7333  * in which to create the page information.
7334  *
7335  * Returns the number of bytes valid in the buffer.
7336  */
7337 static	int
7338 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7339 {
7340 	struct log_parameter *lpp = (struct log_parameter *)buf;
7341 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7342 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7343 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7344 
7345 	lpp->param_code[0] = 0;
7346 	lpp->param_code[1] = 0;
7347 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7348 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7349 
7350 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7351 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7352 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7353 			++num_pages_supported;
7354 		}
7355 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7356 		++num_pages_supported;
7357 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7358 		++num_pages_supported;
7359 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7360 		++num_pages_supported;
7361 	}
7362 
7363 	lpp->param_len = num_pages_supported;
7364 
7365 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7366 	    num_pages_supported);
7367 }
7368 
7369 /*
7370  * sata_build_lsense_page_10() is used to create the
7371  * SCSI LOG SENSE page 0x10 (self-test results)
7372  *
7373  * Takes a sata_drive_info t * and the address of a buffer
7374  * in which to create the page information as well as a sata_hba_inst_t *.
7375  *
7376  * Returns the number of bytes valid in the buffer.
7377  *
7378  * Note: Self test and SMART data is accessible in device log pages.
7379  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
7380  * of data can be transferred by a single command), or by the General Purpose
7381  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
7382  * - approximately 33MB - can be transferred by a single command.
7383  * The SCT Command response (either error or command) is the same for both
7384  * the SMART and GPL methods of issuing commands.
7385  * This function uses READ LOG EXT command when drive supports LBA48, and
7386  * SMART READ command otherwise.
7387  *
7388  * Since above commands are executed in a synchronous mode, this function
7389  * should not be called in an interrupt context.
7390  */
7391 static	int
7392 sata_build_lsense_page_10(
7393 	sata_drive_info_t *sdinfo,
7394 	uint8_t *buf,
7395 	sata_hba_inst_t *sata_hba_inst)
7396 {
7397 	struct log_parameter *lpp = (struct log_parameter *)buf;
7398 	int rval;
7399 
7400 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
7401 		struct smart_ext_selftest_log *ext_selftest_log;
7402 
7403 		ext_selftest_log = kmem_zalloc(
7404 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
7405 
7406 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
7407 		    ext_selftest_log, 0);
7408 		if (rval == 0) {
7409 			int index, start_index;
7410 			struct smart_ext_selftest_log_entry *entry;
7411 			static const struct smart_ext_selftest_log_entry empty =
7412 			    {0};
7413 			uint16_t block_num;
7414 			int count;
7415 			boolean_t only_one_block = B_FALSE;
7416 
7417 			index = ext_selftest_log->
7418 			    smart_ext_selftest_log_index[0];
7419 			index |= ext_selftest_log->
7420 			    smart_ext_selftest_log_index[1] << 8;
7421 			if (index == 0)
7422 				goto out;
7423 
7424 			--index;	/* Correct for 0 origin */
7425 			start_index = index;	/* remember where we started */
7426 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7427 			if (block_num != 0) {
7428 				rval = sata_ext_smart_selftest_read_log(
7429 				    sata_hba_inst, sdinfo, ext_selftest_log,
7430 				    block_num);
7431 				if (rval != 0)
7432 					goto out;
7433 			}
7434 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7435 			entry =
7436 			    &ext_selftest_log->
7437 			    smart_ext_selftest_log_entries[index];
7438 
7439 			for (count = 1;
7440 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7441 			    ++count) {
7442 				uint8_t status;
7443 				uint8_t code;
7444 				uint8_t sense_key;
7445 				uint8_t add_sense_code;
7446 				uint8_t add_sense_code_qual;
7447 
7448 				/* If this is an unused entry, we are done */
7449 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
7450 					/* Broken firmware on some disks */
7451 					if (index + 1 ==
7452 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
7453 						--entry;
7454 						--index;
7455 						if (bcmp(entry, &empty,
7456 						    sizeof (empty)) == 0)
7457 							goto out;
7458 					} else
7459 						goto out;
7460 				}
7461 
7462 				if (only_one_block &&
7463 				    start_index == index)
7464 					goto out;
7465 
7466 				lpp->param_code[0] = 0;
7467 				lpp->param_code[1] = count;
7468 				lpp->param_ctrl_flags =
7469 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7470 				lpp->param_len =
7471 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7472 
7473 				status = entry->smart_ext_selftest_log_status;
7474 				status >>= 4;
7475 				switch (status) {
7476 				case 0:
7477 				default:
7478 					sense_key = KEY_NO_SENSE;
7479 					add_sense_code =
7480 					    SD_SCSI_ASC_NO_ADD_SENSE;
7481 					add_sense_code_qual = 0;
7482 					break;
7483 				case 1:
7484 					sense_key = KEY_ABORTED_COMMAND;
7485 					add_sense_code =
7486 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7487 					add_sense_code_qual = SCSI_COMPONENT_81;
7488 					break;
7489 				case 2:
7490 					sense_key = KEY_ABORTED_COMMAND;
7491 					add_sense_code =
7492 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7493 					add_sense_code_qual = SCSI_COMPONENT_82;
7494 					break;
7495 				case 3:
7496 					sense_key = KEY_ABORTED_COMMAND;
7497 					add_sense_code =
7498 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7499 					add_sense_code_qual = SCSI_COMPONENT_83;
7500 					break;
7501 				case 4:
7502 					sense_key = KEY_HARDWARE_ERROR;
7503 					add_sense_code =
7504 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7505 					add_sense_code_qual = SCSI_COMPONENT_84;
7506 					break;
7507 				case 5:
7508 					sense_key = KEY_HARDWARE_ERROR;
7509 					add_sense_code =
7510 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7511 					add_sense_code_qual = SCSI_COMPONENT_85;
7512 					break;
7513 				case 6:
7514 					sense_key = KEY_HARDWARE_ERROR;
7515 					add_sense_code =
7516 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7517 					add_sense_code_qual = SCSI_COMPONENT_86;
7518 					break;
7519 				case 7:
7520 					sense_key = KEY_MEDIUM_ERROR;
7521 					add_sense_code =
7522 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7523 					add_sense_code_qual = SCSI_COMPONENT_87;
7524 					break;
7525 				case 8:
7526 					sense_key = KEY_HARDWARE_ERROR;
7527 					add_sense_code =
7528 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7529 					add_sense_code_qual = SCSI_COMPONENT_88;
7530 					break;
7531 				}
7532 				code = 0;	/* unspecified */
7533 				status |= (code << 4);
7534 				lpp->param_values[0] = status;
7535 				lpp->param_values[1] = 0; /* unspecified */
7536 				lpp->param_values[2] = entry->
7537 				    smart_ext_selftest_log_timestamp[1];
7538 				lpp->param_values[3] = entry->
7539 				    smart_ext_selftest_log_timestamp[0];
7540 				if (status != 0) {
7541 					lpp->param_values[4] = 0;
7542 					lpp->param_values[5] = 0;
7543 					lpp->param_values[6] = entry->
7544 					    smart_ext_selftest_log_failing_lba
7545 					    [5];
7546 					lpp->param_values[7] = entry->
7547 					    smart_ext_selftest_log_failing_lba
7548 					    [4];
7549 					lpp->param_values[8] = entry->
7550 					    smart_ext_selftest_log_failing_lba
7551 					    [3];
7552 					lpp->param_values[9] = entry->
7553 					    smart_ext_selftest_log_failing_lba
7554 					    [2];
7555 					lpp->param_values[10] = entry->
7556 					    smart_ext_selftest_log_failing_lba
7557 					    [1];
7558 					lpp->param_values[11] = entry->
7559 					    smart_ext_selftest_log_failing_lba
7560 					    [0];
7561 				} else {	/* No bad block address */
7562 					lpp->param_values[4] = 0xff;
7563 					lpp->param_values[5] = 0xff;
7564 					lpp->param_values[6] = 0xff;
7565 					lpp->param_values[7] = 0xff;
7566 					lpp->param_values[8] = 0xff;
7567 					lpp->param_values[9] = 0xff;
7568 					lpp->param_values[10] = 0xff;
7569 					lpp->param_values[11] = 0xff;
7570 				}
7571 
7572 				lpp->param_values[12] = sense_key;
7573 				lpp->param_values[13] = add_sense_code;
7574 				lpp->param_values[14] = add_sense_code_qual;
7575 				lpp->param_values[15] = 0; /* undefined */
7576 
7577 				lpp = (struct log_parameter *)
7578 				    (((uint8_t *)lpp) +
7579 				    SCSI_LOG_PARAM_HDR_LEN +
7580 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
7581 
7582 				--index;	/* Back up to previous entry */
7583 				if (index < 0) {
7584 					if (block_num > 0) {
7585 						--block_num;
7586 					} else {
7587 						struct read_log_ext_directory
7588 						    logdir;
7589 
7590 						rval =
7591 						    sata_read_log_ext_directory(
7592 						    sata_hba_inst, sdinfo,
7593 						    &logdir);
7594 						if (rval == -1)
7595 							goto out;
7596 						if ((logdir.read_log_ext_vers
7597 						    [0] == 0) &&
7598 						    (logdir.read_log_ext_vers
7599 						    [1] == 0))
7600 							goto out;
7601 						block_num =
7602 						    logdir.read_log_ext_nblks
7603 						    [EXT_SMART_SELFTEST_LOG_PAGE
7604 						    - 1][0];
7605 						block_num |= logdir.
7606 						    read_log_ext_nblks
7607 						    [EXT_SMART_SELFTEST_LOG_PAGE
7608 						    - 1][1] << 8;
7609 						--block_num;
7610 						only_one_block =
7611 						    (block_num == 0);
7612 					}
7613 					rval = sata_ext_smart_selftest_read_log(
7614 					    sata_hba_inst, sdinfo,
7615 					    ext_selftest_log, block_num);
7616 					if (rval != 0)
7617 						goto out;
7618 
7619 					index =
7620 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
7621 					    1;
7622 				}
7623 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7624 				entry = &ext_selftest_log->
7625 				    smart_ext_selftest_log_entries[index];
7626 			}
7627 		}
7628 out:
7629 		kmem_free(ext_selftest_log,
7630 		    sizeof (struct smart_ext_selftest_log));
7631 	} else {
7632 		struct smart_selftest_log *selftest_log;
7633 
7634 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
7635 		    KM_SLEEP);
7636 
7637 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
7638 		    selftest_log);
7639 
7640 		if (rval == 0) {
7641 			int index;
7642 			int count;
7643 			struct smart_selftest_log_entry *entry;
7644 			static const struct smart_selftest_log_entry empty =
7645 			    { 0 };
7646 
7647 			index = selftest_log->smart_selftest_log_index;
7648 			if (index == 0)
7649 				goto done;
7650 			--index;	/* Correct for 0 origin */
7651 			entry = &selftest_log->
7652 			    smart_selftest_log_entries[index];
7653 			for (count = 1;
7654 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7655 			    ++count) {
7656 				uint8_t status;
7657 				uint8_t code;
7658 				uint8_t sense_key;
7659 				uint8_t add_sense_code;
7660 				uint8_t add_sense_code_qual;
7661 
7662 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
7663 					goto done;
7664 
7665 				lpp->param_code[0] = 0;
7666 				lpp->param_code[1] = count;
7667 				lpp->param_ctrl_flags =
7668 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7669 				lpp->param_len =
7670 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7671 
7672 				status = entry->smart_selftest_log_status;
7673 				status >>= 4;
7674 				switch (status) {
7675 				case 0:
7676 				default:
7677 					sense_key = KEY_NO_SENSE;
7678 					add_sense_code =
7679 					    SD_SCSI_ASC_NO_ADD_SENSE;
7680 					break;
7681 				case 1:
7682 					sense_key = KEY_ABORTED_COMMAND;
7683 					add_sense_code =
7684 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7685 					add_sense_code_qual = SCSI_COMPONENT_81;
7686 					break;
7687 				case 2:
7688 					sense_key = KEY_ABORTED_COMMAND;
7689 					add_sense_code =
7690 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7691 					add_sense_code_qual = SCSI_COMPONENT_82;
7692 					break;
7693 				case 3:
7694 					sense_key = KEY_ABORTED_COMMAND;
7695 					add_sense_code =
7696 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7697 					add_sense_code_qual = SCSI_COMPONENT_83;
7698 					break;
7699 				case 4:
7700 					sense_key = KEY_HARDWARE_ERROR;
7701 					add_sense_code =
7702 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7703 					add_sense_code_qual = SCSI_COMPONENT_84;
7704 					break;
7705 				case 5:
7706 					sense_key = KEY_HARDWARE_ERROR;
7707 					add_sense_code =
7708 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7709 					add_sense_code_qual = SCSI_COMPONENT_85;
7710 					break;
7711 				case 6:
7712 					sense_key = KEY_HARDWARE_ERROR;
7713 					add_sense_code =
7714 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7715 					add_sense_code_qual = SCSI_COMPONENT_86;
7716 					break;
7717 				case 7:
7718 					sense_key = KEY_MEDIUM_ERROR;
7719 					add_sense_code =
7720 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7721 					add_sense_code_qual = SCSI_COMPONENT_87;
7722 					break;
7723 				case 8:
7724 					sense_key = KEY_HARDWARE_ERROR;
7725 					add_sense_code =
7726 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7727 					add_sense_code_qual = SCSI_COMPONENT_88;
7728 					break;
7729 				}
7730 				code = 0;	/* unspecified */
7731 				status |= (code << 4);
7732 				lpp->param_values[0] = status;
7733 				lpp->param_values[1] = 0; /* unspecified */
7734 				lpp->param_values[2] = entry->
7735 				    smart_selftest_log_timestamp[1];
7736 				lpp->param_values[3] = entry->
7737 				    smart_selftest_log_timestamp[0];
7738 				if (status != 0) {
7739 					lpp->param_values[4] = 0;
7740 					lpp->param_values[5] = 0;
7741 					lpp->param_values[6] = 0;
7742 					lpp->param_values[7] = 0;
7743 					lpp->param_values[8] = entry->
7744 					    smart_selftest_log_failing_lba[3];
7745 					lpp->param_values[9] = entry->
7746 					    smart_selftest_log_failing_lba[2];
7747 					lpp->param_values[10] = entry->
7748 					    smart_selftest_log_failing_lba[1];
7749 					lpp->param_values[11] = entry->
7750 					    smart_selftest_log_failing_lba[0];
7751 				} else {	/* No block address */
7752 					lpp->param_values[4] = 0xff;
7753 					lpp->param_values[5] = 0xff;
7754 					lpp->param_values[6] = 0xff;
7755 					lpp->param_values[7] = 0xff;
7756 					lpp->param_values[8] = 0xff;
7757 					lpp->param_values[9] = 0xff;
7758 					lpp->param_values[10] = 0xff;
7759 					lpp->param_values[11] = 0xff;
7760 				}
7761 				lpp->param_values[12] = sense_key;
7762 				lpp->param_values[13] = add_sense_code;
7763 				lpp->param_values[14] = add_sense_code_qual;
7764 				lpp->param_values[15] = 0; /* undefined */
7765 
7766 				lpp = (struct log_parameter *)
7767 				    (((uint8_t *)lpp) +
7768 				    SCSI_LOG_PARAM_HDR_LEN +
7769 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
7770 				--index;	/* back up to previous entry */
7771 				if (index < 0) {
7772 					index =
7773 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
7774 				}
7775 				entry = &selftest_log->
7776 				    smart_selftest_log_entries[index];
7777 			}
7778 		}
7779 done:
7780 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
7781 	}
7782 
7783 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
7784 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
7785 }
7786 
7787 /*
7788  * sata_build_lsense_page_2f() is used to create the
7789  * SCSI LOG SENSE page 0x2f (informational exceptions)
7790  *
7791  * Takes a sata_drive_info t * and the address of a buffer
7792  * in which to create the page information as well as a sata_hba_inst_t *.
7793  *
7794  * Returns the number of bytes valid in the buffer.
7795  *
7796  * Because it invokes function(s) that send synchronously executed command
7797  * to the HBA, it cannot be called in the interrupt context.
7798  */
7799 static	int
7800 sata_build_lsense_page_2f(
7801 	sata_drive_info_t *sdinfo,
7802 	uint8_t *buf,
7803 	sata_hba_inst_t *sata_hba_inst)
7804 {
7805 	struct log_parameter *lpp = (struct log_parameter *)buf;
7806 	int rval;
7807 	uint8_t *smart_data;
7808 	uint8_t temp;
7809 	sata_id_t *sata_id;
7810 #define	SMART_NO_TEMP	0xff
7811 
7812 	lpp->param_code[0] = 0;
7813 	lpp->param_code[1] = 0;
7814 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7815 
7816 	/* Now get the SMART status w.r.t. threshold exceeded */
7817 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
7818 	switch (rval) {
7819 	case 1:
7820 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
7821 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
7822 		break;
7823 	case 0:
7824 	case -1:	/* failed to get data */
7825 		lpp->param_values[0] = 0;	/* No failure predicted */
7826 		lpp->param_values[1] = 0;
7827 		break;
7828 #if defined(SATA_DEBUG)
7829 	default:
7830 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
7831 		/* NOTREACHED */
7832 #endif
7833 	}
7834 
7835 	sata_id = &sdinfo->satadrv_id;
7836 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
7837 		temp = SMART_NO_TEMP;
7838 	else {
7839 		/* Now get the temperature */
7840 		smart_data = kmem_zalloc(512, KM_SLEEP);
7841 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
7842 		    SCT_STATUS_LOG_PAGE, 1);
7843 		if (rval == -1)
7844 			temp = SMART_NO_TEMP;
7845 		else {
7846 			temp = smart_data[200];
7847 			if (temp & 0x80) {
7848 				if (temp & 0x7f)
7849 					temp = 0;
7850 				else
7851 					temp = SMART_NO_TEMP;
7852 			}
7853 		}
7854 		kmem_free(smart_data, 512);
7855 	}
7856 
7857 	lpp->param_values[2] = temp;	/* most recent temperature */
7858 	lpp->param_values[3] = 0;	/* required vendor specific byte */
7859 
7860 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
7861 
7862 
7863 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
7864 }
7865 
7866 /*
7867  * sata_build_lsense_page_30() is used to create the
7868  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
7869  *
7870  * Takes a sata_drive_info t * and the address of a buffer
7871  * in which to create the page information as well as a sata_hba_inst_t *.
7872  *
7873  * Returns the number of bytes valid in the buffer.
7874  */
7875 static int
7876 sata_build_lsense_page_30(
7877 	sata_drive_info_t *sdinfo,
7878 	uint8_t *buf,
7879 	sata_hba_inst_t *sata_hba_inst)
7880 {
7881 	struct smart_data *smart_data = (struct smart_data *)buf;
7882 	int rval;
7883 
7884 	/* Now do the SMART READ DATA */
7885 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
7886 	if (rval == -1)
7887 		return (0);
7888 
7889 	return (sizeof (struct smart_data));
7890 }
7891 
7892 /*
7893  * sata_build_lsense_page_0e() is used to create the
7894  * SCSI LOG SENSE page 0e (supported log pages)
7895  *
7896  * Date of Manufacture (0x0001)
7897  *	YEAR = "0000"
7898  *	WEEK = "00"
7899  * Accounting Date (0x0002)
7900  *	6 ASCII space character(20h)
7901  * Specified cycle count over device lifetime
7902  *	VALUE - THRESH - the delta between max and min;
7903  * Accumulated start-stop cycles
7904  *	VALUE - WORST - the accumulated cycles;
7905  *
7906  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
7907  *
7908  * Takes a sata_drive_info t * and the address of a buffer
7909  * in which to create the page information as well as a sata_hba_inst_t *.
7910  *
7911  * Returns the number of bytes valid in the buffer.
7912  */
7913 static	int
7914 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
7915 	sata_pkt_txlate_t *spx)
7916 {
7917 	struct start_stop_cycle_counter_log *log_page;
7918 	int i, rval, index;
7919 	uint8_t smart_data[512], id, value, worst, thresh;
7920 	uint32_t max_count, cycles;
7921 
7922 	/* Now do the SMART READ DATA */
7923 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
7924 	    (struct smart_data *)smart_data);
7925 	if (rval == -1)
7926 		return (0);
7927 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
7928 		index = (i * 12) + 2;
7929 		id = smart_data[index];
7930 		if (id != SMART_START_STOP_COUNT_ID)
7931 			continue;
7932 		else {
7933 			thresh = smart_data[index + 2];
7934 			value = smart_data[index + 3];
7935 			worst = smart_data[index + 4];
7936 			break;
7937 		}
7938 	}
7939 	if (id != SMART_START_STOP_COUNT_ID)
7940 		return (0);
7941 	max_count = value - thresh;
7942 	cycles = value - worst;
7943 
7944 	log_page = (struct start_stop_cycle_counter_log *)buf;
7945 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
7946 	log_page->code = 0x0e;
7947 	log_page->page_len_low = 0x24;
7948 
7949 	log_page->manufactor_date_low = 0x1;
7950 	log_page->param_1.fmt_link = 0x1; /* 01b */
7951 	log_page->param_len_1 = 0x06;
7952 	for (i = 0; i < 4; i++) {
7953 		log_page->year_manu[i] = 0x30;
7954 		if (i < 2)
7955 			log_page->week_manu[i] = 0x30;
7956 	}
7957 
7958 	log_page->account_date_low = 0x02;
7959 	log_page->param_2.fmt_link = 0x01; /* 01b */
7960 	log_page->param_len_2 = 0x06;
7961 	for (i = 0; i < 4; i++) {
7962 		log_page->year_account[i] = 0x20;
7963 		if (i < 2)
7964 			log_page->week_account[i] = 0x20;
7965 	}
7966 
7967 	log_page->lifetime_code_low = 0x03;
7968 	log_page->param_3.fmt_link = 0x03; /* 11b */
7969 	log_page->param_len_3 = 0x04;
7970 	/* VALUE - THRESH - the delta between max and min */
7971 	log_page->cycle_code_low = 0x04;
7972 	log_page->param_4.fmt_link = 0x03; /* 11b */
7973 	log_page->param_len_4 = 0x04;
7974 	/* WORST - THRESH - the distance from 'now' to min */
7975 
7976 	for (i = 0; i < 4; i++) {
7977 		log_page->cycle_lifetime[i] =
7978 		    (max_count >> (8 * (3 - i))) & 0xff;
7979 		log_page->cycle_accumulated[i] =
7980 		    (cycles >> (8 * (3 - i))) & 0xff;
7981 	}
7982 
7983 	return (sizeof (struct start_stop_cycle_counter_log));
7984 }
7985 
7986 /*
7987  * This function was used for build a ATA read verify sector command
7988  */
7989 static void
7990 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
7991 {
7992 	scmd->satacmd_cmd_reg = SATAC_RDVER;
7993 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
7994 
7995 	scmd->satacmd_sec_count_lsb = sec & 0xff;
7996 	scmd->satacmd_lba_low_lsb = lba & 0xff;
7997 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
7998 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
7999 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8000 	scmd->satacmd_features_reg = 0;
8001 	scmd->satacmd_status_reg = 0;
8002 	scmd->satacmd_error_reg = 0;
8003 }
8004 
8005 /*
8006  * This function was used for building an ATA
8007  * command, and only command register need to
8008  * be defined, other register will be zero or na.
8009  */
8010 static void
8011 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8012 {
8013 	scmd->satacmd_addr_type = 0;
8014 	scmd->satacmd_cmd_reg = cmd;
8015 	scmd->satacmd_device_reg = 0;
8016 	scmd->satacmd_sec_count_lsb = 0;
8017 	scmd->satacmd_lba_low_lsb = 0;
8018 	scmd->satacmd_lba_mid_lsb = 0;
8019 	scmd->satacmd_lba_high_lsb = 0;
8020 	scmd->satacmd_features_reg = 0;
8021 	scmd->satacmd_status_reg = 0;
8022 	scmd->satacmd_error_reg = 0;
8023 }
8024 
8025 /*
8026  * This function was used for changing the standby
8027  * timer format from SCSI to ATA.
8028  */
8029 static uint8_t
8030 sata_get_standby_timer(uint8_t *timer)
8031 {
8032 	uint32_t i = 0, count = 0;
8033 	uint8_t ata_count;
8034 
8035 	for (i = 0; i < 4; i++) {
8036 		count = count << 8 | timer[i];
8037 	}
8038 
8039 	if (count == 0)
8040 		return (0);
8041 
8042 	if (count >= 1 && count <= 12000)
8043 		ata_count = (count -1) / 50 + 1;
8044 	else if (count > 12000 && count <= 12600)
8045 		ata_count = 0xfc;
8046 	else if (count > 12601 && count <= 12750)
8047 		ata_count = 0xff;
8048 	else if (count > 12750 && count <= 17999)
8049 		ata_count = 0xf1;
8050 	else if (count > 18000 && count <= 198000)
8051 		ata_count = count / 18000 + 240;
8052 	else
8053 		ata_count = 0xfd;
8054 	return (ata_count);
8055 }
8056 
8057 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8058 
8059 /*
8060  * Start command for ATAPI device.
8061  * This function processes scsi_pkt requests.
8062  * Now CD/DVD, tape and ATAPI disk devices are supported.
8063  * Most commands are packet without any translation into Packet Command.
8064  * Some may be trapped and executed as SATA commands (not clear which one).
8065  *
8066  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8067  * execution).
8068  * Returns other TRAN_XXXX codes if command is not accepted or completed
8069  * (see return values for sata_hba_start()).
8070  *
8071  * Note:
8072  * Inquiry cdb format differs between transport version 2 and 3.
8073  * However, the transport version 3 devices that were checked did not adhere
8074  * to the specification (ignored MSB of the allocation length). Therefore,
8075  * the transport version is not checked, but Inquiry allocation length is
8076  * truncated to 255 bytes if the original allocation length set-up by the
8077  * target driver is greater than 255 bytes.
8078  */
8079 static int
8080 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8081 {
8082 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8083 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8084 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8085 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8086 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8087 	    &spx->txlt_sata_pkt->satapkt_device);
8088 	int cport = SATA_TXLT_CPORT(spx);
8089 	int cdblen;
8090 	int rval, reason;
8091 	int synch;
8092 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8093 
8094 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8095 
8096 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
8097 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8098 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8099 		return (rval);
8100 	}
8101 
8102 	/*
8103 	 * ATAPI device executes some ATA commands in addition to those
8104 	 * commands sent via PACKET command. These ATA commands may be
8105 	 * executed by the regular SATA translation functions. None needs
8106 	 * to be captured now.
8107 	 *
8108 	 * Commands sent via PACKET command include:
8109 	 *	MMC command set for ATAPI CD/DVD device
8110 	 *	SSC command set for ATAPI TAPE device
8111 	 *	SBC command set for ATAPI disk device
8112 	 *
8113 	 */
8114 
8115 	/* Check the size of cdb */
8116 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8117 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
8118 		sata_log(NULL, CE_WARN,
8119 		    "sata: invalid ATAPI cdb length %d",
8120 		    scsipkt->pkt_cdblen);
8121 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8122 		return (TRAN_BADPKT);
8123 	}
8124 
8125 	SATAATAPITRACE(spx, cdblen);
8126 
8127 	/*
8128 	 * For non-read/write commands we need to
8129 	 * map buffer
8130 	 */
8131 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8132 	case SCMD_READ:
8133 	case SCMD_READ_G1:
8134 	case SCMD_READ_G5:
8135 	case SCMD_READ_G4:
8136 	case SCMD_WRITE:
8137 	case SCMD_WRITE_G1:
8138 	case SCMD_WRITE_G5:
8139 	case SCMD_WRITE_G4:
8140 		break;
8141 	default:
8142 		if (bp != NULL) {
8143 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8144 				bp_mapin(bp);
8145 		}
8146 		break;
8147 	}
8148 	/*
8149 	 * scmd->satacmd_flags.sata_data_direction default -
8150 	 * SATA_DIR_NODATA_XFER - is set by
8151 	 * sata_txlt_generic_pkt_info().
8152 	 */
8153 	if (scmd->satacmd_bp) {
8154 		if (scmd->satacmd_bp->b_flags & B_READ) {
8155 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8156 		} else {
8157 			scmd->satacmd_flags.sata_data_direction =
8158 			    SATA_DIR_WRITE;
8159 		}
8160 	}
8161 
8162 	/*
8163 	 * Set up ATAPI packet command.
8164 	 */
8165 
8166 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8167 
8168 	/* Copy cdb into sata_cmd */
8169 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8170 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8171 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8172 
8173 	/* See note in the command header */
8174 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8175 		if (scmd->satacmd_acdb[3] != 0)
8176 			scmd->satacmd_acdb[4] = 255;
8177 	}
8178 
8179 #ifdef SATA_DEBUG
8180 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8181 		uint8_t *p = scmd->satacmd_acdb;
8182 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8183 
8184 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8185 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8186 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8187 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8188 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8189 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8190 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8191 	}
8192 #endif
8193 
8194 	/*
8195 	 * Preset request sense data to NO SENSE.
8196 	 * If there is no way to get error information via Request Sense,
8197 	 * the packet request sense data would not have to be modified by HBA,
8198 	 * but it could be returned as is.
8199 	 */
8200 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8201 	sata_fixed_sense_data_preset(
8202 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8203 
8204 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8205 		/* Need callback function */
8206 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8207 		synch = FALSE;
8208 	} else
8209 		synch = TRUE;
8210 
8211 	/* Transfer command to HBA */
8212 	if (sata_hba_start(spx, &rval) != 0) {
8213 		/* Pkt not accepted for execution */
8214 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8215 		return (rval);
8216 	}
8217 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8218 	/*
8219 	 * If execution is non-synchronous,
8220 	 * a callback function will handle potential errors, translate
8221 	 * the response and will do a callback to a target driver.
8222 	 * If it was synchronous, use the same framework callback to check
8223 	 * an execution status.
8224 	 */
8225 	if (synch) {
8226 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8227 		    "synchronous execution status %x\n",
8228 		    spx->txlt_sata_pkt->satapkt_reason);
8229 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8230 	}
8231 	return (TRAN_ACCEPT);
8232 }
8233 
8234 
8235 /*
8236  * ATAPI Packet command completion.
8237  *
8238  * Failure of the command passed via Packet command are considered device
8239  * error. SATA HBA driver would have to retrieve error data (via Request
8240  * Sense command delivered via error retrieval sata packet) and copy it
8241  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8242  */
8243 static void
8244 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8245 {
8246 	sata_pkt_txlate_t *spx =
8247 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8248 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8249 	struct scsi_extended_sense *sense;
8250 	struct buf *bp;
8251 	int rval;
8252 
8253 #ifdef SATA_DEBUG
8254 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8255 #endif
8256 
8257 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8258 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8259 
8260 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8261 		/* Normal completion */
8262 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8263 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8264 		scsipkt->pkt_reason = CMD_CMPLT;
8265 		*scsipkt->pkt_scbp = STATUS_GOOD;
8266 		if (spx->txlt_tmp_buf != NULL) {
8267 			/* Temporary buffer was used */
8268 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8269 			if (bp->b_flags & B_READ) {
8270 				rval = ddi_dma_sync(
8271 				    spx->txlt_buf_dma_handle, 0, 0,
8272 				    DDI_DMA_SYNC_FORCPU);
8273 				ASSERT(rval == DDI_SUCCESS);
8274 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8275 				    bp->b_bcount);
8276 			}
8277 		}
8278 	} else {
8279 		/*
8280 		 * Something went wrong - analyze return
8281 		 */
8282 		*scsipkt->pkt_scbp = STATUS_CHECK;
8283 		sense = sata_arq_sense(spx);
8284 
8285 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8286 			/*
8287 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8288 			 * Under this condition ERR bit is set for ATA command,
8289 			 * and CHK bit set for ATAPI command.
8290 			 *
8291 			 * Please check st_intr & sdintr about how pkt_reason
8292 			 * is used.
8293 			 */
8294 			scsipkt->pkt_reason = CMD_CMPLT;
8295 
8296 			/*
8297 			 * We may not have ARQ data if there was a double
8298 			 * error. But sense data in sata packet was pre-set
8299 			 * with NO SENSE so it is valid even if HBA could
8300 			 * not retrieve a real sense data.
8301 			 * Just copy this sense data into scsi pkt sense area.
8302 			 */
8303 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8304 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8305 #ifdef SATA_DEBUG
8306 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8307 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8308 				    "sata_txlt_atapi_completion: %02x\n"
8309 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8310 				    "          %02x %02x %02x %02x %02x %02x "
8311 				    "          %02x %02x %02x %02x %02x %02x\n",
8312 				    scsipkt->pkt_reason,
8313 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8314 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8315 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8316 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8317 				    rqsp[16], rqsp[17]);
8318 			}
8319 #endif
8320 		} else {
8321 			switch (sata_pkt->satapkt_reason) {
8322 			case SATA_PKT_PORT_ERROR:
8323 				/*
8324 				 * We have no device data.
8325 				 */
8326 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8327 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8328 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8329 				    STATE_GOT_STATUS);
8330 				sense->es_key = KEY_HARDWARE_ERROR;
8331 				break;
8332 
8333 			case SATA_PKT_TIMEOUT:
8334 				scsipkt->pkt_reason = CMD_TIMEOUT;
8335 				scsipkt->pkt_statistics |=
8336 				    STAT_TIMEOUT | STAT_DEV_RESET;
8337 				/*
8338 				 * Need to check if HARDWARE_ERROR/
8339 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8340 				 * appropriate.
8341 				 */
8342 				break;
8343 
8344 			case SATA_PKT_ABORTED:
8345 				scsipkt->pkt_reason = CMD_ABORTED;
8346 				scsipkt->pkt_statistics |= STAT_ABORTED;
8347 				/* Should we set key COMMAND_ABPRTED? */
8348 				break;
8349 
8350 			case SATA_PKT_RESET:
8351 				scsipkt->pkt_reason = CMD_RESET;
8352 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
8353 				/*
8354 				 * May be we should set Unit Attention /
8355 				 * Reset. Perhaps the same should be
8356 				 * returned for disks....
8357 				 */
8358 				sense->es_key = KEY_UNIT_ATTENTION;
8359 				sense->es_add_code = SD_SCSI_ASC_RESET;
8360 				break;
8361 
8362 			default:
8363 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8364 				    "sata_txlt_atapi_completion: "
8365 				    "invalid packet completion reason"));
8366 				scsipkt->pkt_reason = CMD_TRAN_ERR;
8367 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8368 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8369 				    STATE_GOT_STATUS);
8370 				break;
8371 			}
8372 		}
8373 	}
8374 
8375 	SATAATAPITRACE(spx, 0);
8376 
8377 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
8378 	    scsipkt->pkt_comp != NULL) {
8379 		/* scsi callback required */
8380 		(*scsipkt->pkt_comp)(scsipkt);
8381 	}
8382 }
8383 
8384 /*
8385  * Set up error retrieval sata command for ATAPI Packet Command error data
8386  * recovery.
8387  *
8388  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
8389  * returns SATA_FAILURE otherwise.
8390  */
8391 
8392 static int
8393 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
8394 {
8395 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
8396 	sata_cmd_t *scmd;
8397 	struct buf *bp;
8398 
8399 	/*
8400 	 * Allocate dma-able buffer error data.
8401 	 * Buffer allocation will take care of buffer alignment and other DMA
8402 	 * attributes.
8403 	 */
8404 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
8405 	if (bp == NULL) {
8406 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
8407 		    "sata_get_err_retrieval_pkt: "
8408 		    "cannot allocate buffer for error data", NULL);
8409 		return (SATA_FAILURE);
8410 	}
8411 	bp_mapin(bp); /* make data buffer accessible */
8412 
8413 	/* Operation modes are up to the caller */
8414 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8415 
8416 	/* Synchronous mode, no callback - may be changed by the caller */
8417 	spkt->satapkt_comp = NULL;
8418 	spkt->satapkt_time = sata_default_pkt_time;
8419 
8420 	scmd = &spkt->satapkt_cmd;
8421 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8422 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8423 
8424 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8425 
8426 	/*
8427 	 * Set-up acdb. Request Sense CDB (packet command content) is
8428 	 * not in DMA-able buffer. Its handling is HBA-specific (how
8429 	 * it is transfered into packet FIS).
8430 	 */
8431 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8432 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
8433 	/* Following zeroing of pad bytes may not be necessary */
8434 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
8435 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
8436 
8437 	/*
8438 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
8439 	 * before accessing it. Handle is in usual place in translate struct.
8440 	 */
8441 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
8442 
8443 	/*
8444 	 * Preset request sense data to NO SENSE.
8445 	 * Here it is redundant, only for a symetry with scsi-originated
8446 	 * packets. It should not be used for anything but debugging.
8447 	 */
8448 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8449 	sata_fixed_sense_data_preset(
8450 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8451 
8452 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8453 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8454 
8455 	return (SATA_SUCCESS);
8456 }
8457 
8458 /*
8459  * Set-up ATAPI packet command.
8460  * Data transfer direction has to be set-up in sata_cmd structure prior to
8461  * calling this function.
8462  *
8463  * Returns void
8464  */
8465 
8466 static void
8467 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
8468 {
8469 	scmd->satacmd_addr_type = 0;		/* N/A */
8470 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
8471 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8472 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
8473 	scmd->satacmd_lba_high_lsb =
8474 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
8475 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
8476 
8477 	/*
8478 	 * We want all data to be transfered via DMA.
8479 	 * But specify it only if drive supports DMA and DMA mode is
8480 	 * selected - some drives are sensitive about it.
8481 	 * Hopefully it wil work for all drives....
8482 	 */
8483 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
8484 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
8485 
8486 	/*
8487 	 * Features register requires special care for devices that use
8488 	 * Serial ATA bridge - they need an explicit specification of
8489 	 * the data transfer direction for Packet DMA commands.
8490 	 * Setting this bit is harmless if DMA is not used.
8491 	 *
8492 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
8493 	 * spec they follow.
8494 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
8495 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
8496 	 * ATA/ATAPI-7 support is explicitly indicated.
8497 	 */
8498 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
8499 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
8500 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
8501 		/*
8502 		 * Specification of major version is valid and version 7
8503 		 * is supported. It does automatically imply that all
8504 		 * spec features are supported. For now, we assume that
8505 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
8506 		 */
8507 		if ((sdinfo->satadrv_id.ai_dirdma &
8508 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
8509 			if (scmd->satacmd_flags.sata_data_direction ==
8510 			    SATA_DIR_READ)
8511 			scmd->satacmd_features_reg |=
8512 			    SATA_ATAPI_F_DATA_DIR_READ;
8513 		}
8514 	}
8515 }
8516 
8517 
8518 #ifdef SATA_DEBUG
8519 
8520 /* Display 18 bytes of Inquiry data */
8521 static void
8522 sata_show_inqry_data(uint8_t *buf)
8523 {
8524 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
8525 	uint8_t *p;
8526 
8527 	cmn_err(CE_NOTE, "Inquiry data:");
8528 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
8529 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
8530 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
8531 	cmn_err(CE_NOTE, "ATAPI transport version %d",
8532 	    SATA_ATAPI_TRANS_VERSION(inq));
8533 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
8534 	    inq->inq_rdf, inq->inq_aenc);
8535 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
8536 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
8537 	p = (uint8_t *)inq->inq_vid;
8538 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
8539 	    "%02x %02x %02x %02x",
8540 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
8541 	p = (uint8_t *)inq->inq_vid;
8542 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
8543 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
8544 
8545 	p = (uint8_t *)inq->inq_pid;
8546 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
8547 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
8548 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8549 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8550 	p = (uint8_t *)inq->inq_pid;
8551 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
8552 	    "%c %c %c %c %c %c %c %c",
8553 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8554 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8555 
8556 	p = (uint8_t *)inq->inq_revision;
8557 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
8558 	    p[0], p[1], p[2], p[3]);
8559 	p = (uint8_t *)inq->inq_revision;
8560 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
8561 	    p[0], p[1], p[2], p[3]);
8562 
8563 }
8564 
8565 
8566 static void
8567 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
8568 {
8569 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
8570 
8571 	if (scsi_pkt == NULL)
8572 		return;
8573 	if (count != 0) {
8574 		/* saving cdb */
8575 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
8576 		    SATA_ATAPI_MAX_CDB_LEN);
8577 		bcopy(scsi_pkt->pkt_cdbp,
8578 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
8579 	} else {
8580 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
8581 		    sts_sensedata,
8582 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
8583 		    SATA_ATAPI_MIN_RQSENSE_LEN);
8584 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
8585 		    scsi_pkt->pkt_reason;
8586 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
8587 		    spx->txlt_sata_pkt->satapkt_reason;
8588 
8589 		if (++sata_atapi_trace_index >= 64)
8590 			sata_atapi_trace_index = 0;
8591 	}
8592 }
8593 
8594 #endif
8595 
8596 /*
8597  * Fetch inquiry data from ATAPI device
8598  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
8599  *
8600  * Note:
8601  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
8602  * where the caller expects to see the inquiry data.
8603  *
8604  */
8605 
8606 static int
8607 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
8608     sata_address_t *saddr, struct scsi_inquiry *inq)
8609 {
8610 	sata_pkt_txlate_t *spx;
8611 	sata_pkt_t *spkt;
8612 	struct buf *bp;
8613 	sata_drive_info_t *sdinfo;
8614 	sata_cmd_t *scmd;
8615 	int rval;
8616 	uint8_t *rqsp;
8617 #ifdef SATA_DEBUG
8618 	char msg_buf[MAXPATHLEN];
8619 #endif
8620 
8621 	ASSERT(sata_hba != NULL);
8622 
8623 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
8624 	spx->txlt_sata_hba_inst = sata_hba;
8625 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
8626 	spkt = sata_pkt_alloc(spx, NULL);
8627 	if (spkt == NULL) {
8628 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8629 		return (SATA_FAILURE);
8630 	}
8631 	/* address is needed now */
8632 	spkt->satapkt_device.satadev_addr = *saddr;
8633 
8634 	/* scsi_inquiry size buffer */
8635 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
8636 	if (bp == NULL) {
8637 		sata_pkt_free(spx);
8638 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8639 		SATA_LOG_D((sata_hba, CE_WARN,
8640 		    "sata_get_atapi_inquiry_data: "
8641 		    "cannot allocate data buffer"));
8642 		return (SATA_FAILURE);
8643 	}
8644 	bp_mapin(bp); /* make data buffer accessible */
8645 
8646 	scmd = &spkt->satapkt_cmd;
8647 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8648 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8649 
8650 	/* Use synchronous mode */
8651 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8652 	spkt->satapkt_comp = NULL;
8653 	spkt->satapkt_time = sata_default_pkt_time;
8654 
8655 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
8656 
8657 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8658 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8659 
8660 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8661 	sdinfo = sata_get_device_info(sata_hba,
8662 	    &spx->txlt_sata_pkt->satapkt_device);
8663 	if (sdinfo == NULL) {
8664 		/* we have to be carefull about the disapearing device */
8665 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8666 		rval = SATA_FAILURE;
8667 		goto cleanup;
8668 	}
8669 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8670 
8671 	/*
8672 	 * Set-up acdb. This works for atapi transport version 2 and later.
8673 	 */
8674 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8675 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8676 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
8677 	scmd->satacmd_acdb[1] = 0x00;
8678 	scmd->satacmd_acdb[2] = 0x00;
8679 	scmd->satacmd_acdb[3] = 0x00;
8680 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
8681 	scmd->satacmd_acdb[5] = 0x00;
8682 
8683 	sata_fixed_sense_data_preset(
8684 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8685 
8686 	/* Transfer command to HBA */
8687 	if (sata_hba_start(spx, &rval) != 0) {
8688 		/* Pkt not accepted for execution */
8689 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
8690 		    "sata_get_atapi_inquiry_data: "
8691 		    "Packet not accepted for execution - ret: %02x", rval);
8692 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8693 		rval = SATA_FAILURE;
8694 		goto cleanup;
8695 	}
8696 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8697 
8698 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
8699 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
8700 		    "sata_get_atapi_inquiry_data: "
8701 		    "Packet completed successfully - ret: %02x", rval);
8702 		if (spx->txlt_buf_dma_handle != NULL) {
8703 			/*
8704 			 * Sync buffer. Handle is in usual place in translate
8705 			 * struct.
8706 			 */
8707 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
8708 			    DDI_DMA_SYNC_FORCPU);
8709 			ASSERT(rval == DDI_SUCCESS);
8710 		}
8711 		/*
8712 		 * Normal completion - copy data into caller's buffer
8713 		 */
8714 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
8715 		    sizeof (struct scsi_inquiry));
8716 #ifdef SATA_DEBUG
8717 		if (sata_debug_flags & SATA_DBG_ATAPI) {
8718 			sata_show_inqry_data((uint8_t *)inq);
8719 		}
8720 #endif
8721 		rval = SATA_SUCCESS;
8722 	} else {
8723 		/*
8724 		 * Something went wrong - analyze return - check rqsense data
8725 		 */
8726 		rval = SATA_FAILURE;
8727 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8728 			/*
8729 			 * ARQ data hopefull show something other than NO SENSE
8730 			 */
8731 			rqsp = scmd->satacmd_rqsense;
8732 #ifdef SATA_DEBUG
8733 			if (sata_debug_flags & SATA_DBG_ATAPI) {
8734 				msg_buf[0] = '\0';
8735 				(void) snprintf(msg_buf, MAXPATHLEN,
8736 				    "ATAPI packet completion reason: %02x\n"
8737 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
8738 				    "          %02x %02x %02x %02x %02x %02x\n"
8739 				    "          %02x %02x %02x %02x %02x %02x",
8740 				    spkt->satapkt_reason,
8741 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8742 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8743 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8744 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8745 				    rqsp[16], rqsp[17]);
8746 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8747 				    "%s", msg_buf);
8748 			}
8749 #endif
8750 		} else {
8751 			switch (spkt->satapkt_reason) {
8752 			case SATA_PKT_PORT_ERROR:
8753 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
8754 				    "sata_get_atapi_inquiry_data: "
8755 				    "packet reason: port error", NULL);
8756 				break;
8757 
8758 			case SATA_PKT_TIMEOUT:
8759 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
8760 				    "sata_get_atapi_inquiry_data: "
8761 				    "packet reason: timeout", NULL);
8762 				break;
8763 
8764 			case SATA_PKT_ABORTED:
8765 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
8766 				    "sata_get_atapi_inquiry_data: "
8767 				    "packet reason: aborted", NULL);
8768 				break;
8769 
8770 			case SATA_PKT_RESET:
8771 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
8772 				    "sata_get_atapi_inquiry_data: "
8773 				    "packet reason: reset\n", NULL);
8774 				break;
8775 			default:
8776 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
8777 				    "sata_get_atapi_inquiry_data: "
8778 				    "invalid packet reason: %02x\n",
8779 				    spkt->satapkt_reason);
8780 				break;
8781 			}
8782 		}
8783 	}
8784 cleanup:
8785 	sata_free_local_buffer(spx);
8786 	sata_pkt_free(spx);
8787 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
8788 	return (rval);
8789 }
8790 
8791 
8792 
8793 
8794 
8795 #if 0
8796 #ifdef SATA_DEBUG
8797 
8798 /*
8799  * Test ATAPI packet command.
8800  * Single threaded test: send packet command in synch mode, process completion
8801  *
8802  */
8803 static void
8804 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
8805 {
8806 	sata_pkt_txlate_t *spx;
8807 	sata_pkt_t *spkt;
8808 	struct buf *bp;
8809 	sata_device_t sata_device;
8810 	sata_drive_info_t *sdinfo;
8811 	sata_cmd_t *scmd;
8812 	int rval;
8813 	uint8_t *rqsp;
8814 
8815 	ASSERT(sata_hba_inst != NULL);
8816 	sata_device.satadev_addr.cport = cport;
8817 	sata_device.satadev_addr.pmport = 0;
8818 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
8819 	sata_device.satadev_rev = SATA_DEVICE_REV;
8820 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
8821 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
8822 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
8823 	if (sdinfo == NULL) {
8824 		sata_log(sata_hba_inst, CE_WARN,
8825 		    "sata_test_atapi_packet_command: "
8826 		    "no device info for cport %d",
8827 		    sata_device.satadev_addr.cport);
8828 		return;
8829 	}
8830 
8831 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
8832 	spx->txlt_sata_hba_inst = sata_hba_inst;
8833 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
8834 	spkt = sata_pkt_alloc(spx, NULL);
8835 	if (spkt == NULL) {
8836 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8837 		return;
8838 	}
8839 	/* address is needed now */
8840 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
8841 
8842 	/* 1024k buffer */
8843 	bp = sata_alloc_local_buffer(spx, 1024);
8844 	if (bp == NULL) {
8845 		sata_pkt_free(spx);
8846 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8847 		sata_log(sata_hba_inst, CE_WARN,
8848 		    "sata_test_atapi_packet_command: "
8849 		    "cannot allocate data buffer");
8850 		return;
8851 	}
8852 	bp_mapin(bp); /* make data buffer accessible */
8853 
8854 	scmd = &spkt->satapkt_cmd;
8855 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8856 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8857 
8858 	/* Use synchronous mode */
8859 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8860 
8861 	/* Synchronous mode, no callback - may be changed by the caller */
8862 	spkt->satapkt_comp = NULL;
8863 	spkt->satapkt_time = sata_default_pkt_time;
8864 
8865 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
8866 
8867 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8868 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8869 
8870 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8871 
8872 	/* Set-up acdb. */
8873 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8874 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8875 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
8876 	scmd->satacmd_acdb[1] = 0x00;
8877 	scmd->satacmd_acdb[2] = 0x00;
8878 	scmd->satacmd_acdb[3] = 0x00;
8879 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
8880 	scmd->satacmd_acdb[5] = 0x00;
8881 
8882 	sata_fixed_sense_data_preset(
8883 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8884 
8885 	/* Transfer command to HBA */
8886 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
8887 	if (sata_hba_start(spx, &rval) != 0) {
8888 		/* Pkt not accepted for execution */
8889 		sata_log(sata_hba_inst, CE_WARN,
8890 		    "sata_test_atapi_packet_command: "
8891 		    "Packet not accepted for execution - ret: %02x", rval);
8892 		mutex_exit(
8893 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
8894 		goto cleanup;
8895 	}
8896 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
8897 
8898 	if (spx->txlt_buf_dma_handle != NULL) {
8899 		/*
8900 		 * Sync buffer. Handle is in usual place in translate struct.
8901 		 */
8902 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
8903 		    DDI_DMA_SYNC_FORCPU);
8904 		ASSERT(rval == DDI_SUCCESS);
8905 	}
8906 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
8907 		sata_log(sata_hba_inst, CE_WARN,
8908 		    "sata_test_atapi_packet_command: "
8909 		    "Packet completed successfully");
8910 		/*
8911 		 * Normal completion - show inquiry data
8912 		 */
8913 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
8914 	} else {
8915 		/*
8916 		 * Something went wrong - analyze return - check rqsense data
8917 		 */
8918 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8919 			/*
8920 			 * ARQ data hopefull show something other than NO SENSE
8921 			 */
8922 			rqsp = scmd->satacmd_rqsense;
8923 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8924 			    "ATAPI packet completion reason: %02x\n"
8925 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8926 			    "          %02x %02x %02x %02x %02x %02x "
8927 			    "          %02x %02x %02x %02x %02x %02x\n",
8928 			    spkt->satapkt_reason,
8929 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8930 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8931 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8932 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8933 			    rqsp[16], rqsp[17]);
8934 		} else {
8935 			switch (spkt->satapkt_reason) {
8936 			case SATA_PKT_PORT_ERROR:
8937 				sata_log(sata_hba_inst, CE_WARN,
8938 				    "sata_test_atapi_packet_command: "
8939 				    "packet reason: port error\n");
8940 				break;
8941 
8942 			case SATA_PKT_TIMEOUT:
8943 				sata_log(sata_hba_inst, CE_WARN,
8944 				    "sata_test_atapi_packet_command: "
8945 				    "packet reason: timeout\n");
8946 				break;
8947 
8948 			case SATA_PKT_ABORTED:
8949 				sata_log(sata_hba_inst, CE_WARN,
8950 				    "sata_test_atapi_packet_command: "
8951 				    "packet reason: aborted\n");
8952 				break;
8953 
8954 			case SATA_PKT_RESET:
8955 				sata_log(sata_hba_inst, CE_WARN,
8956 				    "sata_test_atapi_packet_command: "
8957 				    "packet reason: reset\n");
8958 				break;
8959 			default:
8960 				sata_log(sata_hba_inst, CE_WARN,
8961 				    "sata_test_atapi_packet_command: "
8962 				    "invalid packet reason: %02x\n",
8963 				    spkt->satapkt_reason);
8964 				break;
8965 			}
8966 		}
8967 	}
8968 cleanup:
8969 	sata_free_local_buffer(spx);
8970 	sata_pkt_free(spx);
8971 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
8972 }
8973 
8974 #endif /* SATA_DEBUG */
8975 #endif /* 1 */
8976 
8977 
8978 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
8979 
8980 /*
8981  * Validate sata_tran info
8982  * SATA_FAILURE returns if structure is inconsistent or structure revision
8983  * does not match one used by the framework.
8984  *
8985  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
8986  * required function pointers.
8987  * Returns SATA_FAILURE otherwise.
8988  */
8989 static int
8990 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
8991 {
8992 	/*
8993 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
8994 	 * of the SATA interface.
8995 	 */
8996 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
8997 		sata_log(NULL, CE_WARN,
8998 		    "sata: invalid sata_hba_tran version %d for driver %s",
8999 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9000 		return (SATA_FAILURE);
9001 	}
9002 
9003 	if (dip != sata_tran->sata_tran_hba_dip) {
9004 		SATA_LOG_D((NULL, CE_WARN,
9005 		    "sata: inconsistent sata_tran_hba_dip "
9006 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9007 		return (SATA_FAILURE);
9008 	}
9009 
9010 	if (sata_tran->sata_tran_probe_port == NULL ||
9011 	    sata_tran->sata_tran_start == NULL ||
9012 	    sata_tran->sata_tran_abort == NULL ||
9013 	    sata_tran->sata_tran_reset_dport == NULL ||
9014 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9015 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9016 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9017 	    NULL) {
9018 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9019 		    "required functions"));
9020 	}
9021 	return (SATA_SUCCESS);
9022 }
9023 
9024 /*
9025  * Remove HBA instance from sata_hba_list.
9026  */
9027 static void
9028 sata_remove_hba_instance(dev_info_t *dip)
9029 {
9030 	sata_hba_inst_t	*sata_hba_inst;
9031 
9032 	mutex_enter(&sata_mutex);
9033 	for (sata_hba_inst = sata_hba_list;
9034 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9035 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9036 		if (sata_hba_inst->satahba_dip == dip)
9037 			break;
9038 	}
9039 
9040 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9041 #ifdef SATA_DEBUG
9042 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9043 		    "unknown HBA instance\n");
9044 #endif
9045 		ASSERT(FALSE);
9046 	}
9047 	if (sata_hba_inst == sata_hba_list) {
9048 		sata_hba_list = sata_hba_inst->satahba_next;
9049 		if (sata_hba_list) {
9050 			sata_hba_list->satahba_prev =
9051 			    (struct sata_hba_inst *)NULL;
9052 		}
9053 		if (sata_hba_inst == sata_hba_list_tail) {
9054 			sata_hba_list_tail = NULL;
9055 		}
9056 	} else if (sata_hba_inst == sata_hba_list_tail) {
9057 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9058 		if (sata_hba_list_tail) {
9059 			sata_hba_list_tail->satahba_next =
9060 			    (struct sata_hba_inst *)NULL;
9061 		}
9062 	} else {
9063 		sata_hba_inst->satahba_prev->satahba_next =
9064 		    sata_hba_inst->satahba_next;
9065 		sata_hba_inst->satahba_next->satahba_prev =
9066 		    sata_hba_inst->satahba_prev;
9067 	}
9068 	mutex_exit(&sata_mutex);
9069 }
9070 
9071 /*
9072  * Probe all SATA ports of the specified HBA instance.
9073  * The assumption is that there are no target and attachment point minor nodes
9074  * created by the boot subsystems, so we do not need to prune device tree.
9075  *
9076  * This function is called only from sata_hba_attach(). It does not have to
9077  * be protected by controller mutex, because the hba_attached flag is not set
9078  * yet and no one would be touching this HBA instance other than this thread.
9079  * Determines if port is active and what type of the device is attached
9080  * (if any). Allocates necessary structures for each port.
9081  *
9082  * An AP (Attachement Point) node is created for each SATA device port even
9083  * when there is no device attached.
9084  */
9085 
9086 static 	void
9087 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9088 {
9089 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9090 	int			ncport;
9091 	sata_cport_info_t 	*cportinfo;
9092 	sata_drive_info_t	*drive;
9093 	sata_device_t		sata_device;
9094 	int			rval;
9095 	dev_t			minor_number;
9096 	char			name[16];
9097 	clock_t			start_time, cur_time;
9098 
9099 	/*
9100 	 * Probe controller ports first, to find port status and
9101 	 * any port multiplier attached.
9102 	 */
9103 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9104 		/* allocate cport structure */
9105 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9106 		ASSERT(cportinfo != NULL);
9107 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9108 
9109 		mutex_enter(&cportinfo->cport_mutex);
9110 
9111 		cportinfo->cport_addr.cport = ncport;
9112 		cportinfo->cport_addr.pmport = 0;
9113 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9114 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9115 		cportinfo->cport_state |= SATA_STATE_PROBING;
9116 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9117 
9118 		/*
9119 		 * Regardless if a port is usable or not, create
9120 		 * an attachment point
9121 		 */
9122 		mutex_exit(&cportinfo->cport_mutex);
9123 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9124 		    ncport, 0, SATA_ADDR_CPORT);
9125 		(void) sprintf(name, "%d", ncport);
9126 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9127 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9128 		    DDI_SUCCESS) {
9129 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9130 			    "cannot create SATA attachment point for port %d",
9131 			    ncport);
9132 		}
9133 
9134 		/* Probe port */
9135 		start_time = ddi_get_lbolt();
9136 	reprobe_cport:
9137 		sata_device.satadev_addr.cport = ncport;
9138 		sata_device.satadev_addr.pmport = 0;
9139 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9140 		sata_device.satadev_rev = SATA_DEVICE_REV;
9141 
9142 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9143 		    (dip, &sata_device);
9144 
9145 		mutex_enter(&cportinfo->cport_mutex);
9146 		cportinfo->cport_scr = sata_device.satadev_scr;
9147 		if (rval != SATA_SUCCESS) {
9148 			/* Something went wrong? Fail the port */
9149 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9150 			mutex_exit(&cportinfo->cport_mutex);
9151 			continue;
9152 		}
9153 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9154 		cportinfo->cport_state |= SATA_STATE_PROBED;
9155 		cportinfo->cport_dev_type = sata_device.satadev_type;
9156 
9157 		cportinfo->cport_state |= SATA_STATE_READY;
9158 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9159 			mutex_exit(&cportinfo->cport_mutex);
9160 			continue;
9161 		}
9162 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9163 			/*
9164 			 * There is some device attached.
9165 			 * Allocate device info structure
9166 			 */
9167 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9168 				mutex_exit(&cportinfo->cport_mutex);
9169 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9170 				    kmem_zalloc(sizeof (sata_drive_info_t),
9171 				    KM_SLEEP);
9172 				mutex_enter(&cportinfo->cport_mutex);
9173 			}
9174 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9175 			drive->satadrv_addr = cportinfo->cport_addr;
9176 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9177 			drive->satadrv_type = cportinfo->cport_dev_type;
9178 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9179 
9180 			mutex_exit(&cportinfo->cport_mutex);
9181 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9182 			    SATA_SUCCESS) {
9183 				/*
9184 				 * Plugged device was not correctly identified.
9185 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9186 				 */
9187 				cur_time = ddi_get_lbolt();
9188 				if ((cur_time - start_time) <
9189 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9190 					/* sleep for a while */
9191 					delay(drv_usectohz(
9192 					    SATA_DEV_RETRY_DLY));
9193 					goto reprobe_cport;
9194 				}
9195 			}
9196 		} else { /* SATA_DTYPE_PMULT */
9197 			mutex_exit(&cportinfo->cport_mutex);
9198 
9199 			/* Allocate sata_pmult_info and sata_pmport_info */
9200 			sata_alloc_pmult(sata_hba_inst, &sata_device);
9201 
9202 			/* Log the information of the port multiplier */
9203 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9204 
9205 			/* Probe its pmports */
9206 			sata_probe_pmports(sata_hba_inst, ncport);
9207 		}
9208 	}
9209 }
9210 
9211 /*
9212  * Probe all device ports behind a port multiplier.
9213  *
9214  * PMult-related structure should be allocated before by sata_alloc_pmult().
9215  *
9216  * NOTE1: Only called from sata_probe_ports()
9217  * NOTE2: No mutex should be hold.
9218  */
9219 static void
9220 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9221 {
9222 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9223 	sata_pmult_info_t	*pmultinfo = NULL;
9224 	sata_pmport_info_t 	*pmportinfo = NULL;
9225 	sata_drive_info_t	*drive = NULL;
9226 	sata_device_t		sata_device;
9227 
9228 	clock_t			start_time, cur_time;
9229 	int			npmport;
9230 	int			rval;
9231 
9232 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9233 
9234 	/* Probe Port Multiplier ports */
9235 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9236 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9237 		start_time = ddi_get_lbolt();
9238 reprobe_pmport:
9239 		sata_device.satadev_addr.cport = ncport;
9240 		sata_device.satadev_addr.pmport = npmport;
9241 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9242 		sata_device.satadev_rev = SATA_DEVICE_REV;
9243 
9244 		/* Let HBA driver probe it. */
9245 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9246 		    (dip, &sata_device);
9247 		mutex_enter(&pmportinfo->pmport_mutex);
9248 
9249 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9250 
9251 		if (rval != SATA_SUCCESS) {
9252 			pmportinfo->pmport_state =
9253 			    SATA_PSTATE_FAILED;
9254 			mutex_exit(&pmportinfo->pmport_mutex);
9255 			continue;
9256 		}
9257 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9258 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9259 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9260 
9261 		pmportinfo->pmport_state |= SATA_STATE_READY;
9262 		if (pmportinfo->pmport_dev_type ==
9263 		    SATA_DTYPE_NONE) {
9264 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9265 			    "no device found at port %d:%d", ncport, npmport);
9266 			mutex_exit(&pmportinfo->pmport_mutex);
9267 			continue;
9268 		}
9269 		/* Port multipliers cannot be chained */
9270 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9271 		/*
9272 		 * There is something attached to Port
9273 		 * Multiplier device port
9274 		 * Allocate device info structure
9275 		 */
9276 		if (pmportinfo->pmport_sata_drive == NULL) {
9277 			mutex_exit(&pmportinfo->pmport_mutex);
9278 			pmportinfo->pmport_sata_drive =
9279 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9280 			mutex_enter(&pmportinfo->pmport_mutex);
9281 		}
9282 		drive = pmportinfo->pmport_sata_drive;
9283 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9284 		drive->satadrv_addr.pmport = npmport;
9285 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9286 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9287 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9288 
9289 		mutex_exit(&pmportinfo->pmport_mutex);
9290 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9291 
9292 		if (rval != SATA_SUCCESS) {
9293 			/*
9294 			 * Plugged device was not correctly identified.
9295 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9296 			 */
9297 			cur_time = ddi_get_lbolt();
9298 			if ((cur_time - start_time) < drv_usectohz(
9299 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9300 				/* sleep for a while */
9301 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9302 				goto reprobe_pmport;
9303 			}
9304 		}
9305 	}
9306 }
9307 
9308 /*
9309  * Add SATA device for specified HBA instance & port (SCSI target
9310  * device nodes).
9311  * This function is called (indirectly) only from sata_hba_attach().
9312  * A target node is created when there is a supported type device attached,
9313  * but may be removed if it cannot be put online.
9314  *
9315  * This function cannot be called from an interrupt context.
9316  *
9317  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9318  *
9319  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9320  * device identification failed - adding a device could be retried.
9321  *
9322  */
9323 static 	int
9324 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9325     sata_device_t *sata_device)
9326 {
9327 	sata_cport_info_t 	*cportinfo;
9328 	sata_pmult_info_t	*pminfo;
9329 	sata_pmport_info_t	*pmportinfo;
9330 	dev_info_t		*cdip;		/* child dip */
9331 	sata_address_t		*saddr = &sata_device->satadev_addr;
9332 	uint8_t			cport, pmport;
9333 	int			rval;
9334 
9335 	cport = saddr->cport;
9336 	pmport = saddr->pmport;
9337 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9338 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9339 
9340 	/*
9341 	 * Some device is attached to a controller port.
9342 	 * We rely on controllers distinquishing between no-device,
9343 	 * attached port multiplier and other kind of attached device.
9344 	 * We need to get Identify Device data and determine
9345 	 * positively the dev type before trying to attach
9346 	 * the target driver.
9347 	 */
9348 	sata_device->satadev_rev = SATA_DEVICE_REV;
9349 	switch (saddr->qual) {
9350 	case SATA_ADDR_CPORT:
9351 		/*
9352 		 * Add a non-port-multiplier device at controller port.
9353 		 */
9354 		saddr->qual = SATA_ADDR_DCPORT;
9355 
9356 		rval = sata_probe_device(sata_hba_inst, sata_device);
9357 		if (rval != SATA_SUCCESS ||
9358 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
9359 			return (SATA_FAILURE);
9360 
9361 		mutex_enter(&cportinfo->cport_mutex);
9362 		sata_show_drive_info(sata_hba_inst,
9363 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
9364 
9365 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9366 			/*
9367 			 * Could not determine device type or
9368 			 * a device is not supported.
9369 			 * Degrade this device to unknown.
9370 			 */
9371 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
9372 			mutex_exit(&cportinfo->cport_mutex);
9373 			return (SATA_SUCCESS);
9374 		}
9375 		cportinfo->cport_dev_type = sata_device->satadev_type;
9376 		cportinfo->cport_tgtnode_clean = B_TRUE;
9377 		mutex_exit(&cportinfo->cport_mutex);
9378 
9379 		/*
9380 		 * Initialize device to the desired state. Even if it
9381 		 * fails, the device will still attach but syslog
9382 		 * will show the warning.
9383 		 */
9384 		if (sata_initialize_device(sata_hba_inst,
9385 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
9386 			/* Retry */
9387 			rval = sata_initialize_device(sata_hba_inst,
9388 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
9389 
9390 			if (rval == SATA_RETRY)
9391 				sata_log(sata_hba_inst, CE_WARN,
9392 				    "SATA device at port %d - "
9393 				    "default device features could not be set."
9394 				    " Device may not operate as expected.",
9395 				    cport);
9396 		}
9397 
9398 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9399 		if (cdip == NULL) {
9400 			/*
9401 			 * Attaching target node failed.
9402 			 * We retain sata_drive_info structure...
9403 			 */
9404 			return (SATA_SUCCESS);
9405 		}
9406 
9407 		mutex_enter(&cportinfo->cport_mutex);
9408 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
9409 		    satadrv_state = SATA_STATE_READY;
9410 		mutex_exit(&cportinfo->cport_mutex);
9411 
9412 		break;
9413 
9414 	case SATA_ADDR_PMPORT:
9415 		saddr->qual = SATA_ADDR_DPMPORT;
9416 
9417 		mutex_enter(&cportinfo->cport_mutex);
9418 		/* It must be a Port Multiplier at the controller port */
9419 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
9420 
9421 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9422 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
9423 		mutex_exit(&cportinfo->cport_mutex);
9424 
9425 		rval = sata_probe_device(sata_hba_inst, sata_device);
9426 		if (rval != SATA_SUCCESS ||
9427 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
9428 			return (SATA_FAILURE);
9429 		}
9430 
9431 		mutex_enter(&pmportinfo->pmport_mutex);
9432 		sata_show_drive_info(sata_hba_inst,
9433 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
9434 
9435 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9436 			/*
9437 			 * Could not determine device type.
9438 			 * Degrade this device to unknown.
9439 			 */
9440 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
9441 			mutex_exit(&pmportinfo->pmport_mutex);
9442 			return (SATA_SUCCESS);
9443 		}
9444 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
9445 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
9446 		mutex_exit(&pmportinfo->pmport_mutex);
9447 
9448 		/*
9449 		 * Initialize device to the desired state.
9450 		 * Even if it fails, the device will still
9451 		 * attach but syslog will show the warning.
9452 		 */
9453 		if (sata_initialize_device(sata_hba_inst,
9454 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
9455 			/* Retry */
9456 			rval = sata_initialize_device(sata_hba_inst,
9457 			    pmportinfo->pmport_sata_drive);
9458 
9459 			if (rval == SATA_RETRY)
9460 				sata_log(sata_hba_inst, CE_WARN,
9461 				    "SATA device at port %d:%d - "
9462 				    "default device features could not be set."
9463 				    " Device may not operate as expected.",
9464 				    cport, pmport);
9465 		}
9466 
9467 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9468 		if (cdip == NULL) {
9469 			/*
9470 			 * Attaching target node failed.
9471 			 * We retain sata_drive_info structure...
9472 			 */
9473 			return (SATA_SUCCESS);
9474 		}
9475 		mutex_enter(&pmportinfo->pmport_mutex);
9476 		pmportinfo->pmport_sata_drive->satadrv_state |=
9477 		    SATA_STATE_READY;
9478 		mutex_exit(&pmportinfo->pmport_mutex);
9479 
9480 		break;
9481 
9482 	default:
9483 		return (SATA_FAILURE);
9484 	}
9485 
9486 	return (SATA_SUCCESS);
9487 }
9488 
9489 /*
9490  * Clean up target node at specific address.
9491  *
9492  * NOTE: No Mutex should be hold.
9493  */
9494 static int
9495 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
9496     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
9497 {
9498 	uint8_t cport, pmport, qual;
9499 	dev_info_t *tdip;
9500 
9501 	cport = sata_device->satadev_addr.cport;
9502 	pmport = sata_device->satadev_addr.pmport;
9503 	qual = sata_device->satadev_addr.qual;
9504 
9505 	if (qual == SATA_ADDR_DCPORT) {
9506 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9507 		    "sata_hba_ioctl: disconnect device at port %d", cport));
9508 	} else {
9509 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9510 		    "sata_hba_ioctl: disconnect device at port %d:%d",
9511 		    cport, pmport));
9512 	}
9513 
9514 	/* We are addressing attached device, not a port */
9515 	sata_device->satadev_addr.qual =
9516 	    sdinfo->satadrv_addr.qual;
9517 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
9518 	    &sata_device->satadev_addr);
9519 	if (tdip != NULL && ndi_devi_offline(tdip,
9520 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
9521 		/*
9522 		 * Problem :
9523 		 * The target node remained attached.
9524 		 * This happens when the device file was open
9525 		 * or a node was waiting for resources.
9526 		 * Cannot do anything about it.
9527 		 */
9528 		if (qual == SATA_ADDR_DCPORT) {
9529 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9530 			    "sata_hba_ioctl: disconnect: could "
9531 			    "not unconfigure device before "
9532 			    "disconnecting the SATA port %d",
9533 			    cport));
9534 		} else {
9535 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9536 			    "sata_hba_ioctl: disconnect: could "
9537 			    "not unconfigure device before "
9538 			    "disconnecting the SATA port %d:%d",
9539 			    cport, pmport));
9540 		}
9541 		/*
9542 		 * Set DEVICE REMOVED state in the target
9543 		 * node. It will prevent access to the device
9544 		 * even when a new device is attached, until
9545 		 * the old target node is released, removed and
9546 		 * recreated for a new  device.
9547 		 */
9548 		sata_set_device_removed(tdip);
9549 
9550 		/*
9551 		 * Instruct event daemon to try the target
9552 		 * node cleanup later.
9553 		 */
9554 		sata_set_target_node_cleanup(
9555 		    sata_hba_inst, &sata_device->satadev_addr);
9556 	}
9557 
9558 
9559 	return (SATA_SUCCESS);
9560 }
9561 
9562 
9563 /*
9564  * Create scsi target node for attached device, create node properties and
9565  * attach the node.
9566  * The node could be removed if the device onlining fails.
9567  *
9568  * A dev_info_t pointer is returned if operation is successful, NULL is
9569  * returned otherwise.
9570  */
9571 
9572 static dev_info_t *
9573 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
9574 			sata_address_t *sata_addr)
9575 {
9576 	dev_info_t *cdip = NULL;
9577 	int rval;
9578 	char *nname = NULL;
9579 	char **compatible = NULL;
9580 	int ncompatible;
9581 	struct scsi_inquiry inq;
9582 	sata_device_t sata_device;
9583 	sata_drive_info_t *sdinfo;
9584 	int target;
9585 	int i;
9586 
9587 	sata_device.satadev_rev = SATA_DEVICE_REV;
9588 	sata_device.satadev_addr = *sata_addr;
9589 
9590 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
9591 
9592 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9593 
9594 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
9595 	    sata_addr->pmport, sata_addr->qual);
9596 
9597 	if (sdinfo == NULL) {
9598 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9599 		    sata_addr->cport)));
9600 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9601 		    "sata_create_target_node: no sdinfo for target %x",
9602 		    target));
9603 		return (NULL);
9604 	}
9605 
9606 	/*
9607 	 * create or get scsi inquiry data, expected by
9608 	 * scsi_hba_nodename_compatible_get()
9609 	 * SATA hard disks get Identify Data translated into Inguiry Data.
9610 	 * ATAPI devices respond directly to Inquiry request.
9611 	 */
9612 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9613 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
9614 		    (uint8_t *)&inq);
9615 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9616 		    sata_addr->cport)));
9617 	} else { /* Assume supported ATAPI device */
9618 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9619 		    sata_addr->cport)));
9620 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
9621 		    &inq) == SATA_FAILURE)
9622 			return (NULL);
9623 		/*
9624 		 * Save supported ATAPI transport version
9625 		 */
9626 		sdinfo->satadrv_atapi_trans_ver =
9627 		    SATA_ATAPI_TRANS_VERSION(&inq);
9628 	}
9629 
9630 	/* determine the node name and compatible */
9631 	scsi_hba_nodename_compatible_get(&inq, NULL,
9632 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
9633 
9634 #ifdef SATA_DEBUG
9635 	if (sata_debug_flags & SATA_DBG_NODES) {
9636 		if (nname == NULL) {
9637 			cmn_err(CE_NOTE, "sata_create_target_node: "
9638 			    "cannot determine nodename for target %d\n",
9639 			    target);
9640 		} else {
9641 			cmn_err(CE_WARN, "sata_create_target_node: "
9642 			    "target %d nodename: %s\n", target, nname);
9643 		}
9644 		if (compatible == NULL) {
9645 			cmn_err(CE_WARN,
9646 			    "sata_create_target_node: no compatible name\n");
9647 		} else {
9648 			for (i = 0; i < ncompatible; i++) {
9649 				cmn_err(CE_WARN, "sata_create_target_node: "
9650 				    "compatible name: %s\n", compatible[i]);
9651 			}
9652 		}
9653 	}
9654 #endif
9655 
9656 	/* if nodename can't be determined, log error and exit */
9657 	if (nname == NULL) {
9658 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9659 		    "sata_create_target_node: cannot determine nodename "
9660 		    "for target %d\n", target));
9661 		scsi_hba_nodename_compatible_free(nname, compatible);
9662 		return (NULL);
9663 	}
9664 	/*
9665 	 * Create scsi target node
9666 	 */
9667 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
9668 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
9669 	    "device-type", "scsi");
9670 
9671 	if (rval != DDI_PROP_SUCCESS) {
9672 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
9673 		    "updating device_type prop failed %d", rval));
9674 		goto fail;
9675 	}
9676 
9677 	/*
9678 	 * Create target node properties: target & lun
9679 	 */
9680 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
9681 	if (rval != DDI_PROP_SUCCESS) {
9682 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
9683 		    "updating target prop failed %d", rval));
9684 		goto fail;
9685 	}
9686 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
9687 	if (rval != DDI_PROP_SUCCESS) {
9688 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
9689 		    "updating target prop failed %d", rval));
9690 		goto fail;
9691 	}
9692 
9693 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
9694 		/*
9695 		 * Add "variant" property
9696 		 */
9697 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
9698 		    "variant", "atapi");
9699 		if (rval != DDI_PROP_SUCCESS) {
9700 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9701 			    "sata_create_target_node: variant atapi "
9702 			    "property could not be created: %d", rval));
9703 			goto fail;
9704 		}
9705 	}
9706 	/* decorate the node with compatible */
9707 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
9708 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
9709 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9710 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
9711 		    (void *)cdip));
9712 		goto fail;
9713 	}
9714 
9715 
9716 	/*
9717 	 * Now, try to attach the driver. If probing of the device fails,
9718 	 * the target node may be removed
9719 	 */
9720 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
9721 
9722 	scsi_hba_nodename_compatible_free(nname, compatible);
9723 
9724 	if (rval == NDI_SUCCESS)
9725 		return (cdip);
9726 
9727 	/* target node was removed - are we sure? */
9728 	return (NULL);
9729 
9730 fail:
9731 	scsi_hba_nodename_compatible_free(nname, compatible);
9732 	ddi_prop_remove_all(cdip);
9733 	rval = ndi_devi_free(cdip);
9734 	if (rval != NDI_SUCCESS) {
9735 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
9736 		    "node removal failed %d", rval));
9737 	}
9738 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
9739 	    "cannot create target node for SATA device at port %d",
9740 	    sata_addr->cport);
9741 	return (NULL);
9742 }
9743 
9744 /*
9745  * Remove a target node.
9746  */
9747 static void
9748 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
9749 			sata_address_t *sata_addr)
9750 {
9751 	dev_info_t *tdip;
9752 	uint8_t cport = sata_addr->cport;
9753 	uint8_t pmport = sata_addr->pmport;
9754 	uint8_t qual = sata_addr->qual;
9755 
9756 	/* Note the sata daemon uses the address of the port/pmport */
9757 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
9758 
9759 	/* Remove target node */
9760 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
9761 	if (tdip != NULL) {
9762 		/*
9763 		 * Target node exists.  Unconfigure device
9764 		 * then remove the target node (one ndi
9765 		 * operation).
9766 		 */
9767 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
9768 			/*
9769 			 * PROBLEM - no device, but target node remained. This
9770 			 * happens when the file was open or node was waiting
9771 			 * for resources.
9772 			 */
9773 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9774 			    "sata_remove_target_node: "
9775 			    "Failed to remove target node for "
9776 			    "detached SATA device."));
9777 			/*
9778 			 * Set target node state to DEVI_DEVICE_REMOVED. But
9779 			 * re-check first that the node still exists.
9780 			 */
9781 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
9782 			    cport, pmport);
9783 			if (tdip != NULL) {
9784 				sata_set_device_removed(tdip);
9785 				/*
9786 				 * Instruct event daemon to retry the cleanup
9787 				 * later.
9788 				 */
9789 				sata_set_target_node_cleanup(sata_hba_inst,
9790 				    sata_addr);
9791 			}
9792 		}
9793 
9794 		if (qual == SATA_ADDR_CPORT)
9795 			sata_log(sata_hba_inst, CE_WARN,
9796 			    "SATA device detached at port %d", cport);
9797 		else
9798 			sata_log(sata_hba_inst, CE_WARN,
9799 			    "SATA device detached at port %d:%d",
9800 			    cport, pmport);
9801 	}
9802 #ifdef SATA_DEBUG
9803 	else {
9804 		if (qual == SATA_ADDR_CPORT)
9805 			sata_log(sata_hba_inst, CE_WARN,
9806 			    "target node not found at port %d", cport);
9807 		else
9808 			sata_log(sata_hba_inst, CE_WARN,
9809 			    "target node not found at port %d:%d",
9810 			    cport, pmport);
9811 	}
9812 #endif
9813 }
9814 
9815 
9816 /*
9817  * Re-probe sata port, check for a device and attach info
9818  * structures when necessary. Identify Device data is fetched, if possible.
9819  * Assumption: sata address is already validated.
9820  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
9821  * the presence of a device and its type.
9822  *
9823  * flag arg specifies that the function should try multiple times to identify
9824  * device type and to initialize it, or it should return immediately on failure.
9825  * SATA_DEV_IDENTIFY_RETRY - retry
9826  * SATA_DEV_IDENTIFY_NORETRY - no retry
9827  *
9828  * SATA_FAILURE is returned if one of the operations failed.
9829  *
9830  * This function cannot be called in interrupt context - it may sleep.
9831  *
9832  * Note: Port multiplier is supported.
9833  */
9834 static int
9835 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
9836     int flag)
9837 {
9838 	sata_cport_info_t *cportinfo;
9839 	sata_pmult_info_t *pmultinfo;
9840 	sata_drive_info_t *sdinfo, *osdinfo;
9841 	boolean_t init_device = B_FALSE;
9842 	int prev_device_type = SATA_DTYPE_NONE;
9843 	int prev_device_settings = 0;
9844 	int prev_device_state = 0;
9845 	clock_t start_time;
9846 	int retry = B_FALSE;
9847 	uint8_t cport = sata_device->satadev_addr.cport;
9848 	int rval_probe, rval_init;
9849 
9850 	/*
9851 	 * If target is pmport, sata_reprobe_pmport() will handle it.
9852 	 */
9853 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
9854 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
9855 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
9856 
9857 	/* We only care about host sata cport for now */
9858 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
9859 	    sata_device->satadev_addr.cport);
9860 
9861 	/*
9862 	 * If a port multiplier was previously attached (we have no idea it
9863 	 * still there or not), sata_reprobe_pmult() will handle it.
9864 	 */
9865 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
9866 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
9867 
9868 	/* Store sata_drive_info when a non-pmult device was attached. */
9869 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
9870 	if (osdinfo != NULL) {
9871 		/*
9872 		 * We are re-probing port with a previously attached device.
9873 		 * Save previous device type and settings.
9874 		 */
9875 		prev_device_type = cportinfo->cport_dev_type;
9876 		prev_device_settings = osdinfo->satadrv_settings;
9877 		prev_device_state = osdinfo->satadrv_state;
9878 	}
9879 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
9880 		start_time = ddi_get_lbolt();
9881 		retry = B_TRUE;
9882 	}
9883 retry_probe:
9884 
9885 	/* probe port */
9886 	mutex_enter(&cportinfo->cport_mutex);
9887 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9888 	cportinfo->cport_state |= SATA_STATE_PROBING;
9889 	mutex_exit(&cportinfo->cport_mutex);
9890 
9891 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9892 	    (SATA_DIP(sata_hba_inst), sata_device);
9893 
9894 	mutex_enter(&cportinfo->cport_mutex);
9895 	if (rval_probe != SATA_SUCCESS) {
9896 		cportinfo->cport_state = SATA_PSTATE_FAILED;
9897 		mutex_exit(&cportinfo->cport_mutex);
9898 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
9899 		    "SATA port %d probing failed",
9900 		    cportinfo->cport_addr.cport));
9901 		return (SATA_FAILURE);
9902 	}
9903 
9904 	/*
9905 	 * update sata port state and set device type
9906 	 */
9907 	sata_update_port_info(sata_hba_inst, sata_device);
9908 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
9909 
9910 	/*
9911 	 * Sanity check - Port is active? Is the link active?
9912 	 * Is there any device attached?
9913 	 */
9914 	if ((cportinfo->cport_state &
9915 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
9916 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
9917 	    SATA_PORT_DEVLINK_UP) {
9918 		/*
9919 		 * Port in non-usable state or no link active/no device.
9920 		 * Free info structure if necessary (direct attached drive
9921 		 * only, for now!
9922 		 */
9923 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
9924 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
9925 		/* Add here differentiation for device attached or not */
9926 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
9927 		mutex_exit(&cportinfo->cport_mutex);
9928 		if (sdinfo != NULL)
9929 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
9930 		return (SATA_SUCCESS);
9931 	}
9932 
9933 	cportinfo->cport_state |= SATA_STATE_READY;
9934 	cportinfo->cport_state |= SATA_STATE_PROBED;
9935 
9936 	cportinfo->cport_dev_type = sata_device->satadev_type;
9937 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
9938 
9939 	/*
9940 	 * If we are re-probing the port, there may be
9941 	 * sata_drive_info structure attached
9942 	 */
9943 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
9944 
9945 		/*
9946 		 * There is no device, so remove device info structure,
9947 		 * if necessary.
9948 		 */
9949 		/* Device change: Drive -> None */
9950 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
9951 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
9952 		if (sdinfo != NULL) {
9953 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
9954 			sata_log(sata_hba_inst, CE_WARN,
9955 			    "SATA device detached "
9956 			    "from port %d", cportinfo->cport_addr.cport);
9957 		}
9958 		mutex_exit(&cportinfo->cport_mutex);
9959 		return (SATA_SUCCESS);
9960 
9961 	}
9962 
9963 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
9964 
9965 		/* Device (may) change: Drive -> Drive */
9966 		if (sdinfo == NULL) {
9967 			/*
9968 			 * There is some device attached, but there is
9969 			 * no sata_drive_info structure - allocate one
9970 			 */
9971 			mutex_exit(&cportinfo->cport_mutex);
9972 			sdinfo = kmem_zalloc(
9973 			    sizeof (sata_drive_info_t), KM_SLEEP);
9974 			mutex_enter(&cportinfo->cport_mutex);
9975 			/*
9976 			 * Recheck, that the port state did not change when we
9977 			 * released mutex.
9978 			 */
9979 			if (cportinfo->cport_state & SATA_STATE_READY) {
9980 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
9981 				sdinfo->satadrv_addr = cportinfo->cport_addr;
9982 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
9983 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9984 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
9985 			} else {
9986 				/*
9987 				 * Port is not in ready state, we
9988 				 * cannot attach a device.
9989 				 */
9990 				mutex_exit(&cportinfo->cport_mutex);
9991 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
9992 				return (SATA_SUCCESS);
9993 			}
9994 			/*
9995 			 * Since we are adding device, presumably new one,
9996 			 * indicate that it  should be initalized,
9997 			 * as well as some internal framework states).
9998 			 */
9999 			init_device = B_TRUE;
10000 		}
10001 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10002 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10003 	} else {
10004 		/* Device change: Drive -> PMult */
10005 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10006 		if (sdinfo != NULL) {
10007 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10008 			sata_log(sata_hba_inst, CE_WARN,
10009 			    "SATA device detached "
10010 			    "from port %d", cportinfo->cport_addr.cport);
10011 		}
10012 
10013 		sata_log(sata_hba_inst, CE_WARN,
10014 		    "SATA port multiplier detected at port %d",
10015 		    cportinfo->cport_addr.cport);
10016 
10017 		mutex_exit(&cportinfo->cport_mutex);
10018 		sata_alloc_pmult(sata_hba_inst, sata_device);
10019 		sata_show_pmult_info(sata_hba_inst, sata_device);
10020 		mutex_enter(&cportinfo->cport_mutex);
10021 
10022 		/*
10023 		 * Mark all the port multiplier port behind the port
10024 		 * multiplier behind with link events, so that the sata daemon
10025 		 * will update their status.
10026 		 */
10027 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10028 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10029 		mutex_exit(&cportinfo->cport_mutex);
10030 		return (SATA_SUCCESS);
10031 	}
10032 	mutex_exit(&cportinfo->cport_mutex);
10033 
10034 	/*
10035 	 * Figure out what kind of device we are really
10036 	 * dealing with. Failure of identifying device does not fail this
10037 	 * function.
10038 	 */
10039 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10040 	rval_init = SATA_FAILURE;
10041 	mutex_enter(&cportinfo->cport_mutex);
10042 	if (rval_probe == SATA_SUCCESS) {
10043 		/*
10044 		 * If we are dealing with the same type of a device as before,
10045 		 * restore its settings flags.
10046 		 */
10047 		if (osdinfo != NULL &&
10048 		    sata_device->satadev_type == prev_device_type)
10049 			sdinfo->satadrv_settings = prev_device_settings;
10050 
10051 		mutex_exit(&cportinfo->cport_mutex);
10052 		rval_init = SATA_SUCCESS;
10053 		/* Set initial device features, if necessary */
10054 		if (init_device == B_TRUE) {
10055 			rval_init = sata_initialize_device(sata_hba_inst,
10056 			    sdinfo);
10057 		}
10058 		if (rval_init == SATA_SUCCESS)
10059 			return (rval_init);
10060 		/* else we will retry if retry was asked for */
10061 
10062 	} else {
10063 		/*
10064 		 * If there was some device info before we probe the device,
10065 		 * restore previous device setting, so we can retry from scratch
10066 		 * later. Providing, of course, that device has not disapear
10067 		 * during probing process.
10068 		 */
10069 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10070 			if (osdinfo != NULL) {
10071 				cportinfo->cport_dev_type = prev_device_type;
10072 				sdinfo->satadrv_type = prev_device_type;
10073 				sdinfo->satadrv_state = prev_device_state;
10074 			}
10075 		} else {
10076 			/* device is gone */
10077 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10078 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10079 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10080 			mutex_exit(&cportinfo->cport_mutex);
10081 			return (SATA_SUCCESS);
10082 		}
10083 		mutex_exit(&cportinfo->cport_mutex);
10084 	}
10085 
10086 	if (retry) {
10087 		clock_t cur_time = ddi_get_lbolt();
10088 		/*
10089 		 * A device was not successfully identified or initialized.
10090 		 * Track retry time for device identification.
10091 		 */
10092 		if ((cur_time - start_time) <
10093 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10094 			/* sleep for a while */
10095 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10096 			goto retry_probe;
10097 		}
10098 		/* else no more retries */
10099 		mutex_enter(&cportinfo->cport_mutex);
10100 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10101 			if (rval_init == SATA_RETRY) {
10102 				/*
10103 				 * Setting drive features have failed, but
10104 				 * because the drive is still accessible,
10105 				 * keep it and emit a warning message.
10106 				 */
10107 				sata_log(sata_hba_inst, CE_WARN,
10108 				    "SATA device at port %d - desired "
10109 				    "drive features could not be set. "
10110 				    "Device may not operate as expected.",
10111 				    cportinfo->cport_addr.cport);
10112 			} else {
10113 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10114 				    satadrv_state = SATA_DSTATE_FAILED;
10115 			}
10116 		}
10117 		mutex_exit(&cportinfo->cport_mutex);
10118 	}
10119 	return (SATA_SUCCESS);
10120 }
10121 
10122 /*
10123  * Reprobe a controller port that connected to a port multiplier.
10124  *
10125  * NOTE: No Mutex should be hold.
10126  */
10127 static int
10128 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10129     int flag)
10130 {
10131 	_NOTE(ARGUNUSED(flag))
10132 	sata_cport_info_t *cportinfo;
10133 	sata_pmult_info_t *pmultinfo;
10134 	uint8_t cport = sata_device->satadev_addr.cport;
10135 	int rval_probe;
10136 
10137 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10138 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10139 
10140 	/* probe port */
10141 	mutex_enter(&cportinfo->cport_mutex);
10142 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10143 	cportinfo->cport_state |= SATA_STATE_PROBING;
10144 	mutex_exit(&cportinfo->cport_mutex);
10145 
10146 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10147 	    (SATA_DIP(sata_hba_inst), sata_device);
10148 
10149 	mutex_enter(&cportinfo->cport_mutex);
10150 	if (rval_probe != SATA_SUCCESS) {
10151 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10152 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10153 		    "SATA port %d probing failed", cport));
10154 		sata_log(sata_hba_inst, CE_WARN,
10155 		    "SATA port multiplier detached at port %d", cport);
10156 		mutex_exit(&cportinfo->cport_mutex);
10157 		sata_free_pmult(sata_hba_inst, sata_device);
10158 		return (SATA_FAILURE);
10159 	}
10160 
10161 	/*
10162 	 * update sata port state and set device type
10163 	 */
10164 	sata_update_port_info(sata_hba_inst, sata_device);
10165 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10166 	cportinfo->cport_state |= SATA_STATE_PROBED;
10167 
10168 	/*
10169 	 * Sanity check - Port is active? Is the link active?
10170 	 * Is there any device attached?
10171 	 */
10172 	if ((cportinfo->cport_state &
10173 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10174 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10175 	    SATA_PORT_DEVLINK_UP ||
10176 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10177 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10178 		mutex_exit(&cportinfo->cport_mutex);
10179 		sata_free_pmult(sata_hba_inst, sata_device);
10180 		sata_log(sata_hba_inst, CE_WARN,
10181 		    "SATA port multiplier detached at port %d", cport);
10182 		return (SATA_SUCCESS);
10183 	}
10184 
10185 	/*
10186 	 * Device changed: PMult -> Non-PMult
10187 	 *
10188 	 * This situation is uncommon, most possibly being caused by errors
10189 	 * after which the port multiplier is not correct initialized and
10190 	 * recognized. In that case the new device will be marked as unknown
10191 	 * and will not be automatically probed in this routine. Instead
10192 	 * system administrator could manually restart it via cfgadm(1M).
10193 	 */
10194 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10195 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10196 		mutex_exit(&cportinfo->cport_mutex);
10197 		sata_free_pmult(sata_hba_inst, sata_device);
10198 		sata_log(sata_hba_inst, CE_WARN,
10199 		    "SATA port multiplier detached at port %d", cport);
10200 		return (SATA_FAILURE);
10201 	}
10202 
10203 	/*
10204 	 * Now we know it is a port multiplier. However, if this is not the
10205 	 * previously attached port multiplier - they may have different
10206 	 * pmport numbers - we need to re-allocate data structures for every
10207 	 * pmport and drive.
10208 	 *
10209 	 * Port multipliers of the same model have identical values in these
10210 	 * registers, so it is still necessary to update the information of
10211 	 * all drives attached to the previous port multiplier afterwards.
10212 	 */
10213 	if ((sata_device->satadev_gscr.gscr0 != pmultinfo->pmult_gscr.gscr0) ||
10214 	    (sata_device->satadev_gscr.gscr1 != pmultinfo->pmult_gscr.gscr1) ||
10215 	    (sata_device->satadev_gscr.gscr2 != pmultinfo->pmult_gscr.gscr2)) {
10216 
10217 		/* Device changed: PMult -> another PMult */
10218 		mutex_exit(&cportinfo->cport_mutex);
10219 		sata_free_pmult(sata_hba_inst, sata_device);
10220 		sata_alloc_pmult(sata_hba_inst, sata_device);
10221 		mutex_enter(&cportinfo->cport_mutex);
10222 
10223 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10224 		    "SATA port multiplier [changed] at port %d", cport);
10225 		sata_log(sata_hba_inst, CE_WARN,
10226 		    "SATA port multiplier detected at port %d", cport);
10227 	}
10228 
10229 	/*
10230 	 * Mark all the port multiplier port behind the port
10231 	 * multiplier behind with link events, so that the sata daemon
10232 	 * will update their status.
10233 	 */
10234 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10235 	mutex_exit(&cportinfo->cport_mutex);
10236 
10237 	return (SATA_SUCCESS);
10238 }
10239 
10240 /*
10241  * Re-probe a port multiplier port, check for a device and attach info
10242  * structures when necessary. Identify Device data is fetched, if possible.
10243  * Assumption: sata address is already validated as port multiplier port.
10244  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10245  * the presence of a device and its type.
10246  *
10247  * flag arg specifies that the function should try multiple times to identify
10248  * device type and to initialize it, or it should return immediately on failure.
10249  * SATA_DEV_IDENTIFY_RETRY - retry
10250  * SATA_DEV_IDENTIFY_NORETRY - no retry
10251  *
10252  * SATA_FAILURE is returned if one of the operations failed.
10253  *
10254  * This function cannot be called in interrupt context - it may sleep.
10255  *
10256  * NOTE: Should be only called by sata_probe_port() in case target port is a
10257  *       port multiplier port.
10258  * NOTE: No Mutex should be hold.
10259  */
10260 static int
10261 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10262     int flag)
10263 {
10264 	sata_cport_info_t *cportinfo = NULL;
10265 	sata_pmport_info_t *pmportinfo = NULL;
10266 	sata_drive_info_t *sdinfo, *osdinfo;
10267 	sata_device_t sdevice;
10268 	boolean_t init_device = B_FALSE;
10269 	int prev_device_type = SATA_DTYPE_NONE;
10270 	int prev_device_settings = 0;
10271 	int prev_device_state = 0;
10272 	clock_t start_time;
10273 	uint8_t cport = sata_device->satadev_addr.cport;
10274 	uint8_t pmport = sata_device->satadev_addr.pmport;
10275 	int rval;
10276 
10277 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10278 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10279 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10280 
10281 	if (osdinfo != NULL) {
10282 		/*
10283 		 * We are re-probing port with a previously attached device.
10284 		 * Save previous device type and settings.
10285 		 */
10286 		prev_device_type = pmportinfo->pmport_dev_type;
10287 		prev_device_settings = osdinfo->satadrv_settings;
10288 		prev_device_state = osdinfo->satadrv_state;
10289 	}
10290 
10291 	start_time = ddi_get_lbolt();
10292 
10293 	/* check parent status */
10294 	mutex_enter(&cportinfo->cport_mutex);
10295 	if ((cportinfo->cport_state &
10296 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10297 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10298 	    SATA_PORT_DEVLINK_UP) {
10299 		mutex_exit(&cportinfo->cport_mutex);
10300 		return (SATA_FAILURE);
10301 	}
10302 	mutex_exit(&cportinfo->cport_mutex);
10303 
10304 retry_probe_pmport:
10305 
10306 	/* probe port */
10307 	mutex_enter(&pmportinfo->pmport_mutex);
10308 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10309 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10310 	mutex_exit(&pmportinfo->pmport_mutex);
10311 
10312 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10313 	    (SATA_DIP(sata_hba_inst), sata_device);
10314 
10315 	/* might need retry because we cannot touch registers. */
10316 	if (rval == SATA_FAILURE) {
10317 		mutex_enter(&pmportinfo->pmport_mutex);
10318 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10319 		mutex_exit(&pmportinfo->pmport_mutex);
10320 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10321 		    "SATA port %d:%d probing failed",
10322 		    cport, pmport));
10323 		return (SATA_FAILURE);
10324 	} else if (rval == SATA_RETRY) {
10325 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10326 		    "SATA port %d:%d probing failed, retrying...",
10327 		    cport, pmport));
10328 		clock_t cur_time = ddi_get_lbolt();
10329 		/*
10330 		 * A device was not successfully identified or initialized.
10331 		 * Track retry time for device identification.
10332 		 */
10333 		if ((cur_time - start_time) <
10334 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10335 			/* sleep for a while */
10336 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10337 			goto retry_probe_pmport;
10338 		} else {
10339 			mutex_enter(&pmportinfo->pmport_mutex);
10340 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10341 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10342 				    satadrv_state = SATA_DSTATE_FAILED;
10343 			mutex_exit(&pmportinfo->pmport_mutex);
10344 			return (SATA_SUCCESS);
10345 		}
10346 	}
10347 
10348 	/*
10349 	 * Sanity check - Controller port is active? Is the link active?
10350 	 * Is it still a port multiplier?
10351 	 */
10352 	if ((cportinfo->cport_state &
10353 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10354 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10355 	    SATA_PORT_DEVLINK_UP ||
10356 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
10357 		/*
10358 		 * Port in non-usable state or no link active/no
10359 		 * device. Free info structure.
10360 		 */
10361 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10362 
10363 		sdevice.satadev_addr.cport = cport;
10364 		sdevice.satadev_addr.pmport = pmport;
10365 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
10366 		mutex_exit(&cportinfo->cport_mutex);
10367 
10368 		sata_free_pmult(sata_hba_inst, &sdevice);
10369 		return (SATA_FAILURE);
10370 	}
10371 
10372 	/* SATA_SUCCESS NOW */
10373 	/*
10374 	 * update sata port state and set device type
10375 	 */
10376 	mutex_enter(&pmportinfo->pmport_mutex);
10377 	sata_update_pmport_info(sata_hba_inst, sata_device);
10378 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10379 
10380 	/*
10381 	 * Sanity check - Port is active? Is the link active?
10382 	 * Is there any device attached?
10383 	 */
10384 	if ((pmportinfo->pmport_state &
10385 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10386 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10387 	    SATA_PORT_DEVLINK_UP) {
10388 		/*
10389 		 * Port in non-usable state or no link active/no device.
10390 		 * Free info structure if necessary (direct attached drive
10391 		 * only, for now!
10392 		 */
10393 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10394 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10395 		/* Add here differentiation for device attached or not */
10396 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10397 		mutex_exit(&pmportinfo->pmport_mutex);
10398 		if (sdinfo != NULL)
10399 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10400 		return (SATA_SUCCESS);
10401 	}
10402 
10403 	pmportinfo->pmport_state |= SATA_STATE_READY;
10404 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
10405 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10406 
10407 	/*
10408 	 * If we are re-probing the port, there may be
10409 	 * sata_drive_info structure attached
10410 	 * (or sata_pm_info, if PMult is supported).
10411 	 */
10412 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10413 		/*
10414 		 * There is no device, so remove device info structure,
10415 		 * if necessary.
10416 		 */
10417 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10418 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10419 		if (sdinfo != NULL) {
10420 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10421 			sata_log(sata_hba_inst, CE_WARN,
10422 			    "SATA device detached from port %d:%d",
10423 			    cport, pmport);
10424 		}
10425 		mutex_exit(&pmportinfo->pmport_mutex);
10426 		return (SATA_SUCCESS);
10427 	}
10428 
10429 	/* this should not be a pmult */
10430 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
10431 	if (sdinfo == NULL) {
10432 		/*
10433 		 * There is some device attached, but there is
10434 		 * no sata_drive_info structure - allocate one
10435 		 */
10436 		mutex_exit(&pmportinfo->pmport_mutex);
10437 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
10438 		    KM_SLEEP);
10439 		mutex_enter(&pmportinfo->pmport_mutex);
10440 		/*
10441 		 * Recheck, that the port state did not change when we
10442 		 * released mutex.
10443 		 */
10444 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
10445 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
10446 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
10447 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10448 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10449 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10450 		} else {
10451 			/*
10452 			 * Port is not in ready state, we
10453 			 * cannot attach a device.
10454 			 */
10455 			mutex_exit(&pmportinfo->pmport_mutex);
10456 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10457 			return (SATA_SUCCESS);
10458 		}
10459 		/*
10460 		 * Since we are adding device, presumably new one,
10461 		 * indicate that it  should be initalized,
10462 		 * as well as some internal framework states).
10463 		 */
10464 		init_device = B_TRUE;
10465 	}
10466 
10467 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10468 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10469 
10470 	mutex_exit(&pmportinfo->pmport_mutex);
10471 	/*
10472 	 * Figure out what kind of device we are really
10473 	 * dealing with.
10474 	 */
10475 	rval = sata_probe_device(sata_hba_inst, sata_device);
10476 
10477 	mutex_enter(&pmportinfo->pmport_mutex);
10478 	if (rval == SATA_SUCCESS) {
10479 		/*
10480 		 * If we are dealing with the same type of a device as before,
10481 		 * restore its settings flags.
10482 		 */
10483 		if (osdinfo != NULL &&
10484 		    sata_device->satadev_type == prev_device_type)
10485 			sdinfo->satadrv_settings = prev_device_settings;
10486 
10487 		mutex_exit(&pmportinfo->pmport_mutex);
10488 		/* Set initial device features, if necessary */
10489 		if (init_device == B_TRUE) {
10490 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
10491 		}
10492 		if (rval == SATA_SUCCESS)
10493 			return (rval);
10494 	} else {
10495 		/*
10496 		 * If there was some device info before we probe the device,
10497 		 * restore previous device setting, so we can retry from scratch
10498 		 * later. Providing, of course, that device has not disappeared
10499 		 * during probing process.
10500 		 */
10501 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10502 			if (osdinfo != NULL) {
10503 				pmportinfo->pmport_dev_type = prev_device_type;
10504 				sdinfo->satadrv_type = prev_device_type;
10505 				sdinfo->satadrv_state = prev_device_state;
10506 			}
10507 		} else {
10508 			/* device is gone */
10509 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10510 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10511 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10512 			mutex_exit(&pmportinfo->pmport_mutex);
10513 			return (SATA_SUCCESS);
10514 		}
10515 		mutex_exit(&pmportinfo->pmport_mutex);
10516 	}
10517 
10518 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10519 		clock_t cur_time = ddi_get_lbolt();
10520 		/*
10521 		 * A device was not successfully identified or initialized.
10522 		 * Track retry time for device identification.
10523 		 */
10524 		if ((cur_time - start_time) <
10525 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10526 			/* sleep for a while */
10527 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10528 			goto retry_probe_pmport;
10529 		} else {
10530 			mutex_enter(&pmportinfo->pmport_mutex);
10531 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10532 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10533 				    satadrv_state = SATA_DSTATE_FAILED;
10534 			mutex_exit(&pmportinfo->pmport_mutex);
10535 		}
10536 	}
10537 	return (SATA_SUCCESS);
10538 }
10539 
10540 /*
10541  * Allocated related structure for a port multiplier and its device ports
10542  *
10543  * Port multiplier should be ready and probed, and related information like
10544  * the number of the device ports should be store in sata_device_t.
10545  *
10546  * NOTE: No Mutex should be hold.
10547  */
10548 static void
10549 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
10550 {
10551 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
10552 	sata_cport_info_t *cportinfo = NULL;
10553 	sata_pmult_info_t *pmultinfo = NULL;
10554 	sata_pmport_info_t *pmportinfo = NULL;
10555 	dev_t minor_number;
10556 	char name[16];
10557 	uint8_t cport = sata_device->satadev_addr.cport;
10558 	int npmport;
10559 
10560 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10561 
10562 	/* This function might be called while a port-mult is hot-plugged. */
10563 	mutex_enter(&cportinfo->cport_mutex);
10564 
10565 	/* dev_type's not updated when get called from sata_reprobe_port() */
10566 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
10567 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
10568 		/* Create a pmult_info structure */
10569 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
10570 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
10571 	}
10572 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10573 
10574 	pmultinfo->pmult_addr = sata_device->satadev_addr;
10575 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
10576 	pmultinfo->pmult_state = SATA_STATE_PROBING;
10577 	pmultinfo->pmult_gscr = sata_device->satadev_gscr;
10578 	pmultinfo->pmult_num_dev_ports = sata_device->satadev_add_info;
10579 
10580 	/* Initialize pmport_info structure */
10581 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
10582 	    npmport++) {
10583 
10584 		/* if everything is allocated, skip */
10585 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
10586 			continue;
10587 
10588 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
10589 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
10590 		mutex_exit(&cportinfo->cport_mutex);
10591 
10592 		mutex_enter(&pmportinfo->pmport_mutex);
10593 		pmportinfo->pmport_addr.cport = cport;
10594 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
10595 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
10596 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10597 		mutex_exit(&pmportinfo->pmport_mutex);
10598 
10599 		mutex_enter(&cportinfo->cport_mutex);
10600 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
10601 
10602 		/* Create an attachment point */
10603 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
10604 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
10605 		(void) sprintf(name, "%d.%d", cport, npmport);
10606 
10607 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
10608 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
10609 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
10610 			    "cannot create SATA attachment point for "
10611 			    "port %d:%d", cport, npmport);
10612 		}
10613 	}
10614 
10615 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
10616 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
10617 
10618 	mutex_exit(&cportinfo->cport_mutex);
10619 }
10620 
10621 /*
10622  * Free data structures when a port multiplier is removed.
10623  *
10624  * NOTE: No Mutex should be hold.
10625  */
10626 static void
10627 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
10628 {
10629 	sata_cport_info_t *cportinfo;
10630 	sata_pmult_info_t *pmultinfo;
10631 	sata_pmport_info_t *pmportinfo;
10632 	sata_device_t pmport_device;
10633 	sata_drive_info_t *sdinfo;
10634 	dev_info_t *tdip;
10635 	char name[16];
10636 	uint8_t cport = sata_device->satadev_addr.cport;
10637 	int npmport;
10638 
10639 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10640 
10641 	/* This function might be called while port-mult is hot plugged. */
10642 	mutex_enter(&cportinfo->cport_mutex);
10643 
10644 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10645 	ASSERT(pmultinfo != NULL);
10646 
10647 	/* Free pmport_info structure */
10648 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
10649 	    npmport++) {
10650 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
10651 		if (pmportinfo == NULL)
10652 			continue;
10653 		mutex_exit(&cportinfo->cport_mutex);
10654 
10655 		mutex_enter(&pmportinfo->pmport_mutex);
10656 		sdinfo = pmportinfo->pmport_sata_drive;
10657 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10658 		mutex_exit(&pmportinfo->pmport_mutex);
10659 
10660 		/* Remove attachment point. */
10661 		name[0] = '\0';
10662 		(void) sprintf(name, "%d.%d", cport, npmport);
10663 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
10664 		sata_log(sata_hba_inst, CE_NOTE,
10665 		    "Remove attachment point of port %d:%d",
10666 		    cport, npmport);
10667 
10668 		/*
10669 		 * Rumove target node
10670 		 */
10671 		bzero(&pmport_device, sizeof (sata_device_t));
10672 		pmport_device.satadev_rev = SATA_DEVICE_REV;
10673 		pmport_device.satadev_addr.cport = cport;
10674 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
10675 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
10676 
10677 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10678 		    &(pmport_device.satadev_addr));
10679 		if (tdip != NULL && ndi_devi_offline(tdip,
10680 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10681 			/*
10682 			 * Problem :
10683 			 * The target node remained attached.
10684 			 * This happens when the device file was open
10685 			 * or a node was waiting for resources.
10686 			 * Cannot do anything about it.
10687 			 */
10688 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10689 			    "sata_free_pmult: could not unconfigure device "
10690 			    "before disconnecting the SATA port %d:%d",
10691 			    cport, npmport));
10692 
10693 			/*
10694 			 * Set DEVICE REMOVED state in the target
10695 			 * node. It will prevent access to the device
10696 			 * even when a new device is attached, until
10697 			 * the old target node is released, removed and
10698 			 * recreated for a new  device.
10699 			 */
10700 			sata_set_device_removed(tdip);
10701 
10702 			/*
10703 			 * Instruct event daemon to try the target
10704 			 * node cleanup later.
10705 			 */
10706 			sata_set_target_node_cleanup(
10707 			    sata_hba_inst, &(pmport_device.satadev_addr));
10708 
10709 		}
10710 		mutex_enter(&cportinfo->cport_mutex);
10711 
10712 		/*
10713 		 * Add here differentiation for device attached or not
10714 		 */
10715 		if (sdinfo != NULL)  {
10716 			sata_log(sata_hba_inst, CE_WARN,
10717 			    "SATA device detached from port %d:%d",
10718 			    cport, npmport);
10719 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10720 		}
10721 
10722 		mutex_destroy(&pmportinfo->pmport_mutex);
10723 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
10724 	}
10725 
10726 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
10727 
10728 	cportinfo->cport_devp.cport_sata_pmult = NULL;
10729 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10730 
10731 	sata_log(sata_hba_inst, CE_WARN,
10732 	    "SATA port multiplier detached at port %d", cport);
10733 
10734 	mutex_exit(&cportinfo->cport_mutex);
10735 }
10736 
10737 /*
10738  * Initialize device
10739  * Specified device is initialized to a default state.
10740  *
10741  * Returns SATA_SUCCESS if all device features are set successfully,
10742  * SATA_RETRY if device is accessible but device features were not set
10743  * successfully, and SATA_FAILURE otherwise.
10744  */
10745 static int
10746 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
10747     sata_drive_info_t *sdinfo)
10748 {
10749 	int rval;
10750 
10751 	sata_save_drive_settings(sdinfo);
10752 
10753 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
10754 
10755 	sata_init_write_cache_mode(sdinfo);
10756 
10757 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
10758 
10759 	/* Determine current data transfer mode */
10760 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
10761 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
10762 	} else if ((sdinfo->satadrv_id.ai_validinfo &
10763 	    SATA_VALIDINFO_88) != 0 &&
10764 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
10765 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
10766 	} else if ((sdinfo->satadrv_id.ai_dworddma &
10767 	    SATA_MDMA_SEL_MASK) != 0) {
10768 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
10769 	} else
10770 		/* DMA supported, not no DMA transfer mode is selected !? */
10771 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
10772 
10773 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
10774 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
10775 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
10776 
10777 	return (rval);
10778 }
10779 
10780 
10781 /*
10782  * Initialize write cache mode.
10783  *
10784  * The default write cache setting for SATA HDD is provided by sata_write_cache
10785  * static variable. ATAPI CD/DVDs devices have write cache default is
10786  * determined by sata_atapicdvd_write_cache static variable.
10787  * ATAPI tape devices have write cache default is determined by
10788  * sata_atapitape_write_cache static variable.
10789  * ATAPI disk devices have write cache default is determined by
10790  * sata_atapidisk_write_cache static variable.
10791  * 1 - enable
10792  * 0 - disable
10793  * any other value - current drive setting
10794  *
10795  * Although there is not reason to disable write cache on CD/DVD devices,
10796  * tape devices and ATAPI disk devices, the default setting control is provided
10797  * for the maximun flexibility.
10798  *
10799  * In the future, it may be overridden by the
10800  * disk-write-cache-enable property setting, if it is defined.
10801  * Returns SATA_SUCCESS if all device features are set successfully,
10802  * SATA_FAILURE otherwise.
10803  */
10804 static void
10805 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
10806 {
10807 	switch (sdinfo->satadrv_type) {
10808 	case SATA_DTYPE_ATADISK:
10809 		if (sata_write_cache == 1)
10810 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
10811 		else if (sata_write_cache == 0)
10812 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
10813 		/*
10814 		 * When sata_write_cache value is not 0 or 1,
10815 		 * a current setting of the drive's write cache is used.
10816 		 */
10817 		break;
10818 	case SATA_DTYPE_ATAPICD:
10819 		if (sata_atapicdvd_write_cache == 1)
10820 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
10821 		else if (sata_atapicdvd_write_cache == 0)
10822 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
10823 		/*
10824 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
10825 		 * a current setting of the drive's write cache is used.
10826 		 */
10827 		break;
10828 	case SATA_DTYPE_ATAPITAPE:
10829 		if (sata_atapitape_write_cache == 1)
10830 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
10831 		else if (sata_atapitape_write_cache == 0)
10832 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
10833 		/*
10834 		 * When sata_atapitape_write_cache value is not 0 or 1,
10835 		 * a current setting of the drive's write cache is used.
10836 		 */
10837 		break;
10838 	case SATA_DTYPE_ATAPIDISK:
10839 		if (sata_atapidisk_write_cache == 1)
10840 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
10841 		else if (sata_atapidisk_write_cache == 0)
10842 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
10843 		/*
10844 		 * When sata_atapidisk_write_cache value is not 0 or 1,
10845 		 * a current setting of the drive's write cache is used.
10846 		 */
10847 		break;
10848 	}
10849 }
10850 
10851 
10852 /*
10853  * Validate sata address.
10854  * Specified cport, pmport and qualifier has to match
10855  * passed sata_scsi configuration info.
10856  * The presence of an attached device is not verified.
10857  *
10858  * Returns 0 when address is valid, -1 otherwise.
10859  */
10860 static int
10861 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
10862 	int pmport, int qual)
10863 {
10864 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
10865 		goto invalid_address;
10866 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
10867 		goto invalid_address;
10868 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
10869 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
10870 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
10871 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
10872 		goto invalid_address;
10873 
10874 	return (0);
10875 
10876 invalid_address:
10877 	return (-1);
10878 
10879 }
10880 
10881 /*
10882  * Validate scsi address
10883  * SCSI target address is translated into SATA cport/pmport and compared
10884  * with a controller port/device configuration. LUN has to be 0.
10885  * Returns 0 if a scsi target refers to an attached device,
10886  * returns 1 if address is valid but device is not attached,
10887  * returns -1 if bad address or device is of an unsupported type.
10888  * Upon return sata_device argument is set.
10889  *
10890  * Port multiplier is supported now.
10891  */
10892 static int
10893 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
10894 	struct scsi_address *ap, sata_device_t *sata_device)
10895 {
10896 	int cport, pmport, qual, rval;
10897 
10898 	rval = -1;	/* Invalid address */
10899 	if (ap->a_lun != 0)
10900 		goto out;
10901 
10902 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
10903 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
10904 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
10905 
10906 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
10907 		goto out;
10908 
10909 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
10910 	    0) {
10911 
10912 		sata_cport_info_t *cportinfo;
10913 		sata_pmult_info_t *pmultinfo;
10914 		sata_drive_info_t *sdinfo = NULL;
10915 
10916 		rval = 1;	/* Valid sata address */
10917 
10918 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10919 		if (qual == SATA_ADDR_DCPORT) {
10920 			if (cportinfo == NULL ||
10921 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
10922 				goto out;
10923 
10924 			if ((cportinfo->cport_dev_type &
10925 			    SATA_VALID_DEV_TYPE) == 0) {
10926 				rval = -1;
10927 				goto out;
10928 			}
10929 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10930 
10931 		} else if (qual == SATA_ADDR_DPMPORT) {
10932 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10933 			if (pmultinfo == NULL) {
10934 				rval = -1;
10935 				goto out;
10936 			}
10937 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
10938 			    NULL ||
10939 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
10940 			    pmport) == SATA_DTYPE_NONE)
10941 				goto out;
10942 
10943 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
10944 			    pmport);
10945 		} else {
10946 			rval = -1;
10947 			goto out;
10948 		}
10949 		if ((sdinfo == NULL) ||
10950 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
10951 			goto out;
10952 
10953 		sata_device->satadev_type = sdinfo->satadrv_type;
10954 		sata_device->satadev_addr.qual = qual;
10955 		sata_device->satadev_addr.cport = cport;
10956 		sata_device->satadev_addr.pmport = pmport;
10957 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
10958 		return (0);
10959 	}
10960 out:
10961 	if (rval == 1) {
10962 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
10963 		    "sata_validate_scsi_address: no valid target %x lun %x",
10964 		    ap->a_target, ap->a_lun);
10965 	}
10966 	return (rval);
10967 }
10968 
10969 /*
10970  * Find dip corresponding to passed device number
10971  *
10972  * Returns NULL if invalid device number is passed or device cannot be found,
10973  * Returns dip is device is found.
10974  */
10975 static dev_info_t *
10976 sata_devt_to_devinfo(dev_t dev)
10977 {
10978 	dev_info_t *dip;
10979 #ifndef __lock_lint
10980 	struct devnames *dnp;
10981 	major_t major = getmajor(dev);
10982 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
10983 
10984 	if (major >= devcnt)
10985 		return (NULL);
10986 
10987 	dnp = &devnamesp[major];
10988 	LOCK_DEV_OPS(&(dnp->dn_lock));
10989 	dip = dnp->dn_head;
10990 	while (dip && (ddi_get_instance(dip) != instance)) {
10991 		dip = ddi_get_next(dip);
10992 	}
10993 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
10994 #endif
10995 
10996 	return (dip);
10997 }
10998 
10999 
11000 /*
11001  * Probe device.
11002  * This function issues Identify Device command and initializes local
11003  * sata_drive_info structure if the device can be identified.
11004  * The device type is determined by examining Identify Device
11005  * command response.
11006  * If the sata_hba_inst has linked drive info structure for this
11007  * device address, the Identify Device data is stored into sata_drive_info
11008  * structure linked to the port info structure.
11009  *
11010  * sata_device has to refer to the valid sata port(s) for HBA described
11011  * by sata_hba_inst structure.
11012  *
11013  * Returns:
11014  *	SATA_SUCCESS if device type was successfully probed and port-linked
11015  *		drive info structure was updated;
11016  * 	SATA_FAILURE if there is no device, or device was not probed
11017  *		successully;
11018  *	SATA_RETRY if device probe can be retried later.
11019  * If a device cannot be identified, sata_device's dev_state and dev_type
11020  * fields are set to unknown.
11021  * There are no retries in this function. Any retries should be managed by
11022  * the caller.
11023  */
11024 
11025 
11026 static int
11027 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11028 {
11029 	sata_pmport_info_t *pmportinfo;
11030 	sata_drive_info_t *sdinfo;
11031 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11032 	int rval;
11033 
11034 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11035 	    sata_device->satadev_addr.cport) &
11036 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11037 
11038 	sata_device->satadev_type = SATA_DTYPE_NONE;
11039 
11040 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11041 	    sata_device->satadev_addr.cport)));
11042 
11043 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11044 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11045 		    sata_device->satadev_addr.cport,
11046 		    sata_device->satadev_addr.pmport);
11047 		ASSERT(pmportinfo != NULL);
11048 	}
11049 
11050 	/* Get pointer to port-linked sata device info structure */
11051 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11052 	if (sdinfo != NULL) {
11053 		sdinfo->satadrv_state &=
11054 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11055 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11056 	} else {
11057 		/* No device to probe */
11058 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11059 		    sata_device->satadev_addr.cport)));
11060 		sata_device->satadev_type = SATA_DTYPE_NONE;
11061 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11062 		return (SATA_FAILURE);
11063 	}
11064 	/*
11065 	 * Need to issue both types of identify device command and
11066 	 * determine device type by examining retreived data/status.
11067 	 * First, ATA Identify Device.
11068 	 */
11069 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11070 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11071 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11072 	    sata_device->satadev_addr.cport)));
11073 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11074 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11075 	if (rval == SATA_RETRY) {
11076 		/* We may try to check for ATAPI device */
11077 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11078 			/*
11079 			 * HBA supports ATAPI - try to issue Identify Packet
11080 			 * Device command.
11081 			 */
11082 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11083 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11084 		}
11085 	}
11086 	if (rval == SATA_SUCCESS) {
11087 		/*
11088 		 * Got something responding positively to ATA Identify Device
11089 		 * or to Identify Packet Device cmd.
11090 		 * Save last used device type.
11091 		 */
11092 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11093 
11094 		/* save device info, if possible */
11095 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11096 		    sata_device->satadev_addr.cport)));
11097 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11098 		if (sdinfo == NULL) {
11099 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11100 			    sata_device->satadev_addr.cport)));
11101 			return (SATA_FAILURE);
11102 		}
11103 		/*
11104 		 * Copy drive info into the port-linked drive info structure.
11105 		 */
11106 		*sdinfo = new_sdinfo;
11107 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11108 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11109 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11110 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11111 			    sata_device->satadev_addr.cport) =
11112 			    sdinfo->satadrv_type;
11113 		else { /* SATA_ADDR_DPMPORT */
11114 			mutex_enter(&pmportinfo->pmport_mutex);
11115 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11116 			    sata_device->satadev_addr.cport,
11117 			    sata_device->satadev_addr.pmport) =
11118 			    sdinfo->satadrv_type;
11119 			mutex_exit(&pmportinfo->pmport_mutex);
11120 		}
11121 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11122 		    sata_device->satadev_addr.cport)));
11123 		return (SATA_SUCCESS);
11124 	}
11125 
11126 	/*
11127 	 * It may be SATA_RETRY or SATA_FAILURE return.
11128 	 * Looks like we cannot determine the device type at this time.
11129 	 */
11130 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11131 	    sata_device->satadev_addr.cport)));
11132 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11133 	if (sdinfo != NULL) {
11134 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11135 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11136 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11137 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11138 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11139 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11140 			    sata_device->satadev_addr.cport) =
11141 			    SATA_DTYPE_UNKNOWN;
11142 		else {
11143 			/* SATA_ADDR_DPMPORT */
11144 			mutex_enter(&pmportinfo->pmport_mutex);
11145 			if ((SATA_PMULT_INFO(sata_hba_inst,
11146 			    sata_device->satadev_addr.cport) != NULL) &&
11147 			    (SATA_PMPORT_INFO(sata_hba_inst,
11148 			    sata_device->satadev_addr.cport,
11149 			    sata_device->satadev_addr.pmport) != NULL))
11150 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11151 				    sata_device->satadev_addr.cport,
11152 				    sata_device->satadev_addr.pmport) =
11153 				    SATA_DTYPE_UNKNOWN;
11154 			mutex_exit(&pmportinfo->pmport_mutex);
11155 		}
11156 	}
11157 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11158 	    sata_device->satadev_addr.cport)));
11159 	return (rval);
11160 }
11161 
11162 /*
11163  * Get pointer to sata_drive_info structure.
11164  *
11165  * The sata_device has to contain address (cport, pmport and qualifier) for
11166  * specified sata_scsi structure.
11167  *
11168  * Returns NULL if device address is not valid for this HBA configuration.
11169  * Otherwise, returns a pointer to sata_drive_info structure.
11170  *
11171  * This function should be called with a port mutex held.
11172  */
11173 static sata_drive_info_t *
11174 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11175     sata_device_t *sata_device)
11176 {
11177 	uint8_t cport = sata_device->satadev_addr.cport;
11178 	uint8_t pmport = sata_device->satadev_addr.pmport;
11179 	uint8_t qual = sata_device->satadev_addr.qual;
11180 
11181 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11182 		return (NULL);
11183 
11184 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11185 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11186 		/* Port not probed yet */
11187 		return (NULL);
11188 
11189 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11190 		return (NULL);
11191 
11192 	if (qual == SATA_ADDR_DCPORT) {
11193 		/* Request for a device on a controller port */
11194 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11195 		    SATA_DTYPE_PMULT)
11196 			/* Port multiplier attached */
11197 			return (NULL);
11198 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11199 	}
11200 	if (qual == SATA_ADDR_DPMPORT) {
11201 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11202 		    SATA_DTYPE_PMULT)
11203 			return (NULL);
11204 
11205 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11206 			return (NULL);
11207 
11208 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11209 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11210 			/* Port multiplier port not probed yet */
11211 			return (NULL);
11212 
11213 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11214 	}
11215 
11216 	/* we should not get here */
11217 	return (NULL);
11218 }
11219 
11220 
11221 /*
11222  * sata_identify_device.
11223  * Send Identify Device command to SATA HBA driver.
11224  * If command executes successfully, update sata_drive_info structure pointed
11225  * to by sdinfo argument, including Identify Device data.
11226  * If command fails, invalidate data in sata_drive_info.
11227  *
11228  * Cannot be called from interrupt level.
11229  *
11230  * Returns:
11231  * SATA_SUCCESS if the device was identified as a supported device,
11232  * SATA_RETRY if the device was not identified but could be retried,
11233  * SATA_FAILURE if the device was not identified and identify attempt
11234  *	should not be retried.
11235  */
11236 static int
11237 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11238     sata_drive_info_t *sdinfo)
11239 {
11240 	uint16_t cfg_word;
11241 	int rval;
11242 
11243 	/* fetch device identify data */
11244 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11245 	    sdinfo)) != SATA_SUCCESS)
11246 		goto fail_unknown;
11247 
11248 	cfg_word = sdinfo->satadrv_id.ai_config;
11249 
11250 	/* Set the correct device type */
11251 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11252 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11253 	} else if (cfg_word == SATA_CFA_TYPE) {
11254 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11255 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11256 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11257 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11258 		case SATA_ATAPI_CDROM_DEV:
11259 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11260 			break;
11261 		case SATA_ATAPI_SQACC_DEV:
11262 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11263 			break;
11264 		case SATA_ATAPI_DIRACC_DEV:
11265 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11266 			break;
11267 		default:
11268 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11269 		}
11270 	} else {
11271 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11272 	}
11273 
11274 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11275 		if (sdinfo->satadrv_capacity == 0) {
11276 			/* Non-LBA disk. Too bad... */
11277 			sata_log(sata_hba_inst, CE_WARN,
11278 			    "SATA disk device at port %d does not support LBA",
11279 			    sdinfo->satadrv_addr.cport);
11280 			rval = SATA_FAILURE;
11281 			goto fail_unknown;
11282 		}
11283 	}
11284 #if 0
11285 	/* Left for historical reason */
11286 	/*
11287 	 * Some initial version of SATA spec indicated that at least
11288 	 * UDMA mode 4 has to be supported. It is not metioned in
11289 	 * SerialATA 2.6, so this restriction is removed.
11290 	 */
11291 	/* Check for Ultra DMA modes 6 through 0 being supported */
11292 	for (i = 6; i >= 0; --i) {
11293 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
11294 			break;
11295 	}
11296 
11297 	/*
11298 	 * At least UDMA 4 mode has to be supported. If mode 4 or
11299 	 * higher are not supported by the device, fail this
11300 	 * device.
11301 	 */
11302 	if (i < 4) {
11303 		/* No required Ultra DMA mode supported */
11304 		sata_log(sata_hba_inst, CE_WARN,
11305 		    "SATA disk device at port %d does not support UDMA "
11306 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
11307 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11308 		    "mode 4 or higher required, %d supported", i));
11309 		rval = SATA_FAILURE;
11310 		goto fail_unknown;
11311 	}
11312 #endif
11313 
11314 	/*
11315 	 * For Disk devices, if it doesn't support UDMA mode, we would
11316 	 * like to return failure directly.
11317 	 */
11318 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
11319 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
11320 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
11321 		sata_log(sata_hba_inst, CE_WARN,
11322 		    "SATA disk device at port %d does not support UDMA",
11323 		    sdinfo->satadrv_addr.cport);
11324 		rval = SATA_FAILURE;
11325 		goto fail_unknown;
11326 	}
11327 
11328 	return (SATA_SUCCESS);
11329 
11330 fail_unknown:
11331 	/* Invalidate sata_drive_info ? */
11332 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11333 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11334 	return (rval);
11335 }
11336 
11337 /*
11338  * Log/display device information
11339  */
11340 static void
11341 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
11342     sata_drive_info_t *sdinfo)
11343 {
11344 	int valid_version;
11345 	char msg_buf[MAXPATHLEN];
11346 	int i;
11347 
11348 	/* Show HBA path */
11349 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
11350 
11351 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
11352 
11353 	switch (sdinfo->satadrv_type) {
11354 	case SATA_DTYPE_ATADISK:
11355 		(void) sprintf(msg_buf, "SATA disk device at");
11356 		break;
11357 
11358 	case SATA_DTYPE_ATAPICD:
11359 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
11360 		break;
11361 
11362 	case SATA_DTYPE_ATAPITAPE:
11363 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
11364 		break;
11365 
11366 	case SATA_DTYPE_ATAPIDISK:
11367 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
11368 		break;
11369 
11370 	case SATA_DTYPE_UNKNOWN:
11371 		(void) sprintf(msg_buf,
11372 		    "Unsupported SATA device type (cfg 0x%x) at ",
11373 		    sdinfo->satadrv_id.ai_config);
11374 		break;
11375 	}
11376 
11377 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
11378 		cmn_err(CE_CONT, "?\t%s port %d\n",
11379 		    msg_buf, sdinfo->satadrv_addr.cport);
11380 	else
11381 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
11382 		    msg_buf, sdinfo->satadrv_addr.cport,
11383 		    sdinfo->satadrv_addr.pmport);
11384 
11385 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
11386 	    sizeof (sdinfo->satadrv_id.ai_model));
11387 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
11388 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
11389 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
11390 
11391 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
11392 	    sizeof (sdinfo->satadrv_id.ai_fw));
11393 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
11394 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
11395 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
11396 
11397 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
11398 	    sizeof (sdinfo->satadrv_id.ai_drvser));
11399 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
11400 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
11401 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11402 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11403 	} else {
11404 		/*
11405 		 * Some drives do not implement serial number and may
11406 		 * violate the spec by providing spaces rather than zeros
11407 		 * in serial number field. Scan the buffer to detect it.
11408 		 */
11409 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
11410 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
11411 				break;
11412 		}
11413 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
11414 			cmn_err(CE_CONT, "?\tserial number - none\n");
11415 		} else {
11416 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11417 		}
11418 	}
11419 
11420 #ifdef SATA_DEBUG
11421 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
11422 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
11423 		int i;
11424 		for (i = 14; i >= 2; i--) {
11425 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
11426 				valid_version = i;
11427 				break;
11428 			}
11429 		}
11430 		cmn_err(CE_CONT,
11431 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
11432 		    valid_version,
11433 		    sdinfo->satadrv_id.ai_majorversion,
11434 		    sdinfo->satadrv_id.ai_minorversion);
11435 	}
11436 #endif
11437 	/* Log some info */
11438 	cmn_err(CE_CONT, "?\tsupported features:\n");
11439 	msg_buf[0] = '\0';
11440 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11441 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
11442 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
11443 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
11444 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
11445 	}
11446 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
11447 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
11448 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
11449 		(void) strlcat(msg_buf, ", Native Command Queueing",
11450 		    MAXPATHLEN);
11451 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
11452 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
11453 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
11454 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
11455 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
11456 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
11457 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
11458 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
11459 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
11460 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
11461 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
11462 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
11463 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
11464 	if (sdinfo->satadrv_features_support &
11465 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
11466 		msg_buf[0] = '\0';
11467 		(void) snprintf(msg_buf, MAXPATHLEN,
11468 		    "Supported queue depth %d",
11469 		    sdinfo->satadrv_queue_depth);
11470 		if (!(sata_func_enable &
11471 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
11472 			(void) strlcat(msg_buf,
11473 			    " - queueing disabled globally", MAXPATHLEN);
11474 		else if (sdinfo->satadrv_queue_depth >
11475 		    sdinfo->satadrv_max_queue_depth) {
11476 			(void) snprintf(&msg_buf[strlen(msg_buf)],
11477 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
11478 			    (int)sdinfo->satadrv_max_queue_depth);
11479 		}
11480 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
11481 	}
11482 
11483 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11484 #ifdef __i386
11485 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
11486 		    sdinfo->satadrv_capacity);
11487 #else
11488 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
11489 		    sdinfo->satadrv_capacity);
11490 #endif
11491 		cmn_err(CE_CONT, "?%s", msg_buf);
11492 	}
11493 }
11494 
11495 /*
11496  * Log/display port multiplier information
11497  */
11498 static void
11499 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
11500     sata_device_t *sata_device)
11501 {
11502 	_NOTE(ARGUNUSED(sata_hba_inst))
11503 
11504 	char msg_buf[MAXPATHLEN];
11505 	uint32_t gscr0, gscr1, gscr2, gscr64;
11506 
11507 	gscr0 = sata_device->satadev_gscr.gscr0;
11508 	gscr1 = sata_device->satadev_gscr.gscr1;
11509 	gscr2 = sata_device->satadev_gscr.gscr2;
11510 	gscr64 = sata_device->satadev_gscr.gscr64;
11511 
11512 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
11513 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
11514 
11515 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
11516 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
11517 	cmn_err(CE_CONT, "?%s", msg_buf);
11518 
11519 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
11520 	if (gscr1 & (1 << 3))
11521 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
11522 	else if (gscr1 & (1 << 2))
11523 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
11524 	else if (gscr1 & (1 << 1))
11525 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
11526 	else
11527 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
11528 	cmn_err(CE_CONT, "?%s", msg_buf);
11529 
11530 	(void) strcpy(msg_buf, "\tSupport ");
11531 	if (gscr64 & (1 << 3))
11532 		(void) strlcat(msg_buf, "Asy-Notif, ",
11533 		    MAXPATHLEN);
11534 	if (gscr64 & (1 << 2))
11535 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
11536 	if (gscr64 & (1 << 1))
11537 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
11538 	if (gscr64 & (1 << 0))
11539 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
11540 	if ((gscr64 & 0xf) == 0)
11541 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
11542 	cmn_err(CE_CONT, "?%s", msg_buf);
11543 
11544 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
11545 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
11546 	cmn_err(CE_CONT, "?%s", msg_buf);
11547 }
11548 
11549 /*
11550  * sata_save_drive_settings extracts current setting of the device and stores
11551  * it for future reference, in case the device setup would need to be restored
11552  * after the device reset.
11553  *
11554  * For all devices read ahead and write cache settings are saved, if the
11555  * device supports these features at all.
11556  * For ATAPI devices the Removable Media Status Notification setting is saved.
11557  */
11558 static void
11559 sata_save_drive_settings(sata_drive_info_t *sdinfo)
11560 {
11561 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
11562 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
11563 
11564 		/* Current setting of Read Ahead (and Read Cache) */
11565 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
11566 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11567 		else
11568 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
11569 
11570 		/* Current setting of Write Cache */
11571 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
11572 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11573 		else
11574 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11575 	}
11576 
11577 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
11578 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
11579 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
11580 		else
11581 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
11582 	}
11583 }
11584 
11585 
11586 /*
11587  * sata_check_capacity function determines a disk capacity
11588  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
11589  *
11590  * NOTE: CHS mode is not supported! If a device does not support LBA,
11591  * this function is not called.
11592  *
11593  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
11594  */
11595 static uint64_t
11596 sata_check_capacity(sata_drive_info_t *sdinfo)
11597 {
11598 	uint64_t capacity = 0;
11599 	int i;
11600 
11601 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
11602 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
11603 		/* Capacity valid only for LBA-addressable disk devices */
11604 		return (0);
11605 
11606 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
11607 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
11608 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
11609 		/* LBA48 mode supported and enabled */
11610 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
11611 		    SATA_DEV_F_LBA28;
11612 		for (i = 3;  i >= 0;  --i) {
11613 			capacity <<= 16;
11614 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
11615 		}
11616 	} else {
11617 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
11618 		capacity <<= 16;
11619 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
11620 		if (capacity >= 0x1000000)
11621 			/* LBA28 mode */
11622 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
11623 	}
11624 	return (capacity);
11625 }
11626 
11627 
11628 /*
11629  * Allocate consistent buffer for DMA transfer
11630  *
11631  * Cannot be called from interrupt level or with mutex held - it may sleep.
11632  *
11633  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
11634  */
11635 static struct buf *
11636 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
11637 {
11638 	struct scsi_address ap;
11639 	struct buf *bp;
11640 	ddi_dma_attr_t	cur_dma_attr;
11641 
11642 	ASSERT(spx->txlt_sata_pkt != NULL);
11643 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
11644 	ap.a_target = SATA_TO_SCSI_TARGET(
11645 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
11646 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
11647 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
11648 	ap.a_lun = 0;
11649 
11650 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
11651 	    B_READ, SLEEP_FUNC, NULL);
11652 
11653 	if (bp != NULL) {
11654 		/* Allocate DMA resources for this buffer */
11655 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
11656 		/*
11657 		 * We use a local version of the dma_attr, to account
11658 		 * for a device addressing limitations.
11659 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
11660 		 * will cause dma attributes to be adjusted to a lowest
11661 		 * acceptable level.
11662 		 */
11663 		sata_adjust_dma_attr(NULL,
11664 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
11665 
11666 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
11667 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
11668 			scsi_free_consistent_buf(bp);
11669 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11670 			bp = NULL;
11671 		}
11672 	}
11673 	return (bp);
11674 }
11675 
11676 /*
11677  * Release local buffer (consistent buffer for DMA transfer) allocated
11678  * via sata_alloc_local_buffer().
11679  */
11680 static void
11681 sata_free_local_buffer(sata_pkt_txlate_t *spx)
11682 {
11683 	ASSERT(spx->txlt_sata_pkt != NULL);
11684 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
11685 
11686 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
11687 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
11688 
11689 	sata_common_free_dma_rsrcs(spx);
11690 
11691 	/* Free buffer */
11692 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
11693 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11694 }
11695 
11696 /*
11697  * Allocate sata_pkt
11698  * Pkt structure version and embedded strcutures version are initialized.
11699  * sata_pkt and sata_pkt_txlate structures are cross-linked.
11700  *
11701  * Since this may be called in interrupt context by sata_scsi_init_pkt,
11702  * callback argument determines if it can sleep or not.
11703  * Hence, it should not be called from interrupt context.
11704  *
11705  * If successful, non-NULL pointer to a sata pkt is returned.
11706  * Upon failure, NULL pointer is returned.
11707  */
11708 static sata_pkt_t *
11709 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
11710 {
11711 	sata_pkt_t *spkt;
11712 	int kmsflag;
11713 
11714 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
11715 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
11716 	if (spkt == NULL) {
11717 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11718 		    "sata_pkt_alloc: failed"));
11719 		return (NULL);
11720 	}
11721 	spkt->satapkt_rev = SATA_PKT_REV;
11722 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
11723 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
11724 	spkt->satapkt_framework_private = spx;
11725 	spx->txlt_sata_pkt = spkt;
11726 	return (spkt);
11727 }
11728 
11729 /*
11730  * Free sata pkt allocated via sata_pkt_alloc()
11731  */
11732 static void
11733 sata_pkt_free(sata_pkt_txlate_t *spx)
11734 {
11735 	ASSERT(spx->txlt_sata_pkt != NULL);
11736 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
11737 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
11738 	spx->txlt_sata_pkt = NULL;
11739 }
11740 
11741 
11742 /*
11743  * Adjust DMA attributes.
11744  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
11745  * from 8 bits to 16 bits, depending on a command being used.
11746  * Limiting max block count arbitrarily to 256 for all read/write
11747  * commands may affects performance, so check both the device and
11748  * controller capability before adjusting dma attributes.
11749  */
11750 void
11751 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
11752     ddi_dma_attr_t *adj_dma_attr)
11753 {
11754 	uint32_t count_max;
11755 
11756 	/* Copy original attributes */
11757 	*adj_dma_attr = *dma_attr;
11758 	/*
11759 	 * Things to consider: device addressing capability,
11760 	 * "excessive" controller DMA capabilities.
11761 	 * If a device is being probed/initialized, there are
11762 	 * no device info - use default limits then.
11763 	 */
11764 	if (sdinfo == NULL) {
11765 		count_max = dma_attr->dma_attr_granular * 0x100;
11766 		if (dma_attr->dma_attr_count_max > count_max)
11767 			adj_dma_attr->dma_attr_count_max = count_max;
11768 		if (dma_attr->dma_attr_maxxfer > count_max)
11769 			adj_dma_attr->dma_attr_maxxfer = count_max;
11770 		return;
11771 	}
11772 
11773 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11774 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
11775 			/*
11776 			 * 16-bit sector count may be used - we rely on
11777 			 * the assumption that only read and write cmds
11778 			 * will request more than 256 sectors worth of data
11779 			 */
11780 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
11781 		} else {
11782 			/*
11783 			 * 8-bit sector count will be used - default limits
11784 			 * for dma attributes
11785 			 */
11786 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
11787 		}
11788 		/*
11789 		 * Adjust controler dma attributes, if necessary
11790 		 */
11791 		if (dma_attr->dma_attr_count_max > count_max)
11792 			adj_dma_attr->dma_attr_count_max = count_max;
11793 		if (dma_attr->dma_attr_maxxfer > count_max)
11794 			adj_dma_attr->dma_attr_maxxfer = count_max;
11795 	}
11796 }
11797 
11798 
11799 /*
11800  * Allocate DMA resources for the buffer
11801  * This function handles initial DMA resource allocation as well as
11802  * DMA window shift and may be called repeatedly for the same DMA window
11803  * until all DMA cookies in the DMA window are processed.
11804  * To guarantee that there is always a coherent set of cookies to process
11805  * by SATA HBA driver (observing alignment, device granularity, etc.),
11806  * the number of slots for DMA cookies is equal to lesser of  a number of
11807  * cookies in a DMA window and a max number of scatter/gather entries.
11808  *
11809  * Returns DDI_SUCCESS upon successful operation.
11810  * Return failure code of a failing command or DDI_FAILURE when
11811  * internal cleanup failed.
11812  */
11813 static int
11814 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
11815     int (*callback)(caddr_t), caddr_t arg,
11816     ddi_dma_attr_t *cur_dma_attr)
11817 {
11818 	int	rval;
11819 	off_t	offset;
11820 	size_t	size;
11821 	int	max_sg_len, req_len, i;
11822 	uint_t	dma_flags;
11823 	struct buf	*bp;
11824 	uint64_t	cur_txfer_len;
11825 
11826 
11827 	ASSERT(spx->txlt_sata_pkt != NULL);
11828 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
11829 	ASSERT(bp != NULL);
11830 
11831 
11832 	if (spx->txlt_buf_dma_handle == NULL) {
11833 		/*
11834 		 * No DMA resources allocated so far - this is a first call
11835 		 * for this sata pkt.
11836 		 */
11837 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
11838 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
11839 
11840 		if (rval != DDI_SUCCESS) {
11841 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11842 			    "sata_dma_buf_setup: no buf DMA resources %x",
11843 			    rval));
11844 			return (rval);
11845 		}
11846 
11847 		if (bp->b_flags & B_READ)
11848 			dma_flags = DDI_DMA_READ;
11849 		else
11850 			dma_flags = DDI_DMA_WRITE;
11851 
11852 		if (flags & PKT_CONSISTENT)
11853 			dma_flags |= DDI_DMA_CONSISTENT;
11854 
11855 		if (flags & PKT_DMA_PARTIAL)
11856 			dma_flags |= DDI_DMA_PARTIAL;
11857 
11858 		/*
11859 		 * Check buffer alignment and size against dma attributes
11860 		 * Consider dma_attr_align only. There may be requests
11861 		 * with the size lower than device granularity, but they
11862 		 * will not read/write from/to the device, so no adjustment
11863 		 * is necessary. The dma_attr_minxfer theoretically should
11864 		 * be considered, but no HBA driver is checking it.
11865 		 */
11866 		if (IS_P2ALIGNED(bp->b_un.b_addr,
11867 		    cur_dma_attr->dma_attr_align)) {
11868 			rval = ddi_dma_buf_bind_handle(
11869 			    spx->txlt_buf_dma_handle,
11870 			    bp, dma_flags, callback, arg,
11871 			    &spx->txlt_dma_cookie,
11872 			    &spx->txlt_curwin_num_dma_cookies);
11873 		} else { /* Buffer is not aligned */
11874 
11875 			int	(*ddicallback)(caddr_t);
11876 			size_t	bufsz;
11877 
11878 			/* Check id sleeping is allowed */
11879 			ddicallback = (callback == NULL_FUNC) ?
11880 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
11881 
11882 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
11883 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
11884 			    (void *)bp->b_un.b_addr, bp->b_bcount);
11885 
11886 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
11887 				/*
11888 				 * CPU will need to access data in the buffer
11889 				 * (for copying) so map it.
11890 				 */
11891 				bp_mapin(bp);
11892 
11893 			ASSERT(spx->txlt_tmp_buf == NULL);
11894 
11895 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
11896 			rval = ddi_dma_mem_alloc(
11897 			    spx->txlt_buf_dma_handle,
11898 			    bp->b_bcount,
11899 			    &sata_acc_attr,
11900 			    DDI_DMA_STREAMING,
11901 			    ddicallback, NULL,
11902 			    &spx->txlt_tmp_buf,
11903 			    &bufsz,
11904 			    &spx->txlt_tmp_buf_handle);
11905 
11906 			if (rval != DDI_SUCCESS) {
11907 				/* DMA mapping failed */
11908 				(void) ddi_dma_free_handle(
11909 				    &spx->txlt_buf_dma_handle);
11910 				spx->txlt_buf_dma_handle = NULL;
11911 #ifdef SATA_DEBUG
11912 				mbuffail_count++;
11913 #endif
11914 				SATADBG1(SATA_DBG_DMA_SETUP,
11915 				    spx->txlt_sata_hba_inst,
11916 				    "sata_dma_buf_setup: "
11917 				    "buf dma mem alloc failed %x\n", rval);
11918 				return (rval);
11919 			}
11920 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
11921 			    cur_dma_attr->dma_attr_align));
11922 
11923 #ifdef SATA_DEBUG
11924 			mbuf_count++;
11925 
11926 			if (bp->b_bcount != bufsz)
11927 				/*
11928 				 * This will require special handling, because
11929 				 * DMA cookies will be based on the temporary
11930 				 * buffer size, not the original buffer
11931 				 * b_bcount, so the residue may have to
11932 				 * be counted differently.
11933 				 */
11934 				SATADBG2(SATA_DBG_DMA_SETUP,
11935 				    spx->txlt_sata_hba_inst,
11936 				    "sata_dma_buf_setup: bp size %x != "
11937 				    "bufsz %x\n", bp->b_bcount, bufsz);
11938 #endif
11939 			if (dma_flags & DDI_DMA_WRITE) {
11940 				/*
11941 				 * Write operation - copy data into
11942 				 * an aligned temporary buffer. Buffer will be
11943 				 * synced for device by ddi_dma_addr_bind_handle
11944 				 */
11945 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
11946 				    bp->b_bcount);
11947 			}
11948 
11949 			rval = ddi_dma_addr_bind_handle(
11950 			    spx->txlt_buf_dma_handle,
11951 			    NULL,
11952 			    spx->txlt_tmp_buf,
11953 			    bufsz, dma_flags, ddicallback, 0,
11954 			    &spx->txlt_dma_cookie,
11955 			    &spx->txlt_curwin_num_dma_cookies);
11956 		}
11957 
11958 		switch (rval) {
11959 		case DDI_DMA_PARTIAL_MAP:
11960 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
11961 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
11962 			/*
11963 			 * Partial DMA mapping.
11964 			 * Retrieve number of DMA windows for this request.
11965 			 */
11966 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
11967 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
11968 				if (spx->txlt_tmp_buf != NULL) {
11969 					ddi_dma_mem_free(
11970 					    &spx->txlt_tmp_buf_handle);
11971 					spx->txlt_tmp_buf = NULL;
11972 				}
11973 				(void) ddi_dma_unbind_handle(
11974 				    spx->txlt_buf_dma_handle);
11975 				(void) ddi_dma_free_handle(
11976 				    &spx->txlt_buf_dma_handle);
11977 				spx->txlt_buf_dma_handle = NULL;
11978 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11979 				    "sata_dma_buf_setup: numwin failed\n"));
11980 				return (DDI_FAILURE);
11981 			}
11982 			SATADBG2(SATA_DBG_DMA_SETUP,
11983 			    spx->txlt_sata_hba_inst,
11984 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
11985 			    spx->txlt_num_dma_win,
11986 			    spx->txlt_curwin_num_dma_cookies);
11987 			spx->txlt_cur_dma_win = 0;
11988 			break;
11989 
11990 		case DDI_DMA_MAPPED:
11991 			/* DMA fully mapped */
11992 			spx->txlt_num_dma_win = 1;
11993 			spx->txlt_cur_dma_win = 0;
11994 			SATADBG1(SATA_DBG_DMA_SETUP,
11995 			    spx->txlt_sata_hba_inst,
11996 			    "sata_dma_buf_setup: windows: 1 "
11997 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
11998 			break;
11999 
12000 		default:
12001 			/* DMA mapping failed */
12002 			if (spx->txlt_tmp_buf != NULL) {
12003 				ddi_dma_mem_free(
12004 				    &spx->txlt_tmp_buf_handle);
12005 				spx->txlt_tmp_buf = NULL;
12006 			}
12007 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12008 			spx->txlt_buf_dma_handle = NULL;
12009 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12010 			    "sata_dma_buf_setup: buf dma handle binding "
12011 			    "failed %x\n", rval));
12012 			return (rval);
12013 		}
12014 		spx->txlt_curwin_processed_dma_cookies = 0;
12015 		spx->txlt_dma_cookie_list = NULL;
12016 	} else {
12017 		/*
12018 		 * DMA setup is reused. Check if we need to process more
12019 		 * cookies in current window, or to get next window, if any.
12020 		 */
12021 
12022 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12023 		    spx->txlt_curwin_num_dma_cookies);
12024 
12025 		if (spx->txlt_curwin_processed_dma_cookies ==
12026 		    spx->txlt_curwin_num_dma_cookies) {
12027 			/*
12028 			 * All cookies from current DMA window were processed.
12029 			 * Get next DMA window.
12030 			 */
12031 			spx->txlt_cur_dma_win++;
12032 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12033 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12034 				    spx->txlt_cur_dma_win, &offset, &size,
12035 				    &spx->txlt_dma_cookie,
12036 				    &spx->txlt_curwin_num_dma_cookies);
12037 				spx->txlt_curwin_processed_dma_cookies = 0;
12038 			} else {
12039 				/* No more windows! End of request! */
12040 				/* What to do? - panic for now */
12041 				ASSERT(spx->txlt_cur_dma_win >=
12042 				    spx->txlt_num_dma_win);
12043 
12044 				spx->txlt_curwin_num_dma_cookies = 0;
12045 				spx->txlt_curwin_processed_dma_cookies = 0;
12046 				spx->txlt_sata_pkt->
12047 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12048 				return (DDI_SUCCESS);
12049 			}
12050 		}
12051 	}
12052 	/* There better be at least one DMA cookie outstanding */
12053 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12054 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12055 
12056 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12057 		/* The default cookie slot was used in previous run */
12058 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12059 		spx->txlt_dma_cookie_list = NULL;
12060 		spx->txlt_dma_cookie_list_len = 0;
12061 	}
12062 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12063 		/*
12064 		 * Processing a new DMA window - set-up dma cookies list.
12065 		 * We may reuse previously allocated cookie array if it is
12066 		 * possible.
12067 		 */
12068 		if (spx->txlt_dma_cookie_list != NULL &&
12069 		    spx->txlt_dma_cookie_list_len <
12070 		    spx->txlt_curwin_num_dma_cookies) {
12071 			/*
12072 			 * New DMA window contains more cookies than
12073 			 * the previous one. We need larger cookie list - free
12074 			 * the old one.
12075 			 */
12076 			(void) kmem_free(spx->txlt_dma_cookie_list,
12077 			    spx->txlt_dma_cookie_list_len *
12078 			    sizeof (ddi_dma_cookie_t));
12079 			spx->txlt_dma_cookie_list = NULL;
12080 			spx->txlt_dma_cookie_list_len = 0;
12081 		}
12082 		if (spx->txlt_dma_cookie_list == NULL) {
12083 			/*
12084 			 * Calculate lesser of number of cookies in this
12085 			 * DMA window and number of s/g entries.
12086 			 */
12087 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12088 			req_len = MIN(max_sg_len,
12089 			    spx->txlt_curwin_num_dma_cookies);
12090 
12091 			/* Allocate new dma cookie array if necessary */
12092 			if (req_len == 1) {
12093 				/* Only one cookie - no need for a list */
12094 				spx->txlt_dma_cookie_list =
12095 				    &spx->txlt_dma_cookie;
12096 				spx->txlt_dma_cookie_list_len = 1;
12097 			} else {
12098 				/*
12099 				 * More than one cookie - try to allocate space.
12100 				 */
12101 				spx->txlt_dma_cookie_list = kmem_zalloc(
12102 				    sizeof (ddi_dma_cookie_t) * req_len,
12103 				    callback == NULL_FUNC ? KM_NOSLEEP :
12104 				    KM_SLEEP);
12105 				if (spx->txlt_dma_cookie_list == NULL) {
12106 					SATADBG1(SATA_DBG_DMA_SETUP,
12107 					    spx->txlt_sata_hba_inst,
12108 					    "sata_dma_buf_setup: cookie list "
12109 					    "allocation failed\n", NULL);
12110 					/*
12111 					 * We could not allocate space for
12112 					 * neccessary number of dma cookies in
12113 					 * this window, so we fail this request.
12114 					 * Next invocation would try again to
12115 					 * allocate space for cookie list.
12116 					 * Note:Packet residue was not modified.
12117 					 */
12118 					return (DDI_DMA_NORESOURCES);
12119 				} else {
12120 					spx->txlt_dma_cookie_list_len = req_len;
12121 				}
12122 			}
12123 		}
12124 		/*
12125 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12126 		 * First cookie was already fetched.
12127 		 */
12128 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12129 		cur_txfer_len =
12130 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12131 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12132 		spx->txlt_curwin_processed_dma_cookies++;
12133 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12134 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12135 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12136 			    &spx->txlt_dma_cookie_list[i]);
12137 			cur_txfer_len +=
12138 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12139 			spx->txlt_curwin_processed_dma_cookies++;
12140 			spx->txlt_sata_pkt->
12141 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12142 		}
12143 	} else {
12144 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12145 		    "sata_dma_buf_setup: sliding within DMA window, "
12146 		    "cur cookie %d, total cookies %d\n",
12147 		    spx->txlt_curwin_processed_dma_cookies,
12148 		    spx->txlt_curwin_num_dma_cookies);
12149 
12150 		/*
12151 		 * Not all cookies from the current dma window were used because
12152 		 * of s/g limitation.
12153 		 * There is no need to re-size the list - it was set at
12154 		 * optimal size, or only default entry is used (s/g = 1).
12155 		 */
12156 		if (spx->txlt_dma_cookie_list == NULL) {
12157 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12158 			spx->txlt_dma_cookie_list_len = 1;
12159 		}
12160 		/*
12161 		 * Since we are processing remaining cookies in a DMA window,
12162 		 * there may be less of them than the number of entries in the
12163 		 * current dma cookie list.
12164 		 */
12165 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12166 		    (spx->txlt_curwin_num_dma_cookies -
12167 		    spx->txlt_curwin_processed_dma_cookies));
12168 
12169 		/* Fetch the next batch of cookies */
12170 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12171 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12172 			    &spx->txlt_dma_cookie_list[i]);
12173 			cur_txfer_len +=
12174 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12175 			spx->txlt_sata_pkt->
12176 			    satapkt_cmd.satacmd_num_dma_cookies++;
12177 			spx->txlt_curwin_processed_dma_cookies++;
12178 		}
12179 	}
12180 
12181 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12182 
12183 	/* Point sata_cmd to the cookie list */
12184 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12185 	    &spx->txlt_dma_cookie_list[0];
12186 
12187 	/* Remember number of DMA cookies passed in sata packet */
12188 	spx->txlt_num_dma_cookies =
12189 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12190 
12191 	ASSERT(cur_txfer_len != 0);
12192 	if (cur_txfer_len <= bp->b_bcount)
12193 		spx->txlt_total_residue -= cur_txfer_len;
12194 	else {
12195 		/*
12196 		 * Temporary DMA buffer has been padded by
12197 		 * ddi_dma_mem_alloc()!
12198 		 * This requires special handling, because DMA cookies are
12199 		 * based on the temporary buffer size, not the b_bcount,
12200 		 * and we have extra bytes to transfer - but the packet
12201 		 * residue has to stay correct because we will copy only
12202 		 * the requested number of bytes.
12203 		 */
12204 		spx->txlt_total_residue -= bp->b_bcount;
12205 	}
12206 
12207 	return (DDI_SUCCESS);
12208 }
12209 
12210 /*
12211  * Common routine for releasing DMA resources
12212  */
12213 static void
12214 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12215 {
12216 	if (spx->txlt_buf_dma_handle != NULL) {
12217 		if (spx->txlt_tmp_buf != NULL)  {
12218 			/*
12219 			 * Intermediate DMA buffer was allocated.
12220 			 * Free allocated buffer and associated access handle.
12221 			 */
12222 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12223 			spx->txlt_tmp_buf = NULL;
12224 		}
12225 		/*
12226 		 * Free DMA resources - cookies and handles
12227 		 */
12228 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12229 		if (spx->txlt_dma_cookie_list != NULL) {
12230 			if (spx->txlt_dma_cookie_list !=
12231 			    &spx->txlt_dma_cookie) {
12232 				(void) kmem_free(spx->txlt_dma_cookie_list,
12233 				    spx->txlt_dma_cookie_list_len *
12234 				    sizeof (ddi_dma_cookie_t));
12235 				spx->txlt_dma_cookie_list = NULL;
12236 			}
12237 		}
12238 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12239 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12240 		spx->txlt_buf_dma_handle = NULL;
12241 	}
12242 }
12243 
12244 /*
12245  * Free DMA resources
12246  * Used by the HBA driver to release DMA resources that it does not use.
12247  *
12248  * Returns Void
12249  */
12250 void
12251 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12252 {
12253 	sata_pkt_txlate_t *spx;
12254 
12255 	if (sata_pkt == NULL)
12256 		return;
12257 
12258 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12259 
12260 	sata_common_free_dma_rsrcs(spx);
12261 }
12262 /*
12263  * Fetch Device Identify data.
12264  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12265  * command to a device and get the device identify data.
12266  * The device_info structure has to be set to device type (for selecting proper
12267  * device identify command).
12268  *
12269  * Returns:
12270  * SATA_SUCCESS if cmd succeeded
12271  * SATA_RETRY if cmd was rejected and could be retried,
12272  * SATA_FAILURE if cmd failed and should not be retried (port error)
12273  *
12274  * Cannot be called in an interrupt context.
12275  */
12276 
12277 static int
12278 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
12279     sata_drive_info_t *sdinfo)
12280 {
12281 	struct buf *bp;
12282 	sata_pkt_t *spkt;
12283 	sata_cmd_t *scmd;
12284 	sata_pkt_txlate_t *spx;
12285 	int rval;
12286 
12287 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12288 	spx->txlt_sata_hba_inst = sata_hba_inst;
12289 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12290 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12291 	if (spkt == NULL) {
12292 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12293 		return (SATA_RETRY); /* may retry later */
12294 	}
12295 	/* address is needed now */
12296 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12297 
12298 	/*
12299 	 * Allocate buffer for Identify Data return data
12300 	 */
12301 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
12302 	if (bp == NULL) {
12303 		sata_pkt_free(spx);
12304 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12305 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12306 		    "sata_fetch_device_identify_data: "
12307 		    "cannot allocate buffer for ID"));
12308 		return (SATA_RETRY); /* may retry later */
12309 	}
12310 
12311 	/* Fill sata_pkt */
12312 	sdinfo->satadrv_state = SATA_STATE_PROBING;
12313 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12314 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12315 	/* Synchronous mode, no callback */
12316 	spkt->satapkt_comp = NULL;
12317 	/* Timeout 30s */
12318 	spkt->satapkt_time = sata_default_pkt_time;
12319 
12320 	scmd = &spkt->satapkt_cmd;
12321 	scmd->satacmd_bp = bp;
12322 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12323 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12324 
12325 	/* Build Identify Device cmd in the sata_pkt */
12326 	scmd->satacmd_addr_type = 0;		/* N/A */
12327 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12328 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12329 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
12330 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
12331 	scmd->satacmd_features_reg = 0;		/* N/A */
12332 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12333 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
12334 		/* Identify Packet Device cmd */
12335 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
12336 	} else {
12337 		/* Identify Device cmd - mandatory for all other devices */
12338 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
12339 	}
12340 
12341 	/* Send pkt to SATA HBA driver */
12342 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
12343 
12344 #ifdef SATA_INJECT_FAULTS
12345 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12346 #endif
12347 
12348 	if (rval == SATA_TRAN_ACCEPTED &&
12349 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
12350 		if (spx->txlt_buf_dma_handle != NULL) {
12351 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12352 			    DDI_DMA_SYNC_FORKERNEL);
12353 			ASSERT(rval == DDI_SUCCESS);
12354 		}
12355 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
12356 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
12357 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12358 			    "SATA disk device at port %d - "
12359 			    "partial Identify Data",
12360 			    sdinfo->satadrv_addr.cport));
12361 			rval = SATA_RETRY; /* may retry later */
12362 			goto fail;
12363 		}
12364 		/* Update sata_drive_info */
12365 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
12366 		    sizeof (sata_id_t));
12367 
12368 		sdinfo->satadrv_features_support = 0;
12369 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12370 			/*
12371 			 * Retrieve capacity (disks only) and addressing mode
12372 			 */
12373 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
12374 		} else {
12375 			/*
12376 			 * For ATAPI devices one would have to issue
12377 			 * Get Capacity cmd for media capacity. Not here.
12378 			 */
12379 			sdinfo->satadrv_capacity = 0;
12380 			/*
12381 			 * Check what cdb length is supported
12382 			 */
12383 			if ((sdinfo->satadrv_id.ai_config &
12384 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
12385 				sdinfo->satadrv_atapi_cdb_len = 16;
12386 			else
12387 				sdinfo->satadrv_atapi_cdb_len = 12;
12388 		}
12389 		/* Setup supported features flags */
12390 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
12391 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
12392 
12393 		/* Check for SATA GEN and NCQ support */
12394 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
12395 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
12396 			/* SATA compliance */
12397 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
12398 				sdinfo->satadrv_features_support |=
12399 				    SATA_DEV_F_NCQ;
12400 			if (sdinfo->satadrv_id.ai_satacap &
12401 			    (SATA_1_SPEED | SATA_2_SPEED)) {
12402 				if (sdinfo->satadrv_id.ai_satacap &
12403 				    SATA_2_SPEED)
12404 					sdinfo->satadrv_features_support |=
12405 					    SATA_DEV_F_SATA2;
12406 				if (sdinfo->satadrv_id.ai_satacap &
12407 				    SATA_1_SPEED)
12408 					sdinfo->satadrv_features_support |=
12409 					    SATA_DEV_F_SATA1;
12410 			} else {
12411 				sdinfo->satadrv_features_support |=
12412 				    SATA_DEV_F_SATA1;
12413 			}
12414 		}
12415 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
12416 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
12417 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
12418 
12419 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
12420 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
12421 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
12422 			++sdinfo->satadrv_queue_depth;
12423 			/* Adjust according to controller capabilities */
12424 			sdinfo->satadrv_max_queue_depth = MIN(
12425 			    sdinfo->satadrv_queue_depth,
12426 			    SATA_QDEPTH(sata_hba_inst));
12427 			/* Adjust according to global queue depth limit */
12428 			sdinfo->satadrv_max_queue_depth = MIN(
12429 			    sdinfo->satadrv_max_queue_depth,
12430 			    sata_current_max_qdepth);
12431 			if (sdinfo->satadrv_max_queue_depth == 0)
12432 				sdinfo->satadrv_max_queue_depth = 1;
12433 		} else
12434 			sdinfo->satadrv_max_queue_depth = 1;
12435 
12436 		rval = SATA_SUCCESS;
12437 	} else {
12438 		/*
12439 		 * Woops, no Identify Data.
12440 		 */
12441 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
12442 			rval = SATA_RETRY; /* may retry later */
12443 		} else if (rval == SATA_TRAN_ACCEPTED) {
12444 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
12445 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
12446 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
12447 			    spkt->satapkt_reason == SATA_PKT_RESET)
12448 				rval = SATA_RETRY; /* may retry later */
12449 			else
12450 				rval = SATA_FAILURE;
12451 		} else {
12452 			rval = SATA_FAILURE;
12453 		}
12454 	}
12455 fail:
12456 	/* Free allocated resources */
12457 	sata_free_local_buffer(spx);
12458 	sata_pkt_free(spx);
12459 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
12460 
12461 	return (rval);
12462 }
12463 
12464 
12465 /*
12466  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
12467  * UDMA mode is checked first, followed by MWDMA mode.
12468  * set correctly, so this function is setting it to the highest supported level.
12469  * Older SATA spec required that the device supports at least DMA 4 mode and
12470  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
12471  * restriction has been removed.
12472  *
12473  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
12474  * Returns SATA_FAILURE if proper DMA mode could not be selected.
12475  *
12476  * NOTE: This function should be called only if DMA mode is supported.
12477  */
12478 static int
12479 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
12480 {
12481 	sata_pkt_t *spkt;
12482 	sata_cmd_t *scmd;
12483 	sata_pkt_txlate_t *spx;
12484 	int mode;
12485 	uint8_t subcmd;
12486 	int rval = SATA_SUCCESS;
12487 
12488 	ASSERT(sdinfo != NULL);
12489 	ASSERT(sata_hba_inst != NULL);
12490 
12491 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12492 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
12493 		/* Find highest Ultra DMA mode supported */
12494 		for (mode = 6; mode >= 0; --mode) {
12495 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
12496 				break;
12497 		}
12498 #if 0
12499 		/* Left for historical reasons */
12500 		/*
12501 		 * Some initial version of SATA spec indicated that at least
12502 		 * UDMA mode 4 has to be supported. It is not mentioned in
12503 		 * SerialATA 2.6, so this restriction is removed.
12504 		 */
12505 		if (mode < 4)
12506 			return (SATA_FAILURE);
12507 #endif
12508 
12509 		/*
12510 		 * We're still going to set DMA mode whatever is selected
12511 		 * by default
12512 		 *
12513 		 * We saw an old maxtor sata drive will select Ultra DMA and
12514 		 * Multi-Word DMA simultaneouly by default, which is going
12515 		 * to cause DMA command timed out, so we need to select DMA
12516 		 * mode even when it's already done by default
12517 		 */
12518 
12519 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
12520 
12521 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
12522 		/* Find highest MultiWord DMA mode supported */
12523 		for (mode = 2; mode >= 0; --mode) {
12524 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
12525 				break;
12526 		}
12527 
12528 		/*
12529 		 * We're still going to set DMA mode whatever is selected
12530 		 * by default
12531 		 *
12532 		 * We saw an old maxtor sata drive will select Ultra DMA and
12533 		 * Multi-Word DMA simultaneouly by default, which is going
12534 		 * to cause DMA command timed out, so we need to select DMA
12535 		 * mode even when it's already done by default
12536 		 */
12537 
12538 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
12539 	} else
12540 		return (SATA_SUCCESS);
12541 
12542 	/*
12543 	 * Set DMA mode via SET FEATURES COMMAND.
12544 	 * Prepare packet for SET FEATURES COMMAND.
12545 	 */
12546 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12547 	spx->txlt_sata_hba_inst = sata_hba_inst;
12548 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
12549 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12550 	if (spkt == NULL) {
12551 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12552 		    "sata_set_dma_mode: could not set DMA mode %", mode));
12553 		rval = SATA_FAILURE;
12554 		goto done;
12555 	}
12556 	/* Fill sata_pkt */
12557 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12558 	/* Timeout 30s */
12559 	spkt->satapkt_time = sata_default_pkt_time;
12560 	/* Synchronous mode, no callback, interrupts */
12561 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12562 	spkt->satapkt_comp = NULL;
12563 	scmd = &spkt->satapkt_cmd;
12564 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
12565 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12566 	scmd->satacmd_addr_type = 0;
12567 	scmd->satacmd_device_reg = 0;
12568 	scmd->satacmd_status_reg = 0;
12569 	scmd->satacmd_error_reg = 0;
12570 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
12571 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
12572 	scmd->satacmd_sec_count_lsb = subcmd | mode;
12573 
12574 	/* Transfer command to HBA */
12575 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
12576 	    spkt) != SATA_TRAN_ACCEPTED ||
12577 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
12578 		/* Pkt execution failed */
12579 		rval = SATA_FAILURE;
12580 	}
12581 done:
12582 
12583 	/* Free allocated resources */
12584 	if (spkt != NULL)
12585 		sata_pkt_free(spx);
12586 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
12587 
12588 	return (rval);
12589 }
12590 
12591 
12592 /*
12593  * Set device caching mode.
12594  * One of the following operations should be specified:
12595  * SATAC_SF_ENABLE_READ_AHEAD
12596  * SATAC_SF_DISABLE_READ_AHEAD
12597  * SATAC_SF_ENABLE_WRITE_CACHE
12598  * SATAC_SF_DISABLE_WRITE_CACHE
12599  *
12600  * If operation fails, system log messgage is emitted.
12601  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
12602  * command was sent but did not succeed, and SATA_FAILURE otherwise.
12603  */
12604 
12605 static int
12606 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
12607     int cache_op)
12608 {
12609 	sata_pkt_t *spkt;
12610 	sata_cmd_t *scmd;
12611 	sata_pkt_txlate_t *spx;
12612 	int rval = SATA_SUCCESS;
12613 	int hba_rval;
12614 	char *infop;
12615 
12616 	ASSERT(sdinfo != NULL);
12617 	ASSERT(sata_hba_inst != NULL);
12618 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
12619 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
12620 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
12621 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
12622 
12623 
12624 	/* Prepare packet for SET FEATURES COMMAND */
12625 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12626 	spx->txlt_sata_hba_inst = sata_hba_inst;
12627 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
12628 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12629 	if (spkt == NULL) {
12630 		rval = SATA_FAILURE;
12631 		goto failure;
12632 	}
12633 	/* Fill sata_pkt */
12634 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12635 	/* Timeout 30s */
12636 	spkt->satapkt_time = sata_default_pkt_time;
12637 	/* Synchronous mode, no callback, interrupts */
12638 	spkt->satapkt_op_mode =
12639 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12640 	spkt->satapkt_comp = NULL;
12641 	scmd = &spkt->satapkt_cmd;
12642 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
12643 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12644 	scmd->satacmd_addr_type = 0;
12645 	scmd->satacmd_device_reg = 0;
12646 	scmd->satacmd_status_reg = 0;
12647 	scmd->satacmd_error_reg = 0;
12648 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
12649 	scmd->satacmd_features_reg = cache_op;
12650 
12651 	/* Transfer command to HBA */
12652 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
12653 	    SATA_DIP(sata_hba_inst), spkt);
12654 
12655 #ifdef SATA_INJECT_FAULTS
12656 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12657 #endif
12658 
12659 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
12660 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
12661 		/* Pkt execution failed */
12662 		switch (cache_op) {
12663 		case SATAC_SF_ENABLE_READ_AHEAD:
12664 			infop = "enabling read ahead failed";
12665 			break;
12666 		case SATAC_SF_DISABLE_READ_AHEAD:
12667 			infop = "disabling read ahead failed";
12668 			break;
12669 		case SATAC_SF_ENABLE_WRITE_CACHE:
12670 			infop = "enabling write cache failed";
12671 			break;
12672 		case SATAC_SF_DISABLE_WRITE_CACHE:
12673 			infop = "disabling write cache failed";
12674 			break;
12675 		}
12676 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
12677 		rval = SATA_RETRY;
12678 	}
12679 failure:
12680 	/* Free allocated resources */
12681 	if (spkt != NULL)
12682 		sata_pkt_free(spx);
12683 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
12684 	return (rval);
12685 }
12686 
12687 /*
12688  * Set Removable Media Status Notification (enable/disable)
12689  * state == 0 , disable
12690  * state != 0 , enable
12691  *
12692  * If operation fails, system log messgage is emitted.
12693  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
12694  */
12695 
12696 static int
12697 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
12698     int state)
12699 {
12700 	sata_pkt_t *spkt;
12701 	sata_cmd_t *scmd;
12702 	sata_pkt_txlate_t *spx;
12703 	int rval = SATA_SUCCESS;
12704 	char *infop;
12705 
12706 	ASSERT(sdinfo != NULL);
12707 	ASSERT(sata_hba_inst != NULL);
12708 
12709 	/* Prepare packet for SET FEATURES COMMAND */
12710 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12711 	spx->txlt_sata_hba_inst = sata_hba_inst;
12712 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
12713 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12714 	if (spkt == NULL) {
12715 		rval = SATA_FAILURE;
12716 		goto failure;
12717 	}
12718 	/* Fill sata_pkt */
12719 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12720 	/* Timeout 30s */
12721 	spkt->satapkt_time = sata_default_pkt_time;
12722 	/* Synchronous mode, no callback, interrupts */
12723 	spkt->satapkt_op_mode =
12724 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12725 	spkt->satapkt_comp = NULL;
12726 	scmd = &spkt->satapkt_cmd;
12727 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
12728 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12729 	scmd->satacmd_addr_type = 0;
12730 	scmd->satacmd_device_reg = 0;
12731 	scmd->satacmd_status_reg = 0;
12732 	scmd->satacmd_error_reg = 0;
12733 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
12734 	if (state == 0)
12735 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
12736 	else
12737 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
12738 
12739 	/* Transfer command to HBA */
12740 	if (((*SATA_START_FUNC(sata_hba_inst))(
12741 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
12742 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
12743 		/* Pkt execution failed */
12744 		if (state == 0)
12745 			infop = "disabling Removable Media Status "
12746 			    "Notification failed";
12747 		else
12748 			infop = "enabling Removable Media Status "
12749 			    "Notification failed";
12750 
12751 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
12752 		rval = SATA_FAILURE;
12753 	}
12754 failure:
12755 	/* Free allocated resources */
12756 	if (spkt != NULL)
12757 		sata_pkt_free(spx);
12758 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
12759 	return (rval);
12760 }
12761 
12762 
12763 /*
12764  * Update state and copy port ss* values from passed sata_device structure.
12765  * sata_address is validated - if not valid, nothing is changed in sata_scsi
12766  * configuration struct.
12767  *
12768  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
12769  * regardless of the state in device argument.
12770  *
12771  * Port mutex should be held while calling this function.
12772  */
12773 static void
12774 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
12775     sata_device_t *sata_device)
12776 {
12777 	sata_cport_info_t *cportinfo;
12778 
12779 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
12780 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
12781 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
12782 		    sata_device->satadev_addr.cport)
12783 			return;
12784 
12785 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
12786 		    sata_device->satadev_addr.cport);
12787 
12788 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
12789 		cportinfo->cport_scr = sata_device->satadev_scr;
12790 
12791 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
12792 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
12793 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
12794 		cportinfo->cport_state |=
12795 		    sata_device->satadev_state & SATA_PSTATE_VALID;
12796 	}
12797 }
12798 
12799 void
12800 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
12801     sata_device_t *sata_device)
12802 {
12803 	sata_pmport_info_t *pmportinfo;
12804 
12805 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
12806 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
12807 	    SATA_NUM_PMPORTS(sata_hba_inst,
12808 	    sata_device->satadev_addr.cport) <
12809 	    sata_device->satadev_addr.pmport) {
12810 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
12811 		    "sata_update_port_info: error address %p.",
12812 		    &sata_device->satadev_addr);
12813 		return;
12814 	}
12815 
12816 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
12817 	    sata_device->satadev_addr.cport,
12818 	    sata_device->satadev_addr.pmport);
12819 
12820 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
12821 	pmportinfo->pmport_scr = sata_device->satadev_scr;
12822 
12823 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
12824 	pmportinfo->pmport_state &=
12825 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
12826 	pmportinfo->pmport_state |=
12827 	    sata_device->satadev_state & SATA_PSTATE_VALID;
12828 }
12829 
12830 /*
12831  * Extract SATA port specification from an IOCTL argument.
12832  *
12833  * This function return the port the user land send us as is, unless it
12834  * cannot retrieve port spec, then -1 is returned.
12835  *
12836  * Support port multiplier.
12837  */
12838 static int32_t
12839 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
12840 {
12841 	int32_t port;
12842 
12843 	/* Extract port number from nvpair in dca structure  */
12844 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
12845 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
12846 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
12847 		    port));
12848 		port = -1;
12849 	}
12850 
12851 	return (port);
12852 }
12853 
12854 /*
12855  * Get dev_info_t pointer to the device node pointed to by port argument.
12856  * NOTE: target argument is a value used in ioctls to identify
12857  * the AP - it is not a sata_address.
12858  * It is a combination of cport, pmport and address qualifier, encodded same
12859  * way as a scsi target number.
12860  * At this moment it carries only cport number.
12861  *
12862  * PMult hotplug is supported now.
12863  *
12864  * Returns dev_info_t pointer if target device was found, NULL otherwise.
12865  */
12866 
12867 static dev_info_t *
12868 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
12869 {
12870 	dev_info_t	*cdip = NULL;
12871 	int		target, tgt;
12872 	int 		circ;
12873 	uint8_t		qual;
12874 
12875 	sata_hba_inst_t	*sata_hba_inst;
12876 	scsi_hba_tran_t *scsi_hba_tran;
12877 
12878 	/* Get target id */
12879 	scsi_hba_tran = ddi_get_driver_private(dip);
12880 	if (scsi_hba_tran == NULL)
12881 		return (NULL);
12882 
12883 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
12884 
12885 	if (sata_hba_inst == NULL)
12886 		return (NULL);
12887 
12888 	/* Identify a port-mult by cport_info.cport_dev_type */
12889 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
12890 		qual = SATA_ADDR_DPMPORT;
12891 	else
12892 		qual = SATA_ADDR_DCPORT;
12893 
12894 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
12895 
12896 	/* Retrieve target dip */
12897 	ndi_devi_enter(dip, &circ);
12898 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
12899 		dev_info_t *next = ddi_get_next_sibling(cdip);
12900 
12901 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
12902 		    DDI_PROP_DONTPASS, "target", -1);
12903 		if (tgt == -1) {
12904 			/*
12905 			 * This is actually an error condition, but not
12906 			 * a fatal one. Just continue the search.
12907 			 */
12908 			cdip = next;
12909 			continue;
12910 		}
12911 
12912 		if (tgt == target)
12913 			break;
12914 
12915 		cdip = next;
12916 	}
12917 	ndi_devi_exit(dip, circ);
12918 
12919 	return (cdip);
12920 }
12921 
12922 /*
12923  * Get dev_info_t pointer to the device node pointed to by port argument.
12924  * NOTE: target argument is a value used in ioctls to identify
12925  * the AP - it is not a sata_address.
12926  * It is a combination of cport, pmport and address qualifier, encoded same
12927  * way as a scsi target number.
12928  *
12929  * Returns dev_info_t pointer if target device was found, NULL otherwise.
12930  */
12931 
12932 static dev_info_t *
12933 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
12934 {
12935 	dev_info_t	*cdip = NULL;
12936 	int		target, tgt;
12937 	int 		circ;
12938 
12939 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
12940 
12941 	ndi_devi_enter(dip, &circ);
12942 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
12943 		dev_info_t *next = ddi_get_next_sibling(cdip);
12944 
12945 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
12946 		    DDI_PROP_DONTPASS, "target", -1);
12947 		if (tgt == -1) {
12948 			/*
12949 			 * This is actually an error condition, but not
12950 			 * a fatal one. Just continue the search.
12951 			 */
12952 			cdip = next;
12953 			continue;
12954 		}
12955 
12956 		if (tgt == target)
12957 			break;
12958 
12959 		cdip = next;
12960 	}
12961 	ndi_devi_exit(dip, circ);
12962 
12963 	return (cdip);
12964 }
12965 
12966 /*
12967  * Process sata port disconnect request.
12968  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
12969  * before this request. Nevertheless, if a device is still configured,
12970  * we need to attempt to offline and unconfigure device.
12971  * Regardless of the unconfigure operation results the port is marked as
12972  * deactivated and no access to the attached device is possible.
12973  * If the target node remains because unconfigure operation failed, its state
12974  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
12975  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
12976  * the device and remove old target node.
12977  *
12978  * This function invokes sata_hba_inst->satahba_tran->
12979  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
12980  * If successful, the device structure (if any) attached to the specified port
12981  * is removed and state of the port marked appropriately.
12982  * Failure of the port_deactivate may keep port in the physically active state,
12983  * or may fail the port.
12984  *
12985  * NOTE: Port multiplier is supported.
12986  */
12987 
12988 static int
12989 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
12990     sata_device_t *sata_device)
12991 {
12992 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
12993 	sata_cport_info_t *cportinfo = NULL;
12994 	sata_pmport_info_t *pmportinfo = NULL;
12995 	sata_pmult_info_t *pmultinfo = NULL;
12996 	sata_device_t 		subsdevice;
12997 	int cport, pmport, qual;
12998 	int rval = SATA_SUCCESS;
12999 	int npmport = 0;
13000 	int rv = 0;
13001 
13002 	cport = sata_device->satadev_addr.cport;
13003 	pmport = sata_device->satadev_addr.pmport;
13004 	qual = sata_device->satadev_addr.qual;
13005 
13006 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13007 	if (qual == SATA_ADDR_DCPORT)
13008 		qual = SATA_ADDR_CPORT;
13009 	else
13010 		qual = SATA_ADDR_PMPORT;
13011 
13012 	/*
13013 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13014 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13015 	 * Do the sanity check.
13016 	 */
13017 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13018 		/* No physical port deactivation supported. */
13019 		return (EINVAL);
13020 	}
13021 
13022 	/* Check the current state of the port */
13023 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13024 	    (SATA_DIP(sata_hba_inst), sata_device);
13025 
13026 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13027 
13028 	/*
13029 	 * Processing port mulitiplier
13030 	 */
13031 	if (qual == SATA_ADDR_CPORT &&
13032 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13033 		mutex_enter(&cportinfo->cport_mutex);
13034 
13035 		/* Check controller port status */
13036 		sata_update_port_info(sata_hba_inst, sata_device);
13037 		if (rval != SATA_SUCCESS ||
13038 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13039 			/*
13040 			 * Device port status is unknown or it is in failed
13041 			 * state
13042 			 */
13043 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13044 			    SATA_PSTATE_FAILED;
13045 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13046 			    "sata_hba_ioctl: connect: failed to deactivate "
13047 			    "SATA port %d", cport);
13048 			mutex_exit(&cportinfo->cport_mutex);
13049 			return (EIO);
13050 		}
13051 
13052 		/* Disconnect all sub-devices. */
13053 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13054 		if (pmultinfo != NULL) {
13055 
13056 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13057 			    sata_hba_inst, cport); npmport ++) {
13058 				subsdinfo = SATA_PMPORT_DRV_INFO(
13059 				    sata_hba_inst, cport, npmport);
13060 				if (subsdinfo == NULL)
13061 					continue;
13062 
13063 				subsdevice.satadev_addr = subsdinfo->
13064 				    satadrv_addr;
13065 
13066 				mutex_exit(&cportinfo->cport_mutex);
13067 				if (sata_ioctl_disconnect(sata_hba_inst,
13068 				    &subsdevice) == SATA_SUCCESS) {
13069 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13070 					"[Remove] device at port %d:%d "
13071 					"successfully.", cport, npmport);
13072 				}
13073 				mutex_enter(&cportinfo->cport_mutex);
13074 			}
13075 		}
13076 
13077 		/* Disconnect the port multiplier */
13078 		cportinfo->cport_state &= ~SATA_STATE_READY;
13079 		mutex_exit(&cportinfo->cport_mutex);
13080 
13081 		sata_device->satadev_addr.qual = qual;
13082 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13083 		    (SATA_DIP(sata_hba_inst), sata_device);
13084 
13085 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13086 		    SE_NO_HINT);
13087 
13088 		mutex_enter(&cportinfo->cport_mutex);
13089 		sata_update_port_info(sata_hba_inst, sata_device);
13090 		if (rval != SATA_SUCCESS &&
13091 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13092 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13093 			rv = EIO;
13094 		} else {
13095 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13096 		}
13097 		mutex_exit(&cportinfo->cport_mutex);
13098 
13099 		return (rv);
13100 	}
13101 
13102 	/*
13103 	 * Process non-port-multiplier device - it could be a drive connected
13104 	 * to a port multiplier port or a controller port.
13105 	 */
13106 	if (qual == SATA_ADDR_PMPORT) {
13107 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13108 		mutex_enter(&pmportinfo->pmport_mutex);
13109 		sata_update_pmport_info(sata_hba_inst, sata_device);
13110 		if (rval != SATA_SUCCESS ||
13111 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13112 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13113 			    SATA_PSTATE_FAILED;
13114 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13115 			    "sata_hba_ioctl: connect: failed to deactivate "
13116 			    "SATA port %d:%d", cport, pmport);
13117 			mutex_exit(&pmportinfo->pmport_mutex);
13118 			return (EIO);
13119 		}
13120 
13121 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13122 			sdinfo = pmportinfo->pmport_sata_drive;
13123 			ASSERT(sdinfo != NULL);
13124 		}
13125 
13126 		/*
13127 		 * Set port's dev_state to not ready - this will disable
13128 		 * an access to a potentially attached device.
13129 		 */
13130 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13131 
13132 		/* Remove and release sata_drive info structure. */
13133 		if (sdinfo != NULL) {
13134 			if ((sdinfo->satadrv_type &
13135 			    SATA_VALID_DEV_TYPE) != 0) {
13136 				/*
13137 				 * If a target node exists, try to offline
13138 				 * a device and remove target node.
13139 				 */
13140 				mutex_exit(&pmportinfo->pmport_mutex);
13141 				(void) sata_offline_device(sata_hba_inst,
13142 				    sata_device, sdinfo);
13143 				mutex_enter(&pmportinfo->pmport_mutex);
13144 			}
13145 
13146 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13147 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13148 			(void) kmem_free((void *)sdinfo,
13149 			    sizeof (sata_drive_info_t));
13150 		}
13151 		mutex_exit(&pmportinfo->pmport_mutex);
13152 
13153 	} else if (qual == SATA_ADDR_CPORT) {
13154 		mutex_enter(&cportinfo->cport_mutex);
13155 		sata_update_port_info(sata_hba_inst, sata_device);
13156 		if (rval != SATA_SUCCESS ||
13157 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13158 			/*
13159 			 * Device port status is unknown or it is in failed
13160 			 * state
13161 			 */
13162 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13163 			    SATA_PSTATE_FAILED;
13164 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13165 			    "sata_hba_ioctl: connect: failed to deactivate "
13166 			    "SATA port %d", cport);
13167 			mutex_exit(&cportinfo->cport_mutex);
13168 			return (EIO);
13169 		}
13170 
13171 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13172 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13173 			ASSERT(pmultinfo != NULL);
13174 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13175 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13176 			ASSERT(sdinfo != NULL);
13177 		}
13178 		cportinfo->cport_state &= ~SATA_STATE_READY;
13179 
13180 		if (sdinfo != NULL) {
13181 			if ((sdinfo->satadrv_type &
13182 			    SATA_VALID_DEV_TYPE) != 0) {
13183 				/*
13184 				 * If a target node exists, try to offline
13185 				 * a device and remove target node.
13186 				 */
13187 				mutex_exit(&cportinfo->cport_mutex);
13188 				(void) sata_offline_device(sata_hba_inst,
13189 				    sata_device, sdinfo);
13190 				mutex_enter(&cportinfo->cport_mutex);
13191 			}
13192 
13193 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13194 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13195 			(void) kmem_free((void *)sdinfo,
13196 			    sizeof (sata_drive_info_t));
13197 		}
13198 		mutex_exit(&cportinfo->cport_mutex);
13199 	}
13200 
13201 	/* Just ask HBA driver to deactivate port */
13202 	sata_device->satadev_addr.qual = qual;
13203 
13204 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13205 	    (SATA_DIP(sata_hba_inst), sata_device);
13206 
13207 	/*
13208 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13209 	 * without the hint (to force listener to investivate the state).
13210 	 */
13211 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13212 	    SE_NO_HINT);
13213 
13214 	if (qual == SATA_ADDR_PMPORT) {
13215 		mutex_enter(&pmportinfo->pmport_mutex);
13216 		sata_update_pmport_info(sata_hba_inst, sata_device);
13217 
13218 		if (rval != SATA_SUCCESS &&
13219 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13220 			/*
13221 			 * Port deactivation failure - do not change port
13222 			 * state unless the state returned by HBA indicates a
13223 			 * port failure.
13224 			 *
13225 			 * NOTE: device structures were released, so devices
13226 			 * now are invisible! Port reset is needed to
13227 			 * re-enumerate devices.
13228 			 */
13229 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13230 			rv = EIO;
13231 		} else {
13232 			/*
13233 			 * Deactivation succeded. From now on the sata framework
13234 			 * will not care what is happening to the device, until
13235 			 * the port is activated again.
13236 			 */
13237 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13238 		}
13239 		mutex_exit(&pmportinfo->pmport_mutex);
13240 	} else if (qual == SATA_ADDR_CPORT) {
13241 		mutex_enter(&cportinfo->cport_mutex);
13242 		sata_update_port_info(sata_hba_inst, sata_device);
13243 
13244 		if (rval != SATA_SUCCESS &&
13245 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13246 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13247 			rv = EIO;
13248 		} else {
13249 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13250 		}
13251 		mutex_exit(&cportinfo->cport_mutex);
13252 	}
13253 
13254 	return (rv);
13255 }
13256 
13257 
13258 
13259 /*
13260  * Process sata port connect request
13261  * The sata cfgadm pluging will invoke this operation only if port was found
13262  * in the disconnect state (failed state is also treated as the disconnected
13263  * state).
13264  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
13265  * sata_tran_hotplug_ops->sata_tran_port_activate().
13266  * If successful and a device is found attached to the port,
13267  * the initialization sequence is executed to attach a device structure to
13268  * a port structure. The state of the port and a device would be set
13269  * appropriately.
13270  * The device is not set in configured state (system-wise) by this operation.
13271  *
13272  * Note, that activating the port may generate link events,
13273  * so it is important that following processing and the
13274  * event processing does not interfere with each other!
13275  *
13276  * This operation may remove port failed state and will
13277  * try to make port active and in good standing.
13278  *
13279  * NOTE: Port multiplier is supported.
13280  */
13281 
13282 static int
13283 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
13284     sata_device_t *sata_device)
13285 {
13286 	sata_pmport_info_t	*pmportinfo = NULL;
13287 	uint8_t cport, pmport, qual;
13288 	int rv = 0;
13289 
13290 	cport = sata_device->satadev_addr.cport;
13291 	pmport = sata_device->satadev_addr.pmport;
13292 	qual = sata_device->satadev_addr.qual;
13293 
13294 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13295 	if (qual == SATA_ADDR_DCPORT)
13296 		qual = SATA_ADDR_CPORT;
13297 	else
13298 		qual = SATA_ADDR_PMPORT;
13299 
13300 	if (qual == SATA_ADDR_PMPORT)
13301 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13302 
13303 	/*
13304 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
13305 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
13306 	 * Perform sanity check now.
13307 	 */
13308 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
13309 		/* No physical port activation supported. */
13310 		return (EINVAL);
13311 	}
13312 
13313 	/* Just ask HBA driver to activate port */
13314 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13315 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13316 		/*
13317 		 * Port activation failure.
13318 		 */
13319 		if (qual == SATA_ADDR_CPORT) {
13320 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13321 			    cport)->cport_mutex);
13322 			sata_update_port_info(sata_hba_inst, sata_device);
13323 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13324 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13325 				    SATA_PSTATE_FAILED;
13326 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13327 				    "sata_hba_ioctl: connect: failed to "
13328 				    "activate SATA port %d", cport);
13329 			}
13330 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13331 			    cport)->cport_mutex);
13332 		} else { /* port multiplier device port */
13333 			mutex_enter(&pmportinfo->pmport_mutex);
13334 			sata_update_pmport_info(sata_hba_inst, sata_device);
13335 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13336 				SATA_PMPORT_STATE(sata_hba_inst, cport,
13337 				    pmport) = SATA_PSTATE_FAILED;
13338 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13339 				    "sata_hba_ioctl: connect: failed to "
13340 				    "activate SATA port %d:%d", cport, pmport);
13341 			}
13342 			mutex_exit(&pmportinfo->pmport_mutex);
13343 		}
13344 		return (EIO);
13345 	}
13346 
13347 	/* Virgin port state - will be updated by the port re-probe. */
13348 	if (qual == SATA_ADDR_CPORT) {
13349 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13350 		    cport)->cport_mutex);
13351 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
13352 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13353 		    cport)->cport_mutex);
13354 	} else { /* port multiplier device port */
13355 		mutex_enter(&pmportinfo->pmport_mutex);
13356 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
13357 		mutex_exit(&pmportinfo->pmport_mutex);
13358 	}
13359 
13360 	/*
13361 	 * Probe the port to find its state and attached device.
13362 	 */
13363 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13364 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
13365 		rv = EIO;
13366 
13367 	/*
13368 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13369 	 * without the hint
13370 	 */
13371 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13372 	    SE_NO_HINT);
13373 
13374 	/*
13375 	 * If there is a device attached to the port, emit
13376 	 * a message.
13377 	 */
13378 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
13379 
13380 		if (qual == SATA_ADDR_CPORT) {
13381 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
13382 				sata_log(sata_hba_inst, CE_WARN,
13383 				    "SATA port multiplier detected "
13384 				    "at port %d", cport);
13385 			} else {
13386 				sata_log(sata_hba_inst, CE_WARN,
13387 				    "SATA device detected at port %d", cport);
13388 				if (sata_device->satadev_type ==
13389 				    SATA_DTYPE_UNKNOWN) {
13390 				/*
13391 				 * A device was not successfully identified
13392 				 */
13393 				sata_log(sata_hba_inst, CE_WARN,
13394 				    "Could not identify SATA "
13395 				    "device at port %d", cport);
13396 				}
13397 			}
13398 		} else { /* port multiplier device port */
13399 			sata_log(sata_hba_inst, CE_WARN,
13400 			    "SATA device detected at port %d:%d",
13401 			    cport, pmport);
13402 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13403 				/*
13404 				 * A device was not successfully identified
13405 				 */
13406 				sata_log(sata_hba_inst, CE_WARN,
13407 				    "Could not identify SATA "
13408 				    "device at port %d:%d", cport, pmport);
13409 			}
13410 		}
13411 	}
13412 
13413 	return (rv);
13414 }
13415 
13416 
13417 /*
13418  * Process sata device unconfigure request.
13419  * The unconfigure operation uses generic nexus operation to
13420  * offline a device. It leaves a target device node attached.
13421  * and obviously sata_drive_info attached as well, because
13422  * from the hardware point of view nothing has changed.
13423  */
13424 static int
13425 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
13426     sata_device_t *sata_device)
13427 {
13428 	int rv = 0;
13429 	dev_info_t *tdip;
13430 
13431 	/* We are addressing attached device, not a port */
13432 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
13433 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
13434 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
13435 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
13436 
13437 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
13438 	    &sata_device->satadev_addr)) != NULL) {
13439 
13440 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
13441 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13442 			    "sata_hba_ioctl: unconfigure: "
13443 			    "failed to unconfigure device at SATA port %d:%d",
13444 			    sata_device->satadev_addr.cport,
13445 			    sata_device->satadev_addr.pmport));
13446 			rv = EIO;
13447 		}
13448 		/*
13449 		 * The target node devi_state should be marked with
13450 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
13451 		 * This would be the indication for cfgadm that
13452 		 * the AP node occupant state is 'unconfigured'.
13453 		 */
13454 
13455 	} else {
13456 		/*
13457 		 * This would indicate a failure on the part of cfgadm
13458 		 * to detect correct state of the node prior to this
13459 		 * call - one cannot unconfigure non-existing device.
13460 		 */
13461 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13462 		    "sata_hba_ioctl: unconfigure: "
13463 		    "attempt to unconfigure non-existing device "
13464 		    "at SATA port %d:%d",
13465 		    sata_device->satadev_addr.cport,
13466 		    sata_device->satadev_addr.pmport));
13467 		rv = ENXIO;
13468 	}
13469 	return (rv);
13470 }
13471 
13472 /*
13473  * Process sata device configure request
13474  * If port is in a failed state, operation is aborted - one has to use
13475  * an explicit connect or port activate request to try to get a port into
13476  * non-failed mode. Port reset wil also work in such situation.
13477  * If the port is in disconnected (shutdown) state, the connect operation is
13478  * attempted prior to any other action.
13479  * When port is in the active state, there is a device attached and the target
13480  * node exists, a device was most likely offlined.
13481  * If target node does not exist, a new target node is created. In both cases
13482  * an attempt is made to online (configure) the device.
13483  *
13484  * NOTE: Port multiplier is supported.
13485  */
13486 static int
13487 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
13488     sata_device_t *sata_device)
13489 {
13490 	int cport, pmport, qual;
13491 	int rval;
13492 	boolean_t target = TRUE;
13493 	sata_cport_info_t *cportinfo;
13494 	sata_pmport_info_t *pmportinfo = NULL;
13495 	dev_info_t *tdip;
13496 	sata_drive_info_t *sdinfo;
13497 
13498 	cport = sata_device->satadev_addr.cport;
13499 	pmport = sata_device->satadev_addr.pmport;
13500 	qual = sata_device->satadev_addr.qual;
13501 
13502 	/* Get current port state */
13503 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13504 	    (SATA_DIP(sata_hba_inst), sata_device);
13505 
13506 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13507 	if (qual == SATA_ADDR_DPMPORT) {
13508 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13509 		mutex_enter(&pmportinfo->pmport_mutex);
13510 		sata_update_pmport_info(sata_hba_inst, sata_device);
13511 		if (rval != SATA_SUCCESS ||
13512 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13513 			/*
13514 			 * Obviously, device on a failed port is not visible
13515 			 */
13516 			mutex_exit(&pmportinfo->pmport_mutex);
13517 			return (ENXIO);
13518 		}
13519 		mutex_exit(&pmportinfo->pmport_mutex);
13520 	} else {
13521 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13522 		    cport)->cport_mutex);
13523 		sata_update_port_info(sata_hba_inst, sata_device);
13524 		if (rval != SATA_SUCCESS ||
13525 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13526 			/*
13527 			 * Obviously, device on a failed port is not visible
13528 			 */
13529 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13530 			    cport)->cport_mutex);
13531 			return (ENXIO);
13532 		}
13533 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13534 		    cport)->cport_mutex);
13535 	}
13536 
13537 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
13538 		/* need to activate port */
13539 		target = FALSE;
13540 
13541 		/* Sanity check */
13542 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
13543 			return (ENXIO);
13544 
13545 		/* Just let HBA driver to activate port */
13546 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13547 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13548 			/*
13549 			 * Port activation failure - do not change port state
13550 			 * unless the state returned by HBA indicates a port
13551 			 * failure.
13552 			 */
13553 			if (qual == SATA_ADDR_DPMPORT) {
13554 				mutex_enter(&pmportinfo->pmport_mutex);
13555 				sata_update_pmport_info(sata_hba_inst,
13556 				    sata_device);
13557 				if (sata_device->satadev_state &
13558 				    SATA_PSTATE_FAILED)
13559 					pmportinfo->pmport_state =
13560 					    SATA_PSTATE_FAILED;
13561 				mutex_exit(&pmportinfo->pmport_mutex);
13562 			} else {
13563 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13564 				    cport)->cport_mutex);
13565 				sata_update_port_info(sata_hba_inst,
13566 				    sata_device);
13567 				if (sata_device->satadev_state &
13568 				    SATA_PSTATE_FAILED)
13569 					cportinfo->cport_state =
13570 					    SATA_PSTATE_FAILED;
13571 				mutex_exit(&SATA_CPORT_INFO(
13572 				    sata_hba_inst, cport)->cport_mutex);
13573 			}
13574 		}
13575 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13576 		    "sata_hba_ioctl: configure: "
13577 		    "failed to activate SATA port %d:%d",
13578 		    cport, pmport));
13579 		return (EIO);
13580 	}
13581 	/*
13582 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13583 	 * without the hint.
13584 	 */
13585 	sata_gen_sysevent(sata_hba_inst,
13586 	    &sata_device->satadev_addr, SE_NO_HINT);
13587 
13588 	/* Virgin port state */
13589 	if (qual == SATA_ADDR_DPMPORT) {
13590 		mutex_enter(&pmportinfo->pmport_mutex);
13591 		pmportinfo->pmport_state = 0;
13592 		mutex_exit(&pmportinfo->pmport_mutex);
13593 	} else {
13594 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13595 		    cport)-> cport_mutex);
13596 		cportinfo->cport_state = 0;
13597 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13598 		    cport)->cport_mutex);
13599 	}
13600 	/*
13601 	 * Always reprobe port, to get current device info.
13602 	 */
13603 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13604 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
13605 		return (EIO);
13606 
13607 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
13608 		if (qual == SATA_ADDR_DPMPORT) {
13609 			/*
13610 			 * That's the transition from "inactive" port
13611 			 * to active one with device attached.
13612 			 */
13613 			sata_log(sata_hba_inst, CE_WARN,
13614 			    "SATA device detected at port %d:%d",
13615 			    cport, pmport);
13616 		} else {
13617 			/*
13618 			 * When PM is attached to the cport and cport is
13619 			 * activated, every PM device port needs to be reprobed.
13620 			 * We need to emit message for all devices detected
13621 			 * at port multiplier's device ports.
13622 			 * Add such code here.
13623 			 * For now, just inform about device attached to
13624 			 * cport.
13625 			 */
13626 			sata_log(sata_hba_inst, CE_WARN,
13627 			    "SATA device detected at port %d", cport);
13628 		}
13629 	}
13630 
13631 	/*
13632 	 * This is where real configuration operation starts.
13633 	 *
13634 	 * When PM is attached to the cport and cport is activated,
13635 	 * devices attached PM device ports may have to be configured
13636 	 * explicitly. This may change when port multiplier is supported.
13637 	 * For now, configure only disks and other valid target devices.
13638 	 */
13639 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
13640 		if (qual == SATA_ADDR_DCPORT) {
13641 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13642 				/*
13643 				 * A device was not successfully identified
13644 				 */
13645 				sata_log(sata_hba_inst, CE_WARN,
13646 				    "Could not identify SATA "
13647 				    "device at port %d", cport);
13648 			}
13649 		} else { /* port multiplier device port */
13650 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13651 				/*
13652 				 * A device was not successfully identified
13653 				 */
13654 				sata_log(sata_hba_inst, CE_WARN,
13655 				    "Could not identify SATA "
13656 				    "device at port %d:%d", cport, pmport);
13657 			}
13658 		}
13659 		return (ENXIO);		/* No device to configure */
13660 	}
13661 
13662 	/*
13663 	 * Here we may have a device in reset condition,
13664 	 * but because we are just configuring it, there is
13665 	 * no need to process the reset other than just
13666 	 * to clear device reset condition in the HBA driver.
13667 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
13668 	 * cause a first command sent the HBA driver with the request
13669 	 * to clear device reset condition.
13670 	 */
13671 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13672 	if (qual == SATA_ADDR_DPMPORT)
13673 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
13674 	else
13675 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
13676 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
13677 	if (sdinfo == NULL) {
13678 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13679 		return (ENXIO);
13680 	}
13681 	if (sdinfo->satadrv_event_flags &
13682 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
13683 		sdinfo->satadrv_event_flags = 0;
13684 	}
13685 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
13686 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13687 
13688 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
13689 	    &sata_device->satadev_addr)) != NULL) {
13690 		/*
13691 		 * Target node exists. Verify, that it belongs
13692 		 * to existing, attached device and not to
13693 		 * a removed device.
13694 		 */
13695 		if (sata_check_device_removed(tdip) == B_TRUE) {
13696 			if (qual == SATA_ADDR_DPMPORT)
13697 				sata_log(sata_hba_inst, CE_WARN,
13698 				    "SATA device at port %d cannot be "
13699 				    "configured. "
13700 				    "Application(s) accessing "
13701 				    "previously attached device "
13702 				    "have to release it before newly "
13703 				    "inserted device can be made accessible.",
13704 				    cport);
13705 			else
13706 				sata_log(sata_hba_inst, CE_WARN,
13707 				    "SATA device at port %d:%d cannot be"
13708 				    "configured. "
13709 				    "Application(s) accessing "
13710 				    "previously attached device "
13711 				    "have to release it before newly "
13712 				    "inserted device can be made accessible.",
13713 				    cport, pmport);
13714 			return (EIO);
13715 		}
13716 		/*
13717 		 * Device was not removed and re-inserted.
13718 		 * Try to online it.
13719 		 */
13720 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
13721 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13722 			    "sata_hba_ioctl: configure: "
13723 			    "onlining device at SATA port "
13724 			    "%d:%d failed", cport, pmport));
13725 			return (EIO);
13726 		}
13727 
13728 		if (qual == SATA_ADDR_DPMPORT) {
13729 			mutex_enter(&pmportinfo->pmport_mutex);
13730 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
13731 			mutex_exit(&pmportinfo->pmport_mutex);
13732 		} else {
13733 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13734 			    cport)->cport_mutex);
13735 			cportinfo-> cport_tgtnode_clean = B_TRUE;
13736 			mutex_exit(&SATA_CPORT_INFO(
13737 			    sata_hba_inst, cport)->cport_mutex);
13738 		}
13739 	} else {
13740 		/*
13741 		 * No target node - need to create a new target node.
13742 		 */
13743 		if (qual == SATA_ADDR_DPMPORT) {
13744 			mutex_enter(&pmportinfo->pmport_mutex);
13745 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
13746 			mutex_exit(&pmportinfo->pmport_mutex);
13747 		} else {
13748 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
13749 			    cport_mutex);
13750 			cportinfo-> cport_tgtnode_clean = B_TRUE;
13751 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
13752 			    cport_mutex);
13753 		}
13754 
13755 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
13756 		    sata_hba_inst, &sata_device->satadev_addr);
13757 		if (tdip == NULL) {
13758 			/* Configure operation failed */
13759 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13760 			    "sata_hba_ioctl: configure: "
13761 			    "configuring SATA device at port %d:%d "
13762 			    "failed", cport, pmport));
13763 			return (EIO);
13764 		}
13765 	}
13766 	return (0);
13767 }
13768 
13769 
13770 /*
13771  * Process ioctl deactivate port request.
13772  * Arbitrarily unconfigure attached device, if any.
13773  * Even if the unconfigure fails, proceed with the
13774  * port deactivation.
13775  *
13776  * NOTE: Port Multiplier is supported now.
13777  */
13778 
13779 static int
13780 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
13781     sata_device_t *sata_device)
13782 {
13783 	int cport, pmport, qual;
13784 	int rval, rv = 0;
13785 	int npmport;
13786 	sata_cport_info_t *cportinfo;
13787 	sata_pmport_info_t *pmportinfo;
13788 	sata_pmult_info_t *pmultinfo;
13789 	dev_info_t *tdip;
13790 	sata_drive_info_t *sdinfo = NULL;
13791 	sata_device_t subsdevice;
13792 
13793 	/* Sanity check */
13794 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
13795 		return (ENOTSUP);
13796 
13797 	cport = sata_device->satadev_addr.cport;
13798 	pmport = sata_device->satadev_addr.pmport;
13799 	qual = sata_device->satadev_addr.qual;
13800 
13801 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
13802 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13803 	if (qual == SATA_ADDR_DCPORT)
13804 		qual = SATA_ADDR_CPORT;
13805 	else
13806 		qual = SATA_ADDR_PMPORT;
13807 
13808 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13809 	if (qual == SATA_ADDR_PMPORT)
13810 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13811 
13812 	/*
13813 	 * Processing port multiplier
13814 	 */
13815 	if (qual == SATA_ADDR_CPORT &&
13816 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13817 		mutex_enter(&cportinfo->cport_mutex);
13818 
13819 		/* Deactivate all sub-deices */
13820 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13821 		if (pmultinfo != NULL) {
13822 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13823 			    sata_hba_inst, cport); npmport++) {
13824 
13825 				subsdevice.satadev_addr.cport = cport;
13826 				subsdevice.satadev_addr.pmport =
13827 				    (uint8_t)npmport;
13828 				subsdevice.satadev_addr.qual =
13829 				    SATA_ADDR_DPMPORT;
13830 
13831 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13832 				    "sata_hba_ioctl: deactivate: trying to "
13833 				    "deactivate SATA port %d:%d",
13834 				    cport, npmport);
13835 
13836 				mutex_exit(&cportinfo->cport_mutex);
13837 				if (sata_ioctl_deactivate(sata_hba_inst,
13838 				    &subsdevice) == SATA_SUCCESS) {
13839 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13840 					    "[Deactivate] device at port %d:%d "
13841 					    "successfully.", cport, npmport);
13842 				}
13843 				mutex_enter(&cportinfo->cport_mutex);
13844 			}
13845 		}
13846 
13847 		/* Deactivate the port multiplier now. */
13848 		cportinfo->cport_state &= ~SATA_STATE_READY;
13849 		mutex_exit(&cportinfo->cport_mutex);
13850 
13851 		sata_device->satadev_addr.qual = qual;
13852 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13853 		    (SATA_DIP(sata_hba_inst), sata_device);
13854 
13855 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13856 		    SE_NO_HINT);
13857 
13858 		mutex_enter(&cportinfo->cport_mutex);
13859 		sata_update_port_info(sata_hba_inst, sata_device);
13860 		if (rval != SATA_SUCCESS) {
13861 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13862 				cportinfo->cport_state = SATA_PSTATE_FAILED;
13863 			}
13864 			rv = EIO;
13865 		} else {
13866 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13867 		}
13868 		mutex_exit(&cportinfo->cport_mutex);
13869 
13870 		return (rv);
13871 	}
13872 
13873 	/*
13874 	 * Process non-port-multiplier device - it could be a drive connected
13875 	 * to a port multiplier port or a controller port.
13876 	 */
13877 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13878 	if (qual == SATA_ADDR_CPORT) {
13879 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
13880 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13881 			/* deal only with valid devices */
13882 			if ((cportinfo->cport_dev_type &
13883 			    SATA_VALID_DEV_TYPE) != 0)
13884 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13885 		}
13886 		cportinfo->cport_state &= ~SATA_STATE_READY;
13887 	} else {
13888 		/* Port multiplier device port */
13889 		mutex_enter(&pmportinfo->pmport_mutex);
13890 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
13891 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
13892 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
13893 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
13894 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13895 		mutex_exit(&pmportinfo->pmport_mutex);
13896 	}
13897 
13898 	if (sdinfo != NULL) {
13899 		/*
13900 		 * If a target node exists, try to offline a device and
13901 		 * to remove a target node.
13902 		 */
13903 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
13904 		    cport_mutex);
13905 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
13906 		    &sata_device->satadev_addr);
13907 		if (tdip != NULL) {
13908 			/* target node exist */
13909 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13910 			    "sata_hba_ioctl: port deactivate: "
13911 			    "target node exists.", NULL);
13912 
13913 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
13914 			    NDI_SUCCESS) {
13915 				SATA_LOG_D((sata_hba_inst, CE_WARN,
13916 				    "sata_hba_ioctl: port deactivate: "
13917 				    "failed to unconfigure device at port "
13918 				    "%d:%d before deactivating the port",
13919 				    cport, pmport));
13920 				/*
13921 				 * Set DEVICE REMOVED state in the target
13922 				 * node. It will prevent an access to
13923 				 * the device even when a new device is
13924 				 * attached, until the old target node is
13925 				 * released, removed and recreated for a new
13926 				 * device.
13927 				 */
13928 				sata_set_device_removed(tdip);
13929 
13930 				/*
13931 				 * Instruct the event daemon to try the
13932 				 * target node cleanup later.
13933 				 */
13934 				sata_set_target_node_cleanup(sata_hba_inst,
13935 				    &sata_device->satadev_addr);
13936 			}
13937 		}
13938 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
13939 		    cport_mutex);
13940 		/*
13941 		 * In any case, remove and release sata_drive_info
13942 		 * structure.
13943 		 */
13944 		if (qual == SATA_ADDR_CPORT) {
13945 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13946 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13947 		} else { /* port multiplier device port */
13948 			mutex_enter(&pmportinfo->pmport_mutex);
13949 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13950 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13951 			mutex_exit(&pmportinfo->pmport_mutex);
13952 		}
13953 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
13954 	}
13955 
13956 	if (qual == SATA_ADDR_CPORT) {
13957 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
13958 		    SATA_STATE_PROBING);
13959 	} else if (qual == SATA_ADDR_PMPORT) {
13960 		mutex_enter(&pmportinfo->pmport_mutex);
13961 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
13962 		    SATA_STATE_PROBING);
13963 		mutex_exit(&pmportinfo->pmport_mutex);
13964 	}
13965 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13966 
13967 	/* Just let HBA driver to deactivate port */
13968 	sata_device->satadev_addr.qual = qual;
13969 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13970 	    (SATA_DIP(sata_hba_inst), sata_device);
13971 
13972 	/*
13973 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13974 	 * without the hint
13975 	 */
13976 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13977 	    SE_NO_HINT);
13978 
13979 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
13980 	sata_update_port_info(sata_hba_inst, sata_device);
13981 	if (qual == SATA_ADDR_CPORT) {
13982 		if (rval != SATA_SUCCESS) {
13983 			/*
13984 			 * Port deactivation failure - do not change port state
13985 			 * unless the state returned by HBA indicates a port
13986 			 * failure.
13987 			 */
13988 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13989 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13990 				    SATA_PSTATE_FAILED;
13991 			}
13992 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13993 			    "sata_hba_ioctl: port deactivate: "
13994 			    "cannot deactivate SATA port %d", cport));
13995 			rv = EIO;
13996 		} else {
13997 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13998 		}
13999 	} else {
14000 		mutex_enter(&pmportinfo->pmport_mutex);
14001 		if (rval != SATA_SUCCESS) {
14002 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14003 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14004 				    pmport) = SATA_PSTATE_FAILED;
14005 			}
14006 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14007 			    "sata_hba_ioctl: port deactivate: "
14008 			    "cannot deactivate SATA port %d:%d",
14009 			    cport, pmport));
14010 			rv = EIO;
14011 		} else {
14012 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14013 		}
14014 		mutex_exit(&pmportinfo->pmport_mutex);
14015 	}
14016 
14017 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14018 
14019 	return (rv);
14020 }
14021 
14022 /*
14023  * Process ioctl port activate request.
14024  *
14025  * NOTE: Port multiplier is supported now.
14026  */
14027 static int
14028 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14029     sata_device_t *sata_device)
14030 {
14031 	int cport, pmport, qual;
14032 	sata_cport_info_t *cportinfo;
14033 	sata_pmport_info_t *pmportinfo = NULL;
14034 	boolean_t dev_existed = TRUE;
14035 
14036 	/* Sanity check */
14037 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14038 		return (ENOTSUP);
14039 
14040 	cport = sata_device->satadev_addr.cport;
14041 	pmport = sata_device->satadev_addr.pmport;
14042 	qual = sata_device->satadev_addr.qual;
14043 
14044 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14045 
14046 	/*
14047 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14048 	 * is a device. But what we are dealing with is port/pmport.
14049 	 */
14050 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14051 	if (qual == SATA_ADDR_DCPORT)
14052 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14053 	else
14054 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14055 
14056 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14057 	if (qual == SATA_ADDR_PMPORT) {
14058 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14059 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14060 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14061 			dev_existed = FALSE;
14062 	} else { /* cport */
14063 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14064 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14065 			dev_existed = FALSE;
14066 	}
14067 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14068 
14069 	/* Just let HBA driver to activate port, if necessary */
14070 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14071 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14072 		/*
14073 		 * Port activation failure - do not change port state unless
14074 		 * the state returned by HBA indicates a port failure.
14075 		 */
14076 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14077 		    cport)->cport_mutex);
14078 		sata_update_port_info(sata_hba_inst, sata_device);
14079 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14080 			if (qual == SATA_ADDR_PMPORT) {
14081 				mutex_enter(&pmportinfo->pmport_mutex);
14082 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14083 				mutex_exit(&pmportinfo->pmport_mutex);
14084 			} else
14085 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14086 
14087 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14088 			    cport)->cport_mutex);
14089 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14090 			    "sata_hba_ioctl: port activate: cannot activate "
14091 			    "SATA port %d:%d", cport, pmport));
14092 			return (EIO);
14093 		}
14094 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14095 	}
14096 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14097 	if (qual == SATA_ADDR_PMPORT) {
14098 		mutex_enter(&pmportinfo->pmport_mutex);
14099 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14100 		mutex_exit(&pmportinfo->pmport_mutex);
14101 	} else
14102 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14103 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14104 
14105 	/*
14106 	 * Re-probe port to find its current state and possibly attached device.
14107 	 * Port re-probing may change the cportinfo device type if device is
14108 	 * found attached.
14109 	 * If port probing failed, the device type would be set to
14110 	 * SATA_DTYPE_NONE.
14111 	 */
14112 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14113 	    SATA_DEV_IDENTIFY_RETRY);
14114 
14115 	/*
14116 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14117 	 * without the hint.
14118 	 */
14119 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14120 	    SE_NO_HINT);
14121 
14122 	if (dev_existed == FALSE) {
14123 		if (qual == SATA_ADDR_PMPORT &&
14124 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14125 			/*
14126 			 * That's the transition from the "inactive" port state
14127 			 * or the active port without a device attached to the
14128 			 * active port state with a device attached.
14129 			 */
14130 			sata_log(sata_hba_inst, CE_WARN,
14131 			    "SATA device detected at port %d:%d",
14132 			    cport, pmport);
14133 		} else if (qual == SATA_ADDR_CPORT &&
14134 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14135 			/*
14136 			 * That's the transition from the "inactive" port state
14137 			 * or the active port without a device attached to the
14138 			 * active port state with a device attached.
14139 			 */
14140 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14141 				sata_log(sata_hba_inst, CE_WARN,
14142 				    "SATA device detected at port %d", cport);
14143 			} else {
14144 				sata_log(sata_hba_inst, CE_WARN,
14145 				    "SATA port multiplier detected at port %d",
14146 				    cport);
14147 			}
14148 		}
14149 	}
14150 	return (0);
14151 }
14152 
14153 
14154 
14155 /*
14156  * Process ioctl reset port request.
14157  *
14158  * NOTE: Port-Multiplier is supported.
14159  */
14160 static int
14161 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14162     sata_device_t *sata_device)
14163 {
14164 	int cport, pmport, qual;
14165 	int rv = 0;
14166 
14167 	cport = sata_device->satadev_addr.cport;
14168 	pmport = sata_device->satadev_addr.pmport;
14169 	qual = sata_device->satadev_addr.qual;
14170 
14171 	/*
14172 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14173 	 * is a device. But what we are dealing with is port/pmport.
14174 	 */
14175 	if (qual == SATA_ADDR_DCPORT)
14176 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14177 	else
14178 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14179 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14180 
14181 	/* Sanity check */
14182 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14183 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14184 		    "sata_hba_ioctl: sata_hba_tran missing required "
14185 		    "function sata_tran_reset_dport"));
14186 		return (ENOTSUP);
14187 	}
14188 
14189 	/* Ask HBA to reset port */
14190 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14191 	    sata_device) != SATA_SUCCESS) {
14192 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14193 		    "sata_hba_ioctl: reset port: failed %d:%d",
14194 		    cport, pmport));
14195 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14196 		    cport_mutex);
14197 		sata_update_port_info(sata_hba_inst, sata_device);
14198 		if (qual == SATA_ADDR_CPORT)
14199 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14200 			    SATA_PSTATE_FAILED;
14201 		else {
14202 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14203 			    pmport));
14204 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14205 			    SATA_PSTATE_FAILED;
14206 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14207 			    pmport));
14208 		}
14209 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14210 		    cport_mutex);
14211 		rv = EIO;
14212 	}
14213 	/*
14214 	 * Beacuse the port was reset, it should be probed and
14215 	 * attached device reinitialized. At this point the
14216 	 * port state is unknown - it's state is HBA-specific.
14217 	 * Re-probe port to get its state.
14218 	 */
14219 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14220 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14221 		rv = EIO;
14222 	}
14223 	return (rv);
14224 }
14225 
14226 /*
14227  * Process ioctl reset device request.
14228  *
14229  * NOTE: Port multiplier is supported.
14230  */
14231 static int
14232 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14233     sata_device_t *sata_device)
14234 {
14235 	sata_drive_info_t *sdinfo = NULL;
14236 	sata_pmult_info_t *pmultinfo = NULL;
14237 	int cport, pmport;
14238 	int rv = 0;
14239 
14240 	/* Sanity check */
14241 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14242 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14243 		    "sata_hba_ioctl: sata_hba_tran missing required "
14244 		    "function sata_tran_reset_dport"));
14245 		return (ENOTSUP);
14246 	}
14247 
14248 	cport = sata_device->satadev_addr.cport;
14249 	pmport = sata_device->satadev_addr.pmport;
14250 
14251 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14252 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14253 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14254 		    SATA_DTYPE_PMULT)
14255 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
14256 			    cport_devp.cport_sata_pmult;
14257 		else
14258 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14259 			    sata_device->satadev_addr.cport);
14260 	} else { /* port multiplier */
14261 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14262 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14263 		    sata_device->satadev_addr.cport,
14264 		    sata_device->satadev_addr.pmport);
14265 	}
14266 	if (sdinfo == NULL && pmultinfo == NULL) {
14267 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14268 		return (EINVAL);
14269 	}
14270 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14271 
14272 	/* Ask HBA to reset device */
14273 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14274 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14275 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14276 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
14277 		    cport, pmport));
14278 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14279 		    cport_mutex);
14280 		sata_update_port_info(sata_hba_inst, sata_device);
14281 		/*
14282 		 * Device info structure remains attached. Another device reset
14283 		 * or port disconnect/connect and re-probing is
14284 		 * needed to change it's state
14285 		 */
14286 		if (sdinfo != NULL) {
14287 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
14288 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
14289 		} else if (pmultinfo != NULL) {
14290 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
14291 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
14292 		}
14293 
14294 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14295 		rv = EIO;
14296 	}
14297 	/*
14298 	 * If attached device was a port multiplier, some extra processing
14299 	 * may be needed to bring it back. SATA specification requies a
14300 	 * mandatory software reset on host port to reliably enumerate a port
14301 	 * multiplier, the HBA driver should handle that after reset
14302 	 * operation.
14303 	 */
14304 	return (rv);
14305 }
14306 
14307 
14308 /*
14309  * Process ioctl reset all request.
14310  */
14311 static int
14312 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
14313 {
14314 	sata_device_t sata_device;
14315 	int rv = 0;
14316 	int tcport;
14317 	int tpmport = 0;
14318 
14319 	sata_device.satadev_rev = SATA_DEVICE_REV;
14320 
14321 	/*
14322 	 * There is no protection here for configured devices.
14323 	 */
14324 	/* Sanity check */
14325 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14326 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14327 		    "sata_hba_ioctl: sata_hba_tran missing required "
14328 		    "function sata_tran_reset_dport"));
14329 		return (ENOTSUP);
14330 	}
14331 
14332 	/*
14333 	 * Need to lock all ports, not just one.
14334 	 * If any port is locked by event processing, fail the whole operation.
14335 	 * One port is already locked, but for simplicity lock it again.
14336 	 */
14337 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14338 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14339 		    cport_mutex);
14340 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
14341 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
14342 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14343 			    cport_mutex);
14344 			rv = EBUSY;
14345 			break;
14346 		} else {
14347 			/*
14348 			 * It is enough to lock cport in command-based
14349 			 * switching mode.
14350 			 */
14351 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
14352 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
14353 		}
14354 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14355 		    cport_mutex);
14356 	}
14357 
14358 	if (rv == 0) {
14359 		/*
14360 		 * All cports were successfully locked.
14361 		 * Reset main SATA controller.
14362 		 * Set the device address to port 0, to have a valid device
14363 		 * address.
14364 		 */
14365 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
14366 		sata_device.satadev_addr.cport = 0;
14367 		sata_device.satadev_addr.pmport = 0;
14368 
14369 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14370 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
14371 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14372 			    "sata_hba_ioctl: reset controller failed"));
14373 			return (EIO);
14374 		}
14375 		/*
14376 		 * Because ports were reset, port states are unknown.
14377 		 * They should be re-probed to get their state and
14378 		 * attached devices should be reinitialized.
14379 		 */
14380 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
14381 		    tcport++) {
14382 			sata_device.satadev_addr.cport = tcport;
14383 			sata_device.satadev_addr.pmport = tpmport;
14384 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14385 
14386 			/*
14387 			 * The sata_reprobe_port() will mark a
14388 			 * SATA_EVNT_DEVICE_RESET event on the port
14389 			 * multiplier, all its sub-ports will be probed by
14390 			 * sata daemon afterwards.
14391 			 */
14392 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
14393 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14394 				rv = EIO;
14395 		}
14396 	}
14397 	/*
14398 	 * Unlock all ports
14399 	 */
14400 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14401 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14402 		    cport_mutex);
14403 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
14404 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
14405 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14406 		    cport_mutex);
14407 	}
14408 
14409 	/*
14410 	 * This operation returns EFAULT if either reset
14411 	 * controller failed or a re-probing of any port failed.
14412 	 */
14413 	return (rv);
14414 }
14415 
14416 
14417 /*
14418  * Process ioctl port self test request.
14419  *
14420  * NOTE: Port multiplier code is not completed nor tested.
14421  */
14422 static int
14423 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
14424     sata_device_t *sata_device)
14425 {
14426 	int cport, pmport, qual;
14427 	int rv = 0;
14428 
14429 	/* Sanity check */
14430 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
14431 		return (ENOTSUP);
14432 
14433 	cport = sata_device->satadev_addr.cport;
14434 	pmport = sata_device->satadev_addr.pmport;
14435 	qual = sata_device->satadev_addr.qual;
14436 
14437 	/*
14438 	 * There is no protection here for a configured
14439 	 * device attached to this port.
14440 	 */
14441 
14442 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
14443 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14444 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14445 		    "sata_hba_ioctl: port selftest: "
14446 		    "failed port %d:%d", cport, pmport));
14447 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14448 		    cport_mutex);
14449 		sata_update_port_info(sata_hba_inst, sata_device);
14450 		if (qual == SATA_ADDR_CPORT)
14451 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14452 			    SATA_PSTATE_FAILED;
14453 		else { /* port multiplier device port */
14454 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
14455 			    cport, pmport));
14456 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14457 			    SATA_PSTATE_FAILED;
14458 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
14459 			    cport, pmport));
14460 		}
14461 
14462 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14463 		    cport_mutex);
14464 		return (EIO);
14465 	}
14466 	/*
14467 	 * Beacuse the port was reset in the course of testing, it should be
14468 	 * re-probed and attached device state should be restored. At this
14469 	 * point the port state is unknown - it's state is HBA-specific.
14470 	 * Force port re-probing to get it into a known state.
14471 	 */
14472 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14473 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14474 		rv = EIO;
14475 	return (rv);
14476 }
14477 
14478 
14479 /*
14480  * sata_cfgadm_state:
14481  * Use the sata port state and state of the target node to figure out
14482  * the cfgadm_state.
14483  *
14484  * The port argument is a value with encoded cport,
14485  * pmport and address qualifier, in the same manner as a scsi target number.
14486  * SCSI_TO_SATA_CPORT macro extracts cport number,
14487  * SCSI_TO_SATA_PMPORT extracts pmport number and
14488  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
14489  *
14490  * Port multiplier is supported.
14491  */
14492 
14493 static void
14494 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
14495     devctl_ap_state_t *ap_state)
14496 {
14497 	uint8_t		cport, pmport, qual;
14498 	uint32_t	port_state, pmult_state;
14499 	uint32_t	dev_type;
14500 	sata_drive_info_t *sdinfo;
14501 
14502 	cport = SCSI_TO_SATA_CPORT(port);
14503 	pmport = SCSI_TO_SATA_PMPORT(port);
14504 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
14505 
14506 	/* Check cport state */
14507 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
14508 	if (port_state & SATA_PSTATE_SHUTDOWN ||
14509 	    port_state & SATA_PSTATE_FAILED) {
14510 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
14511 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14512 		if (port_state & SATA_PSTATE_FAILED)
14513 			ap_state->ap_condition = AP_COND_FAILED;
14514 		else
14515 			ap_state->ap_condition = AP_COND_UNKNOWN;
14516 
14517 		return;
14518 	}
14519 
14520 	/* cport state is okay. Now check pmport state */
14521 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
14522 		/* Sanity check */
14523 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
14524 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
14525 		    cport, pmport) == NULL)
14526 			return;
14527 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
14528 		if (port_state & SATA_PSTATE_SHUTDOWN ||
14529 		    port_state & SATA_PSTATE_FAILED) {
14530 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
14531 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14532 			if (port_state & SATA_PSTATE_FAILED)
14533 				ap_state->ap_condition = AP_COND_FAILED;
14534 			else
14535 				ap_state->ap_condition = AP_COND_UNKNOWN;
14536 
14537 			return;
14538 		}
14539 	}
14540 
14541 	/* Port is enabled and ready */
14542 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
14543 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
14544 	else
14545 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
14546 
14547 	switch (dev_type) {
14548 	case SATA_DTYPE_NONE:
14549 	{
14550 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14551 		ap_state->ap_condition = AP_COND_OK;
14552 		/* No device attached */
14553 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
14554 		break;
14555 	}
14556 	case SATA_DTYPE_PMULT:
14557 	{
14558 		/* Need to check port multiplier state */
14559 		ASSERT(qual == SATA_ADDR_DCPORT);
14560 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
14561 		    pmult_state;
14562 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
14563 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
14564 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14565 			if (pmult_state & SATA_PSTATE_FAILED)
14566 				ap_state->ap_condition = AP_COND_FAILED;
14567 			else
14568 				ap_state->ap_condition = AP_COND_UNKNOWN;
14569 
14570 			return;
14571 		}
14572 
14573 		/* Port multiplier is not configurable */
14574 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
14575 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
14576 		ap_state->ap_condition = AP_COND_OK;
14577 		break;
14578 	}
14579 
14580 	case SATA_DTYPE_ATADISK:
14581 	case SATA_DTYPE_ATAPICD:
14582 	case SATA_DTYPE_ATAPITAPE:
14583 	case SATA_DTYPE_ATAPIDISK:
14584 	{
14585 		dev_info_t *tdip = NULL;
14586 		dev_info_t *dip = NULL;
14587 		int circ;
14588 
14589 		dip = SATA_DIP(sata_hba_inst);
14590 		tdip = sata_get_target_dip(dip, cport, pmport);
14591 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
14592 		if (tdip != NULL) {
14593 			ndi_devi_enter(dip, &circ);
14594 			mutex_enter(&(DEVI(tdip)->devi_lock));
14595 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
14596 				/*
14597 				 * There could be the case where previously
14598 				 * configured and opened device was removed
14599 				 * and unknown device was plugged.
14600 				 * In such case we want to show a device, and
14601 				 * its configured or unconfigured state but
14602 				 * indicate unusable condition untill the
14603 				 * old target node is released and removed.
14604 				 */
14605 				ap_state->ap_condition = AP_COND_UNUSABLE;
14606 			} else {
14607 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
14608 				    cport));
14609 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14610 				    cport);
14611 				if (sdinfo != NULL) {
14612 					if ((sdinfo->satadrv_state &
14613 					    SATA_DSTATE_FAILED) != 0)
14614 						ap_state->ap_condition =
14615 						    AP_COND_FAILED;
14616 					else
14617 						ap_state->ap_condition =
14618 						    AP_COND_OK;
14619 				} else {
14620 					ap_state->ap_condition =
14621 					    AP_COND_UNKNOWN;
14622 				}
14623 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
14624 				    cport));
14625 			}
14626 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
14627 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
14628 				ap_state->ap_ostate =
14629 				    AP_OSTATE_UNCONFIGURED;
14630 			} else {
14631 				ap_state->ap_ostate =
14632 				    AP_OSTATE_CONFIGURED;
14633 			}
14634 			mutex_exit(&(DEVI(tdip)->devi_lock));
14635 			ndi_devi_exit(dip, circ);
14636 		} else {
14637 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14638 			ap_state->ap_condition = AP_COND_UNKNOWN;
14639 		}
14640 		break;
14641 	}
14642 	default:
14643 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
14644 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
14645 		ap_state->ap_condition = AP_COND_UNKNOWN;
14646 		/*
14647 		 * This is actually internal error condition (non fatal),
14648 		 * because we have already checked all defined device types.
14649 		 */
14650 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14651 		    "sata_cfgadm_state: Internal error: "
14652 		    "unknown device type"));
14653 		break;
14654 	}
14655 }
14656 
14657 
14658 /*
14659  * Process ioctl get device path request.
14660  *
14661  * NOTE: Port multiplier has no target dip. Devices connected to port
14662  * multiplier have target node attached to the HBA node. The only difference
14663  * between them and the directly-attached device node is a target address.
14664  */
14665 static int
14666 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
14667     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
14668 {
14669 	char path[MAXPATHLEN];
14670 	uint32_t size;
14671 	dev_info_t *tdip;
14672 
14673 	(void) strcpy(path, "/devices");
14674 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14675 	    &sata_device->satadev_addr)) == NULL) {
14676 		/*
14677 		 * No such device. If this is a request for a size, do not
14678 		 * return EINVAL for non-existing target, because cfgadm
14679 		 * will then indicate a meaningless ioctl failure.
14680 		 * If this is a request for a path, indicate invalid
14681 		 * argument.
14682 		 */
14683 		if (ioc->get_size == 0)
14684 			return (EINVAL);
14685 	} else {
14686 		(void) ddi_pathname(tdip, path + strlen(path));
14687 	}
14688 	size = strlen(path) + 1;
14689 
14690 	if (ioc->get_size != 0) {
14691 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
14692 		    mode) != 0)
14693 			return (EFAULT);
14694 	} else {
14695 		if (ioc->bufsiz != size)
14696 			return (EINVAL);
14697 
14698 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
14699 		    mode) != 0)
14700 			return (EFAULT);
14701 	}
14702 	return (0);
14703 }
14704 
14705 /*
14706  * Process ioctl get attachment point type request.
14707  *
14708  * NOTE: Port multiplier is supported.
14709  */
14710 static	int
14711 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
14712     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
14713 {
14714 	uint32_t	type_len;
14715 	const char	*ap_type;
14716 	int		dev_type;
14717 
14718 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
14719 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
14720 		    sata_device->satadev_addr.cport);
14721 	else /* pmport */
14722 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
14723 		    sata_device->satadev_addr.cport,
14724 		    sata_device->satadev_addr.pmport);
14725 
14726 	switch (dev_type) {
14727 	case SATA_DTYPE_NONE:
14728 		ap_type = "port";
14729 		break;
14730 
14731 	case SATA_DTYPE_ATADISK:
14732 	case SATA_DTYPE_ATAPIDISK:
14733 		ap_type = "disk";
14734 		break;
14735 
14736 	case SATA_DTYPE_ATAPICD:
14737 		ap_type = "cd/dvd";
14738 		break;
14739 
14740 	case SATA_DTYPE_ATAPITAPE:
14741 		ap_type = "tape";
14742 		break;
14743 
14744 	case SATA_DTYPE_PMULT:
14745 		ap_type = "sata-pmult";
14746 		break;
14747 
14748 	case SATA_DTYPE_UNKNOWN:
14749 		ap_type = "unknown";
14750 		break;
14751 
14752 	default:
14753 		ap_type = "unsupported";
14754 		break;
14755 
14756 	} /* end of dev_type switch */
14757 
14758 	type_len = strlen(ap_type) + 1;
14759 
14760 	if (ioc->get_size) {
14761 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
14762 		    mode) != 0)
14763 			return (EFAULT);
14764 	} else {
14765 		if (ioc->bufsiz != type_len)
14766 			return (EINVAL);
14767 
14768 		if (ddi_copyout((void *)ap_type, ioc->buf,
14769 		    ioc->bufsiz, mode) != 0)
14770 			return (EFAULT);
14771 	}
14772 	return (0);
14773 
14774 }
14775 
14776 /*
14777  * Process ioctl get device model info request.
14778  * This operation should return to cfgadm the device model
14779  * information string
14780  *
14781  * NOTE: Port multiplier is supported.
14782  */
14783 static	int
14784 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
14785     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
14786 {
14787 	sata_drive_info_t *sdinfo;
14788 	uint32_t info_len;
14789 	char ap_info[SATA_ID_MODEL_LEN + 1];
14790 
14791 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14792 	    sata_device->satadev_addr.cport)->cport_mutex);
14793 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
14794 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14795 		    sata_device->satadev_addr.cport);
14796 	else /* port multiplier */
14797 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14798 		    sata_device->satadev_addr.cport,
14799 		    sata_device->satadev_addr.pmport);
14800 	if (sdinfo == NULL) {
14801 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14802 		    sata_device->satadev_addr.cport)->cport_mutex);
14803 		return (EINVAL);
14804 	}
14805 
14806 #ifdef	_LITTLE_ENDIAN
14807 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
14808 #else	/* _LITTLE_ENDIAN */
14809 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
14810 #endif	/* _LITTLE_ENDIAN */
14811 
14812 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14813 	    sata_device->satadev_addr.cport)->cport_mutex);
14814 
14815 	ap_info[SATA_ID_MODEL_LEN] = '\0';
14816 
14817 	info_len = strlen(ap_info) + 1;
14818 
14819 	if (ioc->get_size) {
14820 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
14821 		    mode) != 0)
14822 			return (EFAULT);
14823 	} else {
14824 		if (ioc->bufsiz < info_len)
14825 			return (EINVAL);
14826 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
14827 		    mode) != 0)
14828 			return (EFAULT);
14829 	}
14830 	return (0);
14831 }
14832 
14833 
14834 /*
14835  * Process ioctl get device firmware revision info request.
14836  * This operation should return to cfgadm the device firmware revision
14837  * information string
14838  *
14839  * Port multiplier is supported.
14840  */
14841 static	int
14842 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
14843     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
14844 {
14845 	sata_drive_info_t *sdinfo;
14846 	uint32_t info_len;
14847 	char ap_info[SATA_ID_FW_LEN + 1];
14848 
14849 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14850 	    sata_device->satadev_addr.cport)->cport_mutex);
14851 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
14852 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14853 		    sata_device->satadev_addr.cport);
14854 	else /* port multiplier */
14855 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14856 		    sata_device->satadev_addr.cport,
14857 		    sata_device->satadev_addr.pmport);
14858 	if (sdinfo == NULL) {
14859 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14860 		    sata_device->satadev_addr.cport)->cport_mutex);
14861 		return (EINVAL);
14862 	}
14863 
14864 #ifdef	_LITTLE_ENDIAN
14865 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
14866 #else	/* _LITTLE_ENDIAN */
14867 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
14868 #endif	/* _LITTLE_ENDIAN */
14869 
14870 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14871 	    sata_device->satadev_addr.cport)->cport_mutex);
14872 
14873 	ap_info[SATA_ID_FW_LEN] = '\0';
14874 
14875 	info_len = strlen(ap_info) + 1;
14876 
14877 	if (ioc->get_size) {
14878 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
14879 		    mode) != 0)
14880 			return (EFAULT);
14881 	} else {
14882 		if (ioc->bufsiz < info_len)
14883 			return (EINVAL);
14884 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
14885 		    mode) != 0)
14886 			return (EFAULT);
14887 	}
14888 	return (0);
14889 }
14890 
14891 
14892 /*
14893  * Process ioctl get device serial number info request.
14894  * This operation should return to cfgadm the device serial number string.
14895  *
14896  * NOTE: Port multiplier is supported.
14897  */
14898 static	int
14899 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
14900     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
14901 {
14902 	sata_drive_info_t *sdinfo;
14903 	uint32_t info_len;
14904 	char ap_info[SATA_ID_SERIAL_LEN + 1];
14905 
14906 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14907 	    sata_device->satadev_addr.cport)->cport_mutex);
14908 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
14909 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14910 		    sata_device->satadev_addr.cport);
14911 	else /* port multiplier */
14912 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14913 		    sata_device->satadev_addr.cport,
14914 		    sata_device->satadev_addr.pmport);
14915 	if (sdinfo == NULL) {
14916 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14917 		    sata_device->satadev_addr.cport)->cport_mutex);
14918 		return (EINVAL);
14919 	}
14920 
14921 #ifdef	_LITTLE_ENDIAN
14922 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
14923 #else	/* _LITTLE_ENDIAN */
14924 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
14925 #endif	/* _LITTLE_ENDIAN */
14926 
14927 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14928 	    sata_device->satadev_addr.cport)->cport_mutex);
14929 
14930 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
14931 
14932 	info_len = strlen(ap_info) + 1;
14933 
14934 	if (ioc->get_size) {
14935 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
14936 		    mode) != 0)
14937 			return (EFAULT);
14938 	} else {
14939 		if (ioc->bufsiz < info_len)
14940 			return (EINVAL);
14941 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
14942 		    mode) != 0)
14943 			return (EFAULT);
14944 	}
14945 	return (0);
14946 }
14947 
14948 
14949 /*
14950  * Preset scsi extended sense data (to NO SENSE)
14951  * First 18 bytes of the sense data are preset to current valid sense
14952  * with a key NO SENSE data.
14953  *
14954  * Returns void
14955  */
14956 static void
14957 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
14958 {
14959 	sense->es_valid = 1;		/* Valid sense */
14960 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
14961 	sense->es_key = KEY_NO_SENSE;
14962 	sense->es_info_1 = 0;
14963 	sense->es_info_2 = 0;
14964 	sense->es_info_3 = 0;
14965 	sense->es_info_4 = 0;
14966 	sense->es_add_len = 10;	/* Additional length - replace with a def */
14967 	sense->es_cmd_info[0] = 0;
14968 	sense->es_cmd_info[1] = 0;
14969 	sense->es_cmd_info[2] = 0;
14970 	sense->es_cmd_info[3] = 0;
14971 	sense->es_add_code = 0;
14972 	sense->es_qual_code = 0;
14973 }
14974 
14975 /*
14976  * Register a legacy cmdk-style devid for the target (disk) device.
14977  *
14978  * Note: This function is called only when the HBA devinfo node has the
14979  * property "use-cmdk-devid-format" set. This property indicates that
14980  * devid compatible with old cmdk (target) driver is to be generated
14981  * for any target device attached to this controller. This will take
14982  * precedence over the devid generated by sd (target) driver.
14983  * This function is derived from cmdk_devid_setup() function in cmdk.c.
14984  */
14985 static void
14986 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
14987 {
14988 	char	*hwid;
14989 	int	modlen;
14990 	int	serlen;
14991 	int	rval;
14992 	ddi_devid_t	devid;
14993 
14994 	/*
14995 	 * device ID is a concatanation of model number, "=", serial number.
14996 	 */
14997 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
14998 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
14999 	    sizeof (sdinfo->satadrv_id.ai_model));
15000 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15001 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15002 	if (modlen == 0)
15003 		goto err;
15004 	hwid[modlen++] = '=';
15005 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15006 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15007 	swab(&hwid[modlen], &hwid[modlen],
15008 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15009 	serlen = sata_check_modser(&hwid[modlen],
15010 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15011 	if (serlen == 0)
15012 		goto err;
15013 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15014 
15015 	/* initialize/register devid */
15016 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15017 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15018 		rval = ddi_devid_register(dip, devid);
15019 		/*
15020 		 * Free up the allocated devid buffer.
15021 		 * NOTE: This doesn't mean unregistering devid.
15022 		 */
15023 		ddi_devid_free(devid);
15024 	}
15025 
15026 	if (rval != DDI_SUCCESS)
15027 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15028 		    " on port %d", sdinfo->satadrv_addr.cport);
15029 err:
15030 	kmem_free(hwid, LEGACY_HWID_LEN);
15031 }
15032 
15033 /*
15034  * valid model/serial string must contain a non-zero non-space characters.
15035  * trim trailing spaces/NULLs.
15036  */
15037 static int
15038 sata_check_modser(char *buf, int buf_len)
15039 {
15040 	boolean_t ret;
15041 	char *s;
15042 	int i;
15043 	int tb;
15044 	char ch;
15045 
15046 	ret = B_FALSE;
15047 	s = buf;
15048 	for (i = 0; i < buf_len; i++) {
15049 		ch = *s++;
15050 		if (ch != ' ' && ch != '\0')
15051 			tb = i + 1;
15052 		if (ch != ' ' && ch != '\0' && ch != '0')
15053 			ret = B_TRUE;
15054 	}
15055 
15056 	if (ret == B_FALSE)
15057 		return (0); /* invalid string */
15058 
15059 	return (tb); /* return length */
15060 }
15061 
15062 /*
15063  * sata_set_drive_features function compares current device features setting
15064  * with the saved device features settings and, if there is a difference,
15065  * it restores device features setting to the previously saved state.
15066  * It also arbitrarily tries to select the highest supported DMA mode.
15067  * Device Identify or Identify Packet Device data has to be current.
15068  * At the moment read ahead and write cache are considered for all devices.
15069  * For atapi devices, Removable Media Status Notification is set in addition
15070  * to common features.
15071  *
15072  * This function cannot be called in the interrupt context (it may sleep).
15073  *
15074  * The input argument sdinfo should point to the drive info structure
15075  * to be updated after features are set. Note, that only
15076  * device (packet) identify data is updated, not the flags indicating the
15077  * supported features.
15078  *
15079  * Returns SATA_SUCCESS if successful or there was nothing to do.
15080  * Device Identify data in the drive info structure pointed to by the sdinfo
15081  * arguments is updated even when no features were set or changed.
15082  *
15083  * Returns SATA_FAILURE if device features could not be set or DMA mode
15084  * for a disk cannot be set and device identify data cannot be fetched.
15085  *
15086  * Returns SATA_RETRY if device features could not be set (other than disk
15087  * DMA mode) but the device identify data was fetched successfully.
15088  *
15089  * Note: This function may fail the port, making it inaccessible.
15090  * In such case the explicit port disconnect/connect or physical device
15091  * detach/attach is required to re-evaluate port state again.
15092  */
15093 
15094 static int
15095 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15096     sata_drive_info_t *sdinfo, int restore)
15097 {
15098 	int rval = SATA_SUCCESS;
15099 	int rval_set;
15100 	sata_drive_info_t new_sdinfo;
15101 	char *finfo = "sata_set_drive_features: cannot";
15102 	char *finfox;
15103 	int cache_op;
15104 
15105 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15106 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15107 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15108 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15109 		/*
15110 		 * Cannot get device identification - caller may retry later
15111 		 */
15112 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15113 		    "%s fetch device identify data\n", finfo);
15114 		return (SATA_FAILURE);
15115 	}
15116 	finfox = (restore != 0) ? " restore device features" :
15117 	    " initialize device features\n";
15118 
15119 	switch (sdinfo->satadrv_type) {
15120 	case SATA_DTYPE_ATADISK:
15121 		/* Arbitrarily set UDMA mode */
15122 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15123 		    SATA_SUCCESS) {
15124 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15125 			    "%s set UDMA mode\n", finfo));
15126 			return (SATA_FAILURE);
15127 		}
15128 		break;
15129 	case SATA_DTYPE_ATAPICD:
15130 	case SATA_DTYPE_ATAPITAPE:
15131 	case SATA_DTYPE_ATAPIDISK:
15132 		/*  Set Removable Media Status Notification, if necessary */
15133 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15134 		    restore != 0) {
15135 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15136 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15137 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15138 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15139 				/* Current setting does not match saved one */
15140 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15141 				    sdinfo->satadrv_settings &
15142 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15143 					rval = SATA_FAILURE;
15144 			}
15145 		}
15146 		/*
15147 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15148 		 * we want to use DMA transfer mode whenever possible.
15149 		 * Some devices require explicit setting of the DMA mode.
15150 		 */
15151 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15152 			/* Set highest supported DMA mode */
15153 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15154 			    SATA_SUCCESS) {
15155 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15156 				    "%s set UDMA mode\n", finfo));
15157 				rval = SATA_FAILURE;
15158 			}
15159 		}
15160 		break;
15161 	}
15162 
15163 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15164 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15165 		/*
15166 		 * neither READ AHEAD nor WRITE CACHE is supported
15167 		 * - do nothing
15168 		 */
15169 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15170 		    "settable features not supported\n", NULL);
15171 		goto update_sdinfo;
15172 	}
15173 
15174 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15175 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15176 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15177 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15178 		/*
15179 		 * both READ AHEAD and WRITE CACHE are enabled
15180 		 * - Nothing to do
15181 		 */
15182 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15183 		    "no device features to set\n", NULL);
15184 		goto update_sdinfo;
15185 	}
15186 
15187 	cache_op = 0;
15188 
15189 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15190 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15191 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15192 			/* Enable read ahead / read cache */
15193 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15194 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15195 			    "enabling read cache\n", NULL);
15196 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15197 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15198 			/* Disable read ahead  / read cache */
15199 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15200 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15201 			    "disabling read cache\n", NULL);
15202 		}
15203 
15204 		if (cache_op != 0) {
15205 			/* Try to set read cache mode */
15206 			rval_set = sata_set_cache_mode(sata_hba_inst,
15207 			    &new_sdinfo, cache_op);
15208 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15209 				rval = rval_set;
15210 		}
15211 	}
15212 
15213 	cache_op = 0;
15214 
15215 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15216 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15217 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15218 			/* Enable write cache */
15219 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15220 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15221 			    "enabling write cache\n", NULL);
15222 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15223 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15224 			/* Disable write cache */
15225 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15226 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15227 			    "disabling write cache\n", NULL);
15228 		}
15229 
15230 		if (cache_op != 0) {
15231 			/* Try to set write cache mode */
15232 			rval_set = sata_set_cache_mode(sata_hba_inst,
15233 			    &new_sdinfo, cache_op);
15234 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15235 				rval = rval_set;
15236 		}
15237 	}
15238 	if (rval != SATA_SUCCESS)
15239 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15240 		    "%s %s", finfo, finfox));
15241 
15242 update_sdinfo:
15243 	/*
15244 	 * We need to fetch Device Identify data again
15245 	 */
15246 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15247 		/*
15248 		 * Cannot get device identification - retry later
15249 		 */
15250 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15251 		    "%s re-fetch device identify data\n", finfo));
15252 		rval = SATA_FAILURE;
15253 	}
15254 	/* Copy device sata info. */
15255 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
15256 
15257 	return (rval);
15258 }
15259 
15260 
15261 /*
15262  *
15263  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
15264  * unable to determine.
15265  *
15266  * Cannot be called in an interrupt context.
15267  *
15268  * Called by sata_build_lsense_page_2f()
15269  */
15270 
15271 static int
15272 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
15273     sata_drive_info_t *sdinfo)
15274 {
15275 	sata_pkt_t *spkt;
15276 	sata_cmd_t *scmd;
15277 	sata_pkt_txlate_t *spx;
15278 	int rval;
15279 
15280 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15281 	spx->txlt_sata_hba_inst = sata_hba_inst;
15282 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15283 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15284 	if (spkt == NULL) {
15285 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15286 		return (-1);
15287 	}
15288 	/* address is needed now */
15289 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15290 
15291 
15292 	/* Fill sata_pkt */
15293 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15294 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15295 	/* Synchronous mode, no callback */
15296 	spkt->satapkt_comp = NULL;
15297 	/* Timeout 30s */
15298 	spkt->satapkt_time = sata_default_pkt_time;
15299 
15300 	scmd = &spkt->satapkt_cmd;
15301 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
15302 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
15303 
15304 	/* Set up which registers need to be returned */
15305 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
15306 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
15307 
15308 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
15309 	scmd->satacmd_addr_type = 0;		/* N/A */
15310 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15311 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15312 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15313 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15314 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
15315 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15316 	scmd->satacmd_cmd_reg = SATAC_SMART;
15317 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15318 	    sdinfo->satadrv_addr.cport)));
15319 
15320 
15321 	/* Send pkt to SATA HBA driver */
15322 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15323 	    SATA_TRAN_ACCEPTED ||
15324 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15325 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15326 		    sdinfo->satadrv_addr.cport)));
15327 		/*
15328 		 * Whoops, no SMART RETURN STATUS
15329 		 */
15330 		rval = -1;
15331 	} else {
15332 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15333 		    sdinfo->satadrv_addr.cport)));
15334 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
15335 			rval = -1;
15336 			goto fail;
15337 		}
15338 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
15339 			rval = -1;
15340 			goto fail;
15341 		}
15342 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
15343 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
15344 			rval = 0;
15345 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
15346 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
15347 			rval = 1;
15348 		else {
15349 			rval = -1;
15350 			goto fail;
15351 		}
15352 	}
15353 fail:
15354 	/* Free allocated resources */
15355 	sata_pkt_free(spx);
15356 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15357 
15358 	return (rval);
15359 }
15360 
15361 /*
15362  *
15363  * Returns 0 if succeeded, -1 otherwise
15364  *
15365  * Cannot be called in an interrupt context.
15366  *
15367  */
15368 static int
15369 sata_fetch_smart_data(
15370 	sata_hba_inst_t *sata_hba_inst,
15371 	sata_drive_info_t *sdinfo,
15372 	struct smart_data *smart_data)
15373 {
15374 	sata_pkt_t *spkt;
15375 	sata_cmd_t *scmd;
15376 	sata_pkt_txlate_t *spx;
15377 	int rval;
15378 
15379 #if ! defined(lint)
15380 	ASSERT(sizeof (struct smart_data) == 512);
15381 #endif
15382 
15383 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15384 	spx->txlt_sata_hba_inst = sata_hba_inst;
15385 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15386 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15387 	if (spkt == NULL) {
15388 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15389 		return (-1);
15390 	}
15391 	/* address is needed now */
15392 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15393 
15394 
15395 	/* Fill sata_pkt */
15396 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15397 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15398 	/* Synchronous mode, no callback */
15399 	spkt->satapkt_comp = NULL;
15400 	/* Timeout 30s */
15401 	spkt->satapkt_time = sata_default_pkt_time;
15402 
15403 	scmd = &spkt->satapkt_cmd;
15404 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15405 
15406 	/*
15407 	 * Allocate buffer for SMART data
15408 	 */
15409 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15410 	    sizeof (struct smart_data));
15411 	if (scmd->satacmd_bp == NULL) {
15412 		sata_pkt_free(spx);
15413 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15414 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15415 		    "sata_fetch_smart_data: "
15416 		    "cannot allocate buffer"));
15417 		return (-1);
15418 	}
15419 
15420 
15421 	/* Build SMART_READ_DATA cmd in the sata_pkt */
15422 	scmd->satacmd_addr_type = 0;		/* N/A */
15423 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15424 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15425 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15426 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15427 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
15428 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15429 	scmd->satacmd_cmd_reg = SATAC_SMART;
15430 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15431 	    sdinfo->satadrv_addr.cport)));
15432 
15433 	/* Send pkt to SATA HBA driver */
15434 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15435 	    SATA_TRAN_ACCEPTED ||
15436 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15437 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15438 		    sdinfo->satadrv_addr.cport)));
15439 		/*
15440 		 * Whoops, no SMART DATA available
15441 		 */
15442 		rval = -1;
15443 		goto fail;
15444 	} else {
15445 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15446 		    sdinfo->satadrv_addr.cport)));
15447 		if (spx->txlt_buf_dma_handle != NULL) {
15448 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
15449 			    DDI_DMA_SYNC_FORKERNEL);
15450 			ASSERT(rval == DDI_SUCCESS);
15451 		}
15452 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
15453 		    sizeof (struct smart_data));
15454 	}
15455 
15456 fail:
15457 	/* Free allocated resources */
15458 	sata_free_local_buffer(spx);
15459 	sata_pkt_free(spx);
15460 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15461 
15462 	return (rval);
15463 }
15464 
15465 /*
15466  * Used by LOG SENSE page 0x10
15467  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
15468  * Note: cannot be called in the interrupt context.
15469  *
15470  * return 0 for success, -1 otherwise
15471  *
15472  */
15473 static int
15474 sata_ext_smart_selftest_read_log(
15475 	sata_hba_inst_t *sata_hba_inst,
15476 	sata_drive_info_t *sdinfo,
15477 	struct smart_ext_selftest_log *ext_selftest_log,
15478 	uint16_t block_num)
15479 {
15480 	sata_pkt_txlate_t *spx;
15481 	sata_pkt_t *spkt;
15482 	sata_cmd_t *scmd;
15483 	int rval;
15484 
15485 #if ! defined(lint)
15486 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
15487 #endif
15488 
15489 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15490 	spx->txlt_sata_hba_inst = sata_hba_inst;
15491 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15492 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15493 	if (spkt == NULL) {
15494 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15495 		return (-1);
15496 	}
15497 	/* address is needed now */
15498 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15499 
15500 
15501 	/* Fill sata_pkt */
15502 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15503 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15504 	/* Synchronous mode, no callback */
15505 	spkt->satapkt_comp = NULL;
15506 	/* Timeout 30s */
15507 	spkt->satapkt_time = sata_default_pkt_time;
15508 
15509 	scmd = &spkt->satapkt_cmd;
15510 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15511 
15512 	/*
15513 	 * Allocate buffer for SMART extended self-test log
15514 	 */
15515 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15516 	    sizeof (struct smart_ext_selftest_log));
15517 	if (scmd->satacmd_bp == NULL) {
15518 		sata_pkt_free(spx);
15519 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15520 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15521 		    "sata_ext_smart_selftest_log: "
15522 		    "cannot allocate buffer"));
15523 		return (-1);
15524 	}
15525 
15526 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
15527 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
15528 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
15529 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
15530 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
15531 	scmd->satacmd_lba_low_msb = 0;
15532 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
15533 	scmd->satacmd_lba_mid_msb = block_num >> 8;
15534 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15535 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
15536 
15537 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15538 	    sdinfo->satadrv_addr.cport)));
15539 
15540 	/* Send pkt to SATA HBA driver */
15541 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15542 	    SATA_TRAN_ACCEPTED ||
15543 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15544 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15545 		    sdinfo->satadrv_addr.cport)));
15546 
15547 		/*
15548 		 * Whoops, no SMART selftest log info available
15549 		 */
15550 		rval = -1;
15551 		goto fail;
15552 	} else {
15553 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15554 		    sdinfo->satadrv_addr.cport)));
15555 
15556 		if (spx->txlt_buf_dma_handle != NULL) {
15557 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
15558 			    DDI_DMA_SYNC_FORKERNEL);
15559 			ASSERT(rval == DDI_SUCCESS);
15560 		}
15561 		bcopy(scmd->satacmd_bp->b_un.b_addr,
15562 		    (uint8_t *)ext_selftest_log,
15563 		    sizeof (struct smart_ext_selftest_log));
15564 		rval = 0;
15565 	}
15566 
15567 fail:
15568 	/* Free allocated resources */
15569 	sata_free_local_buffer(spx);
15570 	sata_pkt_free(spx);
15571 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15572 
15573 	return (rval);
15574 }
15575 
15576 /*
15577  * Returns 0 for success, -1 otherwise
15578  *
15579  * SMART self-test log data is returned in buffer pointed to by selftest_log
15580  */
15581 static int
15582 sata_smart_selftest_log(
15583 	sata_hba_inst_t *sata_hba_inst,
15584 	sata_drive_info_t *sdinfo,
15585 	struct smart_selftest_log *selftest_log)
15586 {
15587 	sata_pkt_t *spkt;
15588 	sata_cmd_t *scmd;
15589 	sata_pkt_txlate_t *spx;
15590 	int rval;
15591 
15592 #if ! defined(lint)
15593 	ASSERT(sizeof (struct smart_selftest_log) == 512);
15594 #endif
15595 
15596 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15597 	spx->txlt_sata_hba_inst = sata_hba_inst;
15598 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15599 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15600 	if (spkt == NULL) {
15601 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15602 		return (-1);
15603 	}
15604 	/* address is needed now */
15605 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15606 
15607 
15608 	/* Fill sata_pkt */
15609 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15610 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15611 	/* Synchronous mode, no callback */
15612 	spkt->satapkt_comp = NULL;
15613 	/* Timeout 30s */
15614 	spkt->satapkt_time = sata_default_pkt_time;
15615 
15616 	scmd = &spkt->satapkt_cmd;
15617 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15618 
15619 	/*
15620 	 * Allocate buffer for SMART SELFTEST LOG
15621 	 */
15622 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15623 	    sizeof (struct smart_selftest_log));
15624 	if (scmd->satacmd_bp == NULL) {
15625 		sata_pkt_free(spx);
15626 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15627 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15628 		    "sata_smart_selftest_log: "
15629 		    "cannot allocate buffer"));
15630 		return (-1);
15631 	}
15632 
15633 	/* Build SMART_READ_LOG cmd in the sata_pkt */
15634 	scmd->satacmd_addr_type = 0;		/* N/A */
15635 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
15636 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
15637 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15638 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15639 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
15640 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15641 	scmd->satacmd_cmd_reg = SATAC_SMART;
15642 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15643 	    sdinfo->satadrv_addr.cport)));
15644 
15645 	/* Send pkt to SATA HBA driver */
15646 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15647 	    SATA_TRAN_ACCEPTED ||
15648 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15649 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15650 		    sdinfo->satadrv_addr.cport)));
15651 		/*
15652 		 * Whoops, no SMART DATA available
15653 		 */
15654 		rval = -1;
15655 		goto fail;
15656 	} else {
15657 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15658 		    sdinfo->satadrv_addr.cport)));
15659 		if (spx->txlt_buf_dma_handle != NULL) {
15660 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
15661 			    DDI_DMA_SYNC_FORKERNEL);
15662 			ASSERT(rval == DDI_SUCCESS);
15663 		}
15664 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
15665 		    sizeof (struct smart_selftest_log));
15666 		rval = 0;
15667 	}
15668 
15669 fail:
15670 	/* Free allocated resources */
15671 	sata_free_local_buffer(spx);
15672 	sata_pkt_free(spx);
15673 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15674 
15675 	return (rval);
15676 }
15677 
15678 
15679 /*
15680  * Returns 0 for success, -1 otherwise
15681  *
15682  * SMART READ LOG data is returned in buffer pointed to by smart_log
15683  */
15684 static int
15685 sata_smart_read_log(
15686 	sata_hba_inst_t *sata_hba_inst,
15687 	sata_drive_info_t *sdinfo,
15688 	uint8_t *smart_log,		/* where the data should be returned */
15689 	uint8_t which_log,		/* which log should be returned */
15690 	uint8_t log_size)		/* # of 512 bytes in log */
15691 {
15692 	sata_pkt_t *spkt;
15693 	sata_cmd_t *scmd;
15694 	sata_pkt_txlate_t *spx;
15695 	int rval;
15696 
15697 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15698 	spx->txlt_sata_hba_inst = sata_hba_inst;
15699 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15700 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15701 	if (spkt == NULL) {
15702 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15703 		return (-1);
15704 	}
15705 	/* address is needed now */
15706 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15707 
15708 
15709 	/* Fill sata_pkt */
15710 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15711 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15712 	/* Synchronous mode, no callback */
15713 	spkt->satapkt_comp = NULL;
15714 	/* Timeout 30s */
15715 	spkt->satapkt_time = sata_default_pkt_time;
15716 
15717 	scmd = &spkt->satapkt_cmd;
15718 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15719 
15720 	/*
15721 	 * Allocate buffer for SMART READ LOG
15722 	 */
15723 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
15724 	if (scmd->satacmd_bp == NULL) {
15725 		sata_pkt_free(spx);
15726 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15727 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15728 		    "sata_smart_read_log: " "cannot allocate buffer"));
15729 		return (-1);
15730 	}
15731 
15732 	/* Build SMART_READ_LOG cmd in the sata_pkt */
15733 	scmd->satacmd_addr_type = 0;		/* N/A */
15734 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
15735 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
15736 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15737 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15738 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
15739 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15740 	scmd->satacmd_cmd_reg = SATAC_SMART;
15741 
15742 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15743 	    sdinfo->satadrv_addr.cport)));
15744 
15745 	/* Send pkt to SATA HBA driver */
15746 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15747 	    SATA_TRAN_ACCEPTED ||
15748 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15749 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15750 		    sdinfo->satadrv_addr.cport)));
15751 
15752 		/*
15753 		 * Whoops, no SMART DATA available
15754 		 */
15755 		rval = -1;
15756 		goto fail;
15757 	} else {
15758 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15759 		    sdinfo->satadrv_addr.cport)));
15760 
15761 		if (spx->txlt_buf_dma_handle != NULL) {
15762 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
15763 			    DDI_DMA_SYNC_FORKERNEL);
15764 			ASSERT(rval == DDI_SUCCESS);
15765 		}
15766 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
15767 		rval = 0;
15768 	}
15769 
15770 fail:
15771 	/* Free allocated resources */
15772 	sata_free_local_buffer(spx);
15773 	sata_pkt_free(spx);
15774 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15775 
15776 	return (rval);
15777 }
15778 
15779 /*
15780  * Used by LOG SENSE page 0x10
15781  *
15782  * return 0 for success, -1 otherwise
15783  *
15784  */
15785 static int
15786 sata_read_log_ext_directory(
15787 	sata_hba_inst_t *sata_hba_inst,
15788 	sata_drive_info_t *sdinfo,
15789 	struct read_log_ext_directory *logdir)
15790 {
15791 	sata_pkt_txlate_t *spx;
15792 	sata_pkt_t *spkt;
15793 	sata_cmd_t *scmd;
15794 	int rval;
15795 
15796 #if ! defined(lint)
15797 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
15798 #endif
15799 
15800 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15801 	spx->txlt_sata_hba_inst = sata_hba_inst;
15802 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15803 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15804 	if (spkt == NULL) {
15805 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15806 		return (-1);
15807 	}
15808 
15809 	/* Fill sata_pkt */
15810 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15811 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15812 	/* Synchronous mode, no callback */
15813 	spkt->satapkt_comp = NULL;
15814 	/* Timeout 30s */
15815 	spkt->satapkt_time = sata_default_pkt_time;
15816 
15817 	scmd = &spkt->satapkt_cmd;
15818 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15819 
15820 	/*
15821 	 * Allocate buffer for SMART READ LOG EXTENDED command
15822 	 */
15823 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15824 	    sizeof (struct read_log_ext_directory));
15825 	if (scmd->satacmd_bp == NULL) {
15826 		sata_pkt_free(spx);
15827 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15828 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15829 		    "sata_read_log_ext_directory: "
15830 		    "cannot allocate buffer"));
15831 		return (-1);
15832 	}
15833 
15834 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
15835 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
15836 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
15837 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
15838 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
15839 	scmd->satacmd_lba_low_msb = 0;
15840 	scmd->satacmd_lba_mid_lsb = 0;
15841 	scmd->satacmd_lba_mid_msb = 0;
15842 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15843 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
15844 
15845 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15846 	    sdinfo->satadrv_addr.cport)));
15847 
15848 	/* Send pkt to SATA HBA driver */
15849 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15850 	    SATA_TRAN_ACCEPTED ||
15851 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15852 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15853 		    sdinfo->satadrv_addr.cport)));
15854 		/*
15855 		 * Whoops, no SMART selftest log info available
15856 		 */
15857 		rval = -1;
15858 		goto fail;
15859 	} else {
15860 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15861 		    sdinfo->satadrv_addr.cport)));
15862 		if (spx->txlt_buf_dma_handle != NULL) {
15863 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
15864 			    DDI_DMA_SYNC_FORKERNEL);
15865 			ASSERT(rval == DDI_SUCCESS);
15866 		}
15867 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
15868 		    sizeof (struct read_log_ext_directory));
15869 		rval = 0;
15870 	}
15871 
15872 fail:
15873 	/* Free allocated resources */
15874 	sata_free_local_buffer(spx);
15875 	sata_pkt_free(spx);
15876 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15877 
15878 	return (rval);
15879 }
15880 
15881 /*
15882  * Set up error retrieval sata command for NCQ command error data
15883  * recovery.
15884  *
15885  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
15886  * returns SATA_FAILURE otherwise.
15887  */
15888 static int
15889 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
15890 {
15891 #ifndef __lock_lint
15892 	_NOTE(ARGUNUSED(sdinfo))
15893 #endif
15894 
15895 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
15896 	sata_cmd_t *scmd;
15897 	struct buf *bp;
15898 
15899 	/* Operation modes are up to the caller */
15900 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15901 
15902 	/* Synchronous mode, no callback - may be changed by the caller */
15903 	spkt->satapkt_comp = NULL;
15904 	spkt->satapkt_time = sata_default_pkt_time;
15905 
15906 	scmd = &spkt->satapkt_cmd;
15907 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
15908 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
15909 
15910 	/*
15911 	 * Allocate dma_able buffer error data.
15912 	 * Buffer allocation will take care of buffer alignment and other DMA
15913 	 * attributes.
15914 	 */
15915 	bp = sata_alloc_local_buffer(spx,
15916 	    sizeof (struct sata_ncq_error_recovery_page));
15917 	if (bp == NULL)
15918 		return (SATA_FAILURE);
15919 
15920 	bp_mapin(bp); /* make data buffer accessible */
15921 	scmd->satacmd_bp = bp;
15922 
15923 	/*
15924 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
15925 	 * before accessing it. Handle is in usual place in translate struct.
15926 	 */
15927 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
15928 
15929 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
15930 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
15931 
15932 	return (SATA_SUCCESS);
15933 }
15934 
15935 /*
15936  * sata_xlate_errors() is used to translate (S)ATA error
15937  * information to SCSI information returned in the SCSI
15938  * packet.
15939  */
15940 static void
15941 sata_xlate_errors(sata_pkt_txlate_t *spx)
15942 {
15943 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
15944 	struct scsi_extended_sense *sense;
15945 
15946 	scsipkt->pkt_reason = CMD_INCOMPLETE;
15947 	*scsipkt->pkt_scbp = STATUS_CHECK;
15948 	sense = sata_arq_sense(spx);
15949 
15950 	switch (spx->txlt_sata_pkt->satapkt_reason) {
15951 	case SATA_PKT_PORT_ERROR:
15952 		/*
15953 		 * We have no device data. Assume no data transfered.
15954 		 */
15955 		sense->es_key = KEY_HARDWARE_ERROR;
15956 		break;
15957 
15958 	case SATA_PKT_DEV_ERROR:
15959 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
15960 		    SATA_STATUS_ERR) {
15961 			/*
15962 			 * determine dev error reason from error
15963 			 * reg content
15964 			 */
15965 			sata_decode_device_error(spx, sense);
15966 			break;
15967 		}
15968 		/* No extended sense key - no info available */
15969 		break;
15970 
15971 	case SATA_PKT_TIMEOUT:
15972 		scsipkt->pkt_reason = CMD_TIMEOUT;
15973 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
15974 		/* No extended sense key */
15975 		break;
15976 
15977 	case SATA_PKT_ABORTED:
15978 		scsipkt->pkt_reason = CMD_ABORTED;
15979 		scsipkt->pkt_statistics |= STAT_ABORTED;
15980 		/* No extended sense key */
15981 		break;
15982 
15983 	case SATA_PKT_RESET:
15984 		/*
15985 		 * pkt aborted either by an explicit reset request from
15986 		 * a host, or due to error recovery
15987 		 */
15988 		scsipkt->pkt_reason = CMD_RESET;
15989 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
15990 		break;
15991 
15992 	default:
15993 		scsipkt->pkt_reason = CMD_TRAN_ERR;
15994 		break;
15995 	}
15996 }
15997 
15998 
15999 
16000 
16001 /*
16002  * Log sata message
16003  * dev pathname msg line preceeds the logged message.
16004  */
16005 
16006 static	void
16007 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16008 {
16009 	char pathname[128];
16010 	dev_info_t *dip = NULL;
16011 	va_list ap;
16012 
16013 	mutex_enter(&sata_log_mutex);
16014 
16015 	va_start(ap, fmt);
16016 	(void) vsprintf(sata_log_buf, fmt, ap);
16017 	va_end(ap);
16018 
16019 	if (sata_hba_inst != NULL) {
16020 		dip = SATA_DIP(sata_hba_inst);
16021 		(void) ddi_pathname(dip, pathname);
16022 	} else {
16023 		pathname[0] = 0;
16024 	}
16025 	if (level == CE_CONT) {
16026 		if (sata_debug_flags == 0)
16027 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16028 		else
16029 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16030 	} else {
16031 		if (level != CE_NOTE) {
16032 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16033 		} else if (sata_msg) {
16034 			cmn_err(level, "%s:\n %s", pathname,
16035 			    sata_log_buf);
16036 		}
16037 	}
16038 
16039 	/* sata trace debug */
16040 	sata_trace_debug(dip, sata_log_buf);
16041 
16042 	mutex_exit(&sata_log_mutex);
16043 }
16044 
16045 
16046 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16047 
16048 /*
16049  * Start or terminate the thread, depending on flag arg and current state
16050  */
16051 static void
16052 sata_event_thread_control(int startstop)
16053 {
16054 	static 	int sata_event_thread_terminating = 0;
16055 	static 	int sata_event_thread_starting = 0;
16056 	int i;
16057 
16058 	mutex_enter(&sata_event_mutex);
16059 
16060 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16061 	    sata_event_thread_terminating == 1)) {
16062 		mutex_exit(&sata_event_mutex);
16063 		return;
16064 	}
16065 	if (startstop == 1 && sata_event_thread_starting == 1) {
16066 		mutex_exit(&sata_event_mutex);
16067 		return;
16068 	}
16069 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16070 		sata_event_thread_starting = 1;
16071 		/* wait til terminate operation completes */
16072 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16073 		while (sata_event_thread_terminating == 1) {
16074 			if (i-- <= 0) {
16075 				sata_event_thread_starting = 0;
16076 				mutex_exit(&sata_event_mutex);
16077 #ifdef SATA_DEBUG
16078 				cmn_err(CE_WARN, "sata_event_thread_control: "
16079 				    "timeout waiting for thread to terminate");
16080 #endif
16081 				return;
16082 			}
16083 			mutex_exit(&sata_event_mutex);
16084 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16085 			mutex_enter(&sata_event_mutex);
16086 		}
16087 	}
16088 	if (startstop == 1) {
16089 		if (sata_event_thread == NULL) {
16090 			sata_event_thread = thread_create(NULL, 0,
16091 			    (void (*)())sata_event_daemon,
16092 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16093 		}
16094 		sata_event_thread_starting = 0;
16095 		mutex_exit(&sata_event_mutex);
16096 		return;
16097 	}
16098 
16099 	/*
16100 	 * If we got here, thread may need to be terminated
16101 	 */
16102 	if (sata_event_thread != NULL) {
16103 		int i;
16104 		/* Signal event thread to go away */
16105 		sata_event_thread_terminating = 1;
16106 		sata_event_thread_terminate = 1;
16107 		cv_signal(&sata_event_cv);
16108 		/*
16109 		 * Wait til daemon terminates.
16110 		 */
16111 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16112 		while (sata_event_thread_terminate == 1) {
16113 			mutex_exit(&sata_event_mutex);
16114 			if (i-- <= 0) {
16115 				/* Daemon did not go away !!! */
16116 #ifdef SATA_DEBUG
16117 				cmn_err(CE_WARN, "sata_event_thread_control: "
16118 				    "cannot terminate event daemon thread");
16119 #endif
16120 				mutex_enter(&sata_event_mutex);
16121 				break;
16122 			}
16123 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16124 			mutex_enter(&sata_event_mutex);
16125 		}
16126 		sata_event_thread_terminating = 0;
16127 	}
16128 	ASSERT(sata_event_thread_terminating == 0);
16129 	ASSERT(sata_event_thread_starting == 0);
16130 	mutex_exit(&sata_event_mutex);
16131 }
16132 
16133 
16134 /*
16135  * SATA HBA event notification function.
16136  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16137  * a port and/or device state or a controller itself.
16138  * Events for different addresses/addr types cannot be combined.
16139  * A warning message is generated for each event type.
16140  * Events are not processed by this function, so only the
16141  * event flag(s)is set for an affected entity and the event thread is
16142  * waken up. Event daemon thread processes all events.
16143  *
16144  * NOTE: Since more than one event may be reported at the same time, one
16145  * cannot determine a sequence of events when opposite event are reported, eg.
16146  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16147  * is taking precedence over reported events, i.e. may cause ignoring some
16148  * events.
16149  */
16150 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16151 
16152 void
16153 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16154 {
16155 	sata_hba_inst_t *sata_hba_inst = NULL;
16156 	sata_address_t *saddr;
16157 	sata_pmult_info_t *pmultinfo;
16158 	sata_drive_info_t *sdinfo;
16159 	sata_port_stats_t *pstats;
16160 	sata_cport_info_t *cportinfo;
16161 	sata_pmport_info_t *pmportinfo;
16162 	int cport, pmport;
16163 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16164 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16165 	char *lcp;
16166 	static char *err_msg_evnt_1 =
16167 	    "sata_hba_event_notify: invalid port event 0x%x ";
16168 	static char *err_msg_evnt_2 =
16169 	    "sata_hba_event_notify: invalid device event 0x%x ";
16170 	int linkevent;
16171 
16172 	/*
16173 	 * There is a possibility that an event will be generated on HBA
16174 	 * that has not completed attachment or is detaching. We still want
16175 	 * to process events until HBA is detached.
16176 	 */
16177 	mutex_enter(&sata_mutex);
16178 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16179 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16180 		if (SATA_DIP(sata_hba_inst) == dip)
16181 			if (sata_hba_inst->satahba_attached == 1)
16182 				break;
16183 	}
16184 	mutex_exit(&sata_mutex);
16185 	if (sata_hba_inst == NULL)
16186 		/* HBA not attached */
16187 		return;
16188 
16189 	ASSERT(sata_device != NULL);
16190 
16191 	/*
16192 	 * Validate address before - do not proceed with invalid address.
16193 	 */
16194 	saddr = &sata_device->satadev_addr;
16195 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16196 		return;
16197 
16198 	cport = saddr->cport;
16199 	pmport = saddr->pmport;
16200 
16201 	buf1[0] = buf2[0] = '\0';
16202 
16203 	/*
16204 	 * If event relates to port or device, check port state.
16205 	 * Port has to be initialized, or we cannot accept an event.
16206 	 */
16207 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16208 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16209 		mutex_enter(&sata_hba_inst->satahba_mutex);
16210 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16211 		mutex_exit(&sata_hba_inst->satahba_mutex);
16212 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16213 			return;
16214 	}
16215 
16216 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16217 	    SATA_ADDR_DPMPORT)) != 0) {
16218 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16219 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16220 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16221 			    "is attached to port %d, ignore pmult/pmport "
16222 			    "event 0x%x", cportinfo->cport_dev_type,
16223 			    cport, event));
16224 			return;
16225 		}
16226 
16227 		mutex_enter(&cportinfo->cport_mutex);
16228 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16229 		mutex_exit(&cportinfo->cport_mutex);
16230 
16231 		/*
16232 		 * The daemon might be processing attachment of port
16233 		 * multiplier, in that case we should ignore events on its
16234 		 * sub-devices.
16235 		 *
16236 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16237 		 * The pmport_state is checked by sata daemon.
16238 		 */
16239 		if (pmultinfo == NULL ||
16240 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16241 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16242 			    "sata_hba_event_notify: pmult is not"
16243 			    "available at port %d:%d, ignore event 0x%x",
16244 			    cport, pmport, event));
16245 			return;
16246 		}
16247 	}
16248 
16249 	if ((saddr->qual &
16250 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16251 
16252 		mutex_enter(&cportinfo->cport_mutex);
16253 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16254 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16255 			    "sata_hba_event_notify: invalid/"
16256 			    "un-implemented port %d:%d (%d ports), "
16257 			    "ignore event 0x%x", cport, pmport,
16258 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
16259 			mutex_exit(&cportinfo->cport_mutex);
16260 			return;
16261 		}
16262 		mutex_exit(&cportinfo->cport_mutex);
16263 
16264 		mutex_enter(&sata_hba_inst->satahba_mutex);
16265 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16266 		    cport, pmport);
16267 		mutex_exit(&sata_hba_inst->satahba_mutex);
16268 
16269 		/* pmport is implemented/valid? */
16270 		if (pmportinfo == NULL) {
16271 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16272 			    "sata_hba_event_notify: invalid/"
16273 			    "un-implemented port %d:%d, ignore "
16274 			    "event 0x%x", cport, pmport, event));
16275 			return;
16276 		}
16277 	}
16278 
16279 	/*
16280 	 * Events refer to devices, ports and controllers - each has
16281 	 * unique address. Events for different addresses cannot be combined.
16282 	 */
16283 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
16284 
16285 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16286 
16287 		/* qualify this event(s) */
16288 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
16289 			/* Invalid event for the device port */
16290 			(void) sprintf(buf2, err_msg_evnt_1,
16291 			    event & SATA_EVNT_PORT_EVENTS);
16292 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16293 			goto event_info;
16294 		}
16295 		if (saddr->qual == SATA_ADDR_CPORT) {
16296 			/* Controller's device port event */
16297 
16298 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
16299 			    cport_event_flags |=
16300 			    event & SATA_EVNT_PORT_EVENTS;
16301 			pstats =
16302 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
16303 			    cport_stats;
16304 		} else {
16305 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16306 			mutex_enter(&pmportinfo->pmport_mutex);
16307 			/* Port multiplier's device port event */
16308 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16309 			    pmport_event_flags |=
16310 			    event & SATA_EVNT_PORT_EVENTS;
16311 			pstats =
16312 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16313 			    pmport_stats;
16314 			mutex_exit(&pmportinfo->pmport_mutex);
16315 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16316 		}
16317 
16318 		/*
16319 		 * Add to statistics and log the message. We have to do it
16320 		 * here rather than in the event daemon, because there may be
16321 		 * multiple events occuring before they are processed.
16322 		 */
16323 		linkevent = event &
16324 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
16325 		if (linkevent) {
16326 			if (linkevent == (SATA_EVNT_LINK_LOST |
16327 			    SATA_EVNT_LINK_ESTABLISHED)) {
16328 				/* This is likely event combination */
16329 				(void) strlcat(buf1, "link lost/established, ",
16330 				    SATA_EVENT_MAX_MSG_LENGTH);
16331 
16332 				if (pstats->link_lost < 0xffffffffffffffffULL)
16333 					pstats->link_lost++;
16334 				if (pstats->link_established <
16335 				    0xffffffffffffffffULL)
16336 					pstats->link_established++;
16337 				linkevent = 0;
16338 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
16339 				(void) strlcat(buf1, "link lost, ",
16340 				    SATA_EVENT_MAX_MSG_LENGTH);
16341 
16342 				if (pstats->link_lost < 0xffffffffffffffffULL)
16343 					pstats->link_lost++;
16344 			} else {
16345 				(void) strlcat(buf1, "link established, ",
16346 				    SATA_EVENT_MAX_MSG_LENGTH);
16347 				if (pstats->link_established <
16348 				    0xffffffffffffffffULL)
16349 					pstats->link_established++;
16350 			}
16351 		}
16352 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
16353 			(void) strlcat(buf1, "device attached, ",
16354 			    SATA_EVENT_MAX_MSG_LENGTH);
16355 			if (pstats->device_attached < 0xffffffffffffffffULL)
16356 				pstats->device_attached++;
16357 		}
16358 		if (event & SATA_EVNT_DEVICE_DETACHED) {
16359 			(void) strlcat(buf1, "device detached, ",
16360 			    SATA_EVENT_MAX_MSG_LENGTH);
16361 			if (pstats->device_detached < 0xffffffffffffffffULL)
16362 				pstats->device_detached++;
16363 		}
16364 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
16365 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16366 			    "port %d power level changed", cport);
16367 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
16368 				pstats->port_pwr_changed++;
16369 		}
16370 
16371 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
16372 			/* There should be no other events for this address */
16373 			(void) sprintf(buf2, err_msg_evnt_1,
16374 			    event & ~SATA_EVNT_PORT_EVENTS);
16375 		}
16376 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16377 
16378 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
16379 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16380 
16381 		/* qualify this event */
16382 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
16383 			/* Invalid event for a device */
16384 			(void) sprintf(buf2, err_msg_evnt_2,
16385 			    event & SATA_EVNT_DEVICE_RESET);
16386 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16387 			goto event_info;
16388 		}
16389 		/* drive event */
16390 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
16391 		if (sdinfo != NULL) {
16392 			if (event & SATA_EVNT_DEVICE_RESET) {
16393 				(void) strlcat(buf1, "device reset, ",
16394 				    SATA_EVENT_MAX_MSG_LENGTH);
16395 				if (sdinfo->satadrv_stats.drive_reset <
16396 				    0xffffffffffffffffULL)
16397 					sdinfo->satadrv_stats.drive_reset++;
16398 				sdinfo->satadrv_event_flags |=
16399 				    SATA_EVNT_DEVICE_RESET;
16400 			}
16401 		}
16402 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
16403 			/* Invalid event for a device */
16404 			(void) sprintf(buf2, err_msg_evnt_2,
16405 			    event & ~SATA_EVNT_DRIVE_EVENTS);
16406 		}
16407 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16408 	} else if (saddr->qual == SATA_ADDR_PMULT) {
16409 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16410 
16411 		/* qualify this event */
16412 		if ((event & (SATA_EVNT_DEVICE_RESET |
16413 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
16414 			/* Invalid event for a port multiplier */
16415 			(void) sprintf(buf2, err_msg_evnt_2,
16416 			    event & SATA_EVNT_DEVICE_RESET);
16417 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16418 			goto event_info;
16419 		}
16420 
16421 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16422 
16423 		if (event & SATA_EVNT_DEVICE_RESET) {
16424 
16425 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
16426 			    "[Reset] port-mult on cport %d", cport);
16427 			pmultinfo->pmult_event_flags |=
16428 			    SATA_EVNT_DEVICE_RESET;
16429 			(void) strlcat(buf1, "pmult reset, ",
16430 			    SATA_EVENT_MAX_MSG_LENGTH);
16431 		}
16432 
16433 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
16434 
16435 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
16436 			    "pmult link changed on cport %d", cport);
16437 			pmultinfo->pmult_event_flags |=
16438 			    SATA_EVNT_PMULT_LINK_CHANGED;
16439 			(void) strlcat(buf1, "pmult link changed, ",
16440 			    SATA_EVENT_MAX_MSG_LENGTH);
16441 		}
16442 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16443 
16444 	} else {
16445 		if (saddr->qual != SATA_ADDR_NULL) {
16446 			/* Wrong address qualifier */
16447 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16448 			    "sata_hba_event_notify: invalid address 0x%x",
16449 			    *(uint32_t *)saddr));
16450 			return;
16451 		}
16452 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
16453 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
16454 			/* Invalid event for the controller */
16455 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16456 			    "sata_hba_event_notify: invalid event 0x%x for "
16457 			    "controller",
16458 			    event & SATA_EVNT_CONTROLLER_EVENTS));
16459 			return;
16460 		}
16461 		buf1[0] = '\0';
16462 		/* This may be a frequent and not interesting event */
16463 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16464 		    "controller power level changed\n", NULL);
16465 
16466 		mutex_enter(&sata_hba_inst->satahba_mutex);
16467 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
16468 		    0xffffffffffffffffULL)
16469 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
16470 
16471 		sata_hba_inst->satahba_event_flags |=
16472 		    SATA_EVNT_PWR_LEVEL_CHANGED;
16473 		mutex_exit(&sata_hba_inst->satahba_mutex);
16474 	}
16475 	/*
16476 	 * If we got here, there is something to do with this HBA
16477 	 * instance.
16478 	 */
16479 	mutex_enter(&sata_hba_inst->satahba_mutex);
16480 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
16481 	mutex_exit(&sata_hba_inst->satahba_mutex);
16482 	mutex_enter(&sata_mutex);
16483 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
16484 	mutex_exit(&sata_mutex);
16485 
16486 	/* Tickle event thread */
16487 	mutex_enter(&sata_event_mutex);
16488 	if (sata_event_thread_active == 0)
16489 		cv_signal(&sata_event_cv);
16490 	mutex_exit(&sata_event_mutex);
16491 
16492 event_info:
16493 	if (buf1[0] != '\0') {
16494 		lcp = strrchr(buf1, ',');
16495 		if (lcp != NULL)
16496 			*lcp = '\0';
16497 	}
16498 	if (saddr->qual == SATA_ADDR_CPORT ||
16499 	    saddr->qual == SATA_ADDR_DCPORT) {
16500 		if (buf1[0] != '\0') {
16501 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
16502 			    cport, buf1);
16503 		}
16504 		if (buf2[0] != '\0') {
16505 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
16506 			    cport, buf2);
16507 		}
16508 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
16509 	    saddr->qual == SATA_ADDR_DPMPORT) {
16510 		if (buf1[0] != '\0') {
16511 			sata_log(sata_hba_inst, CE_NOTE,
16512 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
16513 		}
16514 		if (buf2[0] != '\0') {
16515 			sata_log(sata_hba_inst, CE_NOTE,
16516 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
16517 		}
16518 	}
16519 }
16520 
16521 
16522 /*
16523  * Event processing thread.
16524  * Arg is a pointer to the sata_hba_list pointer.
16525  * It is not really needed, because sata_hba_list is global and static
16526  */
16527 static void
16528 sata_event_daemon(void *arg)
16529 {
16530 #ifndef __lock_lint
16531 	_NOTE(ARGUNUSED(arg))
16532 #endif
16533 	sata_hba_inst_t *sata_hba_inst;
16534 	clock_t lbolt;
16535 
16536 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
16537 	    "SATA event daemon started\n", NULL);
16538 loop:
16539 	/*
16540 	 * Process events here. Walk through all registered HBAs
16541 	 */
16542 	mutex_enter(&sata_mutex);
16543 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16544 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16545 		ASSERT(sata_hba_inst != NULL);
16546 		mutex_enter(&sata_hba_inst->satahba_mutex);
16547 		if (sata_hba_inst->satahba_attached == 0 ||
16548 		    (sata_hba_inst->satahba_event_flags &
16549 		    SATA_EVNT_SKIP) != 0) {
16550 			mutex_exit(&sata_hba_inst->satahba_mutex);
16551 			continue;
16552 		}
16553 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
16554 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
16555 			mutex_exit(&sata_hba_inst->satahba_mutex);
16556 			mutex_exit(&sata_mutex);
16557 			/* Got the controller with pending event */
16558 			sata_process_controller_events(sata_hba_inst);
16559 			/*
16560 			 * Since global mutex was released, there is a
16561 			 * possibility that HBA list has changed, so start
16562 			 * over from the top. Just processed controller
16563 			 * will be passed-over because of the SKIP flag.
16564 			 */
16565 			goto loop;
16566 		}
16567 		mutex_exit(&sata_hba_inst->satahba_mutex);
16568 	}
16569 	/* Clear SKIP flag in all controllers */
16570 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16571 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16572 		mutex_enter(&sata_hba_inst->satahba_mutex);
16573 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
16574 		mutex_exit(&sata_hba_inst->satahba_mutex);
16575 	}
16576 	mutex_exit(&sata_mutex);
16577 
16578 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
16579 	    "SATA EVENT DAEMON suspending itself", NULL);
16580 
16581 #ifdef SATA_DEBUG
16582 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
16583 		sata_log(sata_hba_inst, CE_WARN,
16584 		    "SATA EVENTS PROCESSING DISABLED\n");
16585 		thread_exit(); /* Daemon will not run again */
16586 	}
16587 #endif
16588 	mutex_enter(&sata_event_mutex);
16589 	sata_event_thread_active = 0;
16590 	mutex_exit(&sata_event_mutex);
16591 	/*
16592 	 * Go to sleep/suspend itself and wake up either because new event or
16593 	 * wait timeout. Exit if there is a termination request (driver
16594 	 * unload).
16595 	 */
16596 	do {
16597 		lbolt = ddi_get_lbolt();
16598 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
16599 		mutex_enter(&sata_event_mutex);
16600 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
16601 
16602 		if (sata_event_thread_active != 0) {
16603 			mutex_exit(&sata_event_mutex);
16604 			continue;
16605 		}
16606 
16607 		/* Check if it is time to go away */
16608 		if (sata_event_thread_terminate == 1) {
16609 			/*
16610 			 * It is up to the thread setting above flag to make
16611 			 * sure that this thread is not killed prematurely.
16612 			 */
16613 			sata_event_thread_terminate = 0;
16614 			sata_event_thread = NULL;
16615 			mutex_exit(&sata_event_mutex);
16616 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
16617 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
16618 			thread_exit();  { _NOTE(NOT_REACHED) }
16619 		}
16620 		mutex_exit(&sata_event_mutex);
16621 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
16622 
16623 	mutex_enter(&sata_event_mutex);
16624 	sata_event_thread_active = 1;
16625 	mutex_exit(&sata_event_mutex);
16626 
16627 	mutex_enter(&sata_mutex);
16628 	sata_event_pending &= ~SATA_EVNT_MAIN;
16629 	mutex_exit(&sata_mutex);
16630 
16631 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
16632 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
16633 
16634 	goto loop;
16635 }
16636 
16637 /*
16638  * Specific HBA instance event processing.
16639  *
16640  * NOTE: At the moment, device event processing is limited to hard disks
16641  * only.
16642  * Port multiplier is supported now.
16643  */
16644 static void
16645 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
16646 {
16647 	int ncport;
16648 	uint32_t event_flags;
16649 	sata_address_t *saddr;
16650 	sata_cport_info_t *cportinfo;
16651 	sata_pmult_info_t *pmultinfo;
16652 
16653 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
16654 	    "Processing controller %d event(s)",
16655 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
16656 
16657 	mutex_enter(&sata_hba_inst->satahba_mutex);
16658 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
16659 	event_flags = sata_hba_inst->satahba_event_flags;
16660 	mutex_exit(&sata_hba_inst->satahba_mutex);
16661 	/*
16662 	 * Process controller power change first
16663 	 * HERE
16664 	 */
16665 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
16666 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
16667 
16668 	/*
16669 	 * Search through ports/devices to identify affected port/device.
16670 	 * We may have to process events for more than one port/device.
16671 	 */
16672 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
16673 		/*
16674 		 * Not all ports may be processed in attach by the time we
16675 		 * get an event. Check if port info is initialized.
16676 		 */
16677 		mutex_enter(&sata_hba_inst->satahba_mutex);
16678 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
16679 		mutex_exit(&sata_hba_inst->satahba_mutex);
16680 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
16681 			continue;
16682 
16683 		/* We have initialized controller port info */
16684 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
16685 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
16686 		    cport_event_flags;
16687 		/* Check if port was locked by IOCTL processing */
16688 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
16689 			/*
16690 			 * We ignore port events because port is busy
16691 			 * with AP control processing. Set again
16692 			 * controller and main event flag, so that
16693 			 * events may be processed by the next daemon
16694 			 * run.
16695 			 */
16696 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
16697 			mutex_enter(&sata_hba_inst->satahba_mutex);
16698 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
16699 			mutex_exit(&sata_hba_inst->satahba_mutex);
16700 			mutex_enter(&sata_mutex);
16701 			sata_event_pending |= SATA_EVNT_MAIN;
16702 			mutex_exit(&sata_mutex);
16703 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
16704 			    "Event processing postponed until "
16705 			    "AP control processing completes",
16706 			    NULL);
16707 			/* Check other ports */
16708 			continue;
16709 		} else {
16710 			/*
16711 			 * Set BSY flag so that AP control would not
16712 			 * interfere with events processing for
16713 			 * this port.
16714 			 */
16715 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
16716 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
16717 		}
16718 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
16719 
16720 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
16721 
16722 		if ((event_flags &
16723 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
16724 			/*
16725 			 * Got port event.
16726 			 * We need some hierarchy of event processing as they
16727 			 * are affecting each other:
16728 			 * 1. port failed
16729 			 * 2. device detached/attached
16730 			 * 3. link events - link events may trigger device
16731 			 *    detached or device attached events in some
16732 			 *    circumstances.
16733 			 * 4. port power level changed
16734 			 */
16735 			if (event_flags & SATA_EVNT_PORT_FAILED) {
16736 				sata_process_port_failed_event(sata_hba_inst,
16737 				    saddr);
16738 			}
16739 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
16740 				sata_process_device_detached(sata_hba_inst,
16741 				    saddr);
16742 			}
16743 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
16744 				sata_process_device_attached(sata_hba_inst,
16745 				    saddr);
16746 			}
16747 			if (event_flags &
16748 			    (SATA_EVNT_LINK_ESTABLISHED |
16749 			    SATA_EVNT_LINK_LOST)) {
16750 				sata_process_port_link_events(sata_hba_inst,
16751 				    saddr);
16752 			}
16753 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
16754 				sata_process_port_pwr_change(sata_hba_inst,
16755 				    saddr);
16756 			}
16757 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
16758 				sata_process_target_node_cleanup(
16759 				    sata_hba_inst, saddr);
16760 			}
16761 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
16762 				sata_process_device_autoonline(
16763 				    sata_hba_inst, saddr);
16764 			}
16765 		}
16766 
16767 
16768 		/*
16769 		 * Scan port multiplier and all its sub-ports event flags.
16770 		 * The events are marked by
16771 		 * (1) sata_pmult_info.pmult_event_flags
16772 		 * (2) sata_pmport_info.pmport_event_flags
16773 		 */
16774 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
16775 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
16776 			/*
16777 			 * There should be another extra check: this
16778 			 * port multiplier still exists?
16779 			 */
16780 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
16781 			    ncport);
16782 
16783 			if (pmultinfo != NULL) {
16784 				mutex_exit(&(SATA_CPORT_MUTEX(
16785 				    sata_hba_inst, ncport)));
16786 				sata_process_pmult_events(
16787 				    sata_hba_inst, ncport);
16788 				mutex_enter(&(SATA_CPORT_MUTEX(
16789 				    sata_hba_inst, ncport)));
16790 			} else {
16791 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
16792 				    "Port-multiplier is gone. "
16793 				    "Ignore all sub-device events "
16794 				    "at port %d.", ncport);
16795 			}
16796 		}
16797 
16798 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
16799 		    SATA_DTYPE_NONE) &&
16800 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
16801 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
16802 			    satadrv_event_flags &
16803 			    (SATA_EVNT_DEVICE_RESET |
16804 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
16805 				/* Have device event */
16806 				sata_process_device_reset(sata_hba_inst,
16807 				    saddr);
16808 			}
16809 		}
16810 		/* Release PORT_BUSY flag */
16811 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
16812 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
16813 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
16814 
16815 	} /* End of loop through the controller SATA ports */
16816 }
16817 
16818 /*
16819  * Specific port multiplier instance event processing. At the moment, device
16820  * event processing is limited to link/attach event only.
16821  *
16822  * NOTE: power management event is not supported yet.
16823  */
16824 static void
16825 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
16826 {
16827 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16828 	sata_pmult_info_t *pmultinfo;
16829 	sata_pmport_info_t *pmportinfo;
16830 	sata_address_t *saddr;
16831 	sata_device_t sata_device;
16832 	uint32_t event_flags;
16833 	int npmport;
16834 	int rval;
16835 
16836 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
16837 	    "Processing pmult event(s) on cport %d of controller %d",
16838 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
16839 
16840 	/* First process events on port multiplier */
16841 	mutex_enter(&cportinfo->cport_mutex);
16842 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16843 	event_flags = pmultinfo->pmult_event_flags;
16844 
16845 	/*
16846 	 * Reset event (of port multiplier) has higher priority because the
16847 	 * port multiplier itself might be failed or removed after reset.
16848 	 */
16849 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
16850 		/*
16851 		 * The status of the sub-links are uncertain,
16852 		 * so mark all sub-ports as RESET
16853 		 */
16854 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
16855 		    sata_hba_inst, cport); npmport ++) {
16856 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16857 			    cport, npmport);
16858 			if (pmportinfo == NULL) {
16859 				/* That's weird. */
16860 				SATA_LOG_D((sata_hba_inst, CE_WARN,
16861 				    "sata_hba_event_notify: "
16862 				    "invalid/un-implemented "
16863 				    "port %d:%d (%d ports), ",
16864 				    cport, npmport, SATA_NUM_PMPORTS(
16865 				    sata_hba_inst, cport)));
16866 				continue;
16867 			}
16868 
16869 			mutex_enter(&pmportinfo->pmport_mutex);
16870 
16871 			/* Mark all pmport to unknow state. */
16872 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
16873 			/* Mark all pmports with link events. */
16874 			pmportinfo->pmport_event_flags =
16875 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
16876 			mutex_exit(&pmportinfo->pmport_mutex);
16877 		}
16878 
16879 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
16880 		/*
16881 		 * We need probe the port multiplier to know what has
16882 		 * happened.
16883 		 */
16884 		bzero(&sata_device, sizeof (sata_device_t));
16885 		sata_device.satadev_rev = SATA_DEVICE_REV;
16886 		sata_device.satadev_addr.cport = cport;
16887 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
16888 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
16889 
16890 		mutex_exit(&cportinfo->cport_mutex);
16891 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
16892 		    (SATA_DIP(sata_hba_inst), &sata_device);
16893 		mutex_enter(&cportinfo->cport_mutex);
16894 		if (rval != SATA_SUCCESS) {
16895 			/* Something went wrong? Fail the port */
16896 			cportinfo->cport_state = SATA_PSTATE_FAILED;
16897 			mutex_exit(&cportinfo->cport_mutex);
16898 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16899 			    "SATA port %d probing failed", cport));
16900 
16901 			/* PMult structure must be released.  */
16902 			sata_free_pmult(sata_hba_inst, &sata_device);
16903 			return;
16904 		}
16905 
16906 		sata_update_port_info(sata_hba_inst, &sata_device);
16907 
16908 		/*
16909 		 * Sanity check - Port is active? Is the link active?
16910 		 * The device is still a port multiplier?
16911 		 */
16912 		if ((cportinfo->cport_state &
16913 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
16914 		    ((cportinfo->cport_scr.sstatus &
16915 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
16916 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
16917 			mutex_exit(&cportinfo->cport_mutex);
16918 
16919 			/* PMult structure must be released.  */
16920 			sata_free_pmult(sata_hba_inst, &sata_device);
16921 			return;
16922 		}
16923 
16924 		/* Probed succeed, set port ready. */
16925 		cportinfo->cport_state |=
16926 		    SATA_STATE_PROBED | SATA_STATE_READY;
16927 	}
16928 
16929 	/* Release port multiplier event flags. */
16930 	pmultinfo->pmult_event_flags &=
16931 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
16932 	mutex_exit(&cportinfo->cport_mutex);
16933 
16934 	/*
16935 	 * Check all sub-links.
16936 	 */
16937 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
16938 	    npmport ++) {
16939 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
16940 		mutex_enter(&pmportinfo->pmport_mutex);
16941 		event_flags = pmportinfo->pmport_event_flags;
16942 		mutex_exit(&pmportinfo->pmport_mutex);
16943 		saddr = &pmportinfo->pmport_addr;
16944 
16945 		if ((event_flags &
16946 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
16947 			/*
16948 			 * Got port multiplier port event.
16949 			 * We need some hierarchy of event processing as they
16950 			 * are affecting each other:
16951 			 * 1. device detached/attached
16952 			 * 2. link events - link events may trigger device
16953 			 *    detached or device attached events in some
16954 			 *    circumstances.
16955 			 */
16956 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
16957 				sata_process_pmdevice_detached(sata_hba_inst,
16958 				    saddr);
16959 			}
16960 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
16961 				sata_process_pmdevice_attached(sata_hba_inst,
16962 				    saddr);
16963 			}
16964 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
16965 			    event_flags & SATA_EVNT_LINK_LOST) {
16966 				sata_process_pmport_link_events(sata_hba_inst,
16967 				    saddr);
16968 			}
16969 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
16970 				sata_process_target_node_cleanup(
16971 				    sata_hba_inst, saddr);
16972 			}
16973 		}
16974 
16975 		/* Checking drive event(s). */
16976 		mutex_enter(&pmportinfo->pmport_mutex);
16977 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
16978 		    pmportinfo->pmport_sata_drive != NULL) {
16979 			event_flags = pmportinfo->pmport_sata_drive->
16980 			    satadrv_event_flags;
16981 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
16982 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
16983 
16984 				/* Have device event */
16985 				sata_process_pmdevice_reset(sata_hba_inst,
16986 				    saddr);
16987 			}
16988 		}
16989 		mutex_exit(&pmportinfo->pmport_mutex);
16990 
16991 		/* Release PORT_BUSY flag */
16992 		mutex_enter(&cportinfo->cport_mutex);
16993 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
16994 		mutex_exit(&cportinfo->cport_mutex);
16995 	}
16996 
16997 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
16998 	    "[DONE] pmult event(s) on cport %d of controller %d",
16999 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17000 }
17001 
17002 /*
17003  * Process HBA power level change reported by HBA driver.
17004  * Not implemented at this time - event is ignored.
17005  */
17006 static void
17007 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17008 {
17009 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17010 	    "Processing controller power level change", NULL);
17011 
17012 	/* Ignoring it for now */
17013 	mutex_enter(&sata_hba_inst->satahba_mutex);
17014 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17015 	mutex_exit(&sata_hba_inst->satahba_mutex);
17016 }
17017 
17018 /*
17019  * Process port power level change reported by HBA driver.
17020  * Not implemented at this time - event is ignored.
17021  */
17022 static void
17023 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17024     sata_address_t *saddr)
17025 {
17026 	sata_cport_info_t *cportinfo;
17027 
17028 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17029 	    "Processing port power level change", NULL);
17030 
17031 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17032 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17033 	/* Reset event flag */
17034 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17035 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17036 }
17037 
17038 /*
17039  * Process port failure reported by HBA driver.
17040  * cports support only - no pmports.
17041  */
17042 static void
17043 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17044     sata_address_t *saddr)
17045 {
17046 	sata_cport_info_t *cportinfo;
17047 
17048 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17049 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17050 	/* Reset event flag first */
17051 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17052 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17053 	if ((cportinfo->cport_state &
17054 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17055 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17056 		    cport_mutex);
17057 		return;
17058 	}
17059 	/* Fail the port */
17060 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17061 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17062 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17063 }
17064 
17065 /*
17066  * Device Reset Event processing.
17067  * The seqeunce is managed by 3 stage flags:
17068  * - reset event reported,
17069  * - reset event being processed,
17070  * - request to clear device reset state.
17071  *
17072  * NOTE: This function has to be entered with cport mutex held. It exits with
17073  * mutex held as well, but can release mutex during the processing.
17074  */
17075 static void
17076 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17077     sata_address_t *saddr)
17078 {
17079 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17080 	sata_drive_info_t *sdinfo;
17081 	sata_cport_info_t *cportinfo;
17082 	sata_device_t sata_device;
17083 	int rval_probe, rval_set;
17084 
17085 	/* We only care about host sata cport for now */
17086 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17087 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17088 	/*
17089 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17090 	 * state, ignore reset event.
17091 	 */
17092 	if (((cportinfo->cport_state &
17093 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17094 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17095 		sdinfo->satadrv_event_flags &=
17096 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17097 		return;
17098 	}
17099 
17100 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17101 	    SATA_DTYPE_PMULT)) {
17102 		/*
17103 		 * Should not happened: this is already handled in
17104 		 * sata_hba_event_notify()
17105 		 */
17106 		mutex_exit(&cportinfo->cport_mutex);
17107 		goto done;
17108 	}
17109 
17110 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17111 	    SATA_VALID_DEV_TYPE) == 0) {
17112 		/*
17113 		 * This should not happen - coding error.
17114 		 * But we can recover, so do not panic, just clean up
17115 		 * and if in debug mode, log the message.
17116 		 */
17117 #ifdef SATA_DEBUG
17118 		sata_log(sata_hba_inst, CE_WARN,
17119 		    "sata_process_device_reset: "
17120 		    "Invalid device type with sdinfo!", NULL);
17121 #endif
17122 		sdinfo->satadrv_event_flags = 0;
17123 		return;
17124 	}
17125 
17126 #ifdef SATA_DEBUG
17127 	if ((sdinfo->satadrv_event_flags &
17128 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17129 		/* Nothing to do */
17130 		/* Something is weird - why we are processing dev reset? */
17131 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17132 		    "No device reset event!!!!", NULL);
17133 
17134 		return;
17135 	}
17136 	if ((sdinfo->satadrv_event_flags &
17137 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17138 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17139 		/* Something is weird - new device reset event */
17140 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17141 		    "Overlapping device reset events!", NULL);
17142 	}
17143 #endif
17144 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17145 	    "Processing port %d device reset", saddr->cport);
17146 
17147 	/* Clear event flag */
17148 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17149 
17150 	/* It seems that we always need to check the port state first */
17151 	sata_device.satadev_rev = SATA_DEVICE_REV;
17152 	sata_device.satadev_addr = *saddr;
17153 	/*
17154 	 * We have to exit mutex, because the HBA probe port function may
17155 	 * block on its own mutex.
17156 	 */
17157 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17158 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17159 	    (SATA_DIP(sata_hba_inst), &sata_device);
17160 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17161 	sata_update_port_info(sata_hba_inst, &sata_device);
17162 	if (rval_probe != SATA_SUCCESS) {
17163 		/* Something went wrong? Fail the port */
17164 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17165 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17166 		if (sdinfo != NULL)
17167 			sdinfo->satadrv_event_flags = 0;
17168 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17169 		    cport_mutex);
17170 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17171 		    "SATA port %d probing failed",
17172 		    saddr->cport));
17173 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17174 		    saddr->cport)->cport_mutex);
17175 		return;
17176 	}
17177 	if ((sata_device.satadev_scr.sstatus  &
17178 	    SATA_PORT_DEVLINK_UP_MASK) !=
17179 	    SATA_PORT_DEVLINK_UP ||
17180 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17181 		/*
17182 		 * No device to process, anymore. Some other event processing
17183 		 * would or have already performed port info cleanup.
17184 		 * To be safe (HBA may need it), request clearing device
17185 		 * reset condition.
17186 		 */
17187 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17188 		if (sdinfo != NULL) {
17189 			sdinfo->satadrv_event_flags &=
17190 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17191 			sdinfo->satadrv_event_flags |=
17192 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17193 		}
17194 		return;
17195 	}
17196 
17197 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17198 	if (sdinfo == NULL) {
17199 		return;
17200 	}
17201 	if ((sdinfo->satadrv_event_flags &
17202 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17203 		/*
17204 		 * Start tracking time for device feature restoration and
17205 		 * identification. Save current time (lbolt value).
17206 		 */
17207 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17208 	}
17209 	/* Mark device reset processing as active */
17210 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17211 
17212 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17213 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17214 
17215 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17216 
17217 	if (rval_set  != SATA_SUCCESS) {
17218 		/*
17219 		 * Restoring drive setting failed.
17220 		 * Probe the port first, to check if the port state has changed
17221 		 */
17222 		sata_device.satadev_rev = SATA_DEVICE_REV;
17223 		sata_device.satadev_addr = *saddr;
17224 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17225 		/* probe port */
17226 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17227 		    (SATA_DIP(sata_hba_inst), &sata_device);
17228 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17229 		    cport_mutex);
17230 		if (rval_probe == SATA_SUCCESS &&
17231 		    (sata_device.satadev_state &
17232 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17233 		    (sata_device.satadev_scr.sstatus  &
17234 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17235 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17236 			/*
17237 			 * We may retry this a bit later - in-process reset
17238 			 * condition should be already set.
17239 			 * Track retry time for device identification.
17240 			 */
17241 			if ((cportinfo->cport_dev_type &
17242 			    SATA_VALID_DEV_TYPE) != 0 &&
17243 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17244 			    sdinfo->satadrv_reset_time != 0) {
17245 				clock_t cur_time = ddi_get_lbolt();
17246 				/*
17247 				 * If the retry time limit was not
17248 				 * exceeded, retry.
17249 				 */
17250 				if ((cur_time - sdinfo->satadrv_reset_time) <
17251 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17252 					mutex_enter(
17253 					    &sata_hba_inst->satahba_mutex);
17254 					sata_hba_inst->satahba_event_flags |=
17255 					    SATA_EVNT_MAIN;
17256 					mutex_exit(
17257 					    &sata_hba_inst->satahba_mutex);
17258 					mutex_enter(&sata_mutex);
17259 					sata_event_pending |= SATA_EVNT_MAIN;
17260 					mutex_exit(&sata_mutex);
17261 					return;
17262 				}
17263 				if (rval_set == SATA_RETRY) {
17264 					/*
17265 					 * Setting drive features failed, but
17266 					 * the drive is still accessible,
17267 					 * so emit a warning message before
17268 					 * return.
17269 					 */
17270 					mutex_exit(&SATA_CPORT_INFO(
17271 					    sata_hba_inst,
17272 					    saddr->cport)->cport_mutex);
17273 					goto done;
17274 				}
17275 			}
17276 			/* Fail the drive */
17277 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17278 
17279 			sata_log(sata_hba_inst, CE_WARN,
17280 			    "SATA device at port %d - device failed",
17281 			    saddr->cport);
17282 		}
17283 		/*
17284 		 * No point of retrying - device failed or some other event
17285 		 * processing or already did or will do port info cleanup.
17286 		 * To be safe (HBA may need it),
17287 		 * request clearing device reset condition.
17288 		 */
17289 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
17290 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17291 		sdinfo->satadrv_reset_time = 0;
17292 		return;
17293 	}
17294 done:
17295 	/*
17296 	 * If setting of drive features failed, but the drive is still
17297 	 * accessible, emit a warning message.
17298 	 */
17299 	if (rval_set == SATA_RETRY) {
17300 		sata_log(sata_hba_inst, CE_WARN,
17301 		    "SATA device at port %d - desired setting could not be "
17302 		    "restored after reset. Device may not operate as expected.",
17303 		    saddr->cport);
17304 	}
17305 	/*
17306 	 * Raise the flag indicating that the next sata command could
17307 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17308 	 * reset is reported.
17309 	 */
17310 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17311 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
17312 		sdinfo->satadrv_reset_time = 0;
17313 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
17314 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17315 			sdinfo->satadrv_event_flags &=
17316 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17317 			sdinfo->satadrv_event_flags |=
17318 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17319 		}
17320 	}
17321 }
17322 
17323 
17324 /*
17325  * Port Multiplier Port Device Reset Event processing.
17326  *
17327  * NOTE: This function has to be entered with pmport mutex held. It exits with
17328  * mutex held as well, but can release mutex during the processing.
17329  */
17330 static void
17331 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
17332     sata_address_t *saddr)
17333 {
17334 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17335 	sata_drive_info_t *sdinfo = NULL;
17336 	sata_cport_info_t *cportinfo = NULL;
17337 	sata_pmport_info_t *pmportinfo = NULL;
17338 	sata_pmult_info_t *pminfo = NULL;
17339 	sata_device_t sata_device;
17340 	uint8_t cport = saddr->cport;
17341 	uint8_t pmport = saddr->pmport;
17342 	int rval;
17343 
17344 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17345 	    "Processing drive reset at port %d:%d", cport, pmport);
17346 
17347 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17348 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17349 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
17350 
17351 	/*
17352 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17353 	 * state, ignore reset event.
17354 	 */
17355 	if (((cportinfo->cport_state &
17356 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17357 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17358 		sdinfo->satadrv_event_flags &=
17359 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17360 		return;
17361 	}
17362 
17363 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
17364 		/*
17365 		 * This should not happen - coding error.
17366 		 * But we can recover, so do not panic, just clean up
17367 		 * and if in debug mode, log the message.
17368 		 */
17369 #ifdef SATA_DEBUG
17370 		sata_log(sata_hba_inst, CE_WARN,
17371 		    "sata_process_pmdevice_reset: "
17372 		    "Invalid device type with sdinfo!", NULL);
17373 #endif
17374 		sdinfo->satadrv_event_flags = 0;
17375 		return;
17376 	}
17377 
17378 #ifdef SATA_DEBUG
17379 	if ((sdinfo->satadrv_event_flags &
17380 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17381 		/* Nothing to do */
17382 		/* Something is weird - why we are processing dev reset? */
17383 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17384 		    "No device reset event!!!!", NULL);
17385 
17386 		return;
17387 	}
17388 	if ((sdinfo->satadrv_event_flags &
17389 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17390 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17391 		/* Something is weird - new device reset event */
17392 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17393 		    "Overlapping device reset events!", NULL);
17394 	}
17395 #endif
17396 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17397 	    "Processing port %d:%d device reset", cport, pmport);
17398 
17399 	/* Clear event flag */
17400 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17401 
17402 	/* It seems that we always need to check the port state first */
17403 	sata_device.satadev_rev = SATA_DEVICE_REV;
17404 	sata_device.satadev_addr = *saddr;
17405 	/*
17406 	 * We have to exit mutex, because the HBA probe port function may
17407 	 * block on its own mutex.
17408 	 */
17409 	mutex_exit(&pmportinfo->pmport_mutex);
17410 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17411 	    (SATA_DIP(sata_hba_inst), &sata_device);
17412 	mutex_enter(&pmportinfo->pmport_mutex);
17413 
17414 	sata_update_pmport_info(sata_hba_inst, &sata_device);
17415 	if (rval != SATA_SUCCESS) {
17416 		/* Something went wrong? Fail the port */
17417 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
17418 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
17419 		    saddr->pmport);
17420 		if (sdinfo != NULL)
17421 			sdinfo->satadrv_event_flags = 0;
17422 		mutex_exit(&pmportinfo->pmport_mutex);
17423 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17424 		    "SATA port %d:%d probing failed",
17425 		    saddr->cport, saddr->pmport));
17426 		mutex_enter(&pmportinfo->pmport_mutex);
17427 		return;
17428 	}
17429 	if ((sata_device.satadev_scr.sstatus  &
17430 	    SATA_PORT_DEVLINK_UP_MASK) !=
17431 	    SATA_PORT_DEVLINK_UP ||
17432 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17433 		/*
17434 		 * No device to process, anymore. Some other event processing
17435 		 * would or have already performed port info cleanup.
17436 		 * To be safe (HBA may need it), request clearing device
17437 		 * reset condition.
17438 		 */
17439 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
17440 		    saddr->pmport);
17441 		if (sdinfo != NULL) {
17442 			sdinfo->satadrv_event_flags &=
17443 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17444 			/* must clear flags on cport */
17445 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
17446 			    saddr->cport);
17447 			pminfo->pmult_event_flags |=
17448 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17449 		}
17450 		return;
17451 	}
17452 
17453 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
17454 	    saddr->pmport);
17455 	if (sdinfo == NULL) {
17456 		return;
17457 	}
17458 	if ((sdinfo->satadrv_event_flags &
17459 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17460 		/*
17461 		 * Start tracking time for device feature restoration and
17462 		 * identification. Save current time (lbolt value).
17463 		 */
17464 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17465 	}
17466 	/* Mark device reset processing as active */
17467 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17468 
17469 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17470 	mutex_exit(&pmportinfo->pmport_mutex);
17471 
17472 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
17473 	    SATA_FAILURE) {
17474 		/*
17475 		 * Restoring drive setting failed.
17476 		 * Probe the port first, to check if the port state has changed
17477 		 */
17478 		sata_device.satadev_rev = SATA_DEVICE_REV;
17479 		sata_device.satadev_addr = *saddr;
17480 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
17481 
17482 		/* probe port */
17483 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17484 		    (SATA_DIP(sata_hba_inst), &sata_device);
17485 		mutex_enter(&pmportinfo->pmport_mutex);
17486 		if (rval == SATA_SUCCESS &&
17487 		    (sata_device.satadev_state &
17488 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17489 		    (sata_device.satadev_scr.sstatus  &
17490 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17491 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17492 			/*
17493 			 * We may retry this a bit later - in-process reset
17494 			 * condition should be already set.
17495 			 * Track retry time for device identification.
17496 			 */
17497 			if ((pmportinfo->pmport_dev_type &
17498 			    SATA_VALID_DEV_TYPE) != 0 &&
17499 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
17500 			    sdinfo->satadrv_reset_time != 0) {
17501 				clock_t cur_time = ddi_get_lbolt();
17502 				/*
17503 				 * If the retry time limit was not
17504 				 * exceeded, retry.
17505 				 */
17506 				if ((cur_time - sdinfo->satadrv_reset_time) <
17507 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17508 					mutex_enter(
17509 					    &sata_hba_inst->satahba_mutex);
17510 					sata_hba_inst->satahba_event_flags |=
17511 					    SATA_EVNT_MAIN;
17512 					mutex_exit(
17513 					    &sata_hba_inst->satahba_mutex);
17514 					mutex_enter(&sata_mutex);
17515 					sata_event_pending |= SATA_EVNT_MAIN;
17516 					mutex_exit(&sata_mutex);
17517 					return;
17518 				}
17519 			}
17520 			/* Fail the drive */
17521 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17522 
17523 			sata_log(sata_hba_inst, CE_WARN,
17524 			    "SATA device at port %d:%d - device failed",
17525 			    saddr->cport, saddr->pmport);
17526 		} else {
17527 			/*
17528 			 * No point of retrying - some other event processing
17529 			 * would or already did port info cleanup.
17530 			 * To be safe (HBA may need it),
17531 			 * request clearing device reset condition.
17532 			 */
17533 			sdinfo->satadrv_event_flags |=
17534 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17535 		}
17536 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17537 		sdinfo->satadrv_reset_time = 0;
17538 		return;
17539 	}
17540 	/*
17541 	 * Raise the flag indicating that the next sata command could
17542 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17543 	 * reset is reported.
17544 	 */
17545 	mutex_enter(&pmportinfo->pmport_mutex);
17546 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
17547 		sdinfo->satadrv_reset_time = 0;
17548 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
17549 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
17550 			sdinfo->satadrv_event_flags &=
17551 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17552 			/* must clear flags on cport */
17553 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
17554 			    saddr->cport);
17555 			pminfo->pmult_event_flags |=
17556 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17557 		}
17558 	}
17559 }
17560 
17561 /*
17562  * Port Link Events processing.
17563  * Every link established event may involve device reset (due to
17564  * COMRESET signal, equivalent of the hard reset) so arbitrarily
17565  * set device reset event for an attached device (if any).
17566  * If the port is in SHUTDOWN or FAILED state, ignore link events.
17567  *
17568  * The link established event processing varies, depending on the state
17569  * of the target node, HBA hotplugging capabilities, state of the port.
17570  * If the link is not active, the link established event is ignored.
17571  * If HBA cannot detect device attachment and there is no target node,
17572  * the link established event triggers device attach event processing.
17573  * Else, link established event triggers device reset event processing.
17574  *
17575  * The link lost event processing varies, depending on a HBA hotplugging
17576  * capability and the state of the port (link active or not active).
17577  * If the link is active, the lost link event is ignored.
17578  * If HBA cannot detect device removal, the lost link event triggers
17579  * device detached event processing after link lost timeout.
17580  * Else, the event is ignored.
17581  *
17582  * NOTE: Port multiplier ports events are handled by
17583  * sata_process_pmport_link_events();
17584  */
17585 static void
17586 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
17587     sata_address_t *saddr)
17588 {
17589 	sata_device_t sata_device;
17590 	sata_cport_info_t *cportinfo;
17591 	sata_drive_info_t *sdinfo;
17592 	uint32_t event_flags;
17593 	int rval;
17594 
17595 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17596 	    "Processing port %d link event(s)", saddr->cport);
17597 
17598 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17599 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17600 	event_flags = cportinfo->cport_event_flags;
17601 
17602 	/* Reset event flags first */
17603 	cportinfo->cport_event_flags &=
17604 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
17605 
17606 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
17607 	if ((cportinfo->cport_state &
17608 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
17609 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17610 		    cport_mutex);
17611 		return;
17612 	}
17613 
17614 	/*
17615 	 * For the sanity sake get current port state.
17616 	 * Set device address only. Other sata_device fields should be
17617 	 * set by HBA driver.
17618 	 */
17619 	sata_device.satadev_rev = SATA_DEVICE_REV;
17620 	sata_device.satadev_addr = *saddr;
17621 	/*
17622 	 * We have to exit mutex, because the HBA probe port function may
17623 	 * block on its own mutex.
17624 	 */
17625 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17626 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17627 	    (SATA_DIP(sata_hba_inst), &sata_device);
17628 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17629 	sata_update_port_info(sata_hba_inst, &sata_device);
17630 	if (rval != SATA_SUCCESS) {
17631 		/* Something went wrong? Fail the port */
17632 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17633 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17634 		    cport_mutex);
17635 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17636 		    "SATA port %d probing failed",
17637 		    saddr->cport));
17638 		/*
17639 		 * We may want to release device info structure, but
17640 		 * it is not necessary.
17641 		 */
17642 		return;
17643 	} else {
17644 		/* port probed successfully */
17645 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
17646 	}
17647 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
17648 
17649 		if ((sata_device.satadev_scr.sstatus &
17650 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
17651 			/* Ignore event */
17652 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17653 			    "Ignoring port %d link established event - "
17654 			    "link down",
17655 			    saddr->cport);
17656 			goto linklost;
17657 		}
17658 
17659 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17660 		    "Processing port %d link established event",
17661 		    saddr->cport);
17662 
17663 		/*
17664 		 * For the sanity sake check if a device is attached - check
17665 		 * return state of a port probing.
17666 		 */
17667 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
17668 			/*
17669 			 * HBA port probe indicated that there is a device
17670 			 * attached. Check if the framework had device info
17671 			 * structure attached for this device.
17672 			 */
17673 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
17674 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
17675 				    NULL);
17676 
17677 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17678 				if ((sdinfo->satadrv_type &
17679 				    SATA_VALID_DEV_TYPE) != 0) {
17680 					/*
17681 					 * Dev info structure is present.
17682 					 * If dev_type is set to known type in
17683 					 * the framework's drive info struct
17684 					 * then the device existed before and
17685 					 * the link was probably lost
17686 					 * momentarily - in such case
17687 					 * we may want to check device
17688 					 * identity.
17689 					 * Identity check is not supported now.
17690 					 *
17691 					 * Link established event
17692 					 * triggers device reset event.
17693 					 */
17694 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
17695 					    satadrv_event_flags |=
17696 					    SATA_EVNT_DEVICE_RESET;
17697 				}
17698 			} else if (cportinfo->cport_dev_type ==
17699 			    SATA_DTYPE_NONE) {
17700 				/*
17701 				 * We got new device attached! If HBA does not
17702 				 * generate device attached events, trigger it
17703 				 * here.
17704 				 */
17705 				if (!(SATA_FEATURES(sata_hba_inst) &
17706 				    SATA_CTLF_HOTPLUG)) {
17707 					cportinfo->cport_event_flags |=
17708 					    SATA_EVNT_DEVICE_ATTACHED;
17709 				}
17710 			}
17711 			/* Reset link lost timeout */
17712 			cportinfo->cport_link_lost_time = 0;
17713 		}
17714 	}
17715 linklost:
17716 	if (event_flags & SATA_EVNT_LINK_LOST) {
17717 		if ((sata_device.satadev_scr.sstatus &
17718 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
17719 			/* Ignore event */
17720 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17721 			    "Ignoring port %d link lost event - link is up",
17722 			    saddr->cport);
17723 			goto done;
17724 		}
17725 #ifdef SATA_DEBUG
17726 		if (cportinfo->cport_link_lost_time == 0) {
17727 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17728 			    "Processing port %d link lost event",
17729 			    saddr->cport);
17730 		}
17731 #endif
17732 		/*
17733 		 * When HBA cannot generate device attached/detached events,
17734 		 * we need to track link lost time and eventually generate
17735 		 * device detach event.
17736 		 */
17737 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
17738 			/* We are tracking link lost time */
17739 			if (cportinfo->cport_link_lost_time == 0) {
17740 				/* save current time (lbolt value) */
17741 				cportinfo->cport_link_lost_time =
17742 				    ddi_get_lbolt();
17743 				/* just keep link lost event */
17744 				cportinfo->cport_event_flags |=
17745 				    SATA_EVNT_LINK_LOST;
17746 			} else {
17747 				clock_t cur_time = ddi_get_lbolt();
17748 				if ((cur_time -
17749 				    cportinfo->cport_link_lost_time) >=
17750 				    drv_usectohz(
17751 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
17752 					/* trigger device detach event */
17753 					cportinfo->cport_event_flags |=
17754 					    SATA_EVNT_DEVICE_DETACHED;
17755 					cportinfo->cport_link_lost_time = 0;
17756 					SATADBG1(SATA_DBG_EVENTS,
17757 					    sata_hba_inst,
17758 					    "Triggering port %d "
17759 					    "device detached event",
17760 					    saddr->cport);
17761 				} else {
17762 					/* keep link lost event */
17763 					cportinfo->cport_event_flags |=
17764 					    SATA_EVNT_LINK_LOST;
17765 				}
17766 			}
17767 		}
17768 		/*
17769 		 * We could change port state to disable/delay access to
17770 		 * the attached device until the link is recovered.
17771 		 */
17772 	}
17773 done:
17774 	event_flags = cportinfo->cport_event_flags;
17775 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17776 	if (event_flags != 0) {
17777 		mutex_enter(&sata_hba_inst->satahba_mutex);
17778 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17779 		mutex_exit(&sata_hba_inst->satahba_mutex);
17780 		mutex_enter(&sata_mutex);
17781 		sata_event_pending |= SATA_EVNT_MAIN;
17782 		mutex_exit(&sata_mutex);
17783 	}
17784 }
17785 
17786 /*
17787  * Port Multiplier Port Link Events processing.
17788  */
17789 static void
17790 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
17791     sata_address_t *saddr)
17792 {
17793 	sata_device_t sata_device;
17794 	sata_pmport_info_t *pmportinfo = NULL;
17795 	sata_drive_info_t *sdinfo = NULL;
17796 	uint32_t event_flags;
17797 	uint8_t cport = saddr->cport;
17798 	uint8_t pmport = saddr->pmport;
17799 	int rval;
17800 
17801 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17802 	    "Processing port %d:%d link event(s)",
17803 	    cport, pmport);
17804 
17805 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17806 	mutex_enter(&pmportinfo->pmport_mutex);
17807 	event_flags = pmportinfo->pmport_event_flags;
17808 
17809 	/* Reset event flags first */
17810 	pmportinfo->pmport_event_flags &=
17811 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
17812 
17813 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
17814 	if ((pmportinfo->pmport_state &
17815 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
17816 		mutex_exit(&pmportinfo->pmport_mutex);
17817 		return;
17818 	}
17819 
17820 	/*
17821 	 * For the sanity sake get current port state.
17822 	 * Set device address only. Other sata_device fields should be
17823 	 * set by HBA driver.
17824 	 */
17825 	sata_device.satadev_rev = SATA_DEVICE_REV;
17826 	sata_device.satadev_addr = *saddr;
17827 	/*
17828 	 * We have to exit mutex, because the HBA probe port function may
17829 	 * block on its own mutex.
17830 	 */
17831 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
17832 	    saddr->pmport));
17833 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17834 	    (SATA_DIP(sata_hba_inst), &sata_device);
17835 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
17836 	    saddr->pmport));
17837 	sata_update_pmport_info(sata_hba_inst, &sata_device);
17838 	if (rval != SATA_SUCCESS) {
17839 		/* Something went wrong? Fail the port */
17840 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
17841 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
17842 		    saddr->pmport));
17843 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17844 		    "SATA port %d:%d probing failed",
17845 		    saddr->cport, saddr->pmport));
17846 		/*
17847 		 * We may want to release device info structure, but
17848 		 * it is not necessary.
17849 		 */
17850 		return;
17851 	} else {
17852 		/* port probed successfully */
17853 		pmportinfo->pmport_state |=
17854 		    SATA_STATE_PROBED | SATA_STATE_READY;
17855 	}
17856 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
17857 	    saddr->cport, saddr->pmport));
17858 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
17859 	    saddr->cport, saddr->pmport));
17860 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
17861 
17862 		if ((sata_device.satadev_scr.sstatus &
17863 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
17864 			/* Ignore event */
17865 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17866 			    "Ignoring port %d:%d link established event - "
17867 			    "link down",
17868 			    saddr->cport, saddr->pmport);
17869 			goto linklost;
17870 		}
17871 
17872 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17873 		    "Processing port %d:%d link established event",
17874 		    cport, pmport);
17875 
17876 		/*
17877 		 * For the sanity sake check if a device is attached - check
17878 		 * return state of a port probing.
17879 		 */
17880 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
17881 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
17882 			/*
17883 			 * HBA port probe indicated that there is a device
17884 			 * attached. Check if the framework had device info
17885 			 * structure attached for this device.
17886 			 */
17887 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
17888 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
17889 				    NULL);
17890 
17891 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
17892 				if ((sdinfo->satadrv_type &
17893 				    SATA_VALID_DEV_TYPE) != 0) {
17894 					/*
17895 					 * Dev info structure is present.
17896 					 * If dev_type is set to known type in
17897 					 * the framework's drive info struct
17898 					 * then the device existed before and
17899 					 * the link was probably lost
17900 					 * momentarily - in such case
17901 					 * we may want to check device
17902 					 * identity.
17903 					 * Identity check is not supported now.
17904 					 *
17905 					 * Link established event
17906 					 * triggers device reset event.
17907 					 */
17908 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
17909 					    satadrv_event_flags |=
17910 					    SATA_EVNT_DEVICE_RESET;
17911 				}
17912 			} else if (pmportinfo->pmport_dev_type ==
17913 			    SATA_DTYPE_NONE) {
17914 				/*
17915 				 * We got new device attached! If HBA does not
17916 				 * generate device attached events, trigger it
17917 				 * here.
17918 				 */
17919 				if (!(SATA_FEATURES(sata_hba_inst) &
17920 				    SATA_CTLF_HOTPLUG)) {
17921 					pmportinfo->pmport_event_flags |=
17922 					    SATA_EVNT_DEVICE_ATTACHED;
17923 				}
17924 			}
17925 			/* Reset link lost timeout */
17926 			pmportinfo->pmport_link_lost_time = 0;
17927 		}
17928 	}
17929 linklost:
17930 	if (event_flags & SATA_EVNT_LINK_LOST) {
17931 #ifdef SATA_DEBUG
17932 		if (pmportinfo->pmport_link_lost_time == 0) {
17933 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17934 			    "Processing port %d:%d link lost event",
17935 			    saddr->cport, saddr->pmport);
17936 		}
17937 #endif
17938 		if ((sata_device.satadev_scr.sstatus &
17939 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
17940 			/* Ignore event */
17941 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17942 			    "Ignoring port %d:%d link lost event - link is up",
17943 			    saddr->cport, saddr->pmport);
17944 			goto done;
17945 		}
17946 		/*
17947 		 * When HBA cannot generate device attached/detached events,
17948 		 * we need to track link lost time and eventually generate
17949 		 * device detach event.
17950 		 */
17951 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
17952 			/* We are tracking link lost time */
17953 			if (pmportinfo->pmport_link_lost_time == 0) {
17954 				/* save current time (lbolt value) */
17955 				pmportinfo->pmport_link_lost_time =
17956 				    ddi_get_lbolt();
17957 				/* just keep link lost event */
17958 				pmportinfo->pmport_event_flags |=
17959 				    SATA_EVNT_LINK_LOST;
17960 			} else {
17961 				clock_t cur_time = ddi_get_lbolt();
17962 				if ((cur_time -
17963 				    pmportinfo->pmport_link_lost_time) >=
17964 				    drv_usectohz(
17965 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
17966 					/* trigger device detach event */
17967 					pmportinfo->pmport_event_flags |=
17968 					    SATA_EVNT_DEVICE_DETACHED;
17969 					pmportinfo->pmport_link_lost_time = 0;
17970 					SATADBG2(SATA_DBG_EVENTS,
17971 					    sata_hba_inst,
17972 					    "Triggering port %d:%d "
17973 					    "device detached event",
17974 					    saddr->cport, saddr->pmport);
17975 				} else {
17976 					/* keep link lost event */
17977 					pmportinfo->pmport_event_flags |=
17978 					    SATA_EVNT_LINK_LOST;
17979 				}
17980 			}
17981 		}
17982 		/*
17983 		 * We could change port state to disable/delay access to
17984 		 * the attached device until the link is recovered.
17985 		 */
17986 	}
17987 done:
17988 	event_flags = pmportinfo->pmport_event_flags;
17989 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
17990 	    saddr->pmport));
17991 	if (event_flags != 0) {
17992 		mutex_enter(&sata_hba_inst->satahba_mutex);
17993 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17994 		mutex_exit(&sata_hba_inst->satahba_mutex);
17995 		mutex_enter(&sata_mutex);
17996 		sata_event_pending |= SATA_EVNT_MAIN;
17997 		mutex_exit(&sata_mutex);
17998 	}
17999 }
18000 
18001 /*
18002  * Device Detached Event processing.
18003  * Port is probed to find if a device is really gone. If so,
18004  * the device info structure is detached from the SATA port info structure
18005  * and released.
18006  * Port status is updated.
18007  *
18008  * NOTE: Port multiplier ports events are handled by
18009  * sata_process_pmdevice_detached()
18010  */
18011 static void
18012 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18013     sata_address_t *saddr)
18014 {
18015 	sata_cport_info_t *cportinfo;
18016 	sata_pmport_info_t *pmportinfo;
18017 	sata_drive_info_t *sdevinfo;
18018 	sata_device_t sata_device;
18019 	sata_address_t pmport_addr;
18020 	char name[16];
18021 	uint8_t cport = saddr->cport;
18022 	int npmport;
18023 	int rval;
18024 
18025 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18026 	    "Processing port %d device detached", saddr->cport);
18027 
18028 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18029 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18030 	/* Clear event flag */
18031 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18032 
18033 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18034 	if ((cportinfo->cport_state &
18035 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18036 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18037 		    cport_mutex);
18038 		return;
18039 	}
18040 	/* For sanity, re-probe the port */
18041 	sata_device.satadev_rev = SATA_DEVICE_REV;
18042 	sata_device.satadev_addr = *saddr;
18043 
18044 	/*
18045 	 * We have to exit mutex, because the HBA probe port function may
18046 	 * block on its own mutex.
18047 	 */
18048 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18049 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18050 	    (SATA_DIP(sata_hba_inst), &sata_device);
18051 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18052 	sata_update_port_info(sata_hba_inst, &sata_device);
18053 	if (rval != SATA_SUCCESS) {
18054 		/* Something went wrong? Fail the port */
18055 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18056 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18057 		    cport_mutex);
18058 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18059 		    "SATA port %d probing failed",
18060 		    saddr->cport));
18061 		/*
18062 		 * We may want to release device info structure, but
18063 		 * it is not necessary.
18064 		 */
18065 		return;
18066 	} else {
18067 		/* port probed successfully */
18068 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18069 	}
18070 	/*
18071 	 * Check if a device is still attached. For sanity, check also
18072 	 * link status - if no link, there is no device.
18073 	 */
18074 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18075 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18076 	    SATA_DTYPE_NONE) {
18077 		/*
18078 		 * Device is still attached - ignore detach event.
18079 		 */
18080 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18081 		    cport_mutex);
18082 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18083 		    "Ignoring detach - device still attached to port %d",
18084 		    sata_device.satadev_addr.cport);
18085 		return;
18086 	}
18087 	/*
18088 	 * We need to detach and release device info structure here
18089 	 */
18090 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18091 		/*
18092 		 * A port-multiplier is removed.
18093 		 *
18094 		 * Calling sata_process_pmdevice_detached() does not work
18095 		 * here. The port multiplier is gone, so we cannot probe
18096 		 * sub-port any more and all pmult-related data structure must
18097 		 * be de-allocated immediately. Following structure of every
18098 		 * implemented sub-port behind the pmult are required to
18099 		 * released.
18100 		 *
18101 		 *   - attachment point
18102 		 *   - target node
18103 		 *   - sata_drive_info
18104 		 *   - sata_pmport_info
18105 		 */
18106 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18107 		    cport); npmport ++) {
18108 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18109 			    sata_hba_inst,
18110 			    "Detaching target node at port %d:%d",
18111 			    cport, npmport);
18112 
18113 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18114 
18115 			/* Remove attachment point. */
18116 			name[0] = '\0';
18117 			(void) sprintf(name, "%d.%d", cport, npmport);
18118 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18119 			sata_log(sata_hba_inst, CE_NOTE,
18120 			    "Remove attachment point of port %d:%d",
18121 			    cport, npmport);
18122 
18123 			/* Remove target node */
18124 			pmport_addr.cport = cport;
18125 			pmport_addr.pmport = (uint8_t)npmport;
18126 			pmport_addr.qual = SATA_ADDR_PMPORT;
18127 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18128 
18129 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18130 
18131 			/* Release sata_pmport_info & sata_drive_info. */
18132 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18133 			    cport, npmport);
18134 			ASSERT(pmportinfo != NULL);
18135 
18136 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18137 			if (sdevinfo != NULL) {
18138 				(void) kmem_free((void *) sdevinfo,
18139 				    sizeof (sata_drive_info_t));
18140 			}
18141 
18142 			/* Release sata_pmport_info at last */
18143 			(void) kmem_free((void *) pmportinfo,
18144 			    sizeof (sata_pmport_info_t));
18145 		}
18146 
18147 		/* Finally, release sata_pmult_info */
18148 		(void) kmem_free((void *)
18149 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18150 		    sizeof (sata_pmult_info_t));
18151 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18152 
18153 		sata_log(sata_hba_inst, CE_WARN,
18154 		    "SATA port-multiplier detached at port %d", cport);
18155 
18156 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18157 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18158 		    saddr->cport)->cport_mutex);
18159 	} else {
18160 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18161 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18162 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18163 			(void) kmem_free((void *)sdevinfo,
18164 			    sizeof (sata_drive_info_t));
18165 		}
18166 		sata_log(sata_hba_inst, CE_WARN,
18167 		    "SATA device detached at port %d", cport);
18168 
18169 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18170 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18171 		    saddr->cport)->cport_mutex);
18172 
18173 		/*
18174 		 * Try to offline a device and remove target node
18175 		 * if it still exists
18176 		 */
18177 		sata_remove_target_node(sata_hba_inst, saddr);
18178 	}
18179 
18180 
18181 	/*
18182 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18183 	 * with the hint: SE_HINT_REMOVE
18184 	 */
18185 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18186 }
18187 
18188 /*
18189  * Port Multiplier Port Device Deattached Event processing.
18190  *
18191  * NOTE: No Mutex should be hold.
18192  */
18193 static void
18194 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18195     sata_address_t *saddr)
18196 {
18197 	sata_pmport_info_t *pmportinfo;
18198 	sata_drive_info_t *sdevinfo;
18199 	sata_device_t sata_device;
18200 	int rval;
18201 	uint8_t cport, pmport;
18202 
18203 	cport = saddr->cport;
18204 	pmport = saddr->pmport;
18205 
18206 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18207 	    "Processing port %d:%d device detached",
18208 	    cport, pmport);
18209 
18210 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18211 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18212 
18213 	/* Clear event flag */
18214 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18215 
18216 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18217 	if ((pmportinfo->pmport_state &
18218 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18219 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18220 		return;
18221 	}
18222 	/* For sanity, re-probe the port */
18223 	sata_device.satadev_rev = SATA_DEVICE_REV;
18224 	sata_device.satadev_addr = *saddr;
18225 
18226 	/*
18227 	 * We have to exit mutex, because the HBA probe port function may
18228 	 * block on its own mutex.
18229 	 */
18230 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18231 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18232 	    (SATA_DIP(sata_hba_inst), &sata_device);
18233 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18234 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18235 	if (rval != SATA_SUCCESS) {
18236 		/* Something went wrong? Fail the port */
18237 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18238 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18239 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18240 		    "SATA port %d:%d probing failed",
18241 		    saddr->pmport));
18242 		/*
18243 		 * We may want to release device info structure, but
18244 		 * it is not necessary.
18245 		 */
18246 		return;
18247 	} else {
18248 		/* port probed successfully */
18249 		pmportinfo->pmport_state |=
18250 		    SATA_STATE_PROBED | SATA_STATE_READY;
18251 	}
18252 	/*
18253 	 * Check if a device is still attached. For sanity, check also
18254 	 * link status - if no link, there is no device.
18255 	 */
18256 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18257 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18258 	    SATA_DTYPE_NONE) {
18259 		/*
18260 		 * Device is still attached - ignore detach event.
18261 		 */
18262 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18263 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18264 		    "Ignoring detach - device still attached to port %d",
18265 		    sata_device.satadev_addr.pmport);
18266 		return;
18267 	}
18268 	/*
18269 	 * We need to detach and release device info structure here
18270 	 */
18271 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18272 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18273 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18274 		(void) kmem_free((void *)sdevinfo,
18275 		    sizeof (sata_drive_info_t));
18276 	}
18277 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18278 	/*
18279 	 * Device cannot be reached anymore, even if the target node may be
18280 	 * still present.
18281 	 */
18282 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18283 
18284 	/*
18285 	 * Try to offline a device and remove target node if it still exists
18286 	 */
18287 	sata_remove_target_node(sata_hba_inst, saddr);
18288 
18289 	/*
18290 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18291 	 * with the hint: SE_HINT_REMOVE
18292 	 */
18293 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18294 }
18295 
18296 
18297 /*
18298  * Device Attached Event processing.
18299  * Port state is checked to verify that a device is really attached. If so,
18300  * the device info structure is created and attached to the SATA port info
18301  * structure.
18302  *
18303  * If attached device cannot be identified or set-up, the retry for the
18304  * attach processing is set-up. Subsequent daemon run would try again to
18305  * identify the device, until the time limit is reached
18306  * (SATA_DEV_IDENTIFY_TIMEOUT).
18307  *
18308  * This function cannot be called in interrupt context (it may sleep).
18309  *
18310  * NOTE: Port multiplier ports events are handled by
18311  * sata_process_pmdevice_attached()
18312  */
18313 static void
18314 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
18315     sata_address_t *saddr)
18316 {
18317 	sata_cport_info_t *cportinfo = NULL;
18318 	sata_drive_info_t *sdevinfo = NULL;
18319 	sata_pmult_info_t *pmultinfo = NULL;
18320 	sata_pmport_info_t *pmportinfo = NULL;
18321 	sata_device_t sata_device;
18322 	dev_info_t *tdip;
18323 	uint32_t event_flags = 0, pmult_event_flags = 0;
18324 	int rval;
18325 	int npmport;
18326 
18327 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18328 	    "Processing port %d device attached", saddr->cport);
18329 
18330 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18331 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18332 
18333 	/* Clear attach event flag first */
18334 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18335 
18336 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18337 	if ((cportinfo->cport_state &
18338 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18339 		cportinfo->cport_dev_attach_time = 0;
18340 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18341 		    cport_mutex);
18342 		return;
18343 	}
18344 
18345 	/*
18346 	 * If the sata_drive_info structure is found attached to the port info,
18347 	 * despite the fact the device was removed and now it is re-attached,
18348 	 * the old drive info structure was not removed.
18349 	 * Arbitrarily release device info structure.
18350 	 */
18351 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18352 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18353 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18354 		(void) kmem_free((void *)sdevinfo,
18355 		    sizeof (sata_drive_info_t));
18356 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18357 		    "Arbitrarily detaching old device info.", NULL);
18358 	}
18359 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18360 
18361 	/* For sanity, re-probe the port */
18362 	sata_device.satadev_rev = SATA_DEVICE_REV;
18363 	sata_device.satadev_addr = *saddr;
18364 
18365 	/*
18366 	 * We have to exit mutex, because the HBA probe port function may
18367 	 * block on its own mutex.
18368 	 */
18369 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18370 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18371 	    (SATA_DIP(sata_hba_inst), &sata_device);
18372 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18373 	sata_update_port_info(sata_hba_inst, &sata_device);
18374 	if (rval != SATA_SUCCESS) {
18375 		/* Something went wrong? Fail the port */
18376 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18377 		cportinfo->cport_dev_attach_time = 0;
18378 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18379 		    cport_mutex);
18380 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18381 		    "SATA port %d probing failed",
18382 		    saddr->cport));
18383 		return;
18384 	} else {
18385 		/* port probed successfully */
18386 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18387 	}
18388 	/*
18389 	 * Check if a device is still attached. For sanity, check also
18390 	 * link status - if no link, there is no device.
18391 	 */
18392 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18393 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18394 	    SATA_DTYPE_NONE) {
18395 		/*
18396 		 * No device - ignore attach event.
18397 		 */
18398 		cportinfo->cport_dev_attach_time = 0;
18399 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18400 		    cport_mutex);
18401 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18402 		    "Ignoring attach - no device connected to port %d",
18403 		    sata_device.satadev_addr.cport);
18404 		return;
18405 	}
18406 
18407 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18408 	/*
18409 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18410 	 * with the hint: SE_HINT_INSERT
18411 	 */
18412 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
18413 
18414 	/*
18415 	 * Port reprobing will take care of the creation of the device
18416 	 * info structure and determination of the device type.
18417 	 */
18418 	sata_device.satadev_addr = *saddr;
18419 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
18420 	    SATA_DEV_IDENTIFY_NORETRY);
18421 
18422 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18423 	    cport_mutex);
18424 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
18425 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
18426 		/* Some device is attached to the port */
18427 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
18428 			/*
18429 			 * A device was not successfully attached.
18430 			 * Track retry time for device identification.
18431 			 */
18432 			if (cportinfo->cport_dev_attach_time != 0) {
18433 				clock_t cur_time = ddi_get_lbolt();
18434 				/*
18435 				 * If the retry time limit was not exceeded,
18436 				 * reinstate attach event.
18437 				 */
18438 				if ((cur_time -
18439 				    cportinfo->cport_dev_attach_time) <
18440 				    drv_usectohz(
18441 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
18442 					/* OK, restore attach event */
18443 					cportinfo->cport_event_flags |=
18444 					    SATA_EVNT_DEVICE_ATTACHED;
18445 				} else {
18446 					/* Timeout - cannot identify device */
18447 					cportinfo->cport_dev_attach_time = 0;
18448 					sata_log(sata_hba_inst,
18449 					    CE_WARN,
18450 					    "Could not identify SATA device "
18451 					    "at port %d",
18452 					    saddr->cport);
18453 				}
18454 			} else {
18455 				/*
18456 				 * Start tracking time for device
18457 				 * identification.
18458 				 * Save current time (lbolt value).
18459 				 */
18460 				cportinfo->cport_dev_attach_time =
18461 				    ddi_get_lbolt();
18462 				/* Restore attach event */
18463 				cportinfo->cport_event_flags |=
18464 				    SATA_EVNT_DEVICE_ATTACHED;
18465 			}
18466 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18467 			cportinfo->cport_dev_attach_time = 0;
18468 			sata_log(sata_hba_inst, CE_NOTE,
18469 			    "SATA port-multiplier detected at port %d",
18470 			    saddr->cport);
18471 
18472 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
18473 				/* Log the info of new port multiplier */
18474 				sata_show_pmult_info(sata_hba_inst,
18475 				    &sata_device);
18476 			}
18477 
18478 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
18479 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
18480 			for (npmport = 0; npmport <
18481 			    pmultinfo->pmult_num_dev_ports; npmport++) {
18482 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18483 				    saddr->cport, npmport);
18484 				ASSERT(pmportinfo != NULL);
18485 
18486 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18487 				    saddr->cport)->cport_mutex);
18488 				mutex_enter(&pmportinfo->pmport_mutex);
18489 				/* Marked all pmports with link events. */
18490 				pmportinfo->pmport_event_flags =
18491 				    SATA_EVNT_LINK_ESTABLISHED;
18492 				pmult_event_flags |=
18493 				    pmportinfo->pmport_event_flags;
18494 				mutex_exit(&pmportinfo->pmport_mutex);
18495 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18496 				    saddr->cport)->cport_mutex);
18497 			}
18498 			/* Auto-online is not available for PMult now. */
18499 
18500 		} else {
18501 			/*
18502 			 * If device was successfully attached, the subsequent
18503 			 * action depends on a state of the
18504 			 * sata_auto_online variable. If it is set to zero.
18505 			 * an explicit 'configure' command will be needed to
18506 			 * configure it. If its value is non-zero, we will
18507 			 * attempt to online (configure) the device.
18508 			 * First, log the message indicating that a device
18509 			 * was attached.
18510 			 */
18511 			cportinfo->cport_dev_attach_time = 0;
18512 			sata_log(sata_hba_inst, CE_WARN,
18513 			    "SATA device detected at port %d", saddr->cport);
18514 
18515 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18516 				sata_drive_info_t new_sdinfo;
18517 
18518 				/* Log device info data */
18519 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
18520 				    cportinfo));
18521 				sata_show_drive_info(sata_hba_inst,
18522 				    &new_sdinfo);
18523 			}
18524 
18525 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18526 			    saddr->cport)->cport_mutex);
18527 
18528 			/*
18529 			 * Make sure that there is no target node for that
18530 			 * device. If so, release it. It should not happen,
18531 			 * unless we had problem removing the node when
18532 			 * device was detached.
18533 			 */
18534 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
18535 			    saddr->cport, saddr->pmport);
18536 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18537 			    saddr->cport)->cport_mutex);
18538 			if (tdip != NULL) {
18539 
18540 #ifdef SATA_DEBUG
18541 				if ((cportinfo->cport_event_flags &
18542 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
18543 					sata_log(sata_hba_inst, CE_WARN,
18544 					    "sata_process_device_attached: "
18545 					    "old device target node exists!");
18546 #endif
18547 				/*
18548 				 * target node exists - try to unconfigure
18549 				 * device and remove the node.
18550 				 */
18551 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18552 				    saddr->cport)->cport_mutex);
18553 				rval = ndi_devi_offline(tdip,
18554 				    NDI_DEVI_REMOVE);
18555 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18556 				    saddr->cport)->cport_mutex);
18557 
18558 				if (rval == NDI_SUCCESS) {
18559 					cportinfo->cport_event_flags &=
18560 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
18561 					cportinfo->cport_tgtnode_clean = B_TRUE;
18562 				} else {
18563 					/*
18564 					 * PROBLEM - the target node remained
18565 					 * and it belongs to a previously
18566 					 * attached device.
18567 					 * This happens when the file was open
18568 					 * or the node was waiting for
18569 					 * resources at the time the
18570 					 * associated device was removed.
18571 					 * Instruct event daemon to retry the
18572 					 * cleanup later.
18573 					 */
18574 					sata_log(sata_hba_inst,
18575 					    CE_WARN,
18576 					    "Application(s) accessing "
18577 					    "previously attached SATA "
18578 					    "device have to release "
18579 					    "it before newly inserted "
18580 					    "device can be made accessible.",
18581 					    saddr->cport);
18582 					cportinfo->cport_event_flags |=
18583 					    SATA_EVNT_TARGET_NODE_CLEANUP;
18584 					cportinfo->cport_tgtnode_clean =
18585 					    B_FALSE;
18586 				}
18587 			}
18588 			if (sata_auto_online != 0) {
18589 				cportinfo->cport_event_flags |=
18590 				    SATA_EVNT_AUTOONLINE_DEVICE;
18591 			}
18592 
18593 		}
18594 	} else {
18595 		cportinfo->cport_dev_attach_time = 0;
18596 	}
18597 
18598 	event_flags = cportinfo->cport_event_flags;
18599 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18600 	if (event_flags != 0 || pmult_event_flags != 0) {
18601 		mutex_enter(&sata_hba_inst->satahba_mutex);
18602 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18603 		mutex_exit(&sata_hba_inst->satahba_mutex);
18604 		mutex_enter(&sata_mutex);
18605 		sata_event_pending |= SATA_EVNT_MAIN;
18606 		mutex_exit(&sata_mutex);
18607 	}
18608 }
18609 
18610 /*
18611  * Port Multiplier Port Device Attached Event processing.
18612  *
18613  * NOTE: No Mutex should be hold.
18614  */
18615 static void
18616 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
18617     sata_address_t *saddr)
18618 {
18619 	sata_pmport_info_t *pmportinfo;
18620 	sata_drive_info_t *sdinfo;
18621 	sata_device_t sata_device;
18622 	dev_info_t *tdip;
18623 	uint32_t event_flags;
18624 	uint8_t cport = saddr->cport;
18625 	uint8_t pmport = saddr->pmport;
18626 	int rval;
18627 
18628 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18629 	    "Processing port %d:%d device attached", cport, pmport);
18630 
18631 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18632 
18633 	mutex_enter(&pmportinfo->pmport_mutex);
18634 
18635 	/* Clear attach event flag first */
18636 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18637 
18638 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18639 	if ((pmportinfo->pmport_state &
18640 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18641 		pmportinfo->pmport_dev_attach_time = 0;
18642 		mutex_exit(&pmportinfo->pmport_mutex);
18643 		return;
18644 	}
18645 
18646 	/*
18647 	 * If the sata_drive_info structure is found attached to the port info,
18648 	 * despite the fact the device was removed and now it is re-attached,
18649 	 * the old drive info structure was not removed.
18650 	 * Arbitrarily release device info structure.
18651 	 */
18652 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18653 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18654 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18655 		(void) kmem_free((void *)sdinfo,
18656 		    sizeof (sata_drive_info_t));
18657 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18658 		    "Arbitrarily detaching old device info.", NULL);
18659 	}
18660 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18661 
18662 	/* For sanity, re-probe the port */
18663 	sata_device.satadev_rev = SATA_DEVICE_REV;
18664 	sata_device.satadev_addr = *saddr;
18665 
18666 	/*
18667 	 * We have to exit mutex, because the HBA probe port function may
18668 	 * block on its own mutex.
18669 	 */
18670 	mutex_exit(&pmportinfo->pmport_mutex);
18671 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18672 	    (SATA_DIP(sata_hba_inst), &sata_device);
18673 	mutex_enter(&pmportinfo->pmport_mutex);
18674 
18675 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18676 	if (rval != SATA_SUCCESS) {
18677 		/* Something went wrong? Fail the port */
18678 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18679 		pmportinfo->pmport_dev_attach_time = 0;
18680 		mutex_exit(&pmportinfo->pmport_mutex);
18681 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18682 		    "SATA port %d:%d probing failed", cport, pmport));
18683 		return;
18684 	} else {
18685 		/* pmport probed successfully */
18686 		pmportinfo->pmport_state |=
18687 		    SATA_STATE_PROBED | SATA_STATE_READY;
18688 	}
18689 	/*
18690 	 * Check if a device is still attached. For sanity, check also
18691 	 * link status - if no link, there is no device.
18692 	 */
18693 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18694 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18695 	    SATA_DTYPE_NONE) {
18696 		/*
18697 		 * No device - ignore attach event.
18698 		 */
18699 		pmportinfo->pmport_dev_attach_time = 0;
18700 		mutex_exit(&pmportinfo->pmport_mutex);
18701 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18702 		    "Ignoring attach - no device connected to port %d:%d",
18703 		    cport, pmport);
18704 		return;
18705 	}
18706 
18707 	mutex_exit(&pmportinfo->pmport_mutex);
18708 	/*
18709 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18710 	 * with the hint: SE_HINT_INSERT
18711 	 */
18712 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
18713 
18714 	/*
18715 	 * Port reprobing will take care of the creation of the device
18716 	 * info structure and determination of the device type.
18717 	 */
18718 	sata_device.satadev_addr = *saddr;
18719 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
18720 	    SATA_DEV_IDENTIFY_NORETRY);
18721 
18722 	mutex_enter(&pmportinfo->pmport_mutex);
18723 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
18724 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
18725 		/* Some device is attached to the port */
18726 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
18727 			/*
18728 			 * A device was not successfully attached.
18729 			 * Track retry time for device identification.
18730 			 */
18731 			if (pmportinfo->pmport_dev_attach_time != 0) {
18732 				clock_t cur_time = ddi_get_lbolt();
18733 				/*
18734 				 * If the retry time limit was not exceeded,
18735 				 * reinstate attach event.
18736 				 */
18737 				if ((cur_time -
18738 				    pmportinfo->pmport_dev_attach_time) <
18739 				    drv_usectohz(
18740 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
18741 					/* OK, restore attach event */
18742 					pmportinfo->pmport_event_flags |=
18743 					    SATA_EVNT_DEVICE_ATTACHED;
18744 				} else {
18745 					/* Timeout - cannot identify device */
18746 					pmportinfo->pmport_dev_attach_time = 0;
18747 					sata_log(sata_hba_inst, CE_WARN,
18748 					    "Could not identify SATA device "
18749 					    "at port %d:%d",
18750 					    cport, pmport);
18751 				}
18752 			} else {
18753 				/*
18754 				 * Start tracking time for device
18755 				 * identification.
18756 				 * Save current time (lbolt value).
18757 				 */
18758 				pmportinfo->pmport_dev_attach_time =
18759 				    ddi_get_lbolt();
18760 				/* Restore attach event */
18761 				pmportinfo->pmport_event_flags |=
18762 				    SATA_EVNT_DEVICE_ATTACHED;
18763 			}
18764 		} else {
18765 			/*
18766 			 * If device was successfully attached, the subsequent
18767 			 * action depends on a state of the
18768 			 * sata_auto_online variable. If it is set to zero.
18769 			 * an explicit 'configure' command will be needed to
18770 			 * configure it. If its value is non-zero, we will
18771 			 * attempt to online (configure) the device.
18772 			 * First, log the message indicating that a device
18773 			 * was attached.
18774 			 */
18775 			pmportinfo->pmport_dev_attach_time = 0;
18776 			sata_log(sata_hba_inst, CE_WARN,
18777 			    "SATA device detected at port %d:%d",
18778 			    cport, pmport);
18779 
18780 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18781 				sata_drive_info_t new_sdinfo;
18782 
18783 				/* Log device info data */
18784 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
18785 				    pmportinfo));
18786 				sata_show_drive_info(sata_hba_inst,
18787 				    &new_sdinfo);
18788 			}
18789 
18790 			mutex_exit(&pmportinfo->pmport_mutex);
18791 
18792 			/*
18793 			 * Make sure that there is no target node for that
18794 			 * device. If so, release it. It should not happen,
18795 			 * unless we had problem removing the node when
18796 			 * device was detached.
18797 			 */
18798 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
18799 			    saddr->cport, saddr->pmport);
18800 			mutex_enter(&pmportinfo->pmport_mutex);
18801 			if (tdip != NULL) {
18802 
18803 #ifdef SATA_DEBUG
18804 				if ((pmportinfo->pmport_event_flags &
18805 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
18806 					sata_log(sata_hba_inst, CE_WARN,
18807 					    "sata_process_device_attached: "
18808 					    "old device target node exists!");
18809 #endif
18810 				/*
18811 				 * target node exists - try to unconfigure
18812 				 * device and remove the node.
18813 				 */
18814 				mutex_exit(&pmportinfo->pmport_mutex);
18815 				rval = ndi_devi_offline(tdip,
18816 				    NDI_DEVI_REMOVE);
18817 				mutex_enter(&pmportinfo->pmport_mutex);
18818 
18819 				if (rval == NDI_SUCCESS) {
18820 					pmportinfo->pmport_event_flags &=
18821 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
18822 					pmportinfo->pmport_tgtnode_clean =
18823 					    B_TRUE;
18824 				} else {
18825 					/*
18826 					 * PROBLEM - the target node remained
18827 					 * and it belongs to a previously
18828 					 * attached device.
18829 					 * This happens when the file was open
18830 					 * or the node was waiting for
18831 					 * resources at the time the
18832 					 * associated device was removed.
18833 					 * Instruct event daemon to retry the
18834 					 * cleanup later.
18835 					 */
18836 					sata_log(sata_hba_inst,
18837 					    CE_WARN,
18838 					    "Application(s) accessing "
18839 					    "previously attached SATA "
18840 					    "device have to release "
18841 					    "it before newly inserted "
18842 					    "device can be made accessible."
18843 					    "at port %d:%d",
18844 					    cport, pmport);
18845 					pmportinfo->pmport_event_flags |=
18846 					    SATA_EVNT_TARGET_NODE_CLEANUP;
18847 					pmportinfo->pmport_tgtnode_clean =
18848 					    B_FALSE;
18849 				}
18850 			}
18851 			if (sata_auto_online != 0) {
18852 				pmportinfo->pmport_event_flags |=
18853 				    SATA_EVNT_AUTOONLINE_DEVICE;
18854 			}
18855 
18856 		}
18857 	} else {
18858 		pmportinfo->pmport_dev_attach_time = 0;
18859 	}
18860 
18861 	event_flags = pmportinfo->pmport_event_flags;
18862 	mutex_exit(&pmportinfo->pmport_mutex);
18863 	if (event_flags != 0) {
18864 		mutex_enter(&sata_hba_inst->satahba_mutex);
18865 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18866 		mutex_exit(&sata_hba_inst->satahba_mutex);
18867 		mutex_enter(&sata_mutex);
18868 		sata_event_pending |= SATA_EVNT_MAIN;
18869 		mutex_exit(&sata_mutex);
18870 	}
18871 
18872 	/* clear the reset_in_progress events */
18873 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18874 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18875 			/* must clear flags on cport */
18876 			sata_pmult_info_t *pminfo =
18877 			    SATA_PMULT_INFO(sata_hba_inst,
18878 			    saddr->cport);
18879 			pminfo->pmult_event_flags |=
18880 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18881 		}
18882 	}
18883 }
18884 
18885 /*
18886  * Device Target Node Cleanup Event processing.
18887  * If the target node associated with a sata port device is in
18888  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
18889  * If the target node cannot be removed, the event flag is left intact,
18890  * so that event daemon may re-run this function later.
18891  *
18892  * This function cannot be called in interrupt context (it may sleep).
18893  *
18894  * NOTE: Processes cport events only, not port multiplier ports.
18895  */
18896 static void
18897 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
18898     sata_address_t *saddr)
18899 {
18900 	sata_cport_info_t *cportinfo;
18901 	dev_info_t *tdip;
18902 
18903 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18904 	    "Processing port %d device target node cleanup", saddr->cport);
18905 
18906 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18907 
18908 	/*
18909 	 * Check if there is target node for that device and it is in the
18910 	 * DEVI_DEVICE_REMOVED state. If so, release it.
18911 	 */
18912 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
18913 	    saddr->pmport);
18914 	if (tdip != NULL) {
18915 		/*
18916 		 * target node exists - check if it is target node of
18917 		 * a removed device.
18918 		 */
18919 		if (sata_check_device_removed(tdip) == B_TRUE) {
18920 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18921 			    "sata_process_target_node_cleanup: "
18922 			    "old device target node exists!", NULL);
18923 			/*
18924 			 * Unconfigure and remove the target node
18925 			 */
18926 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
18927 			    NDI_SUCCESS) {
18928 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18929 				    saddr->cport)->cport_mutex);
18930 				cportinfo->cport_event_flags &=
18931 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
18932 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18933 				    saddr->cport)->cport_mutex);
18934 				return;
18935 			}
18936 			/*
18937 			 * Event daemon will retry the cleanup later.
18938 			 */
18939 			mutex_enter(&sata_hba_inst->satahba_mutex);
18940 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18941 			mutex_exit(&sata_hba_inst->satahba_mutex);
18942 			mutex_enter(&sata_mutex);
18943 			sata_event_pending |= SATA_EVNT_MAIN;
18944 			mutex_exit(&sata_mutex);
18945 		}
18946 	} else {
18947 		if (saddr->qual == SATA_ADDR_CPORT ||
18948 		    saddr->qual == SATA_ADDR_DCPORT) {
18949 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18950 			    saddr->cport)->cport_mutex);
18951 			cportinfo->cport_event_flags &=
18952 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
18953 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18954 			    saddr->cport)->cport_mutex);
18955 		} else {
18956 			/* sanity check */
18957 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
18958 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
18959 			    saddr->cport) == NULL)
18960 				return;
18961 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
18962 			    saddr->pmport) == NULL)
18963 				return;
18964 
18965 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
18966 			    saddr->cport, saddr->pmport)->pmport_mutex);
18967 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
18968 			    saddr->pmport)->pmport_event_flags &=
18969 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
18970 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
18971 			    saddr->cport, saddr->pmport)->pmport_mutex);
18972 		}
18973 	}
18974 }
18975 
18976 /*
18977  * Device AutoOnline Event processing.
18978  * If attached device is to be onlined, an attempt is made to online this
18979  * device, but only if there is no lingering (old) target node present.
18980  * If the device cannot be onlined, the event flag is left intact,
18981  * so that event daemon may re-run this function later.
18982  *
18983  * This function cannot be called in interrupt context (it may sleep).
18984  *
18985  * NOTE: Processes cport events only, not port multiplier ports.
18986  */
18987 static void
18988 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
18989     sata_address_t *saddr)
18990 {
18991 	sata_cport_info_t *cportinfo;
18992 	sata_drive_info_t *sdinfo;
18993 	sata_device_t sata_device;
18994 	dev_info_t *tdip;
18995 
18996 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18997 	    "Processing port %d attached device auto-onlining", saddr->cport);
18998 
18999 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19000 
19001 	/*
19002 	 * Check if device is present and recognized. If not, reset event.
19003 	 */
19004 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19005 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19006 		/* Nothing to online */
19007 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19008 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19009 		    saddr->cport)->cport_mutex);
19010 		return;
19011 	}
19012 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19013 
19014 	/*
19015 	 * Check if there is target node for this device and if it is in the
19016 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19017 	 * the event for later processing.
19018 	 */
19019 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19020 	    saddr->pmport);
19021 	if (tdip != NULL) {
19022 		/*
19023 		 * target node exists - check if it is target node of
19024 		 * a removed device.
19025 		 */
19026 		if (sata_check_device_removed(tdip) == B_TRUE) {
19027 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19028 			    "sata_process_device_autoonline: "
19029 			    "old device target node exists!", NULL);
19030 			/*
19031 			 * Event daemon will retry device onlining later.
19032 			 */
19033 			mutex_enter(&sata_hba_inst->satahba_mutex);
19034 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19035 			mutex_exit(&sata_hba_inst->satahba_mutex);
19036 			mutex_enter(&sata_mutex);
19037 			sata_event_pending |= SATA_EVNT_MAIN;
19038 			mutex_exit(&sata_mutex);
19039 			return;
19040 		}
19041 		/*
19042 		 * If the target node is not in the 'removed" state, assume
19043 		 * that it belongs to this device. There is nothing more to do,
19044 		 * but reset the event.
19045 		 */
19046 	} else {
19047 
19048 		/*
19049 		 * Try to online the device
19050 		 * If there is any reset-related event, remove it. We are
19051 		 * configuring the device and no state restoring is needed.
19052 		 */
19053 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19054 		    saddr->cport)->cport_mutex);
19055 		sata_device.satadev_addr = *saddr;
19056 		if (saddr->qual == SATA_ADDR_CPORT)
19057 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19058 		else
19059 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19060 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19061 		if (sdinfo != NULL) {
19062 			if (sdinfo->satadrv_event_flags &
19063 			    (SATA_EVNT_DEVICE_RESET |
19064 			    SATA_EVNT_INPROC_DEVICE_RESET))
19065 				sdinfo->satadrv_event_flags = 0;
19066 			sdinfo->satadrv_event_flags |=
19067 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19068 
19069 			/* Need to create a new target node. */
19070 			cportinfo->cport_tgtnode_clean = B_TRUE;
19071 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19072 			    saddr->cport)->cport_mutex);
19073 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19074 			    sata_hba_inst, &sata_device.satadev_addr);
19075 			if (tdip == NULL) {
19076 				/*
19077 				 * Configure (onlining) failed.
19078 				 * We will NOT retry
19079 				 */
19080 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19081 				    "sata_process_device_autoonline: "
19082 				    "configuring SATA device at port %d failed",
19083 				    saddr->cport));
19084 			}
19085 		} else {
19086 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19087 			    saddr->cport)->cport_mutex);
19088 		}
19089 
19090 	}
19091 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19092 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19093 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19094 	    saddr->cport)->cport_mutex);
19095 }
19096 
19097 
19098 static void
19099 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19100     int hint)
19101 {
19102 	char ap[MAXPATHLEN];
19103 	nvlist_t *ev_attr_list = NULL;
19104 	int err;
19105 
19106 	/* Allocate and build sysevent attribute list */
19107 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19108 	if (err != 0) {
19109 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19110 		    "sata_gen_sysevent: "
19111 		    "cannot allocate memory for sysevent attributes\n"));
19112 		return;
19113 	}
19114 	/* Add hint attribute */
19115 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19116 	if (err != 0) {
19117 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19118 		    "sata_gen_sysevent: "
19119 		    "failed to add DR_HINT attr for sysevent"));
19120 		nvlist_free(ev_attr_list);
19121 		return;
19122 	}
19123 	/*
19124 	 * Add AP attribute.
19125 	 * Get controller pathname and convert it into AP pathname by adding
19126 	 * a target number.
19127 	 */
19128 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19129 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19130 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19131 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19132 
19133 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19134 	if (err != 0) {
19135 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19136 		    "sata_gen_sysevent: "
19137 		    "failed to add DR_AP_ID attr for sysevent"));
19138 		nvlist_free(ev_attr_list);
19139 		return;
19140 	}
19141 
19142 	/* Generate/log sysevent */
19143 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19144 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19145 	if (err != DDI_SUCCESS) {
19146 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19147 		    "sata_gen_sysevent: "
19148 		    "cannot log sysevent, err code %x\n", err));
19149 	}
19150 
19151 	nvlist_free(ev_attr_list);
19152 }
19153 
19154 
19155 
19156 
19157 /*
19158  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19159  */
19160 static void
19161 sata_set_device_removed(dev_info_t *tdip)
19162 {
19163 	int circ;
19164 
19165 	ASSERT(tdip != NULL);
19166 
19167 	ndi_devi_enter(tdip, &circ);
19168 	mutex_enter(&DEVI(tdip)->devi_lock);
19169 	DEVI_SET_DEVICE_REMOVED(tdip);
19170 	mutex_exit(&DEVI(tdip)->devi_lock);
19171 	ndi_devi_exit(tdip, circ);
19172 }
19173 
19174 
19175 /*
19176  * Set internal event instructing event daemon to try
19177  * to perform the target node cleanup.
19178  */
19179 static void
19180 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19181     sata_address_t *saddr)
19182 {
19183 	if (saddr->qual == SATA_ADDR_CPORT ||
19184 	    saddr->qual == SATA_ADDR_DCPORT) {
19185 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19186 		    saddr->cport)->cport_mutex);
19187 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19188 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19189 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19190 		    cport_tgtnode_clean = B_FALSE;
19191 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19192 		    saddr->cport)->cport_mutex);
19193 	} else {
19194 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19195 		    saddr->cport, saddr->pmport)->pmport_mutex);
19196 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19197 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19198 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19199 		    pmport_tgtnode_clean = B_FALSE;
19200 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19201 		    saddr->cport, saddr->pmport)->pmport_mutex);
19202 	}
19203 	mutex_enter(&sata_hba_inst->satahba_mutex);
19204 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19205 	mutex_exit(&sata_hba_inst->satahba_mutex);
19206 	mutex_enter(&sata_mutex);
19207 	sata_event_pending |= SATA_EVNT_MAIN;
19208 	mutex_exit(&sata_mutex);
19209 }
19210 
19211 
19212 /*
19213  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19214  * i.e. check if the target node state indicates that it belongs to a removed
19215  * device.
19216  *
19217  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19218  * B_FALSE otherwise.
19219  */
19220 static boolean_t
19221 sata_check_device_removed(dev_info_t *tdip)
19222 {
19223 	ASSERT(tdip != NULL);
19224 
19225 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19226 		return (B_TRUE);
19227 	else
19228 		return (B_FALSE);
19229 }
19230 
19231 /* ************************ FAULT INJECTTION **************************** */
19232 
19233 #ifdef SATA_INJECT_FAULTS
19234 
19235 static	uint32_t sata_fault_count = 0;
19236 static	uint32_t sata_fault_suspend_count = 0;
19237 
19238 /*
19239  * Inject sata pkt fault
19240  * It modifies returned values of the sata packet.
19241  * It returns immediately if:
19242  * pkt fault injection is not enabled (via sata_inject_fault,
19243  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19244  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19245  * pkt is not directed to specified fault controller/device
19246  * (sata_fault_ctrl_dev and sata_fault_device).
19247  * If fault controller is not specified, fault injection applies to all
19248  * controllers and devices.
19249  *
19250  * First argument is the pointer to the executed sata packet.
19251  * Second argument is a pointer to a value returned by the HBA tran_start
19252  * function.
19253  * Third argument specifies injected error. Injected sata packet faults
19254  * are the satapkt_reason values.
19255  * SATA_PKT_BUSY		-1	Not completed, busy
19256  * SATA_PKT_DEV_ERROR		1	Device reported error
19257  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
19258  * SATA_PKT_PORT_ERROR		3	Not completed, port error
19259  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
19260  * SATA_PKT_ABORTED		5	Aborted by request
19261  * SATA_PKT_TIMEOUT		6	Operation timeut
19262  * SATA_PKT_RESET		7	Aborted by reset request
19263  *
19264  * Additional global variables affecting the execution:
19265  *
19266  * sata_inject_fault_count variable specifies number of times in row the
19267  * error is injected. Value of -1 specifies permanent fault, ie. every time
19268  * the fault injection point is reached, the fault is injected and a pause
19269  * between fault injection specified by sata_inject_fault_pause_count is
19270  * ignored). Fault injection routine decrements sata_inject_fault_count
19271  * (if greater than zero) until it reaches 0. No fault is injected when
19272  * sata_inject_fault_count is 0 (zero).
19273  *
19274  * sata_inject_fault_pause_count variable specifies number of times a fault
19275  * injection is bypassed (pause between fault injections).
19276  * If set to 0, a fault is injected only a number of times specified by
19277  * sata_inject_fault_count.
19278  *
19279  * The fault counts are static, so for periodic errors they have to be manually
19280  * reset to start repetition sequence from scratch.
19281  * If the original value returned by the HBA tran_start function is not
19282  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
19283  * is injected (to avoid masking real problems);
19284  *
19285  * NOTE: In its current incarnation, this function should be invoked only for
19286  * commands executed in SYNCHRONOUS mode.
19287  */
19288 
19289 
19290 static void
19291 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
19292 {
19293 
19294 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
19295 		return;
19296 
19297 	if (sata_inject_fault_count == 0)
19298 		return;
19299 
19300 	if (fault == 0)
19301 		return;
19302 
19303 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
19304 		return;
19305 
19306 	if (sata_fault_ctrl != NULL) {
19307 		sata_pkt_txlate_t *spx =
19308 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
19309 
19310 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
19311 		    spx->txlt_sata_hba_inst->satahba_dip)
19312 			return;
19313 
19314 		if (sata_fault_device.satadev_addr.cport !=
19315 		    spkt->satapkt_device.satadev_addr.cport ||
19316 		    sata_fault_device.satadev_addr.pmport !=
19317 		    spkt->satapkt_device.satadev_addr.pmport ||
19318 		    sata_fault_device.satadev_addr.qual !=
19319 		    spkt->satapkt_device.satadev_addr.qual)
19320 			return;
19321 	}
19322 
19323 	/* Modify pkt return parameters */
19324 	if (*rval != SATA_TRAN_ACCEPTED ||
19325 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
19326 		sata_fault_count = 0;
19327 		sata_fault_suspend_count = 0;
19328 		return;
19329 	}
19330 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
19331 		/* Pause in the injection */
19332 		sata_fault_suspend_count -= 1;
19333 		return;
19334 	}
19335 
19336 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
19337 		/*
19338 		 * Init inject fault cycle. If fault count is set to -1,
19339 		 * it is a permanent fault.
19340 		 */
19341 		if (sata_inject_fault_count != -1) {
19342 			sata_fault_count = sata_inject_fault_count;
19343 			sata_fault_suspend_count =
19344 			    sata_inject_fault_pause_count;
19345 			if (sata_fault_suspend_count == 0)
19346 				sata_inject_fault_count = 0;
19347 		}
19348 	}
19349 
19350 	if (sata_fault_count != 0)
19351 		sata_fault_count -= 1;
19352 
19353 	switch (fault) {
19354 	case SATA_PKT_BUSY:
19355 		*rval = SATA_TRAN_BUSY;
19356 		spkt->satapkt_reason = SATA_PKT_BUSY;
19357 		break;
19358 
19359 	case SATA_PKT_QUEUE_FULL:
19360 		*rval = SATA_TRAN_QUEUE_FULL;
19361 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
19362 		break;
19363 
19364 	case SATA_PKT_CMD_UNSUPPORTED:
19365 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
19366 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
19367 		break;
19368 
19369 	case SATA_PKT_PORT_ERROR:
19370 		/* This is "rejected" command */
19371 		*rval = SATA_TRAN_PORT_ERROR;
19372 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
19373 		/* Additional error setup could be done here - port state */
19374 		break;
19375 
19376 	case SATA_PKT_DEV_ERROR:
19377 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
19378 		/*
19379 		 * Additional error setup could be done here
19380 		 */
19381 		break;
19382 
19383 	case SATA_PKT_ABORTED:
19384 		spkt->satapkt_reason = SATA_PKT_ABORTED;
19385 		break;
19386 
19387 	case SATA_PKT_TIMEOUT:
19388 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
19389 		/* Additional error setup could be done here */
19390 		break;
19391 
19392 	case SATA_PKT_RESET:
19393 		spkt->satapkt_reason = SATA_PKT_RESET;
19394 		/*
19395 		 * Additional error setup could be done here - device reset
19396 		 */
19397 		break;
19398 
19399 	default:
19400 		break;
19401 	}
19402 }
19403 
19404 #endif
19405 
19406 /*
19407  * SATA Trace Ring Buffer
19408  * ----------------------
19409  *
19410  * Overview
19411  *
19412  * The SATA trace ring buffer is a ring buffer created and managed by
19413  * the SATA framework module that can be used by any module or driver
19414  * within the SATA framework to store debug messages.
19415  *
19416  * Ring Buffer Interfaces:
19417  *
19418  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
19419  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
19420  *
19421  *	Note that the sata_trace_debug() interface was created to give
19422  *	consumers the flexibilty of sending debug messages to ring buffer
19423  *	as variable arguments.  Consumers can send type va_list debug
19424  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
19425  *	and sata_vtrace_debug() relationship is similar to that of
19426  *	cmn_err(9F) and vcmn_err(9F).
19427  *
19428  * Below is a diagram of the SATA trace ring buffer interfaces and
19429  * sample consumers:
19430  *
19431  * +---------------------------------+
19432  * |    o  o  SATA Framework Module  |
19433  * | o  SATA  o     +------------------+      +------------------+
19434  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
19435  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
19436  * | o        o     +------------------+   |  +------------------+
19437  * |    o  o                ^        |     +--|SATA HBA Driver #2|
19438  * |                        |        |        +------------------+
19439  * |           +------------------+  |
19440  * |           |SATA Debug Message|  |
19441  * |           +------------------+  |
19442  * +---------------------------------+
19443  *
19444  * Supporting Routines:
19445  *
19446  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
19447  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
19448  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
19449  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
19450  *
19451  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
19452  * The ring buffer size can be adjusted by setting dmsg_ring_size in
19453  * /etc/system to desired size in unit of bytes.
19454  *
19455  * The individual debug message size in the ring buffer is restricted
19456  * to DMSG_BUF_SIZE.
19457  */
19458 void
19459 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
19460 {
19461 	sata_trace_dmsg_t *dmsg;
19462 
19463 	if (sata_debug_rbuf == NULL) {
19464 		return;
19465 	}
19466 
19467 	/*
19468 	 * If max size of ring buffer is smaller than size
19469 	 * required for one debug message then just return
19470 	 * since we have no room for the debug message.
19471 	 */
19472 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
19473 		return;
19474 	}
19475 
19476 	mutex_enter(&sata_debug_rbuf->lock);
19477 
19478 	/* alloc or reuse on ring buffer */
19479 	dmsg = sata_trace_dmsg_alloc();
19480 
19481 	if (dmsg == NULL) {
19482 		/* resource allocation failed */
19483 		mutex_exit(&sata_debug_rbuf->lock);
19484 		return;
19485 	}
19486 
19487 	dmsg->dip = dip;
19488 	gethrestime(&dmsg->timestamp);
19489 
19490 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
19491 
19492 	mutex_exit(&sata_debug_rbuf->lock);
19493 }
19494 
19495 void
19496 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
19497 {
19498 	va_list ap;
19499 
19500 	va_start(ap, fmt);
19501 	sata_vtrace_debug(dip, fmt, ap);
19502 	va_end(ap);
19503 }
19504 
19505 /*
19506  * This routine is used to manage debug messages
19507  * on ring buffer.
19508  */
19509 static sata_trace_dmsg_t *
19510 sata_trace_dmsg_alloc(void)
19511 {
19512 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
19513 
19514 	if (sata_debug_rbuf->looped == TRUE) {
19515 		sata_debug_rbuf->dmsgp = dmsg->next;
19516 		return (sata_debug_rbuf->dmsgp);
19517 	}
19518 
19519 	/*
19520 	 * If we're looping for the first time,
19521 	 * connect the ring.
19522 	 */
19523 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
19524 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
19525 		dmsg->next = sata_debug_rbuf->dmsgh;
19526 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
19527 		sata_debug_rbuf->looped = TRUE;
19528 		return (sata_debug_rbuf->dmsgp);
19529 	}
19530 
19531 	/* If we've gotten this far then memory allocation is needed */
19532 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
19533 	if (dmsg_alloc == NULL) {
19534 		sata_debug_rbuf->allocfailed++;
19535 		return (dmsg_alloc);
19536 	} else {
19537 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
19538 	}
19539 
19540 	if (sata_debug_rbuf->dmsgp != NULL) {
19541 		dmsg->next = dmsg_alloc;
19542 		sata_debug_rbuf->dmsgp = dmsg->next;
19543 		return (sata_debug_rbuf->dmsgp);
19544 	} else {
19545 		/*
19546 		 * We should only be here if we're initializing
19547 		 * the ring buffer.
19548 		 */
19549 		if (sata_debug_rbuf->dmsgh == NULL) {
19550 			sata_debug_rbuf->dmsgh = dmsg_alloc;
19551 		} else {
19552 			/* Something is wrong */
19553 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
19554 			return (NULL);
19555 		}
19556 
19557 		sata_debug_rbuf->dmsgp = dmsg_alloc;
19558 		return (sata_debug_rbuf->dmsgp);
19559 	}
19560 }
19561 
19562 
19563 /*
19564  * Free all messages on debug ring buffer.
19565  */
19566 static void
19567 sata_trace_dmsg_free(void)
19568 {
19569 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
19570 
19571 	while (dmsg != NULL) {
19572 		dmsg_next = dmsg->next;
19573 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
19574 
19575 		/*
19576 		 * If we've looped around the ring than we're done.
19577 		 */
19578 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
19579 			break;
19580 		} else {
19581 			dmsg = dmsg_next;
19582 		}
19583 	}
19584 }
19585 
19586 
19587 /*
19588  * This function can block
19589  */
19590 static void
19591 sata_trace_rbuf_alloc(void)
19592 {
19593 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
19594 
19595 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
19596 
19597 	if (dmsg_ring_size > 0) {
19598 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
19599 	}
19600 }
19601 
19602 
19603 static void
19604 sata_trace_rbuf_free(void)
19605 {
19606 	sata_trace_dmsg_free();
19607 	mutex_destroy(&sata_debug_rbuf->lock);
19608 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
19609 }
19610 
19611 /*
19612  * If SATA_DEBUG is not defined then this routine is called instead
19613  * of sata_log() via the SATA_LOG_D macro.
19614  */
19615 static void
19616 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
19617     const char *fmt, ...)
19618 {
19619 #ifndef __lock_lint
19620 	_NOTE(ARGUNUSED(level))
19621 #endif
19622 
19623 	dev_info_t *dip = NULL;
19624 	va_list ap;
19625 
19626 	if (sata_hba_inst != NULL) {
19627 		dip = SATA_DIP(sata_hba_inst);
19628 	}
19629 
19630 	va_start(ap, fmt);
19631 	sata_vtrace_debug(dip, fmt, ap);
19632 	va_end(ap);
19633 }
19634