xref: /titanic_52/usr/src/uts/common/io/sata/impl/sata.c (revision 121d13daefbeb0546d0d9c6ef16c753aa6890290)
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 #include <sys/sata/sata_satl.h>
55 
56 #include <sys/scsi/impl/spc3_types.h>
57 
58 /* Debug flags - defined in sata.h */
59 int	sata_debug_flags = 0;
60 int	sata_msg = 0;
61 
62 /*
63  * Flags enabling selected SATA HBA framework functionality
64  */
65 #define	SATA_ENABLE_QUEUING		1
66 #define	SATA_ENABLE_NCQ			2
67 #define	SATA_ENABLE_PROCESS_EVENTS	4
68 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
69 int sata_func_enable =
70 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
71 
72 /*
73  * Global variable setting default maximum queue depth (NCQ or TCQ)
74  * Note:minimum queue depth is 1
75  */
76 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
77 
78 /*
79  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
80  * initialization, using value from sata_max_queue_depth
81  * It is adjusted to minimum supported by the controller and by the device,
82  * if queueing is enabled.
83  */
84 static	int sata_current_max_qdepth;
85 
86 /*
87  * Global variable determining the default behavior after device hotpluggin.
88  * If non-zero, the hotplugged device is onlined (if possible) without explicit
89  * IOCTL request (AP_CONFIGURE).
90  * If zero, hotplugged device is identified, but not onlined.
91  * Enabling (AP_CONNECT) device port with an attached device does not result
92  * in device onlining regardless of the flag setting
93  */
94 int sata_auto_online = 0;
95 
96 #ifdef SATA_DEBUG
97 
98 #define	SATA_LOG_D(args)	sata_log args
99 uint64_t mbuf_count = 0;
100 uint64_t mbuffail_count = 0;
101 
102 sata_atapi_cmd_t sata_atapi_trace[64];
103 uint32_t sata_atapi_trace_index = 0;
104 int sata_atapi_trace_save = 1;
105 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
106 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
107     sata_save_atapi_trace(spx, count);
108 
109 #else
110 #define	SATA_LOG_D(args)	sata_trace_log args
111 #define	SATAATAPITRACE(spx, count)
112 #endif
113 
114 #if 0
115 static void
116 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
117 #endif
118 
119 #ifdef SATA_INJECT_FAULTS
120 
121 #define		SATA_INJECT_PKT_FAULT	1
122 uint32_t	sata_inject_fault = 0;
123 
124 uint32_t	sata_inject_fault_count = 0;
125 uint32_t	sata_inject_fault_pause_count = 0;
126 uint32_t	sata_fault_type = 0;
127 uint32_t	sata_fault_cmd = 0;
128 dev_info_t	*sata_fault_ctrl = NULL;
129 sata_device_t	sata_fault_device;
130 
131 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
132 
133 #endif
134 
135 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
136 
137 static char sata_rev_tag[] = {"1.46"};
138 
139 /*
140  * SATA cb_ops functions
141  */
142 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
143 static 	int sata_hba_close(dev_t, int, int, cred_t *);
144 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
145 
146 /*
147  * SCSA required entry points
148  */
149 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
150     scsi_hba_tran_t *, struct scsi_device *);
151 static	int sata_scsi_tgt_probe(struct scsi_device *,
152     int (*callback)(void));
153 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
154     scsi_hba_tran_t *, struct scsi_device *);
155 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
156 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
157 static 	int sata_scsi_reset(struct scsi_address *, int);
158 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
159 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
160 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
161     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
162     caddr_t);
163 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
164 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
165 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
166 
167 /*
168  * SATA HBA interface functions are defined in sata_hba.h header file
169  */
170 
171 /* Event processing functions */
172 static	void sata_event_daemon(void *);
173 static	void sata_event_thread_control(int);
174 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
175 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
176 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_port_failed_event(sata_hba_inst_t *,
179     sata_address_t *);
180 static	void sata_process_port_link_events(sata_hba_inst_t *,
181     sata_address_t *);
182 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
183     sata_address_t *);
184 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
188 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
189     sata_address_t *);
190 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
191 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
192 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_device_autoonline(sata_hba_inst_t *,
195     sata_address_t *saddr);
196 
197 /*
198  * Local translation functions
199  */
200 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
201 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
202 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
203 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
204 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
205 static	int sata_txlt_read(sata_pkt_txlate_t *);
206 static	int sata_txlt_write(sata_pkt_txlate_t *);
207 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
208 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
209 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
210 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
211 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
212 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
213 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
214 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
215 
216 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
217 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
218 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
219 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
220 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
221 static	void sata_txlt_rw_completion(sata_pkt_t *);
222 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
223 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
224 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
225 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
226 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
227     uint8_t);
228 static	struct scsi_extended_sense *sata_immediate_error_response(
229     sata_pkt_txlate_t *, int);
230 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
231 
232 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
233 static	void sata_txlt_atapi_completion(sata_pkt_t *);
234 
235 /*
236  * Local functions for ioctl
237  */
238 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
239 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
240     devctl_ap_state_t *);
241 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
242 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
243 static	dev_info_t *sata_devt_to_devinfo(dev_t);
244 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
245 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
246 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
247 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
248 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
249 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
250 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
251 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
252 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
253 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
254 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
255     sata_ioctl_data_t *, int mode);
256 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
257     sata_ioctl_data_t *, int mode);
258 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
259     sata_ioctl_data_t *, int mode);
260 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
261     sata_ioctl_data_t *, int mode);
262 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
263     sata_device_t *, sata_ioctl_data_t *, int mode);
264 
265 /*
266  * Local functions
267  */
268 static 	void sata_remove_hba_instance(dev_info_t *);
269 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
270 static 	void sata_probe_ports(sata_hba_inst_t *);
271 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
272 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
273 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
274 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
275 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
276 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
277 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
278 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
279     sata_drive_info_t *);
280 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
281     sata_address_t *);
282 static 	void sata_remove_target_node(sata_hba_inst_t *,
283     sata_address_t *);
284 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
285     struct scsi_address *, sata_device_t *);
286 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
287 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
288 static	void sata_pkt_free(sata_pkt_txlate_t *);
289 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
290     caddr_t, ddi_dma_attr_t *);
291 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
292 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
293 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
294     sata_device_t *);
295 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
296 static	void sata_reidentify_device(sata_pkt_txlate_t *);
297 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
298 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
299 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
300 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
301     ddi_dma_attr_t *);
302 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
303     sata_drive_info_t *);
304 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
305 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
306 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
307 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
308 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
309 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
310 static	int sata_set_drive_features(sata_hba_inst_t *,
311     sata_drive_info_t *, int flag);
312 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
313 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
314 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
315     uint8_t *);
316 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
317     struct scsi_inquiry *);
318 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
319 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
320 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
321 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
322 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
323 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
324     struct mode_cache_scsi3 *, int, int *, int *, int *);
325 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
326     struct mode_info_power_cond *, int, int *, int *, int *);
327 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
328     struct mode_info_excpt_page *, int, int *, int *, int *);
329 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
330     struct mode_acoustic_management *, int, int *, int *, int *);
331 
332 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
333 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
334     sata_hba_inst_t *);
335 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
336     sata_hba_inst_t *);
337 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
338     sata_hba_inst_t *);
339 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
340     sata_pkt_txlate_t *);
341 
342 static	void sata_set_arq_data(sata_pkt_t *);
343 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
344 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
345 static	uint8_t sata_get_standby_timer(uint8_t *timer);
346 
347 static	void sata_save_drive_settings(sata_drive_info_t *);
348 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
349 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
350 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
351 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
352 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
353     sata_drive_info_t *);
354 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
355     struct smart_data *);
356 static	int sata_smart_selftest_log(sata_hba_inst_t *,
357     sata_drive_info_t *,
358     struct smart_selftest_log *);
359 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
360     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
361 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
362     uint8_t *, uint8_t, uint8_t);
363 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
364     struct read_log_ext_directory *);
365 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
366 static	void sata_xlate_errors(sata_pkt_txlate_t *);
367 static	void sata_decode_device_error(sata_pkt_txlate_t *,
368     struct scsi_extended_sense *);
369 static	void sata_set_device_removed(dev_info_t *);
370 static	boolean_t sata_check_device_removed(dev_info_t *);
371 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
372 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
373     sata_drive_info_t *);
374 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
375     sata_drive_info_t *);
376 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
377 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
378 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
379 static  int sata_check_modser(char *, int);
380 
381 
382 
383 /*
384  * SATA Framework will ignore SATA HBA driver cb_ops structure and
385  * register following one with SCSA framework.
386  * Open & close are provided, so scsi framework will not use its own
387  */
388 static struct cb_ops sata_cb_ops = {
389 	sata_hba_open,			/* open */
390 	sata_hba_close,			/* close */
391 	nodev,				/* strategy */
392 	nodev,				/* print */
393 	nodev,				/* dump */
394 	nodev,				/* read */
395 	nodev,				/* write */
396 	sata_hba_ioctl,			/* ioctl */
397 	nodev,				/* devmap */
398 	nodev,				/* mmap */
399 	nodev,				/* segmap */
400 	nochpoll,			/* chpoll */
401 	ddi_prop_op,			/* cb_prop_op */
402 	0,				/* streamtab */
403 	D_NEW | D_MP,			/* cb_flag */
404 	CB_REV,				/* rev */
405 	nodev,				/* aread */
406 	nodev				/* awrite */
407 };
408 
409 
410 extern struct mod_ops mod_miscops;
411 extern uchar_t	scsi_cdb_size[];
412 
413 static struct modlmisc modlmisc = {
414 	&mod_miscops,			/* Type of module */
415 	"SATA Module"			/* module name */
416 };
417 
418 
419 static struct modlinkage modlinkage = {
420 	MODREV_1,
421 	(void *)&modlmisc,
422 	NULL
423 };
424 
425 /*
426  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
427  * i.e. when scsi_pkt has not timeout specified.
428  */
429 static int sata_default_pkt_time = 60;	/* 60 seconds */
430 
431 /*
432  * Intermediate buffer device access attributes - they are required,
433  * but not necessarily used.
434  */
435 static ddi_device_acc_attr_t sata_acc_attr = {
436 	DDI_DEVICE_ATTR_V0,
437 	DDI_STRUCTURE_LE_ACC,
438 	DDI_STRICTORDER_ACC
439 };
440 
441 
442 /*
443  * Mutexes protecting structures in multithreaded operations.
444  * Because events are relatively rare, a single global mutex protecting
445  * data structures should be sufficient. To increase performance, add
446  * separate mutex per each sata port and use global mutex only to protect
447  * common data structures.
448  */
449 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
450 static	kmutex_t sata_log_mutex;	/* protects log */
451 
452 static 	char sata_log_buf[256];
453 
454 /*
455  * sata trace debug
456  */
457 static	sata_trace_rbuf_t *sata_debug_rbuf;
458 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
459 static	void sata_trace_dmsg_free(void);
460 static	void sata_trace_rbuf_alloc(void);
461 static	void sata_trace_rbuf_free(void);
462 
463 int	dmsg_ring_size = DMSG_RING_SIZE;
464 
465 /* Default write cache setting for SATA hard disks */
466 int	sata_write_cache = 1;		/* enabled */
467 
468 /* Default write cache setting for SATA ATAPI CD/DVD */
469 int	sata_atapicdvd_write_cache = 1; /* enabled */
470 
471 /* Default write cache setting for SATA ATAPI tape */
472 int	sata_atapitape_write_cache = 1; /* enabled */
473 
474 /* Default write cache setting for SATA ATAPI disk */
475 int	sata_atapidisk_write_cache = 1;	/* enabled */
476 
477 /*
478  * Linked list of HBA instances
479  */
480 static 	sata_hba_inst_t *sata_hba_list = NULL;
481 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
482 /*
483  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
484  * structure and in sata soft state.
485  */
486 
487 /*
488  * Event daemon related variables
489  */
490 static 	kmutex_t sata_event_mutex;
491 static 	kcondvar_t sata_event_cv;
492 static 	kthread_t *sata_event_thread = NULL;
493 static 	int sata_event_thread_terminate = 0;
494 static 	int sata_event_pending = 0;
495 static 	int sata_event_thread_active = 0;
496 extern 	pri_t minclsyspri;
497 
498 /*
499  * NCQ error recovery command
500  */
501 static const sata_cmd_t sata_rle_cmd = {
502 	SATA_CMD_REV,
503 	NULL,
504 	{
505 		SATA_DIR_READ
506 	},
507 	ATA_ADDR_LBA48,
508 	0,
509 	0,
510 	0,
511 	0,
512 	0,
513 	1,
514 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
515 	0,
516 	0,
517 	0,
518 	SATAC_READ_LOG_EXT,
519 	0,
520 	0,
521 	0,
522 };
523 
524 /*
525  * ATAPI error recovery CDB
526  */
527 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
528 	SCMD_REQUEST_SENSE,
529 	0,			/* Only fixed RQ format is supported */
530 	0,
531 	0,
532 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
533 	0
534 };
535 
536 
537 /* Warlock directives */
538 
539 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
540 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
541 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
542 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
543 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
544 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
545 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
546 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
547 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
548 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
549 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
550 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
551 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
552 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
553     sata_hba_inst::satahba_scsi_tran))
554 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
555 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
556 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
557 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
558 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
559     sata_hba_inst::satahba_event_flags))
560 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
561     sata_cport_info::cport_devp))
562 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
563 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
564 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
565     sata_cport_info::cport_dev_type))
566 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
567 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
568     sata_cport_info::cport_state))
569 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
571     sata_pmport_info::pmport_state))
572 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
573 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
574     sata_pmport_info::pmport_dev_type))
575 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
576 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
577     sata_pmport_info::pmport_sata_drive))
578 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
579     sata_pmport_info::pmport_tgtnode_clean))
580 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
581     sata_pmport_info::pmport_event_flags))
582 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
583 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
584 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
585 #ifdef SATA_DEBUG
586 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
587 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
588 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
589 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
590 #endif
591 
592 /* End of warlock directives */
593 
594 /* ************** loadable module configuration functions ************** */
595 
596 int
597 _init()
598 {
599 	int rval;
600 
601 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
602 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
603 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
604 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
605 	sata_trace_rbuf_alloc();
606 	if ((rval = mod_install(&modlinkage)) != 0) {
607 #ifdef SATA_DEBUG
608 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
609 #endif
610 		sata_trace_rbuf_free();
611 		mutex_destroy(&sata_log_mutex);
612 		cv_destroy(&sata_event_cv);
613 		mutex_destroy(&sata_event_mutex);
614 		mutex_destroy(&sata_mutex);
615 	}
616 	return (rval);
617 }
618 
619 int
620 _fini()
621 {
622 	int rval;
623 
624 	if ((rval = mod_remove(&modlinkage)) != 0)
625 		return (rval);
626 
627 	sata_trace_rbuf_free();
628 	mutex_destroy(&sata_log_mutex);
629 	cv_destroy(&sata_event_cv);
630 	mutex_destroy(&sata_event_mutex);
631 	mutex_destroy(&sata_mutex);
632 	return (rval);
633 }
634 
635 int
636 _info(struct modinfo *modinfop)
637 {
638 	return (mod_info(&modlinkage, modinfop));
639 }
640 
641 
642 
643 /* ********************* SATA HBA entry points ********************* */
644 
645 
646 /*
647  * Called by SATA HBA from _init().
648  * Registers HBA driver instance/sata framework pair with scsi framework, by
649  * calling scsi_hba_init().
650  *
651  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
652  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
653  * cb_ops pointer in SATA HBA driver dev_ops structure.
654  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
655  *
656  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
657  * driver.
658  */
659 int
660 sata_hba_init(struct modlinkage *modlp)
661 {
662 	int rval;
663 	struct dev_ops *hba_ops;
664 
665 	SATADBG1(SATA_DBG_HBA_IF, NULL,
666 	    "sata_hba_init: name %s \n",
667 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
668 	/*
669 	 * Fill-up cb_ops and dev_ops when necessary
670 	 */
671 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
672 	/*
673 	 * Provide pointer to SATA dev_ops
674 	 */
675 	hba_ops->devo_cb_ops = &sata_cb_ops;
676 
677 	/*
678 	 * Register SATA HBA with SCSI framework
679 	 */
680 	if ((rval = scsi_hba_init(modlp)) != 0) {
681 		SATADBG1(SATA_DBG_HBA_IF, NULL,
682 		    "sata_hba_init: scsi hba init failed\n", NULL);
683 		return (rval);
684 	}
685 
686 	return (0);
687 }
688 
689 
690 /* HBA attach stages */
691 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
692 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
693 #define	HBA_ATTACH_STAGE_SETUP		4
694 #define	HBA_ATTACH_STAGE_LINKED		8
695 
696 
697 /*
698  *
699  * Called from SATA HBA driver's attach routine to attach an instance of
700  * the HBA.
701  *
702  * For DDI_ATTACH command:
703  * sata_hba_inst structure is allocated here and initialized with pointers to
704  * SATA framework implementation of required scsi tran functions.
705  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
706  * to the soft structure (sata_hba_inst) allocated by SATA framework for
707  * SATA HBA instance related data.
708  * The scsi_tran's tran_hba_private field is used by SATA framework to
709  * store a pointer to per-HBA-instance of sata_hba_inst structure.
710  * The sata_hba_inst structure is cross-linked to scsi tran structure.
711  * Among other info, a pointer to sata_hba_tran structure is stored in
712  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
713  * linked together into the list, pointed to by sata_hba_list.
714  * On the first HBA instance attach the sata event thread is initialized.
715  * Attachment points are created for all SATA ports of the HBA being attached.
716  * All HBA instance's SATA ports are probed and type of plugged devices is
717  * determined. For each device of a supported type, a target node is created.
718  *
719  * DDI_SUCCESS is returned when attachment process is successful,
720  * DDI_FAILURE is returned otherwise.
721  *
722  * For DDI_RESUME command:
723  * Not implemented at this time (postponed until phase 2 of the development).
724  */
725 int
726 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
727     ddi_attach_cmd_t cmd)
728 {
729 	sata_hba_inst_t	*sata_hba_inst;
730 	scsi_hba_tran_t *scsi_tran = NULL;
731 	int hba_attach_state = 0;
732 	char taskq_name[MAXPATHLEN];
733 
734 	SATADBG3(SATA_DBG_HBA_IF, NULL,
735 	    "sata_hba_attach: node %s (%s%d)\n",
736 	    ddi_node_name(dip), ddi_driver_name(dip),
737 	    ddi_get_instance(dip));
738 
739 	if (cmd == DDI_RESUME) {
740 		/*
741 		 * Postponed until phase 2 of the development
742 		 */
743 		return (DDI_FAILURE);
744 	}
745 
746 	if (cmd != DDI_ATTACH) {
747 		return (DDI_FAILURE);
748 	}
749 
750 	/* cmd == DDI_ATTACH */
751 
752 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
753 		SATA_LOG_D((NULL, CE_WARN,
754 		    "sata_hba_attach: invalid sata_hba_tran"));
755 		return (DDI_FAILURE);
756 	}
757 	/*
758 	 * Allocate and initialize SCSI tran structure.
759 	 * SATA copy of tran_bus_config is provided to create port nodes.
760 	 */
761 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
762 	if (scsi_tran == NULL)
763 		return (DDI_FAILURE);
764 	/*
765 	 * Allocate soft structure for SATA HBA instance.
766 	 * There is a separate softstate for each HBA instance.
767 	 */
768 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
769 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
770 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
771 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
772 
773 	/*
774 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
775 	 * soft structure allocated by SATA framework for
776 	 * SATA HBA instance related data.
777 	 */
778 	scsi_tran->tran_hba_private	= sata_hba_inst;
779 	scsi_tran->tran_tgt_private	= NULL;
780 
781 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
782 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
783 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
784 
785 	scsi_tran->tran_start		= sata_scsi_start;
786 	scsi_tran->tran_reset		= sata_scsi_reset;
787 	scsi_tran->tran_abort		= sata_scsi_abort;
788 	scsi_tran->tran_getcap		= sata_scsi_getcap;
789 	scsi_tran->tran_setcap		= sata_scsi_setcap;
790 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
791 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
792 
793 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
794 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
795 
796 	scsi_tran->tran_reset_notify	= NULL;
797 	scsi_tran->tran_get_bus_addr	= NULL;
798 	scsi_tran->tran_quiesce		= NULL;
799 	scsi_tran->tran_unquiesce	= NULL;
800 	scsi_tran->tran_bus_reset	= NULL;
801 
802 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
803 	    scsi_tran, 0) != DDI_SUCCESS) {
804 #ifdef SATA_DEBUG
805 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
806 		    ddi_driver_name(dip), ddi_get_instance(dip));
807 #endif
808 		goto fail;
809 	}
810 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
811 
812 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
813 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
814 		    "sata", 1) != DDI_PROP_SUCCESS) {
815 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
816 			    "failed to create hba sata prop"));
817 			goto fail;
818 		}
819 	}
820 
821 	/*
822 	 * Save pointers in hba instance soft state.
823 	 */
824 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
825 	sata_hba_inst->satahba_tran = sata_tran;
826 	sata_hba_inst->satahba_dip = dip;
827 
828 	/*
829 	 * Create a task queue to handle emulated commands completion
830 	 * Use node name, dash, instance number as the queue name.
831 	 */
832 	taskq_name[0] = '\0';
833 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
834 	    sizeof (taskq_name));
835 	(void) snprintf(taskq_name + strlen(taskq_name),
836 	    sizeof (taskq_name) - strlen(taskq_name),
837 	    "-%d", DEVI(dip)->devi_instance);
838 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
839 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
840 	    TASKQ_DYNAMIC);
841 
842 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
843 
844 	/*
845 	 * Create events thread if not created yet.
846 	 */
847 	sata_event_thread_control(1);
848 
849 	/*
850 	 * Link this hba instance into the list.
851 	 */
852 	mutex_enter(&sata_mutex);
853 
854 	if (sata_hba_list == NULL) {
855 		/*
856 		 * The first instance of HBA is attached.
857 		 * Set current/active default maximum NCQ/TCQ queue depth for
858 		 * all SATA devices. It is done here and now, to eliminate the
859 		 * possibility of the dynamic, programatic modification of the
860 		 * queue depth via global (and public) sata_max_queue_depth
861 		 * variable (this would require special handling in HBA drivers)
862 		 */
863 		sata_current_max_qdepth = sata_max_queue_depth;
864 		if (sata_current_max_qdepth > 32)
865 			sata_current_max_qdepth = 32;
866 		else if (sata_current_max_qdepth < 1)
867 			sata_current_max_qdepth = 1;
868 	}
869 
870 	sata_hba_inst->satahba_next = NULL;
871 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
872 	if (sata_hba_list == NULL) {
873 		sata_hba_list = sata_hba_inst;
874 	}
875 	if (sata_hba_list_tail != NULL) {
876 		sata_hba_list_tail->satahba_next = sata_hba_inst;
877 	}
878 	sata_hba_list_tail = sata_hba_inst;
879 	mutex_exit(&sata_mutex);
880 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
881 
882 	/*
883 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
884 	 * SATA HBA driver should not use its own open/close entry points.
885 	 *
886 	 * Make sure that instance number doesn't overflow
887 	 * when forming minor numbers.
888 	 */
889 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
890 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
891 	    INST2DEVCTL(ddi_get_instance(dip)),
892 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
893 #ifdef SATA_DEBUG
894 		cmn_err(CE_WARN, "sata_hba_attach: "
895 		    "cannot create devctl minor node");
896 #endif
897 		goto fail;
898 	}
899 
900 
901 	/*
902 	 * Set-up kstats here, if necessary.
903 	 * (postponed until future phase of the development).
904 	 */
905 
906 	/*
907 	 * Indicate that HBA is attached. This will enable events processing
908 	 * for this HBA.
909 	 */
910 	sata_hba_inst->satahba_attached = 1;
911 	/*
912 	 * Probe controller ports. This operation will describe a current
913 	 * controller/port/multipliers/device configuration and will create
914 	 * attachment points.
915 	 * We may end-up with just a controller with no devices attached.
916 	 * For the ports with a supported device attached, device target nodes
917 	 * are created and devices are initialized.
918 	 */
919 	sata_probe_ports(sata_hba_inst);
920 
921 	return (DDI_SUCCESS);
922 
923 fail:
924 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
925 		(void) sata_remove_hba_instance(dip);
926 		if (sata_hba_list == NULL)
927 			sata_event_thread_control(0);
928 	}
929 
930 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
931 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
932 		taskq_destroy(sata_hba_inst->satahba_taskq);
933 	}
934 
935 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
936 		(void) scsi_hba_detach(dip);
937 
938 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
939 		mutex_destroy(&sata_hba_inst->satahba_mutex);
940 		kmem_free((void *)sata_hba_inst,
941 		    sizeof (struct sata_hba_inst));
942 		scsi_hba_tran_free(scsi_tran);
943 	}
944 
945 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
946 	    ddi_driver_name(dip), ddi_get_instance(dip));
947 
948 	return (DDI_FAILURE);
949 }
950 
951 
952 /*
953  * Called by SATA HBA from to detach an instance of the driver.
954  *
955  * For DDI_DETACH command:
956  * Free local structures allocated for SATA HBA instance during
957  * sata_hba_attach processing.
958  *
959  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
960  *
961  * For DDI_SUSPEND command:
962  * Not implemented at this time (postponed until phase 2 of the development)
963  * Returnd DDI_SUCCESS.
964  *
965  * When the last HBA instance is detached, the event daemon is terminated.
966  *
967  * NOTE: Port multiplier is supported.
968  */
969 int
970 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
971 {
972 	dev_info_t	*tdip;
973 	sata_hba_inst_t	*sata_hba_inst;
974 	scsi_hba_tran_t *scsi_hba_tran;
975 	sata_cport_info_t *cportinfo;
976 	sata_pmult_info_t *pminfo;
977 	sata_drive_info_t *sdinfo;
978 	sata_device_t	sdevice;
979 	int ncport, npmport;
980 
981 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
982 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
983 
984 	switch (cmd) {
985 	case DDI_DETACH:
986 
987 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
988 			return (DDI_FAILURE);
989 
990 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
991 		if (sata_hba_inst == NULL)
992 			return (DDI_FAILURE);
993 
994 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
995 			sata_hba_inst->satahba_attached = 1;
996 			return (DDI_FAILURE);
997 		}
998 
999 		/*
1000 		 * Free all target nodes - at this point
1001 		 * devices should be at least offlined
1002 		 * otherwise scsi_hba_detach() should not be called.
1003 		 */
1004 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1005 		    ncport++) {
1006 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1007 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1008 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1009 				if (sdinfo != NULL) {
1010 					tdip = sata_get_target_dip(dip,
1011 					    ncport, 0);
1012 					if (tdip != NULL) {
1013 						if (ndi_devi_offline(tdip,
1014 						    NDI_DEVI_REMOVE) !=
1015 						    NDI_SUCCESS) {
1016 							SATA_LOG_D((
1017 							    sata_hba_inst,
1018 							    CE_WARN,
1019 							    "sata_hba_detach: "
1020 							    "Target node not "
1021 							    "removed !"));
1022 							return (DDI_FAILURE);
1023 						}
1024 					}
1025 				}
1026 			} else { /* SATA_DTYPE_PMULT */
1027 				mutex_enter(&cportinfo->cport_mutex);
1028 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1029 
1030 				if (pminfo == NULL) {
1031 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1032 					    "sata_hba_detach: Port multiplier "
1033 					    "not ready yet!"));
1034 					mutex_exit(&cportinfo->cport_mutex);
1035 					return (DDI_FAILURE);
1036 				}
1037 
1038 				/*
1039 				 * Detach would fail if removal of any of the
1040 				 * target nodes is failed - albeit in that
1041 				 * case some of them may have been removed.
1042 				 */
1043 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1044 				    sata_hba_inst, ncport); npmport++) {
1045 					tdip = sata_get_target_dip(dip, ncport,
1046 					    npmport);
1047 					if (tdip != NULL) {
1048 						if (ndi_devi_offline(tdip,
1049 						    NDI_DEVI_REMOVE) !=
1050 						    NDI_SUCCESS) {
1051 							SATA_LOG_D((
1052 							    sata_hba_inst,
1053 							    CE_WARN,
1054 							    "sata_hba_detach: "
1055 							    "Target node not "
1056 							    "removed !"));
1057 							mutex_exit(&cportinfo->
1058 							    cport_mutex);
1059 							return (DDI_FAILURE);
1060 						}
1061 					}
1062 				}
1063 				mutex_exit(&cportinfo->cport_mutex);
1064 			}
1065 		}
1066 		/*
1067 		 * Disable sata event daemon processing for this HBA
1068 		 */
1069 		sata_hba_inst->satahba_attached = 0;
1070 
1071 		/*
1072 		 * Remove event daemon thread, if it is last HBA instance.
1073 		 */
1074 
1075 		mutex_enter(&sata_mutex);
1076 		if (sata_hba_list->satahba_next == NULL) {
1077 			mutex_exit(&sata_mutex);
1078 			sata_event_thread_control(0);
1079 			mutex_enter(&sata_mutex);
1080 		}
1081 		mutex_exit(&sata_mutex);
1082 
1083 		/* Remove this HBA instance from the HBA list */
1084 		sata_remove_hba_instance(dip);
1085 
1086 		/*
1087 		 * At this point there should be no target nodes attached.
1088 		 * Detach and destroy device and port info structures.
1089 		 */
1090 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1091 		    ncport++) {
1092 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1093 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1094 				sdinfo =
1095 				    cportinfo->cport_devp.cport_sata_drive;
1096 				if (sdinfo != NULL) {
1097 					/* Release device structure */
1098 					kmem_free(sdinfo,
1099 					    sizeof (sata_drive_info_t));
1100 				}
1101 				/* Release cport info */
1102 				mutex_destroy(&cportinfo->cport_mutex);
1103 				kmem_free(cportinfo,
1104 				    sizeof (sata_cport_info_t));
1105 			} else { /* SATA_DTYPE_PMULT */
1106 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1107 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1108 				sata_free_pmult(sata_hba_inst, &sdevice);
1109 			}
1110 		}
1111 
1112 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1113 
1114 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1115 
1116 		taskq_destroy(sata_hba_inst->satahba_taskq);
1117 
1118 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1119 		kmem_free((void *)sata_hba_inst,
1120 		    sizeof (struct sata_hba_inst));
1121 
1122 		return (DDI_SUCCESS);
1123 
1124 	case DDI_SUSPEND:
1125 		/*
1126 		 * Postponed until phase 2
1127 		 */
1128 		return (DDI_FAILURE);
1129 
1130 	default:
1131 		return (DDI_FAILURE);
1132 	}
1133 }
1134 
1135 
1136 /*
1137  * Called by an HBA drive from _fini() routine.
1138  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1139  */
1140 void
1141 sata_hba_fini(struct modlinkage *modlp)
1142 {
1143 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1144 	    "sata_hba_fini: name %s\n",
1145 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1146 
1147 	scsi_hba_fini(modlp);
1148 }
1149 
1150 
1151 /*
1152  * Default open and close routine for sata_hba framework.
1153  *
1154  */
1155 /*
1156  * Open devctl node.
1157  *
1158  * Returns:
1159  * 0 if node was open successfully, error code otherwise.
1160  *
1161  *
1162  */
1163 
1164 static int
1165 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1166 {
1167 #ifndef __lock_lint
1168 	_NOTE(ARGUNUSED(credp))
1169 #endif
1170 	int rv = 0;
1171 	dev_info_t *dip;
1172 	scsi_hba_tran_t *scsi_hba_tran;
1173 	sata_hba_inst_t	*sata_hba_inst;
1174 
1175 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1176 
1177 	if (otyp != OTYP_CHR)
1178 		return (EINVAL);
1179 
1180 	dip = sata_devt_to_devinfo(*devp);
1181 	if (dip == NULL)
1182 		return (ENXIO);
1183 
1184 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1185 		return (ENXIO);
1186 
1187 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1188 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1189 		return (ENXIO);
1190 
1191 	mutex_enter(&sata_mutex);
1192 	if (flags & FEXCL) {
1193 		if (sata_hba_inst->satahba_open_flag != 0) {
1194 			rv = EBUSY;
1195 		} else {
1196 			sata_hba_inst->satahba_open_flag =
1197 			    SATA_DEVCTL_EXOPENED;
1198 		}
1199 	} else {
1200 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1201 			rv = EBUSY;
1202 		} else {
1203 			sata_hba_inst->satahba_open_flag =
1204 			    SATA_DEVCTL_SOPENED;
1205 		}
1206 	}
1207 	mutex_exit(&sata_mutex);
1208 
1209 	return (rv);
1210 }
1211 
1212 
1213 /*
1214  * Close devctl node.
1215  * Returns:
1216  * 0 if node was closed successfully, error code otherwise.
1217  *
1218  */
1219 
1220 static int
1221 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1222 {
1223 #ifndef __lock_lint
1224 	_NOTE(ARGUNUSED(credp))
1225 	_NOTE(ARGUNUSED(flag))
1226 #endif
1227 	dev_info_t *dip;
1228 	scsi_hba_tran_t *scsi_hba_tran;
1229 	sata_hba_inst_t	*sata_hba_inst;
1230 
1231 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1232 
1233 	if (otyp != OTYP_CHR)
1234 		return (EINVAL);
1235 
1236 	dip = sata_devt_to_devinfo(dev);
1237 	if (dip == NULL)
1238 		return (ENXIO);
1239 
1240 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1241 		return (ENXIO);
1242 
1243 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1244 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1245 		return (ENXIO);
1246 
1247 	mutex_enter(&sata_mutex);
1248 	sata_hba_inst->satahba_open_flag = 0;
1249 	mutex_exit(&sata_mutex);
1250 	return (0);
1251 }
1252 
1253 
1254 
1255 /*
1256  * Standard IOCTL commands for SATA hotplugging.
1257  * Implemented DEVCTL_AP commands:
1258  * DEVCTL_AP_CONNECT
1259  * DEVCTL_AP_DISCONNECT
1260  * DEVCTL_AP_CONFIGURE
1261  * DEVCTL_UNCONFIGURE
1262  * DEVCTL_AP_CONTROL
1263  *
1264  * Commands passed to default ndi ioctl handler:
1265  * DEVCTL_DEVICE_GETSTATE
1266  * DEVCTL_DEVICE_ONLINE
1267  * DEVCTL_DEVICE_OFFLINE
1268  * DEVCTL_DEVICE_REMOVE
1269  * DEVCTL_DEVICE_INSERT
1270  * DEVCTL_BUS_GETSTATE
1271  *
1272  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1273  * if not.
1274  *
1275  * Returns:
1276  * 0 if successful,
1277  * error code if operation failed.
1278  *
1279  * Port Multiplier support is supported now.
1280  *
1281  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1282  */
1283 
1284 static int
1285 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1286     int *rvalp)
1287 {
1288 #ifndef __lock_lint
1289 	_NOTE(ARGUNUSED(credp))
1290 	_NOTE(ARGUNUSED(rvalp))
1291 #endif
1292 	int rv = 0;
1293 	int32_t	comp_port = -1;
1294 	dev_info_t *dip;
1295 	devctl_ap_state_t ap_state;
1296 	struct devctl_iocdata *dcp = NULL;
1297 	scsi_hba_tran_t *scsi_hba_tran;
1298 	sata_hba_inst_t *sata_hba_inst;
1299 	sata_device_t sata_device;
1300 	sata_cport_info_t *cportinfo;
1301 	int cport, pmport, qual;
1302 	int rval = SATA_SUCCESS;
1303 
1304 	dip = sata_devt_to_devinfo(dev);
1305 	if (dip == NULL)
1306 		return (ENXIO);
1307 
1308 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1309 		return (ENXIO);
1310 
1311 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1312 	if (sata_hba_inst == NULL)
1313 		return (ENXIO);
1314 
1315 	if (sata_hba_inst->satahba_tran == NULL)
1316 		return (ENXIO);
1317 
1318 	switch (cmd) {
1319 
1320 	case DEVCTL_DEVICE_GETSTATE:
1321 	case DEVCTL_DEVICE_ONLINE:
1322 	case DEVCTL_DEVICE_OFFLINE:
1323 	case DEVCTL_DEVICE_REMOVE:
1324 	case DEVCTL_BUS_GETSTATE:
1325 		/*
1326 		 * There may be more cases that we want to pass to default
1327 		 * handler rather than fail them.
1328 		 */
1329 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1330 	}
1331 
1332 	/* read devctl ioctl data */
1333 	if (cmd != DEVCTL_AP_CONTROL) {
1334 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1335 			return (EFAULT);
1336 
1337 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1338 		    -1) {
1339 			if (dcp)
1340 				ndi_dc_freehdl(dcp);
1341 			return (EINVAL);
1342 		}
1343 
1344 		/*
1345 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1346 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1347 		 */
1348 		cport = SCSI_TO_SATA_CPORT(comp_port);
1349 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1350 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1351 
1352 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1353 		    qual) != 0) {
1354 			ndi_dc_freehdl(dcp);
1355 			return (EINVAL);
1356 		}
1357 
1358 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1359 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1360 		    cport_mutex);
1361 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1362 			/*
1363 			 * Cannot process ioctl request now. Come back later.
1364 			 */
1365 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1366 			    cport_mutex);
1367 			ndi_dc_freehdl(dcp);
1368 			return (EBUSY);
1369 		}
1370 		/* Block event processing for this port */
1371 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1372 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1373 
1374 		sata_device.satadev_addr.cport = cport;
1375 		sata_device.satadev_addr.pmport = pmport;
1376 		sata_device.satadev_addr.qual = qual;
1377 		sata_device.satadev_rev = SATA_DEVICE_REV;
1378 	}
1379 
1380 	switch (cmd) {
1381 
1382 	case DEVCTL_AP_DISCONNECT:
1383 
1384 		/*
1385 		 * Normally, cfgadm sata plugin will try to offline
1386 		 * (unconfigure) device before this request. Nevertheless,
1387 		 * if a device is still configured, we need to
1388 		 * attempt to offline and unconfigure device first, and we will
1389 		 * deactivate the port regardless of the unconfigure
1390 		 * operation results.
1391 		 *
1392 		 */
1393 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1394 
1395 		break;
1396 
1397 	case DEVCTL_AP_UNCONFIGURE:
1398 
1399 		/*
1400 		 * The unconfigure operation uses generic nexus operation to
1401 		 * offline a device. It leaves a target device node attached.
1402 		 * and obviously sata_drive_info attached as well, because
1403 		 * from the hardware point of view nothing has changed.
1404 		 */
1405 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1406 		break;
1407 
1408 	case DEVCTL_AP_CONNECT:
1409 	{
1410 		/*
1411 		 * The sata cfgadm pluging will invoke this operation only if
1412 		 * port was found in the disconnect state (failed state
1413 		 * is also treated as the disconnected state).
1414 		 * If port activation is successful and a device is found
1415 		 * attached to the port, the initialization sequence is
1416 		 * executed to probe the port and attach
1417 		 * a device structure to a port structure. The device is not
1418 		 * set in configured state (system-wise) by this operation.
1419 		 */
1420 
1421 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1422 
1423 		break;
1424 	}
1425 
1426 	case DEVCTL_AP_CONFIGURE:
1427 	{
1428 		/*
1429 		 * A port may be in an active or shutdown state.
1430 		 * If port is in a failed state, operation is aborted.
1431 		 * If a port is in a shutdown state, sata_tran_port_activate()
1432 		 * is invoked prior to any other operation.
1433 		 *
1434 		 * Onlining the device involves creating a new target node.
1435 		 * If there is an old target node present (belonging to
1436 		 * previously removed device), the operation is aborted - the
1437 		 * old node has to be released and removed before configure
1438 		 * operation is attempted.
1439 		 */
1440 
1441 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1442 
1443 		break;
1444 	}
1445 
1446 	case DEVCTL_AP_GETSTATE:
1447 
1448 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1449 
1450 		ap_state.ap_last_change = (time_t)-1;
1451 		ap_state.ap_error_code = 0;
1452 		ap_state.ap_in_transition = 0;
1453 
1454 		/* Copy the return AP-state information to the user space */
1455 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1456 			rv = EFAULT;
1457 		}
1458 		break;
1459 
1460 	case DEVCTL_AP_CONTROL:
1461 	{
1462 		/*
1463 		 * Generic devctl for hardware specific functionality
1464 		 */
1465 		sata_ioctl_data_t	ioc;
1466 
1467 		ASSERT(dcp == NULL);
1468 
1469 		/* Copy in user ioctl data first */
1470 #ifdef _MULTI_DATAMODEL
1471 		if (ddi_model_convert_from(mode & FMODELS) ==
1472 		    DDI_MODEL_ILP32) {
1473 
1474 			sata_ioctl_data_32_t	ioc32;
1475 
1476 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1477 			    sizeof (ioc32), mode) != 0) {
1478 				rv = EFAULT;
1479 				break;
1480 			}
1481 			ioc.cmd 	= (uint_t)ioc32.cmd;
1482 			ioc.port	= (uint_t)ioc32.port;
1483 			ioc.get_size	= (uint_t)ioc32.get_size;
1484 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1485 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1486 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1487 		} else
1488 #endif /* _MULTI_DATAMODEL */
1489 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1490 		    mode) != 0) {
1491 			return (EFAULT);
1492 		}
1493 
1494 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1495 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1496 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1497 
1498 		/*
1499 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1500 		 * a 32-bit number.
1501 		 */
1502 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1503 			return (EINVAL);
1504 		}
1505 		/* validate address */
1506 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1507 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1508 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1509 
1510 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1511 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1512 		    cport, pmport, qual);
1513 
1514 		if (sata_validate_sata_address(sata_hba_inst, cport,
1515 		    pmport, qual) != 0)
1516 			return (EINVAL);
1517 
1518 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1519 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1520 		    cport_mutex);
1521 		/* Is the port locked by event processing daemon ? */
1522 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1523 			/*
1524 			 * Cannot process ioctl request now. Come back later
1525 			 */
1526 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1527 			    cport_mutex);
1528 			return (EBUSY);
1529 		}
1530 		/* Block event processing for this port */
1531 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1532 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1533 
1534 
1535 		sata_device.satadev_addr.cport = cport;
1536 		sata_device.satadev_addr.pmport = pmport;
1537 		sata_device.satadev_addr.qual = qual;
1538 		sata_device.satadev_rev = SATA_DEVICE_REV;
1539 
1540 		switch (ioc.cmd) {
1541 
1542 		case SATA_CFGA_RESET_PORT:
1543 			/*
1544 			 * There is no protection for configured device.
1545 			 */
1546 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1547 			break;
1548 
1549 		case SATA_CFGA_RESET_DEVICE:
1550 			/*
1551 			 * There is no protection for configured device.
1552 			 */
1553 			rv = sata_ioctl_reset_device(sata_hba_inst,
1554 			    &sata_device);
1555 			break;
1556 
1557 		case SATA_CFGA_RESET_ALL:
1558 			/*
1559 			 * There is no protection for configured devices.
1560 			 */
1561 			rv = sata_ioctl_reset_all(sata_hba_inst);
1562 			/*
1563 			 * We return here, because common return is for
1564 			 * a single port operation - we have already unlocked
1565 			 * all ports and no dc handle was allocated.
1566 			 */
1567 			return (rv);
1568 
1569 		case SATA_CFGA_PORT_DEACTIVATE:
1570 			/*
1571 			 * Arbitrarily unconfigure attached device, if any.
1572 			 * Even if the unconfigure fails, proceed with the
1573 			 * port deactivation.
1574 			 */
1575 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1576 
1577 			break;
1578 
1579 		case SATA_CFGA_PORT_ACTIVATE:
1580 
1581 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1582 			break;
1583 
1584 		case SATA_CFGA_PORT_SELF_TEST:
1585 
1586 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1587 			    &sata_device);
1588 			break;
1589 
1590 		case SATA_CFGA_GET_DEVICE_PATH:
1591 
1592 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1593 			    &sata_device, &ioc, mode);
1594 			break;
1595 
1596 		case SATA_CFGA_GET_AP_TYPE:
1597 
1598 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1599 			    &sata_device, &ioc, mode);
1600 			break;
1601 
1602 		case SATA_CFGA_GET_MODEL_INFO:
1603 
1604 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1605 			    &sata_device, &ioc, mode);
1606 			break;
1607 
1608 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1609 
1610 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1611 			    &sata_device, &ioc, mode);
1612 			break;
1613 
1614 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1615 
1616 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1617 			    &sata_device, &ioc, mode);
1618 			break;
1619 
1620 		default:
1621 			rv = EINVAL;
1622 			break;
1623 
1624 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1625 
1626 		break;
1627 	}
1628 
1629 	default:
1630 	{
1631 		/*
1632 		 * If we got here, we got an IOCTL that SATA HBA Framework
1633 		 * does not recognize. Pass ioctl to HBA driver, in case
1634 		 * it could process it.
1635 		 */
1636 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1637 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1638 
1639 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1640 		    "IOCTL 0x%2x not supported in SATA framework, "
1641 		    "passthrough to HBA", cmd);
1642 
1643 		if (sata_tran->sata_tran_ioctl == NULL) {
1644 			rv = EINVAL;
1645 			break;
1646 		}
1647 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1648 		if (rval != 0) {
1649 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1650 			    "IOCTL 0x%2x failed in HBA", cmd);
1651 			rv = rval;
1652 		}
1653 		break;
1654 	}
1655 
1656 	} /* End of main IOCTL switch */
1657 
1658 	if (dcp) {
1659 		ndi_dc_freehdl(dcp);
1660 	}
1661 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1662 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1663 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1664 
1665 	return (rv);
1666 }
1667 
1668 
1669 /*
1670  * Create error retrieval sata packet
1671  *
1672  * A sata packet is allocated and set-up to contain specified error retrieval
1673  * command and appropriate dma-able data buffer.
1674  * No association with any scsi packet is made and no callback routine is
1675  * specified.
1676  *
1677  * Returns a pointer to sata packet upon successfull packet creation.
1678  * Returns NULL, if packet cannot be created.
1679  */
1680 sata_pkt_t *
1681 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1682     int pkt_type)
1683 {
1684 	sata_hba_inst_t	*sata_hba_inst;
1685 	sata_pkt_txlate_t *spx;
1686 	sata_pkt_t *spkt;
1687 	sata_drive_info_t *sdinfo;
1688 
1689 	mutex_enter(&sata_mutex);
1690 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1691 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1692 		if (SATA_DIP(sata_hba_inst) == dip)
1693 			break;
1694 	}
1695 	mutex_exit(&sata_mutex);
1696 	ASSERT(sata_hba_inst != NULL);
1697 
1698 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1699 	if (sdinfo == NULL) {
1700 		sata_log(sata_hba_inst, CE_WARN,
1701 		    "sata: error recovery request for non-attached device at "
1702 		    "cport %d", sata_device->satadev_addr.cport);
1703 		return (NULL);
1704 	}
1705 
1706 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1707 	spx->txlt_sata_hba_inst = sata_hba_inst;
1708 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1709 	spkt = sata_pkt_alloc(spx, NULL);
1710 	if (spkt == NULL) {
1711 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1712 		return (NULL);
1713 	}
1714 	/* address is needed now */
1715 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1716 
1717 	switch (pkt_type) {
1718 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1719 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1720 			return (spkt);
1721 		break;
1722 
1723 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1724 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1725 			return (spkt);
1726 		break;
1727 
1728 	default:
1729 		break;
1730 	}
1731 
1732 	sata_pkt_free(spx);
1733 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1734 	return (NULL);
1735 
1736 }
1737 
1738 
1739 /*
1740  * Free error retrieval sata packet
1741  *
1742  * Free sata packet and any associated resources allocated previously by
1743  * sata_get_error_retrieval_pkt().
1744  *
1745  * Void return.
1746  */
1747 void
1748 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1749 {
1750 	sata_pkt_txlate_t *spx =
1751 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1752 
1753 	ASSERT(sata_pkt != NULL);
1754 
1755 	sata_free_local_buffer(spx);
1756 	sata_pkt_free(spx);
1757 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1758 
1759 }
1760 
1761 /*
1762  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1763  *
1764  * No association with any scsi packet is made and no callback routine is
1765  * specified.
1766  *
1767  * Returns a pointer to sata packet upon successfull packet creation.
1768  * Returns NULL, if packet cannot be created.
1769  *
1770  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1771  * only lower 32 bits are available currently.
1772  */
1773 sata_pkt_t *
1774 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1775     uint8_t regn, uint32_t regv, uint32_t type)
1776 {
1777 	sata_hba_inst_t	*sata_hba_inst;
1778 	sata_pkt_txlate_t *spx;
1779 	sata_pkt_t *spkt;
1780 	sata_cmd_t *scmd;
1781 
1782 	/* Only READ/WRITE commands are accepted. */
1783 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1784 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1785 
1786 	mutex_enter(&sata_mutex);
1787 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1788 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1789 		if (SATA_DIP(sata_hba_inst) == dip)
1790 			break;
1791 	}
1792 	mutex_exit(&sata_mutex);
1793 	ASSERT(sata_hba_inst != NULL);
1794 
1795 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1796 	spx->txlt_sata_hba_inst = sata_hba_inst;
1797 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1798 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1799 	if (spkt == NULL) {
1800 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1801 		return (NULL);
1802 	}
1803 
1804 	/*
1805 	 * NOTE: We need to send this command to the port multiplier,
1806 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1807 	 *
1808 	 * sata_device contains the address of actual target device, and the
1809 	 * pmport number in the command comes from the sata_device structure.
1810 	 */
1811 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1812 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1813 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1814 
1815 	/* Fill sata_pkt */
1816 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1817 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1818 	spkt->satapkt_time = 10; /* Timeout 10s */
1819 
1820 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1821 	scmd = &spkt->satapkt_cmd;
1822 	scmd->satacmd_features_reg = regn & 0xff;
1823 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1824 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1825 	scmd->satacmd_addr_type = 0;		/* N/A */
1826 
1827 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1828 
1829 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1830 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1831 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1832 		scmd->satacmd_flags.sata_special_regs = 1;
1833 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1834 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1835 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1836 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1837 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1838 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1839 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1840 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1841 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1842 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1843 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1844 	}
1845 
1846 	return (spkt);
1847 }
1848 
1849 /*
1850  * Free sata packet and any associated resources allocated previously by
1851  * sata_get_rdwr_pmult_pkt().
1852  *
1853  * Void return.
1854  */
1855 void
1856 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1857 {
1858 	sata_pkt_txlate_t *spx =
1859 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1860 
1861 	/* Free allocated resources */
1862 	sata_pkt_free(spx);
1863 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1864 }
1865 
1866 /*
1867  * Register a port multiplier to framework.
1868  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1869  * 2) Search in the blacklist and update the number of the device ports of the
1870  * port multiplier.
1871  *
1872  * Void return.
1873  */
1874 void
1875 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1876 {
1877 	sata_hba_inst_t *sata_hba_inst = NULL;
1878 	sata_pmult_info_t *pmultinfo;
1879 	sata_pmult_bl_t *blp;
1880 	int cport = sd->satadev_addr.cport;
1881 
1882 	mutex_enter(&sata_mutex);
1883 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1884 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1885 		if (SATA_DIP(sata_hba_inst) == dip)
1886 			if (sata_hba_inst->satahba_attached == 1)
1887 				break;
1888 	}
1889 	mutex_exit(&sata_mutex);
1890 	/* HBA not attached? */
1891 	if (sata_hba_inst == NULL)
1892 		return;
1893 
1894 	/* Number of pmports */
1895 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1896 
1897 	/* Check the blacklist */
1898 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1899 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1900 			continue;
1901 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1902 			continue;
1903 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1904 			continue;
1905 
1906 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1907 		sd->satadev_add_info = blp->bl_flags;
1908 		break;
1909 	}
1910 
1911 	/* Register the port multiplier GSCR */
1912 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1913 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1914 	if (pmultinfo != NULL) {
1915 		pmultinfo->pmult_gscr = *sg;
1916 		pmultinfo->pmult_num_dev_ports =
1917 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1918 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1919 		    "Port multiplier registered at port %d", cport);
1920 	}
1921 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1922 }
1923 
1924 /*
1925  * sata_name_child is for composing the name of the node
1926  * the format of the name is "target,0".
1927  */
1928 static int
1929 sata_name_child(dev_info_t *dip, char *name, int namelen)
1930 {
1931 	int target;
1932 
1933 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1934 	    DDI_PROP_DONTPASS, "target", -1);
1935 	if (target == -1)
1936 		return (DDI_FAILURE);
1937 	(void) snprintf(name, namelen, "%x,0", target);
1938 	return (DDI_SUCCESS);
1939 }
1940 
1941 
1942 
1943 /* ****************** SCSA required entry points *********************** */
1944 
1945 /*
1946  * Implementation of scsi tran_tgt_init.
1947  * sata_scsi_tgt_init() initializes scsi_device structure
1948  *
1949  * If successful, DDI_SUCCESS is returned.
1950  * DDI_FAILURE is returned if addressed device does not exist
1951  */
1952 
1953 static int
1954 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1955     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1956 {
1957 #ifndef __lock_lint
1958 	_NOTE(ARGUNUSED(hba_dip))
1959 	_NOTE(ARGUNUSED(tgt_dip))
1960 #endif
1961 	sata_device_t		sata_device;
1962 	sata_drive_info_t	*sdinfo;
1963 	struct sata_id		*sid;
1964 	sata_hba_inst_t		*sata_hba_inst;
1965 	char			model[SATA_ID_MODEL_LEN + 1];
1966 	char			fw[SATA_ID_FW_LEN + 1];
1967 	char			*vid, *pid;
1968 	int			i;
1969 
1970 	/*
1971 	 * Fail tran_tgt_init for .conf stub node
1972 	 */
1973 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1974 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1975 		ddi_set_name_addr(tgt_dip, NULL);
1976 		return (DDI_FAILURE);
1977 	}
1978 
1979 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1980 
1981 	/* Validate scsi device address */
1982 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1983 	    &sata_device) != 0)
1984 		return (DDI_FAILURE);
1985 
1986 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1987 	    sata_device.satadev_addr.cport)));
1988 
1989 	/* sata_device now contains a valid sata address */
1990 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1991 	if (sdinfo == NULL) {
1992 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1993 		    sata_device.satadev_addr.cport)));
1994 		return (DDI_FAILURE);
1995 	}
1996 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1997 	    sata_device.satadev_addr.cport)));
1998 
1999 	/*
2000 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2001 	 * the target disks.
2002 	 *
2003 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2004 	 * if we need to create cmdk-style devid for all the disk devices
2005 	 * attached to this controller. This property may have been set
2006 	 * from HBA driver's .conf file or by the HBA driver in its
2007 	 * attach(9F) function.
2008 	 */
2009 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2010 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2011 	    "use-cmdk-devid-format", 0) == 1)) {
2012 		/* register a legacy devid for this target node */
2013 		sata_target_devid_register(tgt_dip, sdinfo);
2014 	}
2015 
2016 
2017 	/*
2018 	 * 'Identify Device Data' does not always fit in standard SCSI
2019 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2020 	 * of information.
2021 	 */
2022 	sid = &sdinfo->satadrv_id;
2023 #ifdef	_LITTLE_ENDIAN
2024 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2025 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2026 #else	/* _LITTLE_ENDIAN */
2027 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2028 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2029 #endif	/* _LITTLE_ENDIAN */
2030 	model[SATA_ID_MODEL_LEN] = 0;
2031 	fw[SATA_ID_FW_LEN] = 0;
2032 
2033 	/* split model into into vid/pid */
2034 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2035 		if ((*pid == ' ') || (*pid == '\t'))
2036 			break;
2037 	if (i < SATA_ID_MODEL_LEN) {
2038 		vid = model;
2039 		*pid++ = 0;		/* terminate vid, establish pid */
2040 	} else {
2041 		vid = NULL;		/* vid will stay "ATA     " */
2042 		pid = model;		/* model is all pid */
2043 	}
2044 
2045 	if (vid)
2046 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2047 		    vid, strlen(vid));
2048 	if (pid)
2049 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2050 		    pid, strlen(pid));
2051 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2052 	    fw, strlen(fw));
2053 
2054 	return (DDI_SUCCESS);
2055 }
2056 
2057 /*
2058  * Implementation of scsi tran_tgt_probe.
2059  * Probe target, by calling default scsi routine scsi_hba_probe()
2060  */
2061 static int
2062 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2063 {
2064 	sata_hba_inst_t *sata_hba_inst =
2065 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2066 	int rval;
2067 	uint32_t pm_cap;
2068 
2069 	rval = scsi_hba_probe(sd, callback);
2070 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2071 	    SATA_CAP_LOG_SENSE;
2072 
2073 	if (rval == SCSIPROBE_EXISTS) {
2074 		/*
2075 		 * Set property "pm-capable" on the target device node, so that
2076 		 * the target driver will not try to fetch scsi cycle counters
2077 		 * before enabling device power-management.
2078 		 */
2079 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2080 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2081 			sata_log(sata_hba_inst, CE_WARN,
2082 			    "SATA device at port %d: "
2083 			    "will not be power-managed ",
2084 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2085 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2086 			    "failure updating pm-capable property"));
2087 		}
2088 	}
2089 	return (rval);
2090 }
2091 
2092 /*
2093  * Implementation of scsi tran_tgt_free.
2094  * Release all resources allocated for scsi_device
2095  */
2096 static void
2097 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2098     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2099 {
2100 #ifndef __lock_lint
2101 	_NOTE(ARGUNUSED(hba_dip))
2102 #endif
2103 	sata_device_t		sata_device;
2104 	sata_drive_info_t	*sdinfo;
2105 	sata_hba_inst_t		*sata_hba_inst;
2106 	ddi_devid_t		devid;
2107 
2108 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2109 
2110 	/* Validate scsi device address */
2111 	/*
2112 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2113 	 * was a device at this address, so even if the sata framework internal
2114 	 * resources were alredy released because a device was detached,
2115 	 * this function should be executed as long as its actions do
2116 	 * not require the internal sata view of a device and the address
2117 	 * refers to a valid sata address.
2118 	 * Validating the address here means that we do not trust SCSA...
2119 	 */
2120 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2121 	    &sata_device) == -1)
2122 		return;
2123 
2124 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2125 	    sata_device.satadev_addr.cport)));
2126 
2127 	/* sata_device now should contain a valid sata address */
2128 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2129 	if (sdinfo == NULL) {
2130 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2131 		    sata_device.satadev_addr.cport)));
2132 		return;
2133 	}
2134 	/*
2135 	 * We did not allocate any resources in sata_scsi_tgt_init()
2136 	 * other than few properties.
2137 	 * Free them.
2138 	 */
2139 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2140 	    sata_device.satadev_addr.cport)));
2141 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2142 
2143 	/*
2144 	 * If devid was previously created but not freed up from
2145 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2146 	 */
2147 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2148 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2149 	    "use-cmdk-devid-format", 0) == 1) &&
2150 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2151 		ddi_devid_unregister(tgt_dip);
2152 		ddi_devid_free(devid);
2153 	}
2154 }
2155 
2156 /*
2157  * Implementation of scsi tran_init_pkt
2158  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2159  *
2160  * It seems that we should always allocate pkt, even if the address is
2161  * for non-existing device - just use some default for dma_attr.
2162  * The reason is that there is no way to communicate this to a caller here.
2163  * Subsequent call to sata_scsi_start may fail appropriately.
2164  * Simply returning NULL does not seem to discourage a target driver...
2165  *
2166  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2167  */
2168 static struct scsi_pkt *
2169 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2170     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2171     int (*callback)(caddr_t), caddr_t arg)
2172 {
2173 	sata_hba_inst_t *sata_hba_inst =
2174 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2175 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2176 	sata_device_t sata_device;
2177 	sata_drive_info_t *sdinfo;
2178 	sata_pkt_txlate_t *spx;
2179 	ddi_dma_attr_t cur_dma_attr;
2180 	int rval;
2181 	boolean_t new_pkt = TRUE;
2182 
2183 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2184 
2185 	/*
2186 	 * We need to translate the address, even if it could be
2187 	 * a bogus one, for a non-existing device
2188 	 */
2189 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2190 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2191 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2192 	sata_device.satadev_rev = SATA_DEVICE_REV;
2193 
2194 	if (pkt == NULL) {
2195 		/*
2196 		 * Have to allocate a brand new scsi packet.
2197 		 * We need to operate with auto request sense enabled.
2198 		 */
2199 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2200 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2201 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2202 
2203 		if (pkt == NULL)
2204 			return (NULL);
2205 
2206 		/* Fill scsi packet structure */
2207 		pkt->pkt_comp		= (void (*)())NULL;
2208 		pkt->pkt_time		= 0;
2209 		pkt->pkt_resid		= 0;
2210 		pkt->pkt_statistics	= 0;
2211 		pkt->pkt_reason		= 0;
2212 
2213 		/*
2214 		 * pkt_hba_private will point to sata pkt txlate structure
2215 		 */
2216 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2217 		bzero(spx, sizeof (sata_pkt_txlate_t));
2218 
2219 		spx->txlt_scsi_pkt = pkt;
2220 		spx->txlt_sata_hba_inst = sata_hba_inst;
2221 
2222 		/* Allocate sata_pkt */
2223 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2224 		if (spx->txlt_sata_pkt == NULL) {
2225 			/* Could not allocate sata pkt */
2226 			scsi_hba_pkt_free(ap, pkt);
2227 			return (NULL);
2228 		}
2229 		/* Set sata address */
2230 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2231 		    sata_device.satadev_addr;
2232 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2233 		    sata_device.satadev_rev;
2234 
2235 		if ((bp == NULL) || (bp->b_bcount == 0))
2236 			return (pkt);
2237 
2238 		spx->txlt_total_residue = bp->b_bcount;
2239 	} else {
2240 		new_pkt = FALSE;
2241 		/*
2242 		 * Packet was preallocated/initialized by previous call
2243 		 */
2244 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2245 
2246 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2247 			return (pkt);
2248 		}
2249 
2250 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2251 	}
2252 
2253 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2254 
2255 	/*
2256 	 * We use an adjusted version of the dma_attr, to account
2257 	 * for device addressing limitations.
2258 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2259 	 * happen when a device is not yet configured.
2260 	 */
2261 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2262 	    sata_device.satadev_addr.cport)));
2263 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2264 	    &spx->txlt_sata_pkt->satapkt_device);
2265 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2266 	sata_adjust_dma_attr(sdinfo,
2267 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2268 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2269 	    sata_device.satadev_addr.cport)));
2270 	/*
2271 	 * Allocate necessary DMA resources for the packet's data buffer
2272 	 * NOTE:
2273 	 * In case of read/write commands, DMA resource allocation here is
2274 	 * based on the premise that the transfer length specified in
2275 	 * the read/write scsi cdb will match exactly DMA resources -
2276 	 * returning correct packet residue is crucial.
2277 	 */
2278 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2279 	    &cur_dma_attr)) != DDI_SUCCESS) {
2280 		/*
2281 		 * If a DMA allocation request fails with
2282 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2283 		 * bioerror(9F) with bp and an error code of EFAULT.
2284 		 * If a DMA allocation request fails with
2285 		 * DDI_DMA_TOOBIG, indicate the error by calling
2286 		 * bioerror(9F) with bp and an error code of EINVAL.
2287 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2288 		 * Request may be repeated later - there is no real error.
2289 		 */
2290 		switch (rval) {
2291 		case DDI_DMA_NORESOURCES:
2292 			bioerror(bp, 0);
2293 			break;
2294 		case DDI_DMA_NOMAPPING:
2295 		case DDI_DMA_BADATTR:
2296 			bioerror(bp, EFAULT);
2297 			break;
2298 		case DDI_DMA_TOOBIG:
2299 		default:
2300 			bioerror(bp, EINVAL);
2301 			break;
2302 		}
2303 		if (new_pkt == TRUE) {
2304 			/*
2305 			 * Since this is a new packet, we can clean-up
2306 			 * everything
2307 			 */
2308 			sata_scsi_destroy_pkt(ap, pkt);
2309 		} else {
2310 			/*
2311 			 * This is a re-used packet. It will be target driver's
2312 			 * responsibility to eventually destroy it (which
2313 			 * will free allocated resources).
2314 			 * Here, we just "complete" the request, leaving
2315 			 * allocated resources intact, so the request may
2316 			 * be retried.
2317 			 */
2318 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2319 			sata_pkt_free(spx);
2320 		}
2321 		return (NULL);
2322 	}
2323 	/* Set number of bytes that are not yet accounted for */
2324 	pkt->pkt_resid = spx->txlt_total_residue;
2325 	ASSERT(pkt->pkt_resid >= 0);
2326 
2327 	return (pkt);
2328 }
2329 
2330 /*
2331  * Implementation of scsi tran_start.
2332  * Translate scsi cmd into sata operation and return status.
2333  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2334  * are supported.
2335  * For SATA hard disks, supported scsi commands:
2336  * SCMD_INQUIRY
2337  * SCMD_TEST_UNIT_READY
2338  * SCMD_START_STOP
2339  * SCMD_READ_CAPACITY
2340  * SCMD_REQUEST_SENSE
2341  * SCMD_LOG_SENSE_G1
2342  * SCMD_LOG_SELECT_G1
2343  * SCMD_MODE_SENSE	(specific pages)
2344  * SCMD_MODE_SENSE_G1	(specific pages)
2345  * SCMD_MODE_SELECT	(specific pages)
2346  * SCMD_MODE_SELECT_G1	(specific pages)
2347  * SCMD_SYNCHRONIZE_CACHE
2348  * SCMD_SYNCHRONIZE_CACHE_G1
2349  * SCMD_READ
2350  * SCMD_READ_G1
2351  * SCMD_READ_G4
2352  * SCMD_READ_G5
2353  * SCMD_WRITE
2354  * SCMD_WRITE_BUFFER
2355  * SCMD_WRITE_G1
2356  * SCMD_WRITE_G4
2357  * SCMD_WRITE_G5
2358  * SCMD_SEEK		(noop)
2359  * SCMD_SDIAG
2360  *
2361  * All other commands are rejected as unsupported.
2362  *
2363  * Returns:
2364  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2365  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2366  * a callback could be scheduled.
2367  * TRAN_BADPKT if cmd was directed to invalid address.
2368  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2369  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2370  * was removed and there was no callback specified in scsi pkt.
2371  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2372  * framework was busy performing some other operation(s).
2373  *
2374  */
2375 static int
2376 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2377 {
2378 	sata_hba_inst_t *sata_hba_inst =
2379 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2380 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2381 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2382 	sata_drive_info_t *sdinfo;
2383 	struct buf *bp;
2384 	uint8_t cport, pmport;
2385 	boolean_t dev_gone = B_FALSE;
2386 	int rval;
2387 
2388 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2389 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2390 
2391 	ASSERT(spx != NULL &&
2392 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2393 
2394 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2395 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2396 
2397 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2398 
2399 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2400 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2401 		if (sdinfo == NULL ||
2402 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2403 		    cport_tgtnode_clean == B_FALSE ||
2404 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2405 			dev_gone = B_TRUE;
2406 		}
2407 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2408 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2409 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2410 		    cport) == NULL) {
2411 			dev_gone = B_TRUE;
2412 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2413 		    pmport) == NULL) {
2414 			dev_gone = B_TRUE;
2415 		} else {
2416 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2417 			    cport, pmport)));
2418 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2419 			if (sdinfo == NULL ||
2420 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2421 			    pmport_tgtnode_clean == B_FALSE ||
2422 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2423 				dev_gone = B_TRUE;
2424 			}
2425 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2426 			    cport, pmport)));
2427 		}
2428 	}
2429 
2430 	if (dev_gone == B_TRUE) {
2431 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2432 		pkt->pkt_reason = CMD_DEV_GONE;
2433 		/*
2434 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2435 		 * only in callback function (for normal requests) and
2436 		 * in the dump code path.
2437 		 * So, if the callback is available, we need to do
2438 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2439 		 */
2440 		if (pkt->pkt_comp != NULL) {
2441 			/* scsi callback required */
2442 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2443 			    (task_func_t *)pkt->pkt_comp,
2444 			    (void *)pkt, TQ_NOSLEEP) == NULL)
2445 				/* Scheduling the callback failed */
2446 				return (TRAN_BUSY);
2447 			return (TRAN_ACCEPT);
2448 		}
2449 		/* No callback available */
2450 		return (TRAN_FATAL_ERROR);
2451 	}
2452 
2453 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2454 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2455 		rval = sata_txlt_atapi(spx);
2456 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2457 		    "sata_scsi_start atapi: rval %d\n", rval);
2458 		return (rval);
2459 	}
2460 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2461 
2462 	/*
2463 	 * Checking for power state, if it was on
2464 	 * STOPPED state, then the drive is not capable
2465 	 * of processing media access command.  And
2466 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2467 	 * in the function for different power state.
2468 	 */
2469 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2470 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2471 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2472 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2473 		    SD_SCSI_ASC_LU_NOT_READY));
2474 	}
2475 
2476 	/* ATA Disk commands processing starts here */
2477 
2478 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2479 
2480 	switch (pkt->pkt_cdbp[0]) {
2481 
2482 	case SCMD_INQUIRY:
2483 		/* Mapped to identify device */
2484 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2485 			bp_mapin(bp);
2486 		rval = sata_txlt_inquiry(spx);
2487 		break;
2488 
2489 	case SCMD_TEST_UNIT_READY:
2490 		/*
2491 		 * SAT "SATA to ATA Translation" doc specifies translation
2492 		 * to ATA CHECK POWER MODE.
2493 		 */
2494 		rval = sata_txlt_test_unit_ready(spx);
2495 		break;
2496 
2497 	case SCMD_START_STOP:
2498 		/* Mapping depends on the command */
2499 		rval = sata_txlt_start_stop_unit(spx);
2500 		break;
2501 
2502 	case SCMD_READ_CAPACITY:
2503 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2504 			bp_mapin(bp);
2505 		rval = sata_txlt_read_capacity(spx);
2506 		break;
2507 
2508 	case SCMD_REQUEST_SENSE:
2509 		/*
2510 		 * Always No Sense, since we force ARQ
2511 		 */
2512 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2513 			bp_mapin(bp);
2514 		rval = sata_txlt_request_sense(spx);
2515 		break;
2516 
2517 	case SCMD_LOG_SENSE_G1:
2518 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2519 			bp_mapin(bp);
2520 		rval = sata_txlt_log_sense(spx);
2521 		break;
2522 
2523 	case SCMD_LOG_SELECT_G1:
2524 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2525 			bp_mapin(bp);
2526 		rval = sata_txlt_log_select(spx);
2527 		break;
2528 
2529 	case SCMD_MODE_SENSE:
2530 	case SCMD_MODE_SENSE_G1:
2531 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2532 			bp_mapin(bp);
2533 		rval = sata_txlt_mode_sense(spx);
2534 		break;
2535 
2536 
2537 	case SCMD_MODE_SELECT:
2538 	case SCMD_MODE_SELECT_G1:
2539 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2540 			bp_mapin(bp);
2541 		rval = sata_txlt_mode_select(spx);
2542 		break;
2543 
2544 	case SCMD_SYNCHRONIZE_CACHE:
2545 	case SCMD_SYNCHRONIZE_CACHE_G1:
2546 		rval = sata_txlt_synchronize_cache(spx);
2547 		break;
2548 
2549 	case SCMD_READ:
2550 	case SCMD_READ_G1:
2551 	case SCMD_READ_G4:
2552 	case SCMD_READ_G5:
2553 		rval = sata_txlt_read(spx);
2554 		break;
2555 	case SCMD_WRITE_BUFFER:
2556 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2557 			bp_mapin(bp);
2558 		rval = sata_txlt_write_buffer(spx);
2559 		break;
2560 
2561 	case SCMD_WRITE:
2562 	case SCMD_WRITE_G1:
2563 	case SCMD_WRITE_G4:
2564 	case SCMD_WRITE_G5:
2565 		rval = sata_txlt_write(spx);
2566 		break;
2567 
2568 	case SCMD_SEEK:
2569 		rval = sata_txlt_nodata_cmd_immediate(spx);
2570 		break;
2571 
2572 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2573 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2574 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2575 			bp_mapin(bp);
2576 		rval = sata_txlt_ata_pass_thru(spx);
2577 		break;
2578 
2579 		/* Other cases will be filed later */
2580 		/* postponed until phase 2 of the development */
2581 	default:
2582 		rval = sata_txlt_invalid_command(spx);
2583 		break;
2584 	}
2585 
2586 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2587 	    "sata_scsi_start: rval %d\n", rval);
2588 
2589 	return (rval);
2590 }
2591 
2592 /*
2593  * Implementation of scsi tran_abort.
2594  * Abort specific pkt or all packets.
2595  *
2596  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2597  *
2598  * May be called from an interrupt level.
2599  */
2600 static int
2601 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2602 {
2603 	sata_hba_inst_t *sata_hba_inst =
2604 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2605 	sata_device_t	sata_device;
2606 	sata_pkt_t	*sata_pkt;
2607 
2608 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2609 	    "sata_scsi_abort: %s at target: 0x%x\n",
2610 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2611 
2612 	/* Validate address */
2613 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2614 		/* Invalid address */
2615 		return (0);
2616 
2617 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2618 	    sata_device.satadev_addr.cport)));
2619 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2620 		/* invalid address */
2621 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2622 		    sata_device.satadev_addr.cport)));
2623 		return (0);
2624 	}
2625 	if (scsi_pkt == NULL) {
2626 		/*
2627 		 * Abort all packets.
2628 		 * Although we do not have specific packet, we still need
2629 		 * dummy packet structure to pass device address to HBA.
2630 		 * Allocate one, without sleeping. Fail if pkt cannot be
2631 		 * allocated.
2632 		 */
2633 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2634 		if (sata_pkt == NULL) {
2635 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2636 			    sata_device.satadev_addr.cport)));
2637 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2638 			    "could not allocate sata_pkt"));
2639 			return (0);
2640 		}
2641 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2642 		sata_pkt->satapkt_device = sata_device;
2643 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2644 	} else {
2645 		if (scsi_pkt->pkt_ha_private == NULL) {
2646 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2647 			    sata_device.satadev_addr.cport)));
2648 			return (0); /* Bad scsi pkt */
2649 		}
2650 		/* extract pointer to sata pkt */
2651 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2652 		    txlt_sata_pkt;
2653 	}
2654 
2655 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2656 	    sata_device.satadev_addr.cport)));
2657 	/* Send abort request to HBA */
2658 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2659 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2660 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2661 	    SATA_SUCCESS) {
2662 		if (scsi_pkt == NULL)
2663 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2664 		/* Success */
2665 		return (1);
2666 	}
2667 	/* Else, something did not go right */
2668 	if (scsi_pkt == NULL)
2669 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2670 	/* Failure */
2671 	return (0);
2672 }
2673 
2674 
2675 /*
2676  * Implementation of scsi tran_reset.
2677  * RESET_ALL request is translated into port reset.
2678  * RESET_TARGET requests is translated into a device reset,
2679  * RESET_LUN request is accepted only for LUN 0 and translated into
2680  * device reset.
2681  * The target reset should cause all HBA active and queued packets to
2682  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2683  * the return. HBA should report reset event for the device.
2684  *
2685  * Returns 1 upon success, 0 upon failure.
2686  */
2687 static int
2688 sata_scsi_reset(struct scsi_address *ap, int level)
2689 {
2690 	sata_hba_inst_t	*sata_hba_inst =
2691 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2692 	sata_device_t	sata_device;
2693 	int		val;
2694 
2695 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2696 	    "sata_scsi_reset: level %d target: 0x%x\n",
2697 	    level, ap->a_target);
2698 
2699 	/* Validate address */
2700 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2701 	if (val == -1)
2702 		/* Invalid address */
2703 		return (0);
2704 
2705 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2706 	    sata_device.satadev_addr.cport)));
2707 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2708 		/* invalid address */
2709 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2710 		    sata_device.satadev_addr.cport)));
2711 		return (0);
2712 	}
2713 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2714 	    sata_device.satadev_addr.cport)));
2715 	if (level == RESET_ALL) {
2716 		/* port reset */
2717 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2718 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2719 		else
2720 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2721 
2722 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2723 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2724 			return (1);
2725 		else
2726 			return (0);
2727 
2728 	} else if (val == 0 &&
2729 	    (level == RESET_TARGET || level == RESET_LUN)) {
2730 		/* reset device (device attached) */
2731 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2732 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2733 			return (1);
2734 		else
2735 			return (0);
2736 	}
2737 	return (0);
2738 }
2739 
2740 
2741 /*
2742  * Implementation of scsi tran_getcap (get transport/device capabilities).
2743  * Supported capabilities for SATA hard disks:
2744  * auto-rqsense		(always supported)
2745  * tagged-qing		(supported if HBA supports it)
2746  * untagged-qing	(could be supported if disk supports it, but because
2747  *			 caching behavior allowing untagged queuing actually
2748  *			 results in reduced performance.  sd tries to throttle
2749  *			 back to only 3 outstanding commands, which may
2750  *			 work for real SCSI disks, but with read ahead
2751  *			 caching, having more than 1 outstanding command
2752  *			 results in cache thrashing.)
2753  * sector_size
2754  * dma_max
2755  * interconnect-type	(INTERCONNECT_SATA)
2756  *
2757  * Supported capabilities for ATAPI CD/DVD devices:
2758  * auto-rqsense		(always supported)
2759  * sector_size
2760  * dma_max
2761  * max-cdb-length
2762  * interconnect-type	(INTERCONNECT_SATA)
2763  *
2764  * Supported capabilities for ATAPI TAPE devices:
2765  * auto-rqsense		(always supported)
2766  * dma_max
2767  * max-cdb-length
2768  *
2769  * Supported capabilities for SATA ATAPI hard disks:
2770  * auto-rqsense		(always supported)
2771  * interconnect-type	(INTERCONNECT_SATA)
2772  * max-cdb-length
2773  *
2774  * Request for other capabilities is rejected as unsupported.
2775  *
2776  * Returns supported capability value, or -1 if capability is unsuppported or
2777  * the address is invalid - no device.
2778  */
2779 
2780 static int
2781 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2782 {
2783 
2784 	sata_hba_inst_t 	*sata_hba_inst =
2785 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2786 	sata_device_t		sata_device;
2787 	sata_drive_info_t	*sdinfo;
2788 	ddi_dma_attr_t		adj_dma_attr;
2789 	int 			rval;
2790 
2791 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2792 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2793 	    ap->a_target, cap);
2794 
2795 	/*
2796 	 * We want to process the capabilities on per port granularity.
2797 	 * So, we are specifically restricting ourselves to whom != 0
2798 	 * to exclude the controller wide handling.
2799 	 */
2800 	if (cap == NULL || whom == 0)
2801 		return (-1);
2802 
2803 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2804 		/* Invalid address */
2805 		return (-1);
2806 	}
2807 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2808 	    sata_device.satadev_addr.cport)));
2809 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2810 	    NULL) {
2811 		/* invalid address */
2812 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2813 		    sata_device.satadev_addr.cport)));
2814 		return (-1);
2815 	}
2816 
2817 	switch (scsi_hba_lookup_capstr(cap)) {
2818 	case SCSI_CAP_ARQ:
2819 		rval = 1;		/* ARQ supported, turned on */
2820 		break;
2821 
2822 	case SCSI_CAP_SECTOR_SIZE:
2823 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2824 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2825 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2826 			rval = SATA_ATAPI_SECTOR_SIZE;
2827 		else rval = -1;
2828 		break;
2829 
2830 	/*
2831 	 * untagged queuing cause a performance inversion because of
2832 	 * the way sd operates.  Because of this reason we do not
2833 	 * use it when available.
2834 	 */
2835 	case SCSI_CAP_UNTAGGED_QING:
2836 		if (sdinfo->satadrv_features_enabled &
2837 		    SATA_DEV_F_E_UNTAGGED_QING)
2838 			rval = 1;	/* Untagged queuing available */
2839 		else
2840 			rval = -1;	/* Untagged queuing not available */
2841 		break;
2842 
2843 	case SCSI_CAP_TAGGED_QING:
2844 		if ((sdinfo->satadrv_features_enabled &
2845 		    SATA_DEV_F_E_TAGGED_QING) &&
2846 		    (sdinfo->satadrv_max_queue_depth > 1))
2847 			rval = 1;	/* Tagged queuing available */
2848 		else
2849 			rval = -1;	/* Tagged queuing not available */
2850 		break;
2851 
2852 	case SCSI_CAP_DMA_MAX:
2853 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2854 		    &adj_dma_attr);
2855 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2856 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2857 		break;
2858 
2859 	case SCSI_CAP_INTERCONNECT_TYPE:
2860 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2861 		break;
2862 
2863 	case SCSI_CAP_CDB_LEN:
2864 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2865 			rval = sdinfo->satadrv_atapi_cdb_len;
2866 		else
2867 			rval = -1;
2868 		break;
2869 
2870 	default:
2871 		rval = -1;
2872 		break;
2873 	}
2874 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2875 	    sata_device.satadev_addr.cport)));
2876 	return (rval);
2877 }
2878 
2879 /*
2880  * Implementation of scsi tran_setcap
2881  *
2882  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2883  *
2884  */
2885 static int
2886 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2887 {
2888 	sata_hba_inst_t	*sata_hba_inst =
2889 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2890 	sata_device_t	sata_device;
2891 	sata_drive_info_t	*sdinfo;
2892 	int		rval;
2893 
2894 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2895 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2896 
2897 	/*
2898 	 * We want to process the capabilities on per port granularity.
2899 	 * So, we are specifically restricting ourselves to whom != 0
2900 	 * to exclude the controller wide handling.
2901 	 */
2902 	if (cap == NULL || whom == 0) {
2903 		return (-1);
2904 	}
2905 
2906 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2907 		/* Invalid address */
2908 		return (-1);
2909 	}
2910 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2911 	    sata_device.satadev_addr.cport)));
2912 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2913 	    &sata_device)) == NULL) {
2914 		/* invalid address */
2915 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2916 		    sata_device.satadev_addr.cport)));
2917 		return (-1);
2918 	}
2919 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2920 	    sata_device.satadev_addr.cport)));
2921 
2922 	switch (scsi_hba_lookup_capstr(cap)) {
2923 	case SCSI_CAP_ARQ:
2924 	case SCSI_CAP_SECTOR_SIZE:
2925 	case SCSI_CAP_DMA_MAX:
2926 	case SCSI_CAP_INTERCONNECT_TYPE:
2927 		rval = 0;
2928 		break;
2929 	case SCSI_CAP_UNTAGGED_QING:
2930 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2931 			rval = 1;
2932 			if (value == 1) {
2933 				sdinfo->satadrv_features_enabled |=
2934 				    SATA_DEV_F_E_UNTAGGED_QING;
2935 			} else if (value == 0) {
2936 				sdinfo->satadrv_features_enabled &=
2937 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2938 			} else {
2939 				rval = -1;
2940 			}
2941 		} else {
2942 			rval = 0;
2943 		}
2944 		break;
2945 	case SCSI_CAP_TAGGED_QING:
2946 		/* This can TCQ or NCQ */
2947 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2948 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2949 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2950 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2951 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2952 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2953 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2954 			rval = 1;
2955 			if (value == 1) {
2956 				sdinfo->satadrv_features_enabled |=
2957 				    SATA_DEV_F_E_TAGGED_QING;
2958 			} else if (value == 0) {
2959 				sdinfo->satadrv_features_enabled &=
2960 				    ~SATA_DEV_F_E_TAGGED_QING;
2961 			} else {
2962 				rval = -1;
2963 			}
2964 		} else {
2965 			rval = 0;
2966 		}
2967 		break;
2968 	default:
2969 		rval = -1;
2970 		break;
2971 	}
2972 	return (rval);
2973 }
2974 
2975 /*
2976  * Implementations of scsi tran_destroy_pkt.
2977  * Free resources allocated by sata_scsi_init_pkt()
2978  */
2979 static void
2980 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2981 {
2982 	sata_pkt_txlate_t *spx;
2983 
2984 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2985 
2986 	sata_common_free_dma_rsrcs(spx);
2987 
2988 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2989 	sata_pkt_free(spx);
2990 
2991 	scsi_hba_pkt_free(ap, pkt);
2992 }
2993 
2994 /*
2995  * Implementation of scsi tran_dmafree.
2996  * Free DMA resources allocated by sata_scsi_init_pkt()
2997  */
2998 
2999 static void
3000 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3001 {
3002 #ifndef __lock_lint
3003 	_NOTE(ARGUNUSED(ap))
3004 #endif
3005 	sata_pkt_txlate_t *spx;
3006 
3007 	ASSERT(pkt != NULL);
3008 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3009 
3010 	sata_common_free_dma_rsrcs(spx);
3011 }
3012 
3013 /*
3014  * Implementation of scsi tran_sync_pkt.
3015  *
3016  * The assumption below is that pkt is unique - there is no need to check ap
3017  *
3018  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3019  * into/from the real buffer.
3020  */
3021 static void
3022 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3023 {
3024 #ifndef __lock_lint
3025 	_NOTE(ARGUNUSED(ap))
3026 #endif
3027 	int rval;
3028 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3029 	struct buf *bp;
3030 	int direction;
3031 
3032 	ASSERT(spx != NULL);
3033 	if (spx->txlt_buf_dma_handle != NULL) {
3034 		direction = spx->txlt_sata_pkt->
3035 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3036 		if (spx->txlt_sata_pkt != NULL &&
3037 		    direction != SATA_DIR_NODATA_XFER) {
3038 			if (spx->txlt_tmp_buf != NULL) {
3039 				/* Intermediate DMA buffer used */
3040 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3041 
3042 				if (direction & SATA_DIR_WRITE) {
3043 					bcopy(bp->b_un.b_addr,
3044 					    spx->txlt_tmp_buf, bp->b_bcount);
3045 				}
3046 			}
3047 			/* Sync the buffer for device or for CPU */
3048 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3049 			    (direction & SATA_DIR_WRITE) ?
3050 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3051 			ASSERT(rval == DDI_SUCCESS);
3052 			if (spx->txlt_tmp_buf != NULL &&
3053 			    !(direction & SATA_DIR_WRITE)) {
3054 				/* Intermediate DMA buffer used for read */
3055 				bcopy(spx->txlt_tmp_buf,
3056 				    bp->b_un.b_addr, bp->b_bcount);
3057 			}
3058 
3059 		}
3060 	}
3061 }
3062 
3063 
3064 
3065 /* *******************  SATA - SCSI Translation functions **************** */
3066 /*
3067  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3068  * translation.
3069  */
3070 
3071 /*
3072  * Checks if a device exists and can be access and translates common
3073  * scsi_pkt data to sata_pkt data.
3074  *
3075  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3076  * sata_pkt was set-up.
3077  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3078  * exist and pkt_comp callback was scheduled.
3079  * Returns other TRAN_XXXXX values when error occured and command should be
3080  * rejected with the returned TRAN_XXXXX value.
3081  *
3082  * This function should be called with port mutex held.
3083  */
3084 static int
3085 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason)
3086 {
3087 	sata_drive_info_t *sdinfo;
3088 	sata_device_t sata_device;
3089 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3090 		SATA_DIR_NODATA_XFER,
3091 		/* all other values to 0/FALSE */
3092 	};
3093 	/*
3094 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3095 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3096 	 * indicates that the scsi packet was not accepted (the reason will not
3097 	 * be checked by the scsi target driver).
3098 	 * To make debugging easier, we set pkt_reason to know value here.
3099 	 * It may be changed later when different completion reason is
3100 	 * determined.
3101 	 */
3102 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3103 	*reason = CMD_TRAN_ERR;
3104 
3105 	/* Validate address */
3106 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3107 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3108 
3109 	case -1:
3110 		/* Invalid address or invalid device type */
3111 		return (TRAN_BADPKT);
3112 	case 2:
3113 		/*
3114 		 * Valid address but device type is unknown - Chack if it is
3115 		 * in the reset state and therefore in an indeterminate state.
3116 		 */
3117 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3118 		    &spx->txlt_sata_pkt->satapkt_device);
3119 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3120 		    (SATA_EVNT_DEVICE_RESET |
3121 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3122 			if (!ddi_in_panic()) {
3123 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3124 				*reason = CMD_INCOMPLETE;
3125 				SATADBG1(SATA_DBG_SCSI_IF,
3126 				    spx->txlt_sata_hba_inst,
3127 				    "sata_scsi_start: rejecting command "
3128 				    "because of device reset state\n", NULL);
3129 				return (TRAN_BUSY);
3130 			}
3131 		}
3132 		/* FALLTHROUGH */
3133 	case 1:
3134 		/* valid address but no valid device - it has disappeared */
3135 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3136 		*reason = CMD_DEV_GONE;
3137 		/*
3138 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3139 		 * only in callback function (for normal requests) and
3140 		 * in the dump code path.
3141 		 * So, if the callback is available, we need to do
3142 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3143 		 */
3144 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3145 			/* scsi callback required */
3146 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3147 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3148 			    (void *)spx->txlt_scsi_pkt,
3149 			    TQ_SLEEP) == NULL)
3150 				/* Scheduling the callback failed */
3151 				return (TRAN_BUSY);
3152 
3153 			return (TRAN_ACCEPT);
3154 		}
3155 		return (TRAN_FATAL_ERROR);
3156 	default:
3157 		/* all OK; pkt reason will be overwritten later */
3158 		break;
3159 	}
3160 	/*
3161 	 * If in an interrupt context, reject packet if it is to be
3162 	 * executed in polling mode
3163 	 */
3164 	if (servicing_interrupt() &&
3165 	    (spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3166 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3167 		    "sata_scsi_start: rejecting synchronous command because "
3168 		    "of interrupt context\n", NULL);
3169 		return (TRAN_BUSY);
3170 	}
3171 
3172 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3173 	    &spx->txlt_sata_pkt->satapkt_device);
3174 
3175 	/*
3176 	 * If device is in reset condition, reject the packet with
3177 	 * TRAN_BUSY, unless:
3178 	 * 1. system is panicking (dumping)
3179 	 * In such case only one thread is running and there is no way to
3180 	 * process reset.
3181 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3182 	 * Some cfgadm operations involve drive commands, so reset condition
3183 	 * needs to be ignored for IOCTL operations.
3184 	 */
3185 	if ((sdinfo->satadrv_event_flags &
3186 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3187 
3188 		if (!ddi_in_panic() &&
3189 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3190 		    sata_device.satadev_addr.cport) &
3191 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3192 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3193 			*reason = CMD_INCOMPLETE;
3194 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3195 			    "sata_scsi_start: rejecting command because "
3196 			    "of device reset state\n", NULL);
3197 			return (TRAN_BUSY);
3198 		}
3199 	}
3200 
3201 	/*
3202 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3203 	 * sata_scsi_pkt_init() because pkt init had to work also with
3204 	 * non-existing devices.
3205 	 * Now we know that the packet was set-up for a real device, so its
3206 	 * type is known.
3207 	 */
3208 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3209 
3210 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3211 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3212 	    sata_device.satadev_addr.cport)->cport_event_flags &
3213 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3214 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3215 		    sata_ignore_dev_reset = B_TRUE;
3216 	}
3217 	/*
3218 	 * At this point the generic translation routine determined that the
3219 	 * scsi packet should be accepted. Packet completion reason may be
3220 	 * changed later when a different completion reason is determined.
3221 	 */
3222 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3223 	*reason = CMD_CMPLT;
3224 
3225 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3226 		/* Synchronous execution */
3227 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3228 		    SATA_OPMODE_POLLING;
3229 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3230 		    sata_ignore_dev_reset = ddi_in_panic();
3231 	} else {
3232 		/* Asynchronous execution */
3233 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3234 		    SATA_OPMODE_INTERRUPTS;
3235 	}
3236 	/* Convert queuing information */
3237 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3238 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3239 		    B_TRUE;
3240 	else if (spx->txlt_scsi_pkt->pkt_flags &
3241 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3242 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3243 		    B_TRUE;
3244 
3245 	/* Always limit pkt time */
3246 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3247 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3248 	else
3249 		/* Pass on scsi_pkt time */
3250 		spx->txlt_sata_pkt->satapkt_time =
3251 		    spx->txlt_scsi_pkt->pkt_time;
3252 
3253 	return (TRAN_ACCEPT);
3254 }
3255 
3256 
3257 /*
3258  * Translate ATA Identify Device data to SCSI Inquiry data.
3259  * This function may be called only for ATA devices.
3260  * This function should not be called for ATAPI devices - they
3261  * respond directly to SCSI Inquiry command.
3262  *
3263  * SATA Identify Device data has to be valid in sata_drive_info.
3264  * Buffer has to accomodate the inquiry length (36 bytes).
3265  *
3266  * This function should be called with a port mutex held.
3267  */
3268 static	void
3269 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3270     sata_drive_info_t *sdinfo, uint8_t *buf)
3271 {
3272 
3273 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3274 	struct sata_id *sid = &sdinfo->satadrv_id;
3275 
3276 	/* Start with a nice clean slate */
3277 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3278 
3279 	/*
3280 	 * Rely on the dev_type for setting paripheral qualifier.
3281 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3282 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3283 	 * ATAPI Inquiry may provide more data to the target driver.
3284 	 */
3285 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3286 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3287 
3288 	/* CFA type device is not a removable media device */
3289 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3290 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3291 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3292 	inq->inq_iso = 0;	/* ISO version */
3293 	inq->inq_ecma = 0;	/* ECMA version */
3294 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3295 	inq->inq_aenc = 0;	/* Async event notification cap. */
3296 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3297 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3298 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3299 	inq->inq_len = 31;	/* Additional length */
3300 	inq->inq_dualp = 0;	/* dual port device - NO */
3301 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3302 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3303 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3304 				/*
3305 				 * Queuing support - controller has to
3306 				 * support some sort of command queuing.
3307 				 */
3308 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3309 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3310 	else
3311 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3312 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3313 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3314 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3315 
3316 #ifdef	_LITTLE_ENDIAN
3317 	/* Swap text fields to match SCSI format */
3318 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3319 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3320 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3321 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3322 	else
3323 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3324 #else	/* _LITTLE_ENDIAN */
3325 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3326 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3327 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3328 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3329 	else
3330 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3331 #endif	/* _LITTLE_ENDIAN */
3332 }
3333 
3334 
3335 /*
3336  * Scsi response set up for invalid command (command not supported)
3337  *
3338  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3339  */
3340 static int
3341 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3342 {
3343 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3344 	struct scsi_extended_sense *sense;
3345 
3346 	scsipkt->pkt_reason = CMD_CMPLT;
3347 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3348 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3349 
3350 	*scsipkt->pkt_scbp = STATUS_CHECK;
3351 
3352 	sense = sata_arq_sense(spx);
3353 	sense->es_key = KEY_ILLEGAL_REQUEST;
3354 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3355 
3356 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3357 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3358 
3359 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3360 	    scsipkt->pkt_comp != NULL)
3361 		/* scsi callback required */
3362 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3363 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3364 		    (void *)spx->txlt_scsi_pkt,
3365 		    TQ_SLEEP) == NULL)
3366 			/* Scheduling the callback failed */
3367 			return (TRAN_BUSY);
3368 	return (TRAN_ACCEPT);
3369 }
3370 
3371 /*
3372  * Scsi response set up for check condition with special sense key
3373  * and additional sense code.
3374  *
3375  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3376  */
3377 static int
3378 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3379 {
3380 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3381 	int cport = SATA_TXLT_CPORT(spx);
3382 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3383 	struct scsi_extended_sense *sense;
3384 
3385 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3386 	scsipkt->pkt_reason = CMD_CMPLT;
3387 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3388 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3389 
3390 	*scsipkt->pkt_scbp = STATUS_CHECK;
3391 
3392 	sense = sata_arq_sense(spx);
3393 	sense->es_key = key;
3394 	sense->es_add_code = code;
3395 
3396 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3397 
3398 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3399 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3400 
3401 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3402 		/* scsi callback required */
3403 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3404 		    (task_func_t *)scsi_hba_pkt_comp,
3405 		    (void *)spx->txlt_scsi_pkt,
3406 		    TQ_SLEEP) == NULL)
3407 			/* Scheduling the callback failed */
3408 			return (TRAN_BUSY);
3409 	return (TRAN_ACCEPT);
3410 }
3411 
3412 /*
3413  * Scsi response setup for
3414  * emulated non-data command that requires no action/return data
3415  *
3416  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3417  */
3418 static	int
3419 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3420 {
3421 	int rval;
3422 	int reason;
3423 
3424 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3425 
3426 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3427 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3428 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3429 		return (rval);
3430 	}
3431 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3432 
3433 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3434 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3435 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3436 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3437 
3438 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3439 	    "Scsi_pkt completion reason %x\n",
3440 	    spx->txlt_scsi_pkt->pkt_reason);
3441 
3442 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3443 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3444 		/* scsi callback required */
3445 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3446 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3447 		    (void *)spx->txlt_scsi_pkt,
3448 		    TQ_SLEEP) == NULL)
3449 			/* Scheduling the callback failed */
3450 			return (TRAN_BUSY);
3451 	return (TRAN_ACCEPT);
3452 }
3453 
3454 
3455 /*
3456  * SATA translate command: Inquiry / Identify Device
3457  * Use cached Identify Device data for now, rather than issuing actual
3458  * Device Identify cmd request. If device is detached and re-attached,
3459  * asynchronous event processing should fetch and refresh Identify Device
3460  * data.
3461  * Two VPD pages are supported now:
3462  * Vital Product Data page
3463  * Unit Serial Number page
3464  *
3465  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3466  */
3467 
3468 #define	EVPD			1	/* Extended Vital Product Data flag */
3469 #define	CMDDT			2	/* Command Support Data - Obsolete */
3470 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3471 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3472 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3473 
3474 static int
3475 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3476 {
3477 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3478 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3479 	sata_drive_info_t *sdinfo;
3480 	struct scsi_extended_sense *sense;
3481 	int count;
3482 	uint8_t *p;
3483 	int i, j;
3484 	uint8_t page_buf[0xff]; /* Max length */
3485 	int rval, reason;
3486 
3487 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3488 
3489 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3490 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3491 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3492 		return (rval);
3493 	}
3494 
3495 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3496 	    &spx->txlt_sata_pkt->satapkt_device);
3497 
3498 	ASSERT(sdinfo != NULL);
3499 
3500 	scsipkt->pkt_reason = CMD_CMPLT;
3501 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3502 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3503 
3504 	/* Reject not supported request */
3505 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3506 		*scsipkt->pkt_scbp = STATUS_CHECK;
3507 		sense = sata_arq_sense(spx);
3508 		sense->es_key = KEY_ILLEGAL_REQUEST;
3509 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3510 		goto done;
3511 	}
3512 
3513 	/* Valid Inquiry request */
3514 	*scsipkt->pkt_scbp = STATUS_GOOD;
3515 
3516 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3517 
3518 		/*
3519 		 * Because it is fully emulated command storing data
3520 		 * programatically in the specified buffer, release
3521 		 * preallocated DMA resources before storing data in the buffer,
3522 		 * so no unwanted DMA sync would take place.
3523 		 */
3524 		sata_scsi_dmafree(NULL, scsipkt);
3525 
3526 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3527 			/* Standard Inquiry Data request */
3528 			struct scsi_inquiry inq;
3529 			unsigned int bufsize;
3530 
3531 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3532 			    sdinfo, (uint8_t *)&inq);
3533 			/* Copy no more than requested */
3534 			count = MIN(bp->b_bcount,
3535 			    sizeof (struct scsi_inquiry));
3536 			bufsize = scsipkt->pkt_cdbp[4];
3537 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3538 			count = MIN(count, bufsize);
3539 			bcopy(&inq, bp->b_un.b_addr, count);
3540 
3541 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3542 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3543 			    bufsize - count : 0;
3544 		} else {
3545 			/*
3546 			 * peripheral_qualifier = 0;
3547 			 *
3548 			 * We are dealing only with HD and will be
3549 			 * dealing with CD/DVD devices soon
3550 			 */
3551 			uint8_t peripheral_device_type =
3552 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3553 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3554 
3555 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3556 			case INQUIRY_SUP_VPD_PAGE:
3557 				/*
3558 				 * Request for suported Vital Product Data
3559 				 * pages - assuming only 2 page codes
3560 				 * supported.
3561 				 */
3562 				page_buf[0] = peripheral_device_type;
3563 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3564 				page_buf[2] = 0;
3565 				page_buf[3] = 2; /* page length */
3566 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3567 				page_buf[5] = INQUIRY_USN_PAGE;
3568 				/* Copy no more than requested */
3569 				count = MIN(bp->b_bcount, 6);
3570 				bcopy(page_buf, bp->b_un.b_addr, count);
3571 				break;
3572 
3573 			case INQUIRY_USN_PAGE:
3574 				/*
3575 				 * Request for Unit Serial Number page.
3576 				 * Set-up the page.
3577 				 */
3578 				page_buf[0] = peripheral_device_type;
3579 				page_buf[1] = INQUIRY_USN_PAGE;
3580 				page_buf[2] = 0;
3581 				/* remaining page length */
3582 				page_buf[3] = SATA_ID_SERIAL_LEN;
3583 
3584 				/*
3585 				 * Copy serial number from Identify Device data
3586 				 * words into the inquiry page and swap bytes
3587 				 * when necessary.
3588 				 */
3589 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3590 #ifdef	_LITTLE_ENDIAN
3591 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3592 #else
3593 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3594 #endif
3595 				/*
3596 				 * Least significant character of the serial
3597 				 * number shall appear as the last byte,
3598 				 * according to SBC-3 spec.
3599 				 * Count trailing spaces to determine the
3600 				 * necessary shift length.
3601 				 */
3602 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3603 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3604 					if (*(p - j) != '\0' &&
3605 					    *(p - j) != '\040')
3606 						break;
3607 				}
3608 
3609 				/*
3610 				 * Shift SN string right, so that the last
3611 				 * non-blank character would appear in last
3612 				 * byte of SN field in the page.
3613 				 * 'j' is the shift length.
3614 				 */
3615 				for (i = 0;
3616 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3617 				    i++, p--)
3618 					*p = *(p - j);
3619 
3620 				/*
3621 				 * Add leading spaces - same number as the
3622 				 * shift size
3623 				 */
3624 				for (; j > 0; j--)
3625 					page_buf[4 + j - 1] = '\040';
3626 
3627 				count = MIN(bp->b_bcount,
3628 				    SATA_ID_SERIAL_LEN + 4);
3629 				bcopy(page_buf, bp->b_un.b_addr, count);
3630 				break;
3631 
3632 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3633 				/*
3634 				 * We may want to implement this page, when
3635 				 * identifiers are common for SATA devices
3636 				 * But not now.
3637 				 */
3638 				/*FALLTHROUGH*/
3639 
3640 			default:
3641 				/* Request for unsupported VPD page */
3642 				*scsipkt->pkt_scbp = STATUS_CHECK;
3643 				sense = sata_arq_sense(spx);
3644 				sense->es_key = KEY_ILLEGAL_REQUEST;
3645 				sense->es_add_code =
3646 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3647 				goto done;
3648 			}
3649 		}
3650 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3651 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3652 		    scsipkt->pkt_cdbp[4] - count : 0;
3653 	}
3654 done:
3655 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3656 
3657 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3658 	    "Scsi_pkt completion reason %x\n",
3659 	    scsipkt->pkt_reason);
3660 
3661 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3662 	    scsipkt->pkt_comp != NULL) {
3663 		/* scsi callback required */
3664 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3665 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3666 		    TQ_SLEEP) == NULL)
3667 			/* Scheduling the callback failed */
3668 			return (TRAN_BUSY);
3669 	}
3670 	return (TRAN_ACCEPT);
3671 }
3672 
3673 /*
3674  * SATA translate command: Request Sense.
3675  *
3676  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3677  * At the moment this is an emulated command (ATA version for SATA hard disks).
3678  * May be translated into Check Power Mode command in the future.
3679  *
3680  * Note: There is a mismatch between already implemented Informational
3681  * Exception Mode Select page 0x1C and this function.
3682  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3683  * NO SENSE and set additional sense code to the exception code - this is not
3684  * implemented here.
3685  */
3686 static int
3687 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3688 {
3689 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3690 	struct scsi_extended_sense sense;
3691 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3692 	sata_drive_info_t *sdinfo;
3693 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3694 	int rval, reason, power_state = 0;
3695 
3696 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3697 
3698 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3699 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3700 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3701 		return (rval);
3702 	}
3703 
3704 	scsipkt->pkt_reason = CMD_CMPLT;
3705 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3706 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3707 	*scsipkt->pkt_scbp = STATUS_GOOD;
3708 
3709 	/*
3710 	 * when CONTROL field's NACA bit == 1
3711 	 * return ILLEGAL_REQUEST
3712 	 */
3713 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3714 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3715 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3716 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3717 	}
3718 
3719 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3720 	    &spx->txlt_sata_pkt->satapkt_device);
3721 	ASSERT(sdinfo != NULL);
3722 
3723 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3724 
3725 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3726 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3727 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3728 	if (sata_hba_start(spx, &rval) != 0) {
3729 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3730 		return (rval);
3731 	} else {
3732 		if (scmd->satacmd_error_reg != 0) {
3733 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3734 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3735 			    SD_SCSI_ASC_NO_ADD_SENSE));
3736 		}
3737 	}
3738 
3739 	switch (scmd->satacmd_sec_count_lsb) {
3740 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3741 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3742 			power_state = SATA_POWER_STOPPED;
3743 		else {
3744 			power_state = SATA_POWER_STANDBY;
3745 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3746 		}
3747 		break;
3748 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3749 		power_state = SATA_POWER_IDLE;
3750 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3751 		break;
3752 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3753 	default:		  /* 0x40, 0x41 active mode */
3754 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3755 			power_state = SATA_POWER_IDLE;
3756 		else {
3757 			power_state = SATA_POWER_ACTIVE;
3758 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3759 		}
3760 		break;
3761 	}
3762 
3763 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3764 
3765 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3766 		/*
3767 		 * Because it is fully emulated command storing data
3768 		 * programatically in the specified buffer, release
3769 		 * preallocated DMA resources before storing data in the buffer,
3770 		 * so no unwanted DMA sync would take place.
3771 		 */
3772 		int count = MIN(bp->b_bcount,
3773 		    sizeof (struct scsi_extended_sense));
3774 		sata_scsi_dmafree(NULL, scsipkt);
3775 		bzero(&sense, sizeof (struct scsi_extended_sense));
3776 		sense.es_valid = 0;	/* Valid LBA */
3777 		sense.es_class = 7;	/* Response code 0x70 - current err */
3778 		sense.es_key = KEY_NO_SENSE;
3779 		sense.es_add_len = 6;	/* Additional length */
3780 		/* Copy no more than requested */
3781 		bcopy(&sense, bp->b_un.b_addr, count);
3782 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3783 		scsipkt->pkt_resid = 0;
3784 		switch (power_state) {
3785 		case SATA_POWER_IDLE:
3786 		case SATA_POWER_STANDBY:
3787 			sense.es_add_code =
3788 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3789 			break;
3790 		case SATA_POWER_STOPPED:
3791 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3792 			break;
3793 		case SATA_POWER_ACTIVE:
3794 		default:
3795 			break;
3796 		}
3797 	}
3798 
3799 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3800 	    "Scsi_pkt completion reason %x\n",
3801 	    scsipkt->pkt_reason);
3802 
3803 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3804 		/* scsi callback required */
3805 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3806 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3807 		    TQ_SLEEP) == NULL)
3808 			/* Scheduling the callback failed */
3809 			return (TRAN_BUSY);
3810 	return (TRAN_ACCEPT);
3811 }
3812 
3813 /*
3814  * SATA translate command: Test Unit Ready
3815  * (ATA version for SATA hard disks).
3816  * It is translated into the Check Power Mode command.
3817  *
3818  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3819  */
3820 static int
3821 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3822 {
3823 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3824 	struct scsi_extended_sense *sense;
3825 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3826 	sata_drive_info_t *sdinfo;
3827 	int power_state;
3828 	int rval, reason;
3829 
3830 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3831 
3832 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3833 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3834 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3835 		return (rval);
3836 	}
3837 
3838 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3839 	    &spx->txlt_sata_pkt->satapkt_device);
3840 	ASSERT(sdinfo != NULL);
3841 
3842 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3843 
3844 	/* send CHECK POWER MODE command */
3845 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3846 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3847 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3848 	if (sata_hba_start(spx, &rval) != 0) {
3849 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3850 		return (rval);
3851 	} else {
3852 		if (scmd->satacmd_error_reg != 0) {
3853 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3854 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3855 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3856 		}
3857 	}
3858 
3859 	power_state = scmd->satacmd_sec_count_lsb;
3860 
3861 	/*
3862 	 * return NOT READY when device in STOPPED mode
3863 	 */
3864 	if (power_state == SATA_PWRMODE_STANDBY &&
3865 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3866 		*scsipkt->pkt_scbp = STATUS_CHECK;
3867 		sense = sata_arq_sense(spx);
3868 		sense->es_key = KEY_NOT_READY;
3869 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3870 	} else {
3871 		/*
3872 		 * For other power mode, return GOOD status
3873 		 */
3874 		*scsipkt->pkt_scbp = STATUS_GOOD;
3875 	}
3876 
3877 	scsipkt->pkt_reason = CMD_CMPLT;
3878 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3879 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3880 
3881 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3882 
3883 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3884 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3885 
3886 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3887 		/* scsi callback required */
3888 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3889 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3890 		    TQ_SLEEP) == NULL)
3891 			/* Scheduling the callback failed */
3892 			return (TRAN_BUSY);
3893 
3894 	return (TRAN_ACCEPT);
3895 }
3896 
3897 /*
3898  * SATA translate command: Start Stop Unit
3899  * Translation depends on a command:
3900  *
3901  * Power condition bits will be supported
3902  * and the power level should be maintained by SATL,
3903  * When SATL received a command, it will check the
3904  * power level firstly, and return the status according
3905  * to SAT2 v2.6 and SAT-2 Standby Modifications
3906  *
3907  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3908  * -----------------------------------------------------------------------
3909  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3910  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3911  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3912  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3913  *
3914  *	Unload Media / NOT SUPPORTED YET
3915  *	Load Media / NOT SUPPROTED YET
3916  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3917  *
3918  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3919  * appropriate values in scsi_pkt fields.
3920  */
3921 static int
3922 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3923 {
3924 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3925 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3926 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3927 	int cport = SATA_TXLT_CPORT(spx);
3928 	int rval, reason;
3929 	sata_drive_info_t *sdinfo;
3930 	sata_id_t *sata_id;
3931 
3932 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3933 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3934 
3935 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3936 
3937 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3938 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3939 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3940 		return (rval);
3941 	}
3942 
3943 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
3944 		/* IMMED bit - not supported */
3945 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3946 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3947 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
3948 	}
3949 
3950 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3951 	spx->txlt_sata_pkt->satapkt_comp = NULL;
3952 
3953 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3954 	    &spx->txlt_sata_pkt->satapkt_device);
3955 	ASSERT(sdinfo != NULL);
3956 	sata_id = &sdinfo->satadrv_id;
3957 
3958 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
3959 	case 0:
3960 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
3961 			/* Load/Unload Media - invalid request */
3962 			goto err_out;
3963 		}
3964 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
3965 			/* Start Unit */
3966 			sata_build_read_verify_cmd(scmd, 1, 5);
3967 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3968 			/* Transfer command to HBA */
3969 			if (sata_hba_start(spx, &rval) != 0) {
3970 				/* Pkt not accepted for execution */
3971 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3972 				return (rval);
3973 			} else {
3974 				if (scmd->satacmd_error_reg != 0) {
3975 					goto err_out;
3976 				}
3977 			}
3978 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3979 		} else {
3980 			/* Stop Unit */
3981 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3982 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3983 			if (sata_hba_start(spx, &rval) != 0) {
3984 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3985 				return (rval);
3986 			} else {
3987 				if (scmd->satacmd_error_reg != 0) {
3988 					goto err_out;
3989 				}
3990 			}
3991 			/* ata standby immediate command */
3992 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
3993 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3994 			if (sata_hba_start(spx, &rval) != 0) {
3995 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3996 				return (rval);
3997 			} else {
3998 				if (scmd->satacmd_error_reg != 0) {
3999 					goto err_out;
4000 				}
4001 			}
4002 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4003 		}
4004 		break;
4005 	case 0x1:
4006 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4007 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4008 		if (sata_hba_start(spx, &rval) != 0) {
4009 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4010 			return (rval);
4011 		} else {
4012 			if (scmd->satacmd_error_reg != 0) {
4013 				goto err_out;
4014 			}
4015 		}
4016 		sata_build_read_verify_cmd(scmd, 1, 5);
4017 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4018 		/* Transfer command to HBA */
4019 		if (sata_hba_start(spx, &rval) != 0) {
4020 			/* Pkt not accepted for execution */
4021 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4022 			return (rval);
4023 		} else {
4024 			if (scmd->satacmd_error_reg != 0) {
4025 				goto err_out;
4026 			}
4027 		}
4028 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4029 		break;
4030 	case 0x2:
4031 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4032 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4033 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4034 			if (sata_hba_start(spx, &rval) != 0) {
4035 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4036 				return (rval);
4037 			} else {
4038 				if (scmd->satacmd_error_reg != 0) {
4039 					goto err_out;
4040 				}
4041 			}
4042 		}
4043 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4044 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4045 		if (sata_hba_start(spx, &rval) != 0) {
4046 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4047 			return (rval);
4048 		} else {
4049 			if (scmd->satacmd_error_reg != 0) {
4050 				goto err_out;
4051 			}
4052 		}
4053 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4054 			/*
4055 			 *  POWER CONDITION MODIFIER bit set
4056 			 *  to 0x1 or larger it will be handled
4057 			 *  on the same way as bit = 0x1
4058 			 */
4059 			if (!(sata_id->ai_cmdset84 &
4060 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4061 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4062 				break;
4063 			}
4064 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4065 			scmd->satacmd_features_reg = 0x44;
4066 			scmd->satacmd_lba_low_lsb = 0x4c;
4067 			scmd->satacmd_lba_mid_lsb = 0x4e;
4068 			scmd->satacmd_lba_high_lsb = 0x55;
4069 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4070 			if (sata_hba_start(spx, &rval) != 0) {
4071 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4072 				return (rval);
4073 			} else {
4074 				if (scmd->satacmd_error_reg != 0) {
4075 					goto err_out;
4076 				}
4077 			}
4078 		}
4079 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4080 		break;
4081 	case 0x3:
4082 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4083 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4084 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
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 		}
4094 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4095 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4096 		if (sata_hba_start(spx, &rval) != 0) {
4097 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4098 			return (rval);
4099 		} else {
4100 			if (scmd->satacmd_error_reg != 0) {
4101 				goto err_out;
4102 			}
4103 		}
4104 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4105 		break;
4106 	case 0x7:
4107 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4108 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4109 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4110 		if (sata_hba_start(spx, &rval) != 0) {
4111 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4112 			return (rval);
4113 		} else {
4114 			if (scmd->satacmd_error_reg != 0) {
4115 				goto err_out;
4116 			}
4117 		}
4118 		switch (scmd->satacmd_sec_count_lsb) {
4119 		case SATA_PWRMODE_STANDBY:
4120 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4121 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4122 			    sdinfo->satadrv_standby_timer);
4123 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4124 			if (sata_hba_start(spx, &rval) != 0) {
4125 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4126 				return (rval);
4127 			} else {
4128 				if (scmd->satacmd_error_reg != 0) {
4129 					goto err_out;
4130 				}
4131 			}
4132 			break;
4133 		case SATA_PWRMODE_IDLE:
4134 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4135 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4136 			    sdinfo->satadrv_standby_timer);
4137 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4138 			if (sata_hba_start(spx, &rval) != 0) {
4139 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4140 				return (rval);
4141 			} else {
4142 				if (scmd->satacmd_error_reg != 0) {
4143 					goto err_out;
4144 				}
4145 			}
4146 			break;
4147 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4148 		case SATA_PWRMODE_ACTIVE_SPINUP:
4149 		case SATA_PWRMODE_ACTIVE:
4150 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4151 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4152 			    sdinfo->satadrv_standby_timer);
4153 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4154 			if (sata_hba_start(spx, &rval) != 0) {
4155 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4156 				return (rval);
4157 			} else {
4158 				if (scmd->satacmd_error_reg != 0) {
4159 					goto err_out;
4160 				}
4161 			}
4162 			sata_build_read_verify_cmd(scmd, 1, 5);
4163 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4164 			if (sata_hba_start(spx, &rval) != 0) {
4165 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4166 				return (rval);
4167 			} else {
4168 				if (scmd->satacmd_error_reg != 0) {
4169 					goto err_out;
4170 				}
4171 			}
4172 			break;
4173 		default:
4174 			goto err_out;
4175 		}
4176 		break;
4177 	case 0xb:
4178 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4179 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4180 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4181 			return (sata_txlt_check_condition(spx,
4182 			    KEY_ILLEGAL_REQUEST,
4183 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4184 		}
4185 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4186 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4187 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4188 			if (sata_hba_start(spx, &rval) != 0) {
4189 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4190 				return (rval);
4191 			} else {
4192 				if (scmd->satacmd_error_reg != 0) {
4193 					goto err_out;
4194 				}
4195 			}
4196 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4197 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4198 			if (sata_hba_start(spx, &rval) != 0) {
4199 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4200 				return (rval);
4201 			} else {
4202 				if (scmd->satacmd_error_reg != 0) {
4203 					goto err_out;
4204 				}
4205 			}
4206 		}
4207 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4208 		break;
4209 	default:
4210 err_out:
4211 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4212 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4213 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4214 	}
4215 
4216 	/*
4217 	 * Since it was a synchronous command,
4218 	 * a callback function will be called directly.
4219 	 */
4220 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4221 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4222 	    "synchronous execution status %x\n",
4223 	    spx->txlt_sata_pkt->satapkt_reason);
4224 
4225 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0) {
4226 		sata_set_arq_data(spx->txlt_sata_pkt);
4227 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4228 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
4229 		    TQ_SLEEP) == 0) {
4230 			return (TRAN_BUSY);
4231 		}
4232 	}
4233 	else
4234 
4235 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4236 
4237 	return (TRAN_ACCEPT);
4238 
4239 }
4240 
4241 /*
4242  * SATA translate command:  Read Capacity.
4243  * Emulated command for SATA disks.
4244  * Capacity is retrieved from cached Idenifty Device data.
4245  * Identify Device data shows effective disk capacity, not the native
4246  * capacity, which may be limitted by Set Max Address command.
4247  * This is ATA version for SATA hard disks.
4248  *
4249  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4250  */
4251 static int
4252 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4253 {
4254 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4255 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4256 	sata_drive_info_t *sdinfo;
4257 	uint64_t val;
4258 	uchar_t *rbuf;
4259 	int rval, reason;
4260 
4261 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4262 	    "sata_txlt_read_capacity: ", NULL);
4263 
4264 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4265 
4266 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4267 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4268 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4269 		return (rval);
4270 	}
4271 
4272 	scsipkt->pkt_reason = CMD_CMPLT;
4273 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4274 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4275 	*scsipkt->pkt_scbp = STATUS_GOOD;
4276 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4277 		/*
4278 		 * Because it is fully emulated command storing data
4279 		 * programatically in the specified buffer, release
4280 		 * preallocated DMA resources before storing data in the buffer,
4281 		 * so no unwanted DMA sync would take place.
4282 		 */
4283 		sata_scsi_dmafree(NULL, scsipkt);
4284 
4285 		sdinfo = sata_get_device_info(
4286 		    spx->txlt_sata_hba_inst,
4287 		    &spx->txlt_sata_pkt->satapkt_device);
4288 		/* Last logical block address */
4289 		val = sdinfo->satadrv_capacity - 1;
4290 		rbuf = (uchar_t *)bp->b_un.b_addr;
4291 		/* Need to swap endians to match scsi format */
4292 		rbuf[0] = (val >> 24) & 0xff;
4293 		rbuf[1] = (val >> 16) & 0xff;
4294 		rbuf[2] = (val >> 8) & 0xff;
4295 		rbuf[3] = val & 0xff;
4296 		/* block size - always 512 bytes, for now */
4297 		rbuf[4] = 0;
4298 		rbuf[5] = 0;
4299 		rbuf[6] = 0x02;
4300 		rbuf[7] = 0;
4301 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4302 		scsipkt->pkt_resid = 0;
4303 
4304 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4305 		    sdinfo->satadrv_capacity -1);
4306 	}
4307 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4308 	/*
4309 	 * If a callback was requested, do it now.
4310 	 */
4311 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4312 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4313 
4314 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4315 	    scsipkt->pkt_comp != NULL)
4316 		/* scsi callback required */
4317 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4318 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4319 		    TQ_SLEEP) == NULL)
4320 			/* Scheduling the callback failed */
4321 			return (TRAN_BUSY);
4322 
4323 	return (TRAN_ACCEPT);
4324 }
4325 
4326 /*
4327  * SATA translate command: Mode Sense.
4328  * Translated into appropriate SATA command or emulated.
4329  * Saved Values Page Control (03) are not supported.
4330  *
4331  * NOTE: only caching mode sense page is currently implemented.
4332  *
4333  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4334  */
4335 
4336 #define	LLBAA	0x10	/* Long LBA Accepted */
4337 
4338 static int
4339 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4340 {
4341 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4342 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4343 	sata_drive_info_t *sdinfo;
4344 	sata_id_t *sata_id;
4345 	struct scsi_extended_sense *sense;
4346 	int 		len, bdlen, count, alc_len;
4347 	int		pc;	/* Page Control code */
4348 	uint8_t		*buf;	/* mode sense buffer */
4349 	int		rval, reason;
4350 
4351 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4352 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4353 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4354 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4355 
4356 	buf = kmem_zalloc(1024, KM_SLEEP);
4357 
4358 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4359 
4360 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4361 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4362 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4363 		kmem_free(buf, 1024);
4364 		return (rval);
4365 	}
4366 
4367 	scsipkt->pkt_reason = CMD_CMPLT;
4368 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4369 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4370 
4371 	pc = scsipkt->pkt_cdbp[2] >> 6;
4372 
4373 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4374 		/*
4375 		 * Because it is fully emulated command storing data
4376 		 * programatically in the specified buffer, release
4377 		 * preallocated DMA resources before storing data in the buffer,
4378 		 * so no unwanted DMA sync would take place.
4379 		 */
4380 		sata_scsi_dmafree(NULL, scsipkt);
4381 
4382 		len = 0;
4383 		bdlen = 0;
4384 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4385 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4386 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4387 				bdlen = 16;
4388 			else
4389 				bdlen = 8;
4390 		}
4391 		/* Build mode parameter header */
4392 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4393 			/* 4-byte mode parameter header */
4394 			buf[len++] = 0;		/* mode data length */
4395 			buf[len++] = 0;		/* medium type */
4396 			buf[len++] = 0;		/* dev-specific param */
4397 			buf[len++] = bdlen;	/* Block Descriptor length */
4398 		} else {
4399 			/* 8-byte mode parameter header */
4400 			buf[len++] = 0;		/* mode data length */
4401 			buf[len++] = 0;
4402 			buf[len++] = 0;		/* medium type */
4403 			buf[len++] = 0;		/* dev-specific param */
4404 			if (bdlen == 16)
4405 				buf[len++] = 1;	/* long lba descriptor */
4406 			else
4407 				buf[len++] = 0;
4408 			buf[len++] = 0;
4409 			buf[len++] = 0;		/* Block Descriptor length */
4410 			buf[len++] = bdlen;
4411 		}
4412 
4413 		sdinfo = sata_get_device_info(
4414 		    spx->txlt_sata_hba_inst,
4415 		    &spx->txlt_sata_pkt->satapkt_device);
4416 
4417 		/* Build block descriptor only if not disabled (DBD) */
4418 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4419 			/* Block descriptor - direct-access device format */
4420 			if (bdlen == 8) {
4421 				/* build regular block descriptor */
4422 				buf[len++] =
4423 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4424 				buf[len++] =
4425 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4426 				buf[len++] =
4427 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4428 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4429 				buf[len++] = 0; /* density code */
4430 				buf[len++] = 0;
4431 				if (sdinfo->satadrv_type ==
4432 				    SATA_DTYPE_ATADISK)
4433 					buf[len++] = 2;
4434 				else
4435 					/* ATAPI */
4436 					buf[len++] = 8;
4437 				buf[len++] = 0;
4438 			} else if (bdlen == 16) {
4439 				/* Long LBA Accepted */
4440 				/* build long lba block descriptor */
4441 #ifndef __lock_lint
4442 				buf[len++] =
4443 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4444 				buf[len++] =
4445 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4446 				buf[len++] =
4447 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4448 				buf[len++] =
4449 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4450 #endif
4451 				buf[len++] =
4452 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4453 				buf[len++] =
4454 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4455 				buf[len++] =
4456 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4457 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4458 				buf[len++] = 0;
4459 				buf[len++] = 0; /* density code */
4460 				buf[len++] = 0;
4461 				buf[len++] = 0;
4462 				if (sdinfo->satadrv_type ==
4463 				    SATA_DTYPE_ATADISK)
4464 					buf[len++] = 2;
4465 				else
4466 					/* ATAPI */
4467 					buf[len++] = 8;
4468 				buf[len++] = 0;
4469 			}
4470 		}
4471 
4472 		sata_id = &sdinfo->satadrv_id;
4473 
4474 		/*
4475 		 * Add requested pages.
4476 		 * Page 3 and 4 are obsolete and we are not supporting them.
4477 		 * We deal now with:
4478 		 * caching (read/write cache control).
4479 		 * We should eventually deal with following mode pages:
4480 		 * error recovery  (0x01),
4481 		 * power condition (0x1a),
4482 		 * exception control page (enables SMART) (0x1c),
4483 		 * enclosure management (ses),
4484 		 * protocol-specific port mode (port control).
4485 		 */
4486 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4487 		case MODEPAGE_RW_ERRRECOV:
4488 			/* DAD_MODE_ERR_RECOV */
4489 			/* R/W recovery */
4490 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4491 			break;
4492 		case MODEPAGE_CACHING:
4493 			/* DAD_MODE_CACHE */
4494 			/* Reject not supported request for saved parameters */
4495 			if (pc == 3) {
4496 				*scsipkt->pkt_scbp = STATUS_CHECK;
4497 				sense = sata_arq_sense(spx);
4498 				sense->es_key = KEY_ILLEGAL_REQUEST;
4499 				sense->es_add_code =
4500 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4501 				goto done;
4502 			}
4503 
4504 			/* caching */
4505 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4506 			break;
4507 		case MODEPAGE_INFO_EXCPT:
4508 			/* exception cntrl */
4509 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4510 				len += sata_build_msense_page_1c(sdinfo, pc,
4511 				    buf+len);
4512 			}
4513 			else
4514 				goto err;
4515 			break;
4516 		case MODEPAGE_POWER_COND:
4517 			/* DAD_MODE_POWER_COND */
4518 			/* power condition */
4519 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4520 			break;
4521 
4522 		case MODEPAGE_ACOUSTIC_MANAG:
4523 			/* acoustic management */
4524 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4525 			break;
4526 		case MODEPAGE_ALLPAGES:
4527 			/* all pages */
4528 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4529 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4530 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4531 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4532 				len += sata_build_msense_page_1c(sdinfo, pc,
4533 				    buf+len);
4534 			}
4535 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4536 			break;
4537 		default:
4538 		err:
4539 			/* Invalid request */
4540 			*scsipkt->pkt_scbp = STATUS_CHECK;
4541 			sense = sata_arq_sense(spx);
4542 			sense->es_key = KEY_ILLEGAL_REQUEST;
4543 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4544 			goto done;
4545 		}
4546 
4547 		/* fix total mode data length */
4548 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4549 			/* 4-byte mode parameter header */
4550 			buf[0] = len - 1;	/* mode data length */
4551 		} else {
4552 			buf[0] = (len -2) >> 8;
4553 			buf[1] = (len -2) & 0xff;
4554 		}
4555 
4556 
4557 		/* Check allocation length */
4558 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4559 			alc_len = scsipkt->pkt_cdbp[4];
4560 		} else {
4561 			alc_len = scsipkt->pkt_cdbp[7];
4562 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4563 		}
4564 		/*
4565 		 * We do not check for possible parameters truncation
4566 		 * (alc_len < len) assuming that the target driver works
4567 		 * correctly. Just avoiding overrun.
4568 		 * Copy no more than requested and possible, buffer-wise.
4569 		 */
4570 		count = MIN(alc_len, len);
4571 		count = MIN(bp->b_bcount, count);
4572 		bcopy(buf, bp->b_un.b_addr, count);
4573 
4574 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4575 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4576 	}
4577 	*scsipkt->pkt_scbp = STATUS_GOOD;
4578 done:
4579 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4580 	(void) kmem_free(buf, 1024);
4581 
4582 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4583 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4584 
4585 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4586 	    scsipkt->pkt_comp != NULL)
4587 		/* scsi callback required */
4588 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4589 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4590 		    TQ_SLEEP) == NULL)
4591 			/* Scheduling the callback failed */
4592 			return (TRAN_BUSY);
4593 
4594 	return (TRAN_ACCEPT);
4595 }
4596 
4597 
4598 /*
4599  * SATA translate command: Mode Select.
4600  * Translated into appropriate SATA command or emulated.
4601  * Saving parameters is not supported.
4602  * Changing device capacity is not supported (although theoretically
4603  * possible by executing SET FEATURES/SET MAX ADDRESS)
4604  *
4605  * Assumption is that the target driver is working correctly.
4606  *
4607  * More than one SATA command may be executed to perform operations specified
4608  * by mode select pages. The first error terminates further execution.
4609  * Operations performed successully are not backed-up in such case.
4610  *
4611  * NOTE: Implemented pages:
4612  * - caching page
4613  * - informational exception page
4614  * - acoustic management page
4615  * - power condition page
4616  * Caching setup is remembered so it could be re-stored in case of
4617  * an unexpected device reset.
4618  *
4619  * Returns TRAN_XXXX.
4620  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4621  */
4622 
4623 static int
4624 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4625 {
4626 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4627 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4628 	struct scsi_extended_sense *sense;
4629 	int len, pagelen, count, pllen;
4630 	uint8_t *buf;	/* mode select buffer */
4631 	int rval, stat, reason;
4632 	uint_t nointr_flag;
4633 	int dmod = 0;
4634 
4635 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4636 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4637 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4638 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4639 
4640 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4641 
4642 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4643 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4644 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4645 		return (rval);
4646 	}
4647 	/*
4648 	 * If in interrupt context, reject this packet because it may result
4649 	 * in issuing a synchronous command to HBA.
4650 	 */
4651 	if (servicing_interrupt()) {
4652 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4653 		    "sata_txlt_mode_select: rejecting command because "
4654 		    "of interrupt context\n", NULL);
4655 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4656 		return (TRAN_BUSY);
4657 	}
4658 
4659 	rval = TRAN_ACCEPT;
4660 
4661 	scsipkt->pkt_reason = CMD_CMPLT;
4662 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4663 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4664 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4665 
4666 	/* Reject not supported request */
4667 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4668 		*scsipkt->pkt_scbp = STATUS_CHECK;
4669 		sense = sata_arq_sense(spx);
4670 		sense->es_key = KEY_ILLEGAL_REQUEST;
4671 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4672 		goto done;
4673 	}
4674 
4675 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4676 		pllen = scsipkt->pkt_cdbp[4];
4677 	} else {
4678 		pllen = scsipkt->pkt_cdbp[7];
4679 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4680 	}
4681 
4682 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4683 
4684 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4685 		buf = (uint8_t *)bp->b_un.b_addr;
4686 		count = MIN(bp->b_bcount, pllen);
4687 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4688 		scsipkt->pkt_resid = 0;
4689 		pllen = count;
4690 
4691 		/*
4692 		 * Check the header to skip the block descriptor(s) - we
4693 		 * do not support setting device capacity.
4694 		 * Existing macros do not recognize long LBA dscriptor,
4695 		 * hence manual calculation.
4696 		 */
4697 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4698 			/* 6-bytes CMD, 4 bytes header */
4699 			if (count <= 4)
4700 				goto done;		/* header only */
4701 			len = buf[3] + 4;
4702 		} else {
4703 			/* 10-bytes CMD, 8 bytes header */
4704 			if (count <= 8)
4705 				goto done;		/* header only */
4706 			len = buf[6];
4707 			len = (len << 8) + buf[7] + 8;
4708 		}
4709 		if (len >= count)
4710 			goto done;	/* header + descriptor(s) only */
4711 
4712 		pllen -= len;		/* remaining data length */
4713 
4714 		/*
4715 		 * We may be executing SATA command and want to execute it
4716 		 * in SYNCH mode, regardless of scsi_pkt setting.
4717 		 * Save scsi_pkt setting and indicate SYNCH mode
4718 		 */
4719 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4720 		    scsipkt->pkt_comp != NULL) {
4721 			scsipkt->pkt_flags |= FLAG_NOINTR;
4722 		}
4723 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4724 
4725 		/*
4726 		 * len is now the offset to a first mode select page
4727 		 * Process all pages
4728 		 */
4729 		while (pllen > 0) {
4730 			switch ((int)buf[len]) {
4731 			case MODEPAGE_CACHING:
4732 				/* No support for SP (saving) */
4733 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4734 					*scsipkt->pkt_scbp = STATUS_CHECK;
4735 					sense = sata_arq_sense(spx);
4736 					sense->es_key = KEY_ILLEGAL_REQUEST;
4737 					sense->es_add_code =
4738 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4739 					goto done;
4740 				}
4741 				stat = sata_mode_select_page_8(spx,
4742 				    (struct mode_cache_scsi3 *)&buf[len],
4743 				    pllen, &pagelen, &rval, &dmod);
4744 				/*
4745 				 * The pagelen value indicates the number of
4746 				 * parameter bytes already processed.
4747 				 * The rval is the return value from
4748 				 * sata_tran_start().
4749 				 * The stat indicates the overall status of
4750 				 * the operation(s).
4751 				 */
4752 				if (stat != SATA_SUCCESS)
4753 					/*
4754 					 * Page processing did not succeed -
4755 					 * all error info is already set-up,
4756 					 * just return
4757 					 */
4758 					pllen = 0; /* this breaks the loop */
4759 				else {
4760 					len += pagelen;
4761 					pllen -= pagelen;
4762 				}
4763 				break;
4764 
4765 			case MODEPAGE_INFO_EXCPT:
4766 				stat = sata_mode_select_page_1c(spx,
4767 				    (struct mode_info_excpt_page *)&buf[len],
4768 				    pllen, &pagelen, &rval, &dmod);
4769 				/*
4770 				 * The pagelen value indicates the number of
4771 				 * parameter bytes already processed.
4772 				 * The rval is the return value from
4773 				 * sata_tran_start().
4774 				 * The stat indicates the overall status of
4775 				 * the operation(s).
4776 				 */
4777 				if (stat != SATA_SUCCESS)
4778 					/*
4779 					 * Page processing did not succeed -
4780 					 * all error info is already set-up,
4781 					 * just return
4782 					 */
4783 					pllen = 0; /* this breaks the loop */
4784 				else {
4785 					len += pagelen;
4786 					pllen -= pagelen;
4787 				}
4788 				break;
4789 
4790 			case MODEPAGE_ACOUSTIC_MANAG:
4791 				stat = sata_mode_select_page_30(spx,
4792 				    (struct mode_acoustic_management *)
4793 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4794 				/*
4795 				 * The pagelen value indicates the number of
4796 				 * parameter bytes already processed.
4797 				 * The rval is the return value from
4798 				 * sata_tran_start().
4799 				 * The stat indicates the overall status of
4800 				 * the operation(s).
4801 				 */
4802 				if (stat != SATA_SUCCESS)
4803 					/*
4804 					 * Page processing did not succeed -
4805 					 * all error info is already set-up,
4806 					 * just return
4807 					 */
4808 					pllen = 0; /* this breaks the loop */
4809 				else {
4810 					len += pagelen;
4811 					pllen -= pagelen;
4812 				}
4813 
4814 				break;
4815 			case MODEPAGE_POWER_COND:
4816 				stat = sata_mode_select_page_1a(spx,
4817 				    (struct mode_info_power_cond *)&buf[len],
4818 				    pllen, &pagelen, &rval, &dmod);
4819 				/*
4820 				 * The pagelen value indicates the number of
4821 				 * parameter bytes already processed.
4822 				 * The rval is the return value from
4823 				 * sata_tran_start().
4824 				 * The stat indicates the overall status of
4825 				 * the operation(s).
4826 				 */
4827 				if (stat != SATA_SUCCESS)
4828 					/*
4829 					 * Page processing did not succeed -
4830 					 * all error info is already set-up,
4831 					 * just return
4832 					 */
4833 					pllen = 0; /* this breaks the loop */
4834 				else {
4835 					len += pagelen;
4836 					pllen -= pagelen;
4837 				}
4838 				break;
4839 			default:
4840 				*scsipkt->pkt_scbp = STATUS_CHECK;
4841 				sense = sata_arq_sense(spx);
4842 				sense->es_key = KEY_ILLEGAL_REQUEST;
4843 				sense->es_add_code =
4844 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4845 				goto done;
4846 			}
4847 		}
4848 	}
4849 done:
4850 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4851 	/*
4852 	 * If device parameters were modified, fetch and store the new
4853 	 * Identify Device data. Since port mutex could have been released
4854 	 * for accessing HBA driver, we need to re-check device existence.
4855 	 */
4856 	if (dmod != 0) {
4857 		sata_drive_info_t new_sdinfo, *sdinfo;
4858 		int rv = 0;
4859 
4860 		/*
4861 		 * Following statement has to be changed if this function is
4862 		 * used for devices other than SATA hard disks.
4863 		 */
4864 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4865 
4866 		new_sdinfo.satadrv_addr =
4867 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4868 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4869 		    &new_sdinfo);
4870 
4871 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4872 		/*
4873 		 * Since port mutex could have been released when
4874 		 * accessing HBA driver, we need to re-check that the
4875 		 * framework still holds the device info structure.
4876 		 */
4877 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4878 		    &spx->txlt_sata_pkt->satapkt_device);
4879 		if (sdinfo != NULL) {
4880 			/*
4881 			 * Device still has info structure in the
4882 			 * sata framework. Copy newly fetched info
4883 			 */
4884 			if (rv == 0) {
4885 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4886 				sata_save_drive_settings(sdinfo);
4887 			} else {
4888 				/*
4889 				 * Could not fetch new data - invalidate
4890 				 * sata_drive_info. That makes device
4891 				 * unusable.
4892 				 */
4893 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4894 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4895 			}
4896 		}
4897 		if (rv != 0 || sdinfo == NULL) {
4898 			/*
4899 			 * This changes the overall mode select completion
4900 			 * reason to a failed one !!!!!
4901 			 */
4902 			*scsipkt->pkt_scbp = STATUS_CHECK;
4903 			sense = sata_arq_sense(spx);
4904 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4905 			rval = TRAN_ACCEPT;
4906 		}
4907 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4908 	}
4909 	/* Restore the scsi pkt flags */
4910 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4911 	scsipkt->pkt_flags |= nointr_flag;
4912 
4913 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4914 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4915 
4916 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4917 	    scsipkt->pkt_comp != NULL)
4918 		/* scsi callback required */
4919 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4920 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4921 		    TQ_SLEEP) == NULL)
4922 			/* Scheduling the callback failed */
4923 			return (TRAN_BUSY);
4924 
4925 	return (rval);
4926 }
4927 
4928 /*
4929  * Translate command: ATA Pass Through
4930  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
4931  * PIO Data-Out protocols.  Also supports CK_COND bit.
4932  *
4933  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
4934  * described in Table 111 of SAT-2 (Draft 9).
4935  */
4936 static  int
4937 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
4938 {
4939 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4940 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4941 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4942 	int extend;
4943 	uint64_t lba;
4944 	uint16_t feature, sec_count;
4945 	int t_len, synch;
4946 	int rval, reason;
4947 
4948 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4949 
4950 	rval = sata_txlt_generic_pkt_info(spx, &reason);
4951 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4952 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4953 		return (rval);
4954 	}
4955 
4956 	/* T_DIR bit */
4957 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
4958 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4959 	else
4960 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4961 
4962 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
4963 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
4964 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4965 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4966 	}
4967 
4968 	/* OFFLINE field. If non-zero, invalid command (for now). */
4969 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
4970 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4971 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4972 	}
4973 
4974 	/* PROTOCOL field */
4975 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
4976 	case SATL_APT_P_HW_RESET:
4977 	case SATL_APT_P_SRST:
4978 	case SATL_APT_P_DMA:
4979 	case SATL_APT_P_DMA_QUEUED:
4980 	case SATL_APT_P_DEV_DIAG:
4981 	case SATL_APT_P_DEV_RESET:
4982 	case SATL_APT_P_UDMA_IN:
4983 	case SATL_APT_P_UDMA_OUT:
4984 	case SATL_APT_P_FPDMA:
4985 	case SATL_APT_P_RET_RESP:
4986 		/* Not yet implemented */
4987 	default:
4988 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4989 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4990 
4991 	case SATL_APT_P_NON_DATA:
4992 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
4993 		break;
4994 
4995 	case SATL_APT_P_PIO_DATA_IN:
4996 		/* If PROTOCOL disagrees with T_DIR, invalid command */
4997 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
4998 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4999 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5000 		}
5001 
5002 		/* if there is a buffer, release its DMA resources */
5003 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5004 			sata_scsi_dmafree(NULL, scsipkt);
5005 		} else {
5006 			/* if there is no buffer, how do you PIO in? */
5007 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5008 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5009 		}
5010 
5011 		break;
5012 
5013 	case SATL_APT_P_PIO_DATA_OUT:
5014 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5015 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5016 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5017 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5018 		}
5019 
5020 		/* if there is a buffer, release its DMA resources */
5021 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5022 			sata_scsi_dmafree(NULL, scsipkt);
5023 		} else {
5024 			/* if there is no buffer, how do you PIO out? */
5025 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5026 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5027 		}
5028 
5029 		break;
5030 	}
5031 
5032 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5033 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5034 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5035 		feature = scsipkt->pkt_cdbp[3];
5036 
5037 		sec_count = scsipkt->pkt_cdbp[4];
5038 
5039 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5040 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5041 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5042 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5043 
5044 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5045 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5046 
5047 		break;
5048 
5049 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5050 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5051 			extend = 1;
5052 
5053 			feature = scsipkt->pkt_cdbp[3];
5054 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5055 
5056 			sec_count = scsipkt->pkt_cdbp[5];
5057 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5058 
5059 			lba = scsipkt->pkt_cdbp[11];
5060 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5061 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5062 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5063 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5064 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5065 
5066 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5067 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5068 		} else {
5069 			feature = scsipkt->pkt_cdbp[3];
5070 
5071 			sec_count = scsipkt->pkt_cdbp[5];
5072 
5073 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5074 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5075 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5076 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5077 
5078 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5079 			    0xf0;
5080 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5081 		}
5082 
5083 		break;
5084 	}
5085 
5086 	/* CK_COND bit */
5087 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5088 		if (extend) {
5089 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5090 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5091 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5092 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5093 		}
5094 
5095 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5096 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5097 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5098 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5099 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5100 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5101 	}
5102 
5103 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5104 	if (extend) {
5105 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5106 
5107 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5108 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5109 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5110 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5111 		scmd->satacmd_lba_high_msb = lba >> 40;
5112 	} else {
5113 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5114 
5115 		scmd->satacmd_features_reg_ext = 0;
5116 		scmd->satacmd_sec_count_msb = 0;
5117 		scmd->satacmd_lba_low_msb = 0;
5118 		scmd->satacmd_lba_mid_msb = 0;
5119 		scmd->satacmd_lba_high_msb = 0;
5120 	}
5121 
5122 	scmd->satacmd_features_reg = feature & 0xff;
5123 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5124 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5125 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5126 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5127 
5128 	/* Determine transfer length */
5129 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5130 	case 1:
5131 		t_len = feature;
5132 		break;
5133 	case 2:
5134 		t_len = sec_count;
5135 		break;
5136 	default:
5137 		t_len = 0;
5138 		break;
5139 	}
5140 
5141 	/* Adjust transfer length for the Byte Block bit */
5142 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5143 		t_len *= SATA_DISK_SECTOR_SIZE;
5144 
5145 	/* Start processing command */
5146 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5147 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5148 		synch = FALSE;
5149 	} else {
5150 		synch = TRUE;
5151 	}
5152 
5153 	if (sata_hba_start(spx, &rval) != 0) {
5154 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5155 		return (rval);
5156 	}
5157 
5158 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5159 
5160 	if (synch) {
5161 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5162 	}
5163 
5164 	return (TRAN_ACCEPT);
5165 }
5166 
5167 /*
5168  * Translate command: Log Sense
5169  */
5170 static 	int
5171 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5172 {
5173 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5174 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5175 	sata_drive_info_t *sdinfo;
5176 	struct scsi_extended_sense *sense;
5177 	int 		len, count, alc_len;
5178 	int		pc;	/* Page Control code */
5179 	int		page_code;	/* Page code */
5180 	uint8_t		*buf;	/* log sense buffer */
5181 	int		rval, reason;
5182 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5183 
5184 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5185 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5186 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5187 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5188 
5189 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5190 
5191 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5192 
5193 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5194 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5195 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5196 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5197 		return (rval);
5198 	}
5199 	/*
5200 	 * If in interrupt context, reject this packet because it may result
5201 	 * in issuing a synchronous command to HBA.
5202 	 */
5203 	if (servicing_interrupt()) {
5204 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
5205 		    "sata_log_sense: rejecting command because "
5206 		    "of interrupt context\n", NULL);
5207 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5208 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5209 		return (TRAN_BUSY);
5210 	}
5211 
5212 	scsipkt->pkt_reason = CMD_CMPLT;
5213 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5214 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5215 
5216 	pc = scsipkt->pkt_cdbp[2] >> 6;
5217 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5218 
5219 	/* Reject not supported request for all but cumulative values */
5220 	switch (pc) {
5221 	case PC_CUMULATIVE_VALUES:
5222 		break;
5223 	default:
5224 		*scsipkt->pkt_scbp = STATUS_CHECK;
5225 		sense = sata_arq_sense(spx);
5226 		sense->es_key = KEY_ILLEGAL_REQUEST;
5227 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5228 		goto done;
5229 	}
5230 
5231 	switch (page_code) {
5232 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5233 	case PAGE_CODE_SELF_TEST_RESULTS:
5234 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5235 	case PAGE_CODE_SMART_READ_DATA:
5236 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5237 		break;
5238 	default:
5239 		*scsipkt->pkt_scbp = STATUS_CHECK;
5240 		sense = sata_arq_sense(spx);
5241 		sense->es_key = KEY_ILLEGAL_REQUEST;
5242 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5243 		goto done;
5244 	}
5245 
5246 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5247 		/*
5248 		 * Because log sense uses local buffers for data retrieval from
5249 		 * the devices and sets the data programatically in the
5250 		 * original specified buffer, release preallocated DMA
5251 		 * resources before storing data in the original buffer,
5252 		 * so no unwanted DMA sync would take place.
5253 		 */
5254 		sata_id_t *sata_id;
5255 
5256 		sata_scsi_dmafree(NULL, scsipkt);
5257 
5258 		len = 0;
5259 
5260 		/* Build log parameter header */
5261 		buf[len++] = page_code;	/* page code as in the CDB */
5262 		buf[len++] = 0;		/* reserved */
5263 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5264 		buf[len++] = 0;		/* (LSB) */
5265 
5266 		sdinfo = sata_get_device_info(
5267 		    spx->txlt_sata_hba_inst,
5268 		    &spx->txlt_sata_pkt->satapkt_device);
5269 
5270 		/*
5271 		 * Add requested pages.
5272 		 */
5273 		switch (page_code) {
5274 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5275 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5276 			break;
5277 		case PAGE_CODE_SELF_TEST_RESULTS:
5278 			sata_id = &sdinfo->satadrv_id;
5279 			if ((! (sata_id->ai_cmdset84 &
5280 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5281 			    (! (sata_id->ai_features87 &
5282 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5283 				*scsipkt->pkt_scbp = STATUS_CHECK;
5284 				sense = sata_arq_sense(spx);
5285 				sense->es_key = KEY_ILLEGAL_REQUEST;
5286 				sense->es_add_code =
5287 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5288 
5289 				goto done;
5290 			}
5291 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5292 			    spx->txlt_sata_hba_inst);
5293 			break;
5294 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5295 			sata_id = &sdinfo->satadrv_id;
5296 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5297 				*scsipkt->pkt_scbp = STATUS_CHECK;
5298 				sense = sata_arq_sense(spx);
5299 				sense->es_key = KEY_ILLEGAL_REQUEST;
5300 				sense->es_add_code =
5301 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5302 
5303 				goto done;
5304 			}
5305 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5306 				*scsipkt->pkt_scbp = STATUS_CHECK;
5307 				sense = sata_arq_sense(spx);
5308 				sense->es_key = KEY_ABORTED_COMMAND;
5309 				sense->es_add_code =
5310 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5311 				sense->es_qual_code =
5312 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5313 
5314 				goto done;
5315 			}
5316 
5317 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5318 			    spx->txlt_sata_hba_inst);
5319 			break;
5320 		case PAGE_CODE_SMART_READ_DATA:
5321 			sata_id = &sdinfo->satadrv_id;
5322 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5323 				*scsipkt->pkt_scbp = STATUS_CHECK;
5324 				sense = sata_arq_sense(spx);
5325 				sense->es_key = KEY_ILLEGAL_REQUEST;
5326 				sense->es_add_code =
5327 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5328 
5329 				goto done;
5330 			}
5331 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5332 				*scsipkt->pkt_scbp = STATUS_CHECK;
5333 				sense = sata_arq_sense(spx);
5334 				sense->es_key = KEY_ABORTED_COMMAND;
5335 				sense->es_add_code =
5336 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5337 				sense->es_qual_code =
5338 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5339 
5340 				goto done;
5341 			}
5342 
5343 			/* This page doesn't include a page header */
5344 			len = sata_build_lsense_page_30(sdinfo, buf,
5345 			    spx->txlt_sata_hba_inst);
5346 			goto no_header;
5347 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5348 			sata_id = &sdinfo->satadrv_id;
5349 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5350 				*scsipkt->pkt_scbp = STATUS_CHECK;
5351 				sense = sata_arq_sense(spx);
5352 				sense->es_key = KEY_ILLEGAL_REQUEST;
5353 				sense->es_add_code =
5354 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5355 
5356 				goto done;
5357 			}
5358 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5359 				*scsipkt->pkt_scbp = STATUS_CHECK;
5360 				sense = sata_arq_sense(spx);
5361 				sense->es_key = KEY_ABORTED_COMMAND;
5362 				sense->es_add_code =
5363 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5364 				sense->es_qual_code =
5365 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5366 
5367 				goto done;
5368 			}
5369 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5370 			goto no_header;
5371 		default:
5372 			/* Invalid request */
5373 			*scsipkt->pkt_scbp = STATUS_CHECK;
5374 			sense = sata_arq_sense(spx);
5375 			sense->es_key = KEY_ILLEGAL_REQUEST;
5376 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5377 			goto done;
5378 		}
5379 
5380 		/* set parameter log sense data length */
5381 		buf[2] = len >> 8;	/* log sense length (MSB) */
5382 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5383 
5384 		len += SCSI_LOG_PAGE_HDR_LEN;
5385 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5386 
5387 no_header:
5388 		/* Check allocation length */
5389 		alc_len = scsipkt->pkt_cdbp[7];
5390 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5391 
5392 		/*
5393 		 * We do not check for possible parameters truncation
5394 		 * (alc_len < len) assuming that the target driver works
5395 		 * correctly. Just avoiding overrun.
5396 		 * Copy no more than requested and possible, buffer-wise.
5397 		 */
5398 		count = MIN(alc_len, len);
5399 		count = MIN(bp->b_bcount, count);
5400 		bcopy(buf, bp->b_un.b_addr, count);
5401 
5402 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5403 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5404 	}
5405 	*scsipkt->pkt_scbp = STATUS_GOOD;
5406 done:
5407 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5408 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5409 
5410 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5411 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5412 
5413 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5414 	    scsipkt->pkt_comp != NULL)
5415 		/* scsi callback required */
5416 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5417 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5418 		    TQ_SLEEP) == NULL)
5419 			/* Scheduling the callback failed */
5420 			return (TRAN_BUSY);
5421 
5422 	return (TRAN_ACCEPT);
5423 }
5424 
5425 /*
5426  * Translate command: Log Select
5427  * Not implemented at this time - returns invalid command response.
5428  */
5429 static	int
5430 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5431 {
5432 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5433 	    "sata_txlt_log_select\n", NULL);
5434 
5435 	return (sata_txlt_invalid_command(spx));
5436 }
5437 
5438 
5439 /*
5440  * Translate command: Read (various types).
5441  * Translated into appropriate type of ATA READ command
5442  * for SATA hard disks.
5443  * Both the device capabilities and requested operation mode are
5444  * considered.
5445  *
5446  * Following scsi cdb fields are ignored:
5447  * rdprotect, dpo, fua, fua_nv, group_number.
5448  *
5449  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5450  * enable variable sata_func_enable), the capability of the controller and
5451  * capability of a device are checked and if both support queueing, read
5452  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5453  * command rather than plain READ_XXX command.
5454  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5455  * both the controller and device suport such functionality, the read
5456  * request will be translated to READ_FPDMA_QUEUED command.
5457  * In both cases the maximum queue depth is derived as minimum of:
5458  * HBA capability,device capability and sata_max_queue_depth variable setting.
5459  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5460  * used to pass max queue depth value, and the maximum possible queue depth
5461  * is 32.
5462  *
5463  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5464  * appropriate values in scsi_pkt fields.
5465  */
5466 static int
5467 sata_txlt_read(sata_pkt_txlate_t *spx)
5468 {
5469 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5470 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5471 	sata_drive_info_t *sdinfo;
5472 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5473 	int cport = SATA_TXLT_CPORT(spx);
5474 	uint16_t sec_count;
5475 	uint64_t lba;
5476 	int rval, reason;
5477 	int synch;
5478 
5479 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5480 
5481 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5482 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5483 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5484 		return (rval);
5485 	}
5486 
5487 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5488 	    &spx->txlt_sata_pkt->satapkt_device);
5489 
5490 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5491 	/*
5492 	 * Extract LBA and sector count from scsi CDB.
5493 	 */
5494 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5495 	case SCMD_READ:
5496 		/* 6-byte scsi read cmd : 0x08 */
5497 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5498 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5499 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5500 		sec_count = scsipkt->pkt_cdbp[4];
5501 		/* sec_count 0 will be interpreted as 256 by a device */
5502 		break;
5503 	case SCMD_READ_G1:
5504 		/* 10-bytes scsi read command : 0x28 */
5505 		lba = scsipkt->pkt_cdbp[2];
5506 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5507 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5508 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5509 		sec_count = scsipkt->pkt_cdbp[7];
5510 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5511 		break;
5512 	case SCMD_READ_G5:
5513 		/* 12-bytes scsi read command : 0xA8 */
5514 		lba = scsipkt->pkt_cdbp[2];
5515 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5516 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5517 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5518 		sec_count = scsipkt->pkt_cdbp[6];
5519 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5520 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5521 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5522 		break;
5523 	case SCMD_READ_G4:
5524 		/* 16-bytes scsi read command : 0x88 */
5525 		lba = scsipkt->pkt_cdbp[2];
5526 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5527 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5528 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5529 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5530 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5531 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5532 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5533 		sec_count = scsipkt->pkt_cdbp[10];
5534 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5535 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5536 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5537 		break;
5538 	default:
5539 		/* Unsupported command */
5540 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5541 		return (sata_txlt_invalid_command(spx));
5542 	}
5543 
5544 	/*
5545 	 * Check if specified address exceeds device capacity
5546 	 */
5547 	if ((lba >= sdinfo->satadrv_capacity) ||
5548 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5549 		/* LBA out of range */
5550 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5551 		return (sata_txlt_lba_out_of_range(spx));
5552 	}
5553 
5554 	/*
5555 	 * For zero-length transfer, emulate good completion of the command
5556 	 * (reasons for rejecting the command were already checked).
5557 	 * No DMA resources were allocated.
5558 	 */
5559 	if (spx->txlt_dma_cookie_list == NULL) {
5560 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5561 		return (sata_emul_rw_completion(spx));
5562 	}
5563 
5564 	/*
5565 	 * Build cmd block depending on the device capability and
5566 	 * requested operation mode.
5567 	 * Do not bother with non-dma mode - we are working only with
5568 	 * devices supporting DMA.
5569 	 */
5570 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5571 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5572 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5573 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5574 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5575 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5576 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5577 #ifndef __lock_lint
5578 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5579 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5580 		scmd->satacmd_lba_high_msb = lba >> 40;
5581 #endif
5582 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5583 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5584 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5585 	}
5586 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5587 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5588 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5589 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5590 	scmd->satacmd_features_reg = 0;
5591 	scmd->satacmd_status_reg = 0;
5592 	scmd->satacmd_error_reg = 0;
5593 
5594 	/*
5595 	 * Check if queueing commands should be used and switch
5596 	 * to appropriate command if possible
5597 	 */
5598 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5599 		boolean_t using_queuing;
5600 
5601 		/* Queuing supported by controller and device? */
5602 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5603 		    (sdinfo->satadrv_features_support &
5604 		    SATA_DEV_F_NCQ) &&
5605 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5606 		    SATA_CTLF_NCQ)) {
5607 			using_queuing = B_TRUE;
5608 
5609 			/* NCQ supported - use FPDMA READ */
5610 			scmd->satacmd_cmd_reg =
5611 			    SATAC_READ_FPDMA_QUEUED;
5612 			scmd->satacmd_features_reg_ext =
5613 			    scmd->satacmd_sec_count_msb;
5614 			scmd->satacmd_sec_count_msb = 0;
5615 		} else if ((sdinfo->satadrv_features_support &
5616 		    SATA_DEV_F_TCQ) &&
5617 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5618 		    SATA_CTLF_QCMD)) {
5619 			using_queuing = B_TRUE;
5620 
5621 			/* Legacy queueing */
5622 			if (sdinfo->satadrv_features_support &
5623 			    SATA_DEV_F_LBA48) {
5624 				scmd->satacmd_cmd_reg =
5625 				    SATAC_READ_DMA_QUEUED_EXT;
5626 				scmd->satacmd_features_reg_ext =
5627 				    scmd->satacmd_sec_count_msb;
5628 				scmd->satacmd_sec_count_msb = 0;
5629 			} else {
5630 				scmd->satacmd_cmd_reg =
5631 				    SATAC_READ_DMA_QUEUED;
5632 			}
5633 		} else	/* NCQ nor legacy queuing not supported */
5634 			using_queuing = B_FALSE;
5635 
5636 		/*
5637 		 * If queuing, the sector count goes in the features register
5638 		 * and the secount count will contain the tag.
5639 		 */
5640 		if (using_queuing) {
5641 			scmd->satacmd_features_reg =
5642 			    scmd->satacmd_sec_count_lsb;
5643 			scmd->satacmd_sec_count_lsb = 0;
5644 			scmd->satacmd_flags.sata_queued = B_TRUE;
5645 
5646 			/* Set-up maximum queue depth */
5647 			scmd->satacmd_flags.sata_max_queue_depth =
5648 			    sdinfo->satadrv_max_queue_depth - 1;
5649 		} else if (sdinfo->satadrv_features_enabled &
5650 		    SATA_DEV_F_E_UNTAGGED_QING) {
5651 			/*
5652 			 * Although NCQ/TCQ is not enabled, untagged queuing
5653 			 * may be still used.
5654 			 * Set-up the maximum untagged queue depth.
5655 			 * Use controller's queue depth from sata_hba_tran.
5656 			 * SATA HBA drivers may ignore this value and rely on
5657 			 * the internal limits.For drivers that do not
5658 			 * ignore untaged queue depth, limit the value to
5659 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5660 			 * largest value that can be passed via
5661 			 * satacmd_flags.sata_max_queue_depth.
5662 			 */
5663 			scmd->satacmd_flags.sata_max_queue_depth =
5664 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5665 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5666 
5667 		} else {
5668 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5669 		}
5670 	} else
5671 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5672 
5673 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5674 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5675 	    scmd->satacmd_cmd_reg, lba, sec_count);
5676 
5677 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5678 		/* Need callback function */
5679 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5680 		synch = FALSE;
5681 	} else
5682 		synch = TRUE;
5683 
5684 	/* Transfer command to HBA */
5685 	if (sata_hba_start(spx, &rval) != 0) {
5686 		/* Pkt not accepted for execution */
5687 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5688 		return (rval);
5689 	}
5690 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5691 	/*
5692 	 * If execution is non-synchronous,
5693 	 * a callback function will handle potential errors, translate
5694 	 * the response and will do a callback to a target driver.
5695 	 * If it was synchronous, check execution status using the same
5696 	 * framework callback.
5697 	 */
5698 	if (synch) {
5699 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5700 		    "synchronous execution status %x\n",
5701 		    spx->txlt_sata_pkt->satapkt_reason);
5702 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5703 	}
5704 	return (TRAN_ACCEPT);
5705 }
5706 
5707 
5708 /*
5709  * SATA translate command: Write (various types)
5710  * Translated into appropriate type of ATA WRITE command
5711  * for SATA hard disks.
5712  * Both the device capabilities and requested operation mode are
5713  * considered.
5714  *
5715  * Following scsi cdb fields are ignored:
5716  * rwprotect, dpo, fua, fua_nv, group_number.
5717  *
5718  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5719  * enable variable sata_func_enable), the capability of the controller and
5720  * capability of a device are checked and if both support queueing, write
5721  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5722  * command rather than plain WRITE_XXX command.
5723  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5724  * both the controller and device suport such functionality, the write
5725  * request will be translated to WRITE_FPDMA_QUEUED command.
5726  * In both cases the maximum queue depth is derived as minimum of:
5727  * HBA capability,device capability and sata_max_queue_depth variable setting.
5728  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5729  * used to pass max queue depth value, and the maximum possible queue depth
5730  * is 32.
5731  *
5732  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5733  * appropriate values in scsi_pkt fields.
5734  */
5735 static int
5736 sata_txlt_write(sata_pkt_txlate_t *spx)
5737 {
5738 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5739 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5740 	sata_drive_info_t *sdinfo;
5741 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5742 	int cport = SATA_TXLT_CPORT(spx);
5743 	uint16_t sec_count;
5744 	uint64_t lba;
5745 	int rval, reason;
5746 	int synch;
5747 
5748 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5749 
5750 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5751 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5752 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5753 		return (rval);
5754 	}
5755 
5756 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5757 	    &spx->txlt_sata_pkt->satapkt_device);
5758 
5759 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5760 	/*
5761 	 * Extract LBA and sector count from scsi CDB
5762 	 */
5763 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5764 	case SCMD_WRITE:
5765 		/* 6-byte scsi read cmd : 0x0A */
5766 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5767 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5768 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5769 		sec_count = scsipkt->pkt_cdbp[4];
5770 		/* sec_count 0 will be interpreted as 256 by a device */
5771 		break;
5772 	case SCMD_WRITE_G1:
5773 		/* 10-bytes scsi write command : 0x2A */
5774 		lba = scsipkt->pkt_cdbp[2];
5775 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5776 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5777 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5778 		sec_count = scsipkt->pkt_cdbp[7];
5779 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5780 		break;
5781 	case SCMD_WRITE_G5:
5782 		/* 12-bytes scsi read command : 0xAA */
5783 		lba = scsipkt->pkt_cdbp[2];
5784 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5785 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5786 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5787 		sec_count = scsipkt->pkt_cdbp[6];
5788 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5789 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5790 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5791 		break;
5792 	case SCMD_WRITE_G4:
5793 		/* 16-bytes scsi write command : 0x8A */
5794 		lba = scsipkt->pkt_cdbp[2];
5795 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5796 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5797 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5798 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5799 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5800 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5801 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5802 		sec_count = scsipkt->pkt_cdbp[10];
5803 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5804 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5805 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5806 		break;
5807 	default:
5808 		/* Unsupported command */
5809 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5810 		return (sata_txlt_invalid_command(spx));
5811 	}
5812 
5813 	/*
5814 	 * Check if specified address and length exceeds device capacity
5815 	 */
5816 	if ((lba >= sdinfo->satadrv_capacity) ||
5817 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5818 		/* LBA out of range */
5819 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5820 		return (sata_txlt_lba_out_of_range(spx));
5821 	}
5822 
5823 	/*
5824 	 * For zero-length transfer, emulate good completion of the command
5825 	 * (reasons for rejecting the command were already checked).
5826 	 * No DMA resources were allocated.
5827 	 */
5828 	if (spx->txlt_dma_cookie_list == NULL) {
5829 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5830 		return (sata_emul_rw_completion(spx));
5831 	}
5832 
5833 	/*
5834 	 * Build cmd block depending on the device capability and
5835 	 * requested operation mode.
5836 	 * Do not bother with non-dma mode- we are working only with
5837 	 * devices supporting DMA.
5838 	 */
5839 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5840 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5841 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5842 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5843 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5844 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5845 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5846 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5847 #ifndef __lock_lint
5848 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5849 		scmd->satacmd_lba_high_msb = lba >> 40;
5850 #endif
5851 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5852 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5853 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5854 	}
5855 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5856 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5857 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5858 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5859 	scmd->satacmd_features_reg = 0;
5860 	scmd->satacmd_status_reg = 0;
5861 	scmd->satacmd_error_reg = 0;
5862 
5863 	/*
5864 	 * Check if queueing commands should be used and switch
5865 	 * to appropriate command if possible
5866 	 */
5867 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5868 		boolean_t using_queuing;
5869 
5870 		/* Queuing supported by controller and device? */
5871 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5872 		    (sdinfo->satadrv_features_support &
5873 		    SATA_DEV_F_NCQ) &&
5874 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5875 		    SATA_CTLF_NCQ)) {
5876 			using_queuing = B_TRUE;
5877 
5878 			/* NCQ supported - use FPDMA WRITE */
5879 			scmd->satacmd_cmd_reg =
5880 			    SATAC_WRITE_FPDMA_QUEUED;
5881 			scmd->satacmd_features_reg_ext =
5882 			    scmd->satacmd_sec_count_msb;
5883 			scmd->satacmd_sec_count_msb = 0;
5884 		} else if ((sdinfo->satadrv_features_support &
5885 		    SATA_DEV_F_TCQ) &&
5886 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5887 		    SATA_CTLF_QCMD)) {
5888 			using_queuing = B_TRUE;
5889 
5890 			/* Legacy queueing */
5891 			if (sdinfo->satadrv_features_support &
5892 			    SATA_DEV_F_LBA48) {
5893 				scmd->satacmd_cmd_reg =
5894 				    SATAC_WRITE_DMA_QUEUED_EXT;
5895 				scmd->satacmd_features_reg_ext =
5896 				    scmd->satacmd_sec_count_msb;
5897 				scmd->satacmd_sec_count_msb = 0;
5898 			} else {
5899 				scmd->satacmd_cmd_reg =
5900 				    SATAC_WRITE_DMA_QUEUED;
5901 			}
5902 		} else	/*  NCQ nor legacy queuing not supported */
5903 			using_queuing = B_FALSE;
5904 
5905 		if (using_queuing) {
5906 			scmd->satacmd_features_reg =
5907 			    scmd->satacmd_sec_count_lsb;
5908 			scmd->satacmd_sec_count_lsb = 0;
5909 			scmd->satacmd_flags.sata_queued = B_TRUE;
5910 			/* Set-up maximum queue depth */
5911 			scmd->satacmd_flags.sata_max_queue_depth =
5912 			    sdinfo->satadrv_max_queue_depth - 1;
5913 		} else if (sdinfo->satadrv_features_enabled &
5914 		    SATA_DEV_F_E_UNTAGGED_QING) {
5915 			/*
5916 			 * Although NCQ/TCQ is not enabled, untagged queuing
5917 			 * may be still used.
5918 			 * Set-up the maximum untagged queue depth.
5919 			 * Use controller's queue depth from sata_hba_tran.
5920 			 * SATA HBA drivers may ignore this value and rely on
5921 			 * the internal limits. For drivera that do not
5922 			 * ignore untaged queue depth, limit the value to
5923 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5924 			 * largest value that can be passed via
5925 			 * satacmd_flags.sata_max_queue_depth.
5926 			 */
5927 			scmd->satacmd_flags.sata_max_queue_depth =
5928 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5929 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5930 
5931 		} else {
5932 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5933 		}
5934 	} else
5935 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5936 
5937 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5938 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5939 	    scmd->satacmd_cmd_reg, lba, sec_count);
5940 
5941 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5942 		/* Need callback function */
5943 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5944 		synch = FALSE;
5945 	} else
5946 		synch = TRUE;
5947 
5948 	/* Transfer command to HBA */
5949 	if (sata_hba_start(spx, &rval) != 0) {
5950 		/* Pkt not accepted for execution */
5951 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5952 		return (rval);
5953 	}
5954 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5955 
5956 	/*
5957 	 * If execution is non-synchronous,
5958 	 * a callback function will handle potential errors, translate
5959 	 * the response and will do a callback to a target driver.
5960 	 * If it was synchronous, check execution status using the same
5961 	 * framework callback.
5962 	 */
5963 	if (synch) {
5964 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5965 		    "synchronous execution status %x\n",
5966 		    spx->txlt_sata_pkt->satapkt_reason);
5967 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5968 	}
5969 	return (TRAN_ACCEPT);
5970 }
5971 
5972 
5973 /*
5974  * Implements SCSI SBC WRITE BUFFER command download microcode option
5975  */
5976 static int
5977 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
5978 {
5979 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
5980 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
5981 
5982 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
5983 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5984 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
5985 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5986 
5987 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5988 	struct scsi_extended_sense *sense;
5989 	int rval, mode, sector_count, reason;
5990 	int cport = SATA_TXLT_CPORT(spx);
5991 
5992 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
5993 
5994 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5995 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
5996 
5997 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5998 
5999 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason)) != TRAN_ACCEPT) {
6000 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6001 		return (rval);
6002 	}
6003 	/*
6004 	 * If in interrupt context, reject this packet because it would issue
6005 	 * a synchronous command to HBA.
6006 	 */
6007 	if (servicing_interrupt()) {
6008 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
6009 		    "sata_txlt_write_buffer: rejecting command because "
6010 		    "of interrupt context\n", NULL);
6011 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6012 		return (TRAN_BUSY);
6013 	}
6014 
6015 	/* Use synchronous mode */
6016 	spx->txlt_sata_pkt->satapkt_op_mode
6017 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6018 
6019 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6020 
6021 	scsipkt->pkt_reason = CMD_CMPLT;
6022 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6023 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6024 
6025 	/*
6026 	 * The SCSI to ATA translation specification only calls
6027 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6028 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6029 	 * ATA 8 (draft) got rid of download microcode for temp
6030 	 * and it is even optional for ATA 7, so it may be aborted.
6031 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6032 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6033 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6034 	 * sectors.  Thus the offset really doesn't buy us anything.
6035 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6036 	 * is revised, this can be revisisted.
6037 	 */
6038 	/* Reject not supported request */
6039 	switch (mode) {
6040 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6041 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6042 		break;
6043 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6044 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6045 		break;
6046 	default:
6047 		goto bad_param;
6048 	}
6049 
6050 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6051 
6052 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6053 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6054 		goto bad_param;
6055 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6056 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6057 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6058 	scmd->satacmd_lba_mid_lsb = 0;
6059 	scmd->satacmd_lba_high_lsb = 0;
6060 	scmd->satacmd_device_reg = 0;
6061 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6062 	scmd->satacmd_addr_type = 0;
6063 
6064 	/* Transfer command to HBA */
6065 	if (sata_hba_start(spx, &rval) != 0) {
6066 		/* Pkt not accepted for execution */
6067 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6068 		return (rval);
6069 	}
6070 
6071 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6072 
6073 	/* Then we need synchronous check the status of the disk */
6074 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6075 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6076 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6077 		scsipkt->pkt_reason = CMD_CMPLT;
6078 
6079 		/* Download commmand succeed, so probe and identify device */
6080 		sata_reidentify_device(spx);
6081 	} else {
6082 		/* Something went wrong, microcode download command failed */
6083 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6084 		*scsipkt->pkt_scbp = STATUS_CHECK;
6085 		sense = sata_arq_sense(spx);
6086 		switch (sata_pkt->satapkt_reason) {
6087 		case SATA_PKT_PORT_ERROR:
6088 			/*
6089 			 * We have no device data. Assume no data transfered.
6090 			 */
6091 			sense->es_key = KEY_HARDWARE_ERROR;
6092 			break;
6093 
6094 		case SATA_PKT_DEV_ERROR:
6095 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6096 			    SATA_STATUS_ERR) {
6097 				/*
6098 				 * determine dev error reason from error
6099 				 * reg content
6100 				 */
6101 				sata_decode_device_error(spx, sense);
6102 				break;
6103 			}
6104 			/* No extended sense key - no info available */
6105 			break;
6106 
6107 		case SATA_PKT_TIMEOUT:
6108 			scsipkt->pkt_reason = CMD_TIMEOUT;
6109 			scsipkt->pkt_statistics |=
6110 			    STAT_TIMEOUT | STAT_DEV_RESET;
6111 			/* No extended sense key ? */
6112 			break;
6113 
6114 		case SATA_PKT_ABORTED:
6115 			scsipkt->pkt_reason = CMD_ABORTED;
6116 			scsipkt->pkt_statistics |= STAT_ABORTED;
6117 			/* No extended sense key ? */
6118 			break;
6119 
6120 		case SATA_PKT_RESET:
6121 			/* pkt aborted by an explicit reset from a host */
6122 			scsipkt->pkt_reason = CMD_RESET;
6123 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6124 			break;
6125 
6126 		default:
6127 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6128 			    "sata_txlt_nodata_cmd_completion: "
6129 			    "invalid packet completion reason %d",
6130 			    sata_pkt->satapkt_reason));
6131 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6132 			break;
6133 		}
6134 
6135 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6136 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6137 
6138 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6139 			/* scsi callback required */
6140 			scsi_hba_pkt_comp(scsipkt);
6141 	}
6142 	return (TRAN_ACCEPT);
6143 
6144 bad_param:
6145 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6146 	*scsipkt->pkt_scbp = STATUS_CHECK;
6147 	sense = sata_arq_sense(spx);
6148 	sense->es_key = KEY_ILLEGAL_REQUEST;
6149 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6150 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6151 	    scsipkt->pkt_comp != NULL) {
6152 		/* scsi callback required */
6153 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6154 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6155 		    TQ_SLEEP) == 0) {
6156 			/* Scheduling the callback failed */
6157 			rval = TRAN_BUSY;
6158 		}
6159 	}
6160 	return (rval);
6161 }
6162 
6163 /*
6164  * Re-identify device after doing a firmware download.
6165  */
6166 static void
6167 sata_reidentify_device(sata_pkt_txlate_t *spx)
6168 {
6169 #define	DOWNLOAD_WAIT_TIME_SECS	60
6170 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6171 	int rval;
6172 	int retry_cnt;
6173 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6174 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6175 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6176 	sata_drive_info_t *sdinfo;
6177 
6178 	/*
6179 	 * Before returning good status, probe device.
6180 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6181 	 * The assumption is that the new microcode is applied by the
6182 	 * device. It is a caller responsibility to verify this.
6183 	 */
6184 	for (retry_cnt = 0;
6185 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6186 	    retry_cnt++) {
6187 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6188 
6189 		if (rval == SATA_SUCCESS) { /* Set default features */
6190 			sdinfo = sata_get_device_info(sata_hba_inst,
6191 			    &sata_device);
6192 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6193 			    SATA_SUCCESS) {
6194 				/* retry */
6195 				rval = sata_initialize_device(sata_hba_inst,
6196 				    sdinfo);
6197 				if (rval == SATA_RETRY)
6198 					sata_log(sata_hba_inst, CE_WARN,
6199 					    "SATA device at port %d pmport %d -"
6200 					    " default device features could not"
6201 					    " be set. Device may not operate "
6202 					    "as expected.",
6203 					    sata_device.satadev_addr.cport,
6204 					    sata_device.satadev_addr.pmport);
6205 			}
6206 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6207 				scsi_hba_pkt_comp(scsipkt);
6208 			return;
6209 		} else if (rval == SATA_RETRY) {
6210 			delay(drv_usectohz(1000000 *
6211 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6212 			continue;
6213 		} else	/* failed - no reason to retry */
6214 			break;
6215 	}
6216 
6217 	/*
6218 	 * Something went wrong, device probing failed.
6219 	 */
6220 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6221 	    "Cannot probe device after downloading microcode\n"));
6222 
6223 	/* Reset device to force retrying the probe. */
6224 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6225 	    (SATA_DIP(sata_hba_inst), &sata_device);
6226 
6227 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6228 		scsi_hba_pkt_comp(scsipkt);
6229 }
6230 
6231 
6232 /*
6233  * Translate command: Synchronize Cache.
6234  * Translates into Flush Cache command for SATA hard disks.
6235  *
6236  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6237  * appropriate values in scsi_pkt fields.
6238  */
6239 static 	int
6240 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6241 {
6242 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6243 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6244 	int cport = SATA_TXLT_CPORT(spx);
6245 	int rval, reason;
6246 	int synch;
6247 
6248 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6249 
6250 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
6251 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6252 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6253 		return (rval);
6254 	}
6255 
6256 	scmd->satacmd_addr_type = 0;
6257 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6258 	scmd->satacmd_device_reg = 0;
6259 	scmd->satacmd_sec_count_lsb = 0;
6260 	scmd->satacmd_lba_low_lsb = 0;
6261 	scmd->satacmd_lba_mid_lsb = 0;
6262 	scmd->satacmd_lba_high_lsb = 0;
6263 	scmd->satacmd_features_reg = 0;
6264 	scmd->satacmd_status_reg = 0;
6265 	scmd->satacmd_error_reg = 0;
6266 
6267 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6268 	    "sata_txlt_synchronize_cache\n", NULL);
6269 
6270 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6271 		/* Need to set-up a callback function */
6272 		spx->txlt_sata_pkt->satapkt_comp =
6273 		    sata_txlt_nodata_cmd_completion;
6274 		synch = FALSE;
6275 	} else
6276 		synch = TRUE;
6277 
6278 	/* Transfer command to HBA */
6279 	if (sata_hba_start(spx, &rval) != 0) {
6280 		/* Pkt not accepted for execution */
6281 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6282 		return (rval);
6283 	}
6284 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6285 
6286 	/*
6287 	 * If execution non-synchronous, it had to be completed
6288 	 * a callback function will handle potential errors, translate
6289 	 * the response and will do a callback to a target driver.
6290 	 * If it was synchronous, check status, using the same
6291 	 * framework callback.
6292 	 */
6293 	if (synch) {
6294 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6295 		    "synchronous execution status %x\n",
6296 		    spx->txlt_sata_pkt->satapkt_reason);
6297 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6298 	}
6299 	return (TRAN_ACCEPT);
6300 }
6301 
6302 
6303 /*
6304  * Send pkt to SATA HBA driver
6305  *
6306  * This function may be called only if the operation is requested by scsi_pkt,
6307  * i.e. scsi_pkt is not NULL.
6308  *
6309  * This function has to be called with cport mutex held. It does release
6310  * the mutex when it calls HBA driver sata_tran_start function and
6311  * re-acquires it afterwards.
6312  *
6313  * If return value is 0, pkt was accepted, -1 otherwise
6314  * rval is set to appropriate sata_scsi_start return value.
6315  *
6316  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6317  * have called the sata_pkt callback function for this packet.
6318  *
6319  * The scsi callback has to be performed by the caller of this routine.
6320  */
6321 static int
6322 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6323 {
6324 	int stat;
6325 	uint8_t cport = SATA_TXLT_CPORT(spx);
6326 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6327 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6328 	sata_drive_info_t *sdinfo;
6329 	sata_pmult_info_t *pminfo;
6330 	sata_pmport_info_t *pmportinfo = NULL;
6331 	sata_device_t *sata_device = NULL;
6332 	uint8_t cmd;
6333 	struct sata_cmd_flags cmd_flags;
6334 
6335 	ASSERT(spx->txlt_sata_pkt != NULL);
6336 
6337 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6338 
6339 	sdinfo = sata_get_device_info(sata_hba_inst,
6340 	    &spx->txlt_sata_pkt->satapkt_device);
6341 	ASSERT(sdinfo != NULL);
6342 
6343 	/* Clear device reset state? */
6344 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6345 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6346 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6347 
6348 		/*
6349 		 * Get the pmult_info of the its parent port multiplier, all
6350 		 * sub-devices share a common device reset flags on in
6351 		 * pmult_info.
6352 		 */
6353 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6354 		pmportinfo = pminfo->pmult_dev_port[pmport];
6355 		ASSERT(pminfo != NULL);
6356 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6357 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6358 			    sata_clear_dev_reset = B_TRUE;
6359 			pminfo->pmult_event_flags &=
6360 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6361 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6362 			    "sata_hba_start: clearing device reset state"
6363 			    "on pmult.\n", NULL);
6364 		}
6365 	} else {
6366 		if (sdinfo->satadrv_event_flags &
6367 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6368 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6369 			    sata_clear_dev_reset = B_TRUE;
6370 			sdinfo->satadrv_event_flags &=
6371 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6372 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6373 			    "sata_hba_start: clearing device reset state\n",
6374 			    NULL);
6375 		}
6376 	}
6377 
6378 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6379 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6380 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6381 
6382 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6383 
6384 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6385 	    "Sata cmd 0x%2x\n", cmd);
6386 
6387 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6388 	    spx->txlt_sata_pkt);
6389 
6390 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6391 	/*
6392 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6393 	 * with the sata callback, the sata_pkt could be already destroyed
6394 	 * by the time we check ther return status from the hba_start()
6395 	 * function, because sata_scsi_destroy_pkt() could have been already
6396 	 * called (perhaps in the interrupt context). So, in such case, there
6397 	 * should be no references to it. In other cases, sata_pkt still
6398 	 * exists.
6399 	 */
6400 	if (stat == SATA_TRAN_ACCEPTED) {
6401 		/*
6402 		 * pkt accepted for execution.
6403 		 * If it was executed synchronously, it is already completed
6404 		 * and pkt completion_reason indicates completion status.
6405 		 */
6406 		*rval = TRAN_ACCEPT;
6407 		return (0);
6408 	}
6409 
6410 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6411 	switch (stat) {
6412 	case SATA_TRAN_QUEUE_FULL:
6413 		/*
6414 		 * Controller detected queue full condition.
6415 		 */
6416 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6417 		    "sata_hba_start: queue full\n", NULL);
6418 
6419 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6420 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6421 
6422 		*rval = TRAN_BUSY;
6423 		break;
6424 
6425 	case SATA_TRAN_PORT_ERROR:
6426 		/*
6427 		 * Communication/link with device or general port error
6428 		 * detected before pkt execution begun.
6429 		 */
6430 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6431 		    SATA_ADDR_CPORT ||
6432 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6433 		    SATA_ADDR_DCPORT)
6434 			sata_log(sata_hba_inst, CE_CONT,
6435 			    "SATA port %d error",
6436 			    sata_device->satadev_addr.cport);
6437 		else
6438 			sata_log(sata_hba_inst, CE_CONT,
6439 			    "SATA port %d:%d error\n",
6440 			    sata_device->satadev_addr.cport,
6441 			    sata_device->satadev_addr.pmport);
6442 
6443 		/*
6444 		 * Update the port/device structure.
6445 		 * sata_pkt should be still valid. Since port error is
6446 		 * returned, sata_device content should reflect port
6447 		 * state - it means, that sata address have been changed,
6448 		 * because original packet's sata address refered to a device
6449 		 * attached to some port.
6450 		 */
6451 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6452 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6453 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6454 			mutex_enter(&pmportinfo->pmport_mutex);
6455 			sata_update_pmport_info(sata_hba_inst, sata_device);
6456 			mutex_exit(&pmportinfo->pmport_mutex);
6457 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6458 		} else {
6459 			sata_update_port_info(sata_hba_inst, sata_device);
6460 		}
6461 
6462 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6463 		*rval = TRAN_FATAL_ERROR;
6464 		break;
6465 
6466 	case SATA_TRAN_CMD_UNSUPPORTED:
6467 		/*
6468 		 * Command rejected by HBA as unsupported. It was HBA driver
6469 		 * that rejected the command, command was not sent to
6470 		 * an attached device.
6471 		 */
6472 		if ((sdinfo != NULL) &&
6473 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6474 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6475 			    "sat_hba_start: cmd 0x%2x rejected "
6476 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6477 
6478 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6479 		(void) sata_txlt_invalid_command(spx);
6480 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6481 
6482 		*rval = TRAN_ACCEPT;
6483 		break;
6484 
6485 	case SATA_TRAN_BUSY:
6486 		/*
6487 		 * Command rejected by HBA because other operation prevents
6488 		 * accepting the packet, or device is in RESET condition.
6489 		 */
6490 		if (sdinfo != NULL) {
6491 			sdinfo->satadrv_state =
6492 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6493 
6494 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6495 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6496 				    "sata_hba_start: cmd 0x%2x rejected "
6497 				    "because of device reset condition\n",
6498 				    cmd);
6499 			} else {
6500 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6501 				    "sata_hba_start: cmd 0x%2x rejected "
6502 				    "with SATA_TRAN_BUSY status\n",
6503 				    cmd);
6504 			}
6505 		}
6506 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6507 		*rval = TRAN_BUSY;
6508 		break;
6509 
6510 	default:
6511 		/* Unrecognized HBA response */
6512 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6513 		    "sata_hba_start: unrecognized HBA response "
6514 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6515 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6516 		*rval = TRAN_FATAL_ERROR;
6517 		break;
6518 	}
6519 
6520 	/*
6521 	 * If we got here, the packet was rejected.
6522 	 * Check if we need to remember reset state clearing request
6523 	 */
6524 	if (cmd_flags.sata_clear_dev_reset) {
6525 		/*
6526 		 * Check if device is still configured - it may have
6527 		 * disapeared from the configuration
6528 		 */
6529 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6530 		if (sdinfo != NULL) {
6531 			/*
6532 			 * Restore the flag that requests clearing of
6533 			 * the device reset state,
6534 			 * so the next sata packet may carry it to HBA.
6535 			 */
6536 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6537 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6538 				pminfo->pmult_event_flags |=
6539 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6540 			} else {
6541 				sdinfo->satadrv_event_flags |=
6542 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6543 			}
6544 		}
6545 	}
6546 	return (-1);
6547 }
6548 
6549 /*
6550  * Scsi response setup for invalid LBA
6551  *
6552  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6553  */
6554 static int
6555 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6556 {
6557 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6558 	struct scsi_extended_sense *sense;
6559 
6560 	scsipkt->pkt_reason = CMD_CMPLT;
6561 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6562 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6563 	*scsipkt->pkt_scbp = STATUS_CHECK;
6564 
6565 	*scsipkt->pkt_scbp = STATUS_CHECK;
6566 	sense = sata_arq_sense(spx);
6567 	sense->es_key = KEY_ILLEGAL_REQUEST;
6568 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6569 
6570 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6571 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6572 
6573 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6574 	    scsipkt->pkt_comp != NULL)
6575 		/* scsi callback required */
6576 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6577 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6578 		    TQ_SLEEP) == NULL)
6579 			/* Scheduling the callback failed */
6580 			return (TRAN_BUSY);
6581 	return (TRAN_ACCEPT);
6582 }
6583 
6584 
6585 /*
6586  * Analyze device status and error registers and translate them into
6587  * appropriate scsi sense codes.
6588  * NOTE: non-packet commands only for now
6589  */
6590 static void
6591 sata_decode_device_error(sata_pkt_txlate_t *spx,
6592     struct scsi_extended_sense *sense)
6593 {
6594 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6595 
6596 	ASSERT(sense != NULL);
6597 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6598 	    SATA_STATUS_ERR);
6599 
6600 
6601 	if (err_reg & SATA_ERROR_ICRC) {
6602 		sense->es_key = KEY_ABORTED_COMMAND;
6603 		sense->es_add_code = 0x08; /* Communication failure */
6604 		return;
6605 	}
6606 
6607 	if (err_reg & SATA_ERROR_UNC) {
6608 		sense->es_key = KEY_MEDIUM_ERROR;
6609 		/* Information bytes (LBA) need to be set by a caller */
6610 		return;
6611 	}
6612 
6613 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6614 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6615 		sense->es_key = KEY_UNIT_ATTENTION;
6616 		sense->es_add_code = 0x3a; /* No media present */
6617 		return;
6618 	}
6619 
6620 	if (err_reg & SATA_ERROR_IDNF) {
6621 		if (err_reg & SATA_ERROR_ABORT) {
6622 			sense->es_key = KEY_ABORTED_COMMAND;
6623 		} else {
6624 			sense->es_key = KEY_ILLEGAL_REQUEST;
6625 			sense->es_add_code = 0x21; /* LBA out of range */
6626 		}
6627 		return;
6628 	}
6629 
6630 	if (err_reg & SATA_ERROR_ABORT) {
6631 		ASSERT(spx->txlt_sata_pkt != NULL);
6632 		sense->es_key = KEY_ABORTED_COMMAND;
6633 		return;
6634 	}
6635 }
6636 
6637 /*
6638  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6639  */
6640 static void
6641 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6642 {
6643 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6644 
6645 	*lba = 0;
6646 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6647 		*lba = sata_cmd->satacmd_lba_high_msb;
6648 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6649 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6650 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6651 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6652 	}
6653 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6654 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6655 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6656 }
6657 
6658 /*
6659  * This is fixed sense format - if LBA exceeds the info field size,
6660  * no valid info will be returned (valid bit in extended sense will
6661  * be set to 0).
6662  */
6663 static struct scsi_extended_sense *
6664 sata_arq_sense(sata_pkt_txlate_t *spx)
6665 {
6666 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6667 	struct scsi_arq_status *arqs;
6668 	struct scsi_extended_sense *sense;
6669 
6670 	/* Fill ARQ sense data */
6671 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6672 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6673 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6674 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6675 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6676 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6677 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6678 	arqs->sts_rqpkt_resid = 0;
6679 	sense = &arqs->sts_sensedata;
6680 	bzero(sense, sizeof (struct scsi_extended_sense));
6681 	sata_fixed_sense_data_preset(sense);
6682 	return (sense);
6683 }
6684 
6685 /*
6686  * ATA Pass Through support
6687  * Sets flags indicating that an invalid value was found in some
6688  * field in the command.  It could be something illegal according to
6689  * the SAT-2 spec or it could be a feature that is not (yet?)
6690  * supported.
6691  */
6692 static int
6693 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6694 {
6695 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6696 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6697 
6698 	scsipkt->pkt_reason = CMD_CMPLT;
6699 	*scsipkt->pkt_scbp = STATUS_CHECK;
6700 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6701 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6702 
6703 	sense = sata_arq_sense(spx);
6704 	sense->es_key = KEY_ILLEGAL_REQUEST;
6705 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6706 
6707 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6708 	    scsipkt->pkt_comp != NULL)
6709 		/* scsi callback required */
6710 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6711 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6712 		    TQ_SLEEP) == NULL)
6713 			/* Scheduling the callback failed */
6714 			return (TRAN_BUSY);
6715 
6716 	return (TRAN_ACCEPT);
6717 }
6718 
6719 /*
6720  * Emulated SATA Read/Write command completion for zero-length requests.
6721  * This request always succedes, so in synchronous mode it always returns
6722  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6723  * callback cannot be scheduled.
6724  */
6725 static int
6726 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6727 {
6728 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6729 
6730 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6731 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6732 	scsipkt->pkt_reason = CMD_CMPLT;
6733 	*scsipkt->pkt_scbp = STATUS_GOOD;
6734 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6735 		/* scsi callback required - have to schedule it */
6736 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6737 		    (task_func_t *)scsipkt->pkt_comp,
6738 		    (void *)scsipkt, TQ_SLEEP) == NULL)
6739 			/* Scheduling the callback failed */
6740 			return (TRAN_BUSY);
6741 	}
6742 	return (TRAN_ACCEPT);
6743 }
6744 
6745 
6746 /*
6747  * Translate completion status of SATA read/write commands into scsi response.
6748  * pkt completion_reason is checked to determine the completion status.
6749  * Do scsi callback if necessary.
6750  *
6751  * Note: this function may be called also for synchronously executed
6752  * commands.
6753  * This function may be used only if scsi_pkt is non-NULL.
6754  */
6755 static void
6756 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6757 {
6758 	sata_pkt_txlate_t *spx =
6759 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6760 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6761 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6762 	struct scsi_extended_sense *sense;
6763 	uint64_t lba;
6764 	struct buf *bp;
6765 	int rval;
6766 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6767 		/* Normal completion */
6768 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6769 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6770 		scsipkt->pkt_reason = CMD_CMPLT;
6771 		*scsipkt->pkt_scbp = STATUS_GOOD;
6772 		if (spx->txlt_tmp_buf != NULL) {
6773 			/* Temporary buffer was used */
6774 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6775 			if (bp->b_flags & B_READ) {
6776 				rval = ddi_dma_sync(
6777 				    spx->txlt_buf_dma_handle, 0, 0,
6778 				    DDI_DMA_SYNC_FORCPU);
6779 				ASSERT(rval == DDI_SUCCESS);
6780 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6781 				    bp->b_bcount);
6782 			}
6783 		}
6784 	} else {
6785 		/*
6786 		 * Something went wrong - analyze return
6787 		 */
6788 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6789 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6790 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6791 		*scsipkt->pkt_scbp = STATUS_CHECK;
6792 		sense = sata_arq_sense(spx);
6793 		ASSERT(sense != NULL);
6794 
6795 		/*
6796 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6797 		 * extract from device registers the failing LBA.
6798 		 */
6799 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6800 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6801 			    (scmd->satacmd_lba_mid_msb != 0 ||
6802 			    scmd->satacmd_lba_high_msb != 0)) {
6803 				/*
6804 				 * We have problem reporting this cmd LBA
6805 				 * in fixed sense data format, because of
6806 				 * the size of the scsi LBA fields.
6807 				 */
6808 				sense->es_valid = 0;
6809 			} else {
6810 				sata_extract_error_lba(spx, &lba);
6811 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6812 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6813 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6814 				sense->es_info_4 = lba & 0xFF;
6815 			}
6816 		} else {
6817 			/* Invalid extended sense info */
6818 			sense->es_valid = 0;
6819 		}
6820 
6821 		switch (sata_pkt->satapkt_reason) {
6822 		case SATA_PKT_PORT_ERROR:
6823 			/* We may want to handle DEV GONE state as well */
6824 			/*
6825 			 * We have no device data. Assume no data transfered.
6826 			 */
6827 			sense->es_key = KEY_HARDWARE_ERROR;
6828 			break;
6829 
6830 		case SATA_PKT_DEV_ERROR:
6831 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6832 			    SATA_STATUS_ERR) {
6833 				/*
6834 				 * determine dev error reason from error
6835 				 * reg content
6836 				 */
6837 				sata_decode_device_error(spx, sense);
6838 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6839 					switch (scmd->satacmd_cmd_reg) {
6840 					case SATAC_READ_DMA:
6841 					case SATAC_READ_DMA_EXT:
6842 					case SATAC_READ_DMA_QUEUED:
6843 					case SATAC_READ_DMA_QUEUED_EXT:
6844 					case SATAC_READ_FPDMA_QUEUED:
6845 						/* Unrecovered read error */
6846 						sense->es_add_code =
6847 						    SD_SCSI_ASC_UNREC_READ_ERR;
6848 						break;
6849 					case SATAC_WRITE_DMA:
6850 					case SATAC_WRITE_DMA_EXT:
6851 					case SATAC_WRITE_DMA_QUEUED:
6852 					case SATAC_WRITE_DMA_QUEUED_EXT:
6853 					case SATAC_WRITE_FPDMA_QUEUED:
6854 						/* Write error */
6855 						sense->es_add_code =
6856 						    SD_SCSI_ASC_WRITE_ERR;
6857 						break;
6858 					default:
6859 						/* Internal error */
6860 						SATA_LOG_D((
6861 						    spx->txlt_sata_hba_inst,
6862 						    CE_WARN,
6863 						    "sata_txlt_rw_completion :"
6864 						    "internal error - invalid "
6865 						    "command 0x%2x",
6866 						    scmd->satacmd_cmd_reg));
6867 						break;
6868 					}
6869 				}
6870 				break;
6871 			}
6872 			/* No extended sense key - no info available */
6873 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6874 			break;
6875 
6876 		case SATA_PKT_TIMEOUT:
6877 			scsipkt->pkt_reason = CMD_TIMEOUT;
6878 			scsipkt->pkt_statistics |=
6879 			    STAT_TIMEOUT | STAT_DEV_RESET;
6880 			sense->es_key = KEY_ABORTED_COMMAND;
6881 			break;
6882 
6883 		case SATA_PKT_ABORTED:
6884 			scsipkt->pkt_reason = CMD_ABORTED;
6885 			scsipkt->pkt_statistics |= STAT_ABORTED;
6886 			sense->es_key = KEY_ABORTED_COMMAND;
6887 			break;
6888 
6889 		case SATA_PKT_RESET:
6890 			scsipkt->pkt_reason = CMD_RESET;
6891 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6892 			sense->es_key = KEY_ABORTED_COMMAND;
6893 			break;
6894 
6895 		default:
6896 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6897 			    "sata_txlt_rw_completion: "
6898 			    "invalid packet completion reason"));
6899 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6900 			break;
6901 		}
6902 	}
6903 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6904 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6905 
6906 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6907 		/* scsi callback required */
6908 		scsi_hba_pkt_comp(scsipkt);
6909 }
6910 
6911 
6912 /*
6913  * Translate completion status of non-data commands (i.e. commands returning
6914  * no data).
6915  * pkt completion_reason is checked to determine the completion status.
6916  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6917  *
6918  * Note: this function may be called also for synchronously executed
6919  * commands.
6920  * This function may be used only if scsi_pkt is non-NULL.
6921  */
6922 
6923 static	void
6924 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6925 {
6926 	sata_pkt_txlate_t *spx =
6927 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6928 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6929 
6930 	sata_set_arq_data(sata_pkt);
6931 
6932 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6933 		/* scsi callback required */
6934 		scsi_hba_pkt_comp(scsipkt);
6935 }
6936 
6937 /*
6938  * Completion handler for ATA Pass Through command
6939  */
6940 static void
6941 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
6942 {
6943 	sata_pkt_txlate_t *spx =
6944 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6945 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6946 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6947 	struct buf *bp;
6948 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
6949 
6950 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6951 		/* Normal completion */
6952 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6953 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6954 		scsipkt->pkt_reason = CMD_CMPLT;
6955 		*scsipkt->pkt_scbp = STATUS_GOOD;
6956 
6957 		/*
6958 		 * If the command has CK_COND set
6959 		 */
6960 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
6961 			*scsipkt->pkt_scbp = STATUS_CHECK;
6962 			sata_fill_ata_return_desc(sata_pkt,
6963 			    KEY_RECOVERABLE_ERROR,
6964 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
6965 		}
6966 
6967 		if (spx->txlt_tmp_buf != NULL) {
6968 			/* Temporary buffer was used */
6969 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6970 			if (bp->b_flags & B_READ) {
6971 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6972 				    bp->b_bcount);
6973 			}
6974 		}
6975 	} else {
6976 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6977 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6978 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6979 		*scsipkt->pkt_scbp = STATUS_CHECK;
6980 
6981 		/*
6982 		 * If DF or ERR was set, the HBA should have copied out the
6983 		 * status and error registers to the satacmd structure.
6984 		 */
6985 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
6986 			sense_key = KEY_HARDWARE_ERROR;
6987 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
6988 			addl_sense_qual = 0;
6989 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
6990 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
6991 				sense_key = KEY_NOT_READY;
6992 				addl_sense_code =
6993 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
6994 				addl_sense_qual = 0;
6995 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
6996 				sense_key = KEY_MEDIUM_ERROR;
6997 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
6998 				addl_sense_qual = 0;
6999 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7000 				sense_key = KEY_DATA_PROTECT;
7001 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7002 				addl_sense_qual = 0;
7003 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7004 				sense_key = KEY_ILLEGAL_REQUEST;
7005 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7006 				addl_sense_qual = 0;
7007 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7008 				sense_key = KEY_ABORTED_COMMAND;
7009 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7010 				addl_sense_qual = 0;
7011 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7012 				sense_key = KEY_UNIT_ATTENTION;
7013 				addl_sense_code =
7014 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7015 				addl_sense_qual = 0;
7016 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7017 				sense_key = KEY_UNIT_ATTENTION;
7018 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7019 				addl_sense_qual = 0;
7020 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7021 				sense_key = KEY_ABORTED_COMMAND;
7022 				addl_sense_code =
7023 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7024 				addl_sense_qual = 0;
7025 			}
7026 		}
7027 
7028 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7029 		    addl_sense_qual);
7030 	}
7031 
7032 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7033 		/* scsi callback required */
7034 		scsi_hba_pkt_comp(scsipkt);
7035 }
7036 
7037 /*
7038  * j
7039  */
7040 static void
7041 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7042     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7043 {
7044 	sata_pkt_txlate_t *spx =
7045 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7046 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7047 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7048 	struct sata_apt_sense_data *apt_sd =
7049 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7050 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7051 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7052 	    &(apt_sd->apt_sd_sense);
7053 	int extend = 0;
7054 
7055 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7056 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7057 		extend = 1;
7058 
7059 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7060 
7061 	/* update the residual count */
7062 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7063 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7064 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7065 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7066 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7067 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7068 	    sizeof (struct sata_apt_sense_data);
7069 
7070 	/*
7071 	 * Fill in the Descriptor sense header
7072 	 */
7073 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7074 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7075 	sds->ds_class = CLASS_EXTENDED_SENSE;
7076 	sds->ds_key = sense_key & 0xf;
7077 	sds->ds_add_code = addl_sense_code;
7078 	sds->ds_qual_code = addl_sense_qual;
7079 	sds->ds_addl_sense_length =
7080 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7081 
7082 	/*
7083 	 * Fill in the ATA Return descriptor sense data
7084 	 */
7085 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7086 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7087 	ata_ret_desc->ars_addl_length = 0xc;
7088 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7089 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7090 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7091 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7092 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7093 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7094 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7095 
7096 	if (extend == 1) {
7097 		ata_ret_desc->ars_extend = 1;
7098 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7099 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7100 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7101 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7102 	} else {
7103 		ata_ret_desc->ars_extend = 0;
7104 		ata_ret_desc->ars_sec_count_msb = 0;
7105 		ata_ret_desc->ars_lba_low_msb = 0;
7106 		ata_ret_desc->ars_lba_mid_msb = 0;
7107 		ata_ret_desc->ars_lba_high_msb = 0;
7108 	}
7109 }
7110 
7111 static	void
7112 sata_set_arq_data(sata_pkt_t *sata_pkt)
7113 {
7114 	sata_pkt_txlate_t *spx =
7115 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7116 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7117 	struct scsi_extended_sense *sense;
7118 
7119 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7120 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7121 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7122 		/* Normal completion */
7123 		scsipkt->pkt_reason = CMD_CMPLT;
7124 		*scsipkt->pkt_scbp = STATUS_GOOD;
7125 	} else {
7126 		/* Something went wrong */
7127 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7128 		*scsipkt->pkt_scbp = STATUS_CHECK;
7129 		sense = sata_arq_sense(spx);
7130 		switch (sata_pkt->satapkt_reason) {
7131 		case SATA_PKT_PORT_ERROR:
7132 			/*
7133 			 * We have no device data. Assume no data transfered.
7134 			 */
7135 			sense->es_key = KEY_HARDWARE_ERROR;
7136 			break;
7137 
7138 		case SATA_PKT_DEV_ERROR:
7139 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7140 			    SATA_STATUS_ERR) {
7141 				/*
7142 				 * determine dev error reason from error
7143 				 * reg content
7144 				 */
7145 				sata_decode_device_error(spx, sense);
7146 				break;
7147 			}
7148 			/* No extended sense key - no info available */
7149 			break;
7150 
7151 		case SATA_PKT_TIMEOUT:
7152 			scsipkt->pkt_reason = CMD_TIMEOUT;
7153 			scsipkt->pkt_statistics |=
7154 			    STAT_TIMEOUT | STAT_DEV_RESET;
7155 			/* No extended sense key ? */
7156 			break;
7157 
7158 		case SATA_PKT_ABORTED:
7159 			scsipkt->pkt_reason = CMD_ABORTED;
7160 			scsipkt->pkt_statistics |= STAT_ABORTED;
7161 			/* No extended sense key ? */
7162 			break;
7163 
7164 		case SATA_PKT_RESET:
7165 			/* pkt aborted by an explicit reset from a host */
7166 			scsipkt->pkt_reason = CMD_RESET;
7167 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7168 			break;
7169 
7170 		default:
7171 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7172 			    "sata_txlt_nodata_cmd_completion: "
7173 			    "invalid packet completion reason %d",
7174 			    sata_pkt->satapkt_reason));
7175 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7176 			break;
7177 		}
7178 
7179 	}
7180 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7181 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7182 }
7183 
7184 
7185 /*
7186  * Build Mode sense R/W recovery page
7187  * NOT IMPLEMENTED
7188  */
7189 
7190 static int
7191 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7192 {
7193 #ifndef __lock_lint
7194 	_NOTE(ARGUNUSED(sdinfo))
7195 	_NOTE(ARGUNUSED(pcntrl))
7196 	_NOTE(ARGUNUSED(buf))
7197 #endif
7198 	return (0);
7199 }
7200 
7201 /*
7202  * Build Mode sense caching page  -  scsi-3 implementation.
7203  * Page length distinguishes previous format from scsi-3 format.
7204  * buf must have space for 0x12 bytes.
7205  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7206  *
7207  */
7208 static int
7209 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7210 {
7211 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7212 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7213 
7214 	/*
7215 	 * Most of the fields are set to 0, being not supported and/or disabled
7216 	 */
7217 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7218 
7219 	/* Saved paramters not supported */
7220 	if (pcntrl == 3)
7221 		return (0);
7222 	if (pcntrl == 0 || pcntrl == 2) {
7223 		/*
7224 		 * For now treat current and default parameters as same
7225 		 * That may have to change, if target driver will complain
7226 		 */
7227 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7228 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7229 
7230 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7231 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7232 			page->dra = 1;		/* Read Ahead disabled */
7233 			page->rcd = 1;		/* Read Cache disabled */
7234 		}
7235 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7236 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7237 			page->wce = 1;		/* Write Cache enabled */
7238 	} else {
7239 		/* Changeable parameters */
7240 		page->mode_page.code = MODEPAGE_CACHING;
7241 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7242 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7243 			page->dra = 1;
7244 			page->rcd = 1;
7245 		}
7246 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7247 			page->wce = 1;
7248 	}
7249 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7250 	    sizeof (struct mode_page));
7251 }
7252 
7253 /*
7254  * Build Mode sense exception cntrl page
7255  */
7256 static int
7257 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7258 {
7259 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7260 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7261 
7262 	/*
7263 	 * Most of the fields are set to 0, being not supported and/or disabled
7264 	 */
7265 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7266 
7267 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7268 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7269 
7270 	/* Indicate that this is page is saveable */
7271 	page->mode_page.ps = 1;
7272 
7273 	/*
7274 	 * We will return the same data for default, current and saved page.
7275 	 * The only changeable bit is dexcpt and that bit is required
7276 	 * by the ATA specification to be preserved across power cycles.
7277 	 */
7278 	if (pcntrl != 1) {
7279 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7280 		page->mrie = MRIE_ONLY_ON_REQUEST;
7281 	}
7282 	else
7283 		page->dexcpt = 1;	/* Only changeable parameter */
7284 
7285 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7286 }
7287 
7288 
7289 static int
7290 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7291 {
7292 	struct mode_acoustic_management *page =
7293 	    (struct mode_acoustic_management *)buf;
7294 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7295 
7296 	/*
7297 	 * Most of the fields are set to 0, being not supported and/or disabled
7298 	 */
7299 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7300 
7301 	switch (pcntrl) {
7302 	case P_CNTRL_DEFAULT:
7303 		/*  default paramters not supported */
7304 		return (0);
7305 
7306 	case P_CNTRL_CURRENT:
7307 	case P_CNTRL_SAVED:
7308 		/* Saved and current are supported and are identical */
7309 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7310 		page->mode_page.length =
7311 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7312 		page->mode_page.ps = 1;
7313 
7314 		/* Word 83 indicates if feature is supported */
7315 		/* If feature is not supported */
7316 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7317 			page->acoustic_manag_enable =
7318 			    ACOUSTIC_DISABLED;
7319 		} else {
7320 			page->acoustic_manag_enable =
7321 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7322 			    != 0);
7323 			/* Word 94 inidicates the value */
7324 #ifdef	_LITTLE_ENDIAN
7325 			page->acoustic_manag_level =
7326 			    (uchar_t)sata_id->ai_acoustic;
7327 			page->vendor_recommended_value =
7328 			    sata_id->ai_acoustic >> 8;
7329 #else
7330 			page->acoustic_manag_level =
7331 			    sata_id->ai_acoustic >> 8;
7332 			page->vendor_recommended_value =
7333 			    (uchar_t)sata_id->ai_acoustic;
7334 #endif
7335 		}
7336 		break;
7337 
7338 	case P_CNTRL_CHANGEABLE:
7339 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7340 		page->mode_page.length =
7341 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7342 		page->mode_page.ps = 1;
7343 
7344 		/* Word 83 indicates if the feature is supported */
7345 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7346 			page->acoustic_manag_enable =
7347 			    ACOUSTIC_ENABLED;
7348 			page->acoustic_manag_level = 0xff;
7349 		}
7350 		break;
7351 	}
7352 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7353 	    sizeof (struct mode_page));
7354 }
7355 
7356 
7357 /*
7358  * Build Mode sense power condition page.
7359  */
7360 static int
7361 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7362 {
7363 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7364 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7365 
7366 	/*
7367 	 * Most of the fields are set to 0, being not supported and/or disabled
7368 	 * power condition page length was 0x0a
7369 	 */
7370 	bzero(buf, sizeof (struct mode_info_power_cond));
7371 
7372 	if (pcntrl == P_CNTRL_DEFAULT) {
7373 		/*  default paramters not supported */
7374 		return (0);
7375 	}
7376 
7377 	page->mode_page.code = MODEPAGE_POWER_COND;
7378 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7379 
7380 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7381 		page->standby = 1;
7382 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7383 		    sizeof (uchar_t) * 4);
7384 	}
7385 
7386 	return (sizeof (struct mode_info_power_cond));
7387 }
7388 
7389 /*
7390  * Process mode select caching page 8 (scsi3 format only).
7391  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7392  * if these features are supported by the device. If these features are not
7393  * supported, the command will be terminated with STATUS_CHECK.
7394  * This function fails only if the SET FEATURE command sent to
7395  * the device fails. The page format is not varified, assuming that the
7396  * target driver operates correctly - if parameters length is too short,
7397  * we just drop the page.
7398  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7399  * setting have to be changed.
7400  * SET FEATURE command is executed synchronously, i.e. we wait here until
7401  * it is completed, regardless of the scsi pkt directives.
7402  *
7403  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7404  * changing DRA will change RCD.
7405  *
7406  * More than one SATA command may be executed to perform operations specified
7407  * by mode select pages. The first error terminates further execution.
7408  * Operations performed successully are not backed-up in such case.
7409  *
7410  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7411  * If operation resulted in changing device setup, dmod flag should be set to
7412  * one (1). If parameters were not changed, dmod flag should be set to 0.
7413  * Upon return, if operation required sending command to the device, the rval
7414  * should be set to the value returned by sata_hba_start. If operation
7415  * did not require device access, rval should be set to TRAN_ACCEPT.
7416  * The pagelen should be set to the length of the page.
7417  *
7418  * This function has to be called with a port mutex held.
7419  *
7420  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7421  */
7422 int
7423 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7424     int parmlen, int *pagelen, int *rval, int *dmod)
7425 {
7426 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7427 	sata_drive_info_t *sdinfo;
7428 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7429 	sata_id_t *sata_id;
7430 	struct scsi_extended_sense *sense;
7431 	int wce, dra;	/* Current settings */
7432 
7433 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7434 	    &spx->txlt_sata_pkt->satapkt_device);
7435 	sata_id = &sdinfo->satadrv_id;
7436 	*dmod = 0;
7437 
7438 	/* Verify parameters length. If too short, drop it */
7439 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7440 	    sizeof (struct mode_page)) > parmlen) {
7441 		*scsipkt->pkt_scbp = STATUS_CHECK;
7442 		sense = sata_arq_sense(spx);
7443 		sense->es_key = KEY_ILLEGAL_REQUEST;
7444 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7445 		*pagelen = parmlen;
7446 		*rval = TRAN_ACCEPT;
7447 		return (SATA_FAILURE);
7448 	}
7449 
7450 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7451 
7452 	/* Current setting of Read Ahead (and Read Cache) */
7453 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7454 		dra = 0;	/* 0 == not disabled */
7455 	else
7456 		dra = 1;
7457 	/* Current setting of Write Cache */
7458 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7459 		wce = 1;
7460 	else
7461 		wce = 0;
7462 
7463 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7464 		/* nothing to do */
7465 		*rval = TRAN_ACCEPT;
7466 		return (SATA_SUCCESS);
7467 	}
7468 
7469 	/*
7470 	 * Need to flip some setting
7471 	 * Set-up Internal SET FEATURES command(s)
7472 	 */
7473 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7474 	scmd->satacmd_addr_type = 0;
7475 	scmd->satacmd_device_reg = 0;
7476 	scmd->satacmd_status_reg = 0;
7477 	scmd->satacmd_error_reg = 0;
7478 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7479 	if (page->dra != dra || page->rcd != dra) {
7480 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7481 			/* Need to flip read ahead setting */
7482 			if (dra == 0)
7483 				/* Disable read ahead / read cache */
7484 				scmd->satacmd_features_reg =
7485 				    SATAC_SF_DISABLE_READ_AHEAD;
7486 			else
7487 				/* Enable read ahead  / read cache */
7488 				scmd->satacmd_features_reg =
7489 				    SATAC_SF_ENABLE_READ_AHEAD;
7490 
7491 			/* Transfer command to HBA */
7492 			if (sata_hba_start(spx, rval) != 0)
7493 				/*
7494 				 * Pkt not accepted for execution.
7495 				 */
7496 				return (SATA_FAILURE);
7497 
7498 			*dmod = 1;
7499 
7500 			/* Now process return */
7501 			if (spx->txlt_sata_pkt->satapkt_reason !=
7502 			    SATA_PKT_COMPLETED) {
7503 				goto failure;	/* Terminate */
7504 			}
7505 		} else {
7506 			*scsipkt->pkt_scbp = STATUS_CHECK;
7507 			sense = sata_arq_sense(spx);
7508 			sense->es_key = KEY_ILLEGAL_REQUEST;
7509 			sense->es_add_code =
7510 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7511 			*pagelen = parmlen;
7512 			*rval = TRAN_ACCEPT;
7513 			return (SATA_FAILURE);
7514 		}
7515 	}
7516 
7517 	/* Note that the packet is not removed, so it could be re-used */
7518 	if (page->wce != wce) {
7519 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7520 			/* Need to flip Write Cache setting */
7521 			if (page->wce == 1)
7522 				/* Enable write cache */
7523 				scmd->satacmd_features_reg =
7524 				    SATAC_SF_ENABLE_WRITE_CACHE;
7525 			else
7526 				/* Disable write cache */
7527 				scmd->satacmd_features_reg =
7528 				    SATAC_SF_DISABLE_WRITE_CACHE;
7529 
7530 			/* Transfer command to HBA */
7531 			if (sata_hba_start(spx, rval) != 0)
7532 				/*
7533 				 * Pkt not accepted for execution.
7534 				 */
7535 				return (SATA_FAILURE);
7536 
7537 			*dmod = 1;
7538 
7539 			/* Now process return */
7540 			if (spx->txlt_sata_pkt->satapkt_reason !=
7541 			    SATA_PKT_COMPLETED) {
7542 				goto failure;
7543 			}
7544 		} else {
7545 			*scsipkt->pkt_scbp = STATUS_CHECK;
7546 			sense = sata_arq_sense(spx);
7547 			sense->es_key = KEY_ILLEGAL_REQUEST;
7548 			sense->es_add_code =
7549 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7550 			*pagelen = parmlen;
7551 			*rval = TRAN_ACCEPT;
7552 			return (SATA_FAILURE);
7553 		}
7554 	}
7555 	return (SATA_SUCCESS);
7556 
7557 failure:
7558 	sata_xlate_errors(spx);
7559 
7560 	return (SATA_FAILURE);
7561 }
7562 
7563 /*
7564  * Process mode select informational exceptions control page 0x1c
7565  *
7566  * The only changeable bit is dexcpt (disable exceptions).
7567  * MRIE (method of reporting informational exceptions) must be
7568  * "only on request".
7569  * This page applies to informational exceptions that report
7570  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7571  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7572  * Informational exception conditions occur as the result of background scan
7573  * errors, background self-test errors, or vendor specific events within a
7574  * logical unit. An informational exception condition may occur asynchronous
7575  * to any commands.
7576  *
7577  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7578  * If operation resulted in changing device setup, dmod flag should be set to
7579  * one (1). If parameters were not changed, dmod flag should be set to 0.
7580  * Upon return, if operation required sending command to the device, the rval
7581  * should be set to the value returned by sata_hba_start. If operation
7582  * did not require device access, rval should be set to TRAN_ACCEPT.
7583  * The pagelen should be set to the length of the page.
7584  *
7585  * This function has to be called with a port mutex held.
7586  *
7587  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7588  *
7589  * Cannot be called in the interrupt context.
7590  */
7591 static	int
7592 sata_mode_select_page_1c(
7593 	sata_pkt_txlate_t *spx,
7594 	struct mode_info_excpt_page *page,
7595 	int parmlen,
7596 	int *pagelen,
7597 	int *rval,
7598 	int *dmod)
7599 {
7600 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7601 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7602 	sata_drive_info_t *sdinfo;
7603 	sata_id_t *sata_id;
7604 	struct scsi_extended_sense *sense;
7605 
7606 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7607 	    &spx->txlt_sata_pkt->satapkt_device);
7608 	sata_id = &sdinfo->satadrv_id;
7609 
7610 	*dmod = 0;
7611 
7612 	/* Verify parameters length. If too short, drop it */
7613 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7614 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7615 		*scsipkt->pkt_scbp = STATUS_CHECK;
7616 		sense = sata_arq_sense(spx);
7617 		sense->es_key = KEY_ILLEGAL_REQUEST;
7618 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7619 		*pagelen = parmlen;
7620 		*rval = TRAN_ACCEPT;
7621 		return (SATA_FAILURE);
7622 	}
7623 
7624 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7625 
7626 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7627 		*scsipkt->pkt_scbp = STATUS_CHECK;
7628 		sense = sata_arq_sense(spx);
7629 		sense->es_key = KEY_ILLEGAL_REQUEST;
7630 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7631 		*pagelen = parmlen;
7632 		*rval = TRAN_ACCEPT;
7633 		return (SATA_FAILURE);
7634 	}
7635 
7636 	/* If already in the state requested, we are done */
7637 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7638 		/* nothing to do */
7639 		*rval = TRAN_ACCEPT;
7640 		return (SATA_SUCCESS);
7641 	}
7642 
7643 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7644 
7645 	/* Build SMART_ENABLE or SMART_DISABLE command */
7646 	scmd->satacmd_addr_type = 0;		/* N/A */
7647 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7648 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7649 	scmd->satacmd_features_reg = page->dexcpt ?
7650 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7651 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7652 	scmd->satacmd_cmd_reg = SATAC_SMART;
7653 
7654 	/* Transfer command to HBA */
7655 	if (sata_hba_start(spx, rval) != 0)
7656 		/*
7657 		 * Pkt not accepted for execution.
7658 		 */
7659 		return (SATA_FAILURE);
7660 
7661 	*dmod = 1;	/* At least may have been modified */
7662 
7663 	/* Now process return */
7664 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7665 		return (SATA_SUCCESS);
7666 
7667 	/* Packet did not complete successfully */
7668 	sata_xlate_errors(spx);
7669 
7670 	return (SATA_FAILURE);
7671 }
7672 
7673 /*
7674  * Process mode select acoustic management control page 0x30
7675  *
7676  *
7677  * This function has to be called with a port mutex held.
7678  *
7679  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7680  *
7681  * Cannot be called in the interrupt context.
7682  */
7683 int
7684 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7685     mode_acoustic_management *page, int parmlen, int *pagelen,
7686     int *rval, int *dmod)
7687 {
7688 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7689 	sata_drive_info_t *sdinfo;
7690 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7691 	sata_id_t *sata_id;
7692 	struct scsi_extended_sense *sense;
7693 
7694 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7695 	    &spx->txlt_sata_pkt->satapkt_device);
7696 	sata_id = &sdinfo->satadrv_id;
7697 	*dmod = 0;
7698 
7699 	/* If parmlen is too short or the feature is not supported, drop it */
7700 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7701 	    sizeof (struct mode_page)) > parmlen) ||
7702 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7703 		*scsipkt->pkt_scbp = STATUS_CHECK;
7704 		sense = sata_arq_sense(spx);
7705 		sense->es_key = KEY_ILLEGAL_REQUEST;
7706 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7707 		*pagelen = parmlen;
7708 		*rval = TRAN_ACCEPT;
7709 		return (SATA_FAILURE);
7710 	}
7711 
7712 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7713 	    sizeof (struct mode_page);
7714 
7715 	/*
7716 	 * We can enable and disable acoustice management and
7717 	 * set the acoustic management level.
7718 	 */
7719 
7720 	/*
7721 	 * Set-up Internal SET FEATURES command(s)
7722 	 */
7723 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7724 	scmd->satacmd_addr_type = 0;
7725 	scmd->satacmd_device_reg = 0;
7726 	scmd->satacmd_status_reg = 0;
7727 	scmd->satacmd_error_reg = 0;
7728 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7729 	if (page->acoustic_manag_enable) {
7730 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7731 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7732 	} else {	/* disabling acoustic management */
7733 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7734 	}
7735 
7736 	/* Transfer command to HBA */
7737 	if (sata_hba_start(spx, rval) != 0)
7738 		/*
7739 		 * Pkt not accepted for execution.
7740 		 */
7741 		return (SATA_FAILURE);
7742 
7743 	/* Now process return */
7744 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7745 		sata_xlate_errors(spx);
7746 		return (SATA_FAILURE);
7747 	}
7748 
7749 	*dmod = 1;
7750 
7751 	return (SATA_SUCCESS);
7752 }
7753 
7754 /*
7755  * Process mode select power condition page 0x1a
7756  *
7757  * This function has to be called with a port mutex held.
7758  *
7759  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7760  *
7761  * Cannot be called in the interrupt context.
7762  */
7763 int
7764 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7765     mode_info_power_cond *page, int parmlen, int *pagelen,
7766     int *rval, int *dmod)
7767 {
7768 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7769 	sata_drive_info_t *sdinfo;
7770 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7771 	sata_id_t *sata_id;
7772 	struct scsi_extended_sense *sense;
7773 	uint8_t ata_count;
7774 	int i, len;
7775 
7776 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7777 	    &spx->txlt_sata_pkt->satapkt_device);
7778 	sata_id = &sdinfo->satadrv_id;
7779 	*dmod = 0;
7780 
7781 	len = sizeof (struct mode_info_power_cond);
7782 	len += sizeof (struct mode_page);
7783 
7784 	/* If parmlen is too short or the feature is not supported, drop it */
7785 	if ((len < parmlen) || (page->idle == 1) ||
7786 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7787 		*scsipkt->pkt_scbp = STATUS_CHECK;
7788 		sense = sata_arq_sense(spx);
7789 		sense->es_key = KEY_ILLEGAL_REQUEST;
7790 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7791 		*pagelen = parmlen;
7792 		*rval = TRAN_ACCEPT;
7793 		return (SATA_FAILURE);
7794 	}
7795 
7796 	*pagelen = len;
7797 
7798 	/*
7799 	 * Set-up Internal STANDBY command(s)
7800 	 */
7801 	if (page->standby == 0)
7802 		goto out;
7803 
7804 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7805 
7806 	scmd->satacmd_addr_type = 0;
7807 	scmd->satacmd_sec_count_lsb = ata_count;
7808 	scmd->satacmd_lba_low_lsb = 0;
7809 	scmd->satacmd_lba_mid_lsb = 0;
7810 	scmd->satacmd_lba_high_lsb = 0;
7811 	scmd->satacmd_features_reg = 0;
7812 	scmd->satacmd_device_reg = 0;
7813 	scmd->satacmd_status_reg = 0;
7814 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7815 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7816 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7817 
7818 	/* Transfer command to HBA */
7819 	if (sata_hba_start(spx, rval) != 0) {
7820 		return (SATA_FAILURE);
7821 	} else {
7822 		if ((scmd->satacmd_error_reg != 0) ||
7823 		    (spx->txlt_sata_pkt->satapkt_reason !=
7824 		    SATA_PKT_COMPLETED)) {
7825 			sata_xlate_errors(spx);
7826 			return (SATA_FAILURE);
7827 		}
7828 	}
7829 
7830 	for (i = 0; i < 4; i++) {
7831 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7832 	}
7833 out:
7834 	*dmod = 1;
7835 	return (SATA_SUCCESS);
7836 }
7837 
7838 /*
7839  * sata_build_lsense_page0() is used to create the
7840  * SCSI LOG SENSE page 0 (supported log pages)
7841  *
7842  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7843  * (supported log pages, self-test results, informational exceptions
7844  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7845  *
7846  * Takes a sata_drive_info t * and the address of a buffer
7847  * in which to create the page information.
7848  *
7849  * Returns the number of bytes valid in the buffer.
7850  */
7851 static	int
7852 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7853 {
7854 	struct log_parameter *lpp = (struct log_parameter *)buf;
7855 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7856 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7857 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7858 
7859 	lpp->param_code[0] = 0;
7860 	lpp->param_code[1] = 0;
7861 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7862 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7863 
7864 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7865 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7866 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7867 			++num_pages_supported;
7868 		}
7869 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7870 		++num_pages_supported;
7871 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7872 		++num_pages_supported;
7873 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7874 		++num_pages_supported;
7875 	}
7876 
7877 	lpp->param_len = num_pages_supported;
7878 
7879 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7880 	    num_pages_supported);
7881 }
7882 
7883 /*
7884  * sata_build_lsense_page_10() is used to create the
7885  * SCSI LOG SENSE page 0x10 (self-test results)
7886  *
7887  * Takes a sata_drive_info t * and the address of a buffer
7888  * in which to create the page information as well as a sata_hba_inst_t *.
7889  *
7890  * Returns the number of bytes valid in the buffer.
7891  *
7892  * Note: Self test and SMART data is accessible in device log pages.
7893  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
7894  * of data can be transferred by a single command), or by the General Purpose
7895  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
7896  * - approximately 33MB - can be transferred by a single command.
7897  * The SCT Command response (either error or command) is the same for both
7898  * the SMART and GPL methods of issuing commands.
7899  * This function uses READ LOG EXT command when drive supports LBA48, and
7900  * SMART READ command otherwise.
7901  *
7902  * Since above commands are executed in a synchronous mode, this function
7903  * should not be called in an interrupt context.
7904  */
7905 static	int
7906 sata_build_lsense_page_10(
7907 	sata_drive_info_t *sdinfo,
7908 	uint8_t *buf,
7909 	sata_hba_inst_t *sata_hba_inst)
7910 {
7911 	struct log_parameter *lpp = (struct log_parameter *)buf;
7912 	int rval;
7913 
7914 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
7915 		struct smart_ext_selftest_log *ext_selftest_log;
7916 
7917 		ext_selftest_log = kmem_zalloc(
7918 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
7919 
7920 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
7921 		    ext_selftest_log, 0);
7922 		if (rval == 0) {
7923 			int index, start_index;
7924 			struct smart_ext_selftest_log_entry *entry;
7925 			static const struct smart_ext_selftest_log_entry empty =
7926 			    {0};
7927 			uint16_t block_num;
7928 			int count;
7929 			boolean_t only_one_block = B_FALSE;
7930 
7931 			index = ext_selftest_log->
7932 			    smart_ext_selftest_log_index[0];
7933 			index |= ext_selftest_log->
7934 			    smart_ext_selftest_log_index[1] << 8;
7935 			if (index == 0)
7936 				goto out;
7937 
7938 			--index;	/* Correct for 0 origin */
7939 			start_index = index;	/* remember where we started */
7940 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7941 			if (block_num != 0) {
7942 				rval = sata_ext_smart_selftest_read_log(
7943 				    sata_hba_inst, sdinfo, ext_selftest_log,
7944 				    block_num);
7945 				if (rval != 0)
7946 					goto out;
7947 			}
7948 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7949 			entry =
7950 			    &ext_selftest_log->
7951 			    smart_ext_selftest_log_entries[index];
7952 
7953 			for (count = 1;
7954 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7955 			    ++count) {
7956 				uint8_t status;
7957 				uint8_t code;
7958 				uint8_t sense_key;
7959 				uint8_t add_sense_code;
7960 				uint8_t add_sense_code_qual;
7961 
7962 				/* If this is an unused entry, we are done */
7963 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
7964 					/* Broken firmware on some disks */
7965 					if (index + 1 ==
7966 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
7967 						--entry;
7968 						--index;
7969 						if (bcmp(entry, &empty,
7970 						    sizeof (empty)) == 0)
7971 							goto out;
7972 					} else
7973 						goto out;
7974 				}
7975 
7976 				if (only_one_block &&
7977 				    start_index == index)
7978 					goto out;
7979 
7980 				lpp->param_code[0] = 0;
7981 				lpp->param_code[1] = count;
7982 				lpp->param_ctrl_flags =
7983 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7984 				lpp->param_len =
7985 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7986 
7987 				status = entry->smart_ext_selftest_log_status;
7988 				status >>= 4;
7989 				switch (status) {
7990 				case 0:
7991 				default:
7992 					sense_key = KEY_NO_SENSE;
7993 					add_sense_code =
7994 					    SD_SCSI_ASC_NO_ADD_SENSE;
7995 					add_sense_code_qual = 0;
7996 					break;
7997 				case 1:
7998 					sense_key = KEY_ABORTED_COMMAND;
7999 					add_sense_code =
8000 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8001 					add_sense_code_qual = SCSI_COMPONENT_81;
8002 					break;
8003 				case 2:
8004 					sense_key = KEY_ABORTED_COMMAND;
8005 					add_sense_code =
8006 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8007 					add_sense_code_qual = SCSI_COMPONENT_82;
8008 					break;
8009 				case 3:
8010 					sense_key = KEY_ABORTED_COMMAND;
8011 					add_sense_code =
8012 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8013 					add_sense_code_qual = SCSI_COMPONENT_83;
8014 					break;
8015 				case 4:
8016 					sense_key = KEY_HARDWARE_ERROR;
8017 					add_sense_code =
8018 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8019 					add_sense_code_qual = SCSI_COMPONENT_84;
8020 					break;
8021 				case 5:
8022 					sense_key = KEY_HARDWARE_ERROR;
8023 					add_sense_code =
8024 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8025 					add_sense_code_qual = SCSI_COMPONENT_85;
8026 					break;
8027 				case 6:
8028 					sense_key = KEY_HARDWARE_ERROR;
8029 					add_sense_code =
8030 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8031 					add_sense_code_qual = SCSI_COMPONENT_86;
8032 					break;
8033 				case 7:
8034 					sense_key = KEY_MEDIUM_ERROR;
8035 					add_sense_code =
8036 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8037 					add_sense_code_qual = SCSI_COMPONENT_87;
8038 					break;
8039 				case 8:
8040 					sense_key = KEY_HARDWARE_ERROR;
8041 					add_sense_code =
8042 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8043 					add_sense_code_qual = SCSI_COMPONENT_88;
8044 					break;
8045 				}
8046 				code = 0;	/* unspecified */
8047 				status |= (code << 4);
8048 				lpp->param_values[0] = status;
8049 				lpp->param_values[1] = 0; /* unspecified */
8050 				lpp->param_values[2] = entry->
8051 				    smart_ext_selftest_log_timestamp[1];
8052 				lpp->param_values[3] = entry->
8053 				    smart_ext_selftest_log_timestamp[0];
8054 				if (status != 0) {
8055 					lpp->param_values[4] = 0;
8056 					lpp->param_values[5] = 0;
8057 					lpp->param_values[6] = entry->
8058 					    smart_ext_selftest_log_failing_lba
8059 					    [5];
8060 					lpp->param_values[7] = entry->
8061 					    smart_ext_selftest_log_failing_lba
8062 					    [4];
8063 					lpp->param_values[8] = entry->
8064 					    smart_ext_selftest_log_failing_lba
8065 					    [3];
8066 					lpp->param_values[9] = entry->
8067 					    smart_ext_selftest_log_failing_lba
8068 					    [2];
8069 					lpp->param_values[10] = entry->
8070 					    smart_ext_selftest_log_failing_lba
8071 					    [1];
8072 					lpp->param_values[11] = entry->
8073 					    smart_ext_selftest_log_failing_lba
8074 					    [0];
8075 				} else {	/* No bad block address */
8076 					lpp->param_values[4] = 0xff;
8077 					lpp->param_values[5] = 0xff;
8078 					lpp->param_values[6] = 0xff;
8079 					lpp->param_values[7] = 0xff;
8080 					lpp->param_values[8] = 0xff;
8081 					lpp->param_values[9] = 0xff;
8082 					lpp->param_values[10] = 0xff;
8083 					lpp->param_values[11] = 0xff;
8084 				}
8085 
8086 				lpp->param_values[12] = sense_key;
8087 				lpp->param_values[13] = add_sense_code;
8088 				lpp->param_values[14] = add_sense_code_qual;
8089 				lpp->param_values[15] = 0; /* undefined */
8090 
8091 				lpp = (struct log_parameter *)
8092 				    (((uint8_t *)lpp) +
8093 				    SCSI_LOG_PARAM_HDR_LEN +
8094 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8095 
8096 				--index;	/* Back up to previous entry */
8097 				if (index < 0) {
8098 					if (block_num > 0) {
8099 						--block_num;
8100 					} else {
8101 						struct read_log_ext_directory
8102 						    logdir;
8103 
8104 						rval =
8105 						    sata_read_log_ext_directory(
8106 						    sata_hba_inst, sdinfo,
8107 						    &logdir);
8108 						if (rval == -1)
8109 							goto out;
8110 						if ((logdir.read_log_ext_vers
8111 						    [0] == 0) &&
8112 						    (logdir.read_log_ext_vers
8113 						    [1] == 0))
8114 							goto out;
8115 						block_num =
8116 						    logdir.read_log_ext_nblks
8117 						    [EXT_SMART_SELFTEST_LOG_PAGE
8118 						    - 1][0];
8119 						block_num |= logdir.
8120 						    read_log_ext_nblks
8121 						    [EXT_SMART_SELFTEST_LOG_PAGE
8122 						    - 1][1] << 8;
8123 						--block_num;
8124 						only_one_block =
8125 						    (block_num == 0);
8126 					}
8127 					rval = sata_ext_smart_selftest_read_log(
8128 					    sata_hba_inst, sdinfo,
8129 					    ext_selftest_log, block_num);
8130 					if (rval != 0)
8131 						goto out;
8132 
8133 					index =
8134 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8135 					    1;
8136 				}
8137 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8138 				entry = &ext_selftest_log->
8139 				    smart_ext_selftest_log_entries[index];
8140 			}
8141 		}
8142 out:
8143 		kmem_free(ext_selftest_log,
8144 		    sizeof (struct smart_ext_selftest_log));
8145 	} else {
8146 		struct smart_selftest_log *selftest_log;
8147 
8148 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8149 		    KM_SLEEP);
8150 
8151 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8152 		    selftest_log);
8153 
8154 		if (rval == 0) {
8155 			int index;
8156 			int count;
8157 			struct smart_selftest_log_entry *entry;
8158 			static const struct smart_selftest_log_entry empty =
8159 			    { 0 };
8160 
8161 			index = selftest_log->smart_selftest_log_index;
8162 			if (index == 0)
8163 				goto done;
8164 			--index;	/* Correct for 0 origin */
8165 			entry = &selftest_log->
8166 			    smart_selftest_log_entries[index];
8167 			for (count = 1;
8168 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8169 			    ++count) {
8170 				uint8_t status;
8171 				uint8_t code;
8172 				uint8_t sense_key;
8173 				uint8_t add_sense_code;
8174 				uint8_t add_sense_code_qual;
8175 
8176 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8177 					goto done;
8178 
8179 				lpp->param_code[0] = 0;
8180 				lpp->param_code[1] = count;
8181 				lpp->param_ctrl_flags =
8182 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8183 				lpp->param_len =
8184 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8185 
8186 				status = entry->smart_selftest_log_status;
8187 				status >>= 4;
8188 				switch (status) {
8189 				case 0:
8190 				default:
8191 					sense_key = KEY_NO_SENSE;
8192 					add_sense_code =
8193 					    SD_SCSI_ASC_NO_ADD_SENSE;
8194 					break;
8195 				case 1:
8196 					sense_key = KEY_ABORTED_COMMAND;
8197 					add_sense_code =
8198 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8199 					add_sense_code_qual = SCSI_COMPONENT_81;
8200 					break;
8201 				case 2:
8202 					sense_key = KEY_ABORTED_COMMAND;
8203 					add_sense_code =
8204 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8205 					add_sense_code_qual = SCSI_COMPONENT_82;
8206 					break;
8207 				case 3:
8208 					sense_key = KEY_ABORTED_COMMAND;
8209 					add_sense_code =
8210 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8211 					add_sense_code_qual = SCSI_COMPONENT_83;
8212 					break;
8213 				case 4:
8214 					sense_key = KEY_HARDWARE_ERROR;
8215 					add_sense_code =
8216 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8217 					add_sense_code_qual = SCSI_COMPONENT_84;
8218 					break;
8219 				case 5:
8220 					sense_key = KEY_HARDWARE_ERROR;
8221 					add_sense_code =
8222 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8223 					add_sense_code_qual = SCSI_COMPONENT_85;
8224 					break;
8225 				case 6:
8226 					sense_key = KEY_HARDWARE_ERROR;
8227 					add_sense_code =
8228 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8229 					add_sense_code_qual = SCSI_COMPONENT_86;
8230 					break;
8231 				case 7:
8232 					sense_key = KEY_MEDIUM_ERROR;
8233 					add_sense_code =
8234 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8235 					add_sense_code_qual = SCSI_COMPONENT_87;
8236 					break;
8237 				case 8:
8238 					sense_key = KEY_HARDWARE_ERROR;
8239 					add_sense_code =
8240 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8241 					add_sense_code_qual = SCSI_COMPONENT_88;
8242 					break;
8243 				}
8244 				code = 0;	/* unspecified */
8245 				status |= (code << 4);
8246 				lpp->param_values[0] = status;
8247 				lpp->param_values[1] = 0; /* unspecified */
8248 				lpp->param_values[2] = entry->
8249 				    smart_selftest_log_timestamp[1];
8250 				lpp->param_values[3] = entry->
8251 				    smart_selftest_log_timestamp[0];
8252 				if (status != 0) {
8253 					lpp->param_values[4] = 0;
8254 					lpp->param_values[5] = 0;
8255 					lpp->param_values[6] = 0;
8256 					lpp->param_values[7] = 0;
8257 					lpp->param_values[8] = entry->
8258 					    smart_selftest_log_failing_lba[3];
8259 					lpp->param_values[9] = entry->
8260 					    smart_selftest_log_failing_lba[2];
8261 					lpp->param_values[10] = entry->
8262 					    smart_selftest_log_failing_lba[1];
8263 					lpp->param_values[11] = entry->
8264 					    smart_selftest_log_failing_lba[0];
8265 				} else {	/* No block address */
8266 					lpp->param_values[4] = 0xff;
8267 					lpp->param_values[5] = 0xff;
8268 					lpp->param_values[6] = 0xff;
8269 					lpp->param_values[7] = 0xff;
8270 					lpp->param_values[8] = 0xff;
8271 					lpp->param_values[9] = 0xff;
8272 					lpp->param_values[10] = 0xff;
8273 					lpp->param_values[11] = 0xff;
8274 				}
8275 				lpp->param_values[12] = sense_key;
8276 				lpp->param_values[13] = add_sense_code;
8277 				lpp->param_values[14] = add_sense_code_qual;
8278 				lpp->param_values[15] = 0; /* undefined */
8279 
8280 				lpp = (struct log_parameter *)
8281 				    (((uint8_t *)lpp) +
8282 				    SCSI_LOG_PARAM_HDR_LEN +
8283 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8284 				--index;	/* back up to previous entry */
8285 				if (index < 0) {
8286 					index =
8287 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8288 				}
8289 				entry = &selftest_log->
8290 				    smart_selftest_log_entries[index];
8291 			}
8292 		}
8293 done:
8294 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8295 	}
8296 
8297 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8298 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8299 }
8300 
8301 /*
8302  * sata_build_lsense_page_2f() is used to create the
8303  * SCSI LOG SENSE page 0x2f (informational exceptions)
8304  *
8305  * Takes a sata_drive_info t * and the address of a buffer
8306  * in which to create the page information as well as a sata_hba_inst_t *.
8307  *
8308  * Returns the number of bytes valid in the buffer.
8309  *
8310  * Because it invokes function(s) that send synchronously executed command
8311  * to the HBA, it cannot be called in the interrupt context.
8312  */
8313 static	int
8314 sata_build_lsense_page_2f(
8315 	sata_drive_info_t *sdinfo,
8316 	uint8_t *buf,
8317 	sata_hba_inst_t *sata_hba_inst)
8318 {
8319 	struct log_parameter *lpp = (struct log_parameter *)buf;
8320 	int rval;
8321 	uint8_t *smart_data;
8322 	uint8_t temp;
8323 	sata_id_t *sata_id;
8324 #define	SMART_NO_TEMP	0xff
8325 
8326 	lpp->param_code[0] = 0;
8327 	lpp->param_code[1] = 0;
8328 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8329 
8330 	/* Now get the SMART status w.r.t. threshold exceeded */
8331 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8332 	switch (rval) {
8333 	case 1:
8334 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8335 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8336 		break;
8337 	case 0:
8338 	case -1:	/* failed to get data */
8339 		lpp->param_values[0] = 0;	/* No failure predicted */
8340 		lpp->param_values[1] = 0;
8341 		break;
8342 #if defined(SATA_DEBUG)
8343 	default:
8344 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8345 		/* NOTREACHED */
8346 #endif
8347 	}
8348 
8349 	sata_id = &sdinfo->satadrv_id;
8350 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8351 		temp = SMART_NO_TEMP;
8352 	else {
8353 		/* Now get the temperature */
8354 		smart_data = kmem_zalloc(512, KM_SLEEP);
8355 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8356 		    SCT_STATUS_LOG_PAGE, 1);
8357 		if (rval == -1)
8358 			temp = SMART_NO_TEMP;
8359 		else {
8360 			temp = smart_data[200];
8361 			if (temp & 0x80) {
8362 				if (temp & 0x7f)
8363 					temp = 0;
8364 				else
8365 					temp = SMART_NO_TEMP;
8366 			}
8367 		}
8368 		kmem_free(smart_data, 512);
8369 	}
8370 
8371 	lpp->param_values[2] = temp;	/* most recent temperature */
8372 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8373 
8374 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8375 
8376 
8377 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8378 }
8379 
8380 /*
8381  * sata_build_lsense_page_30() is used to create the
8382  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8383  *
8384  * Takes a sata_drive_info t * and the address of a buffer
8385  * in which to create the page information as well as a sata_hba_inst_t *.
8386  *
8387  * Returns the number of bytes valid in the buffer.
8388  */
8389 static int
8390 sata_build_lsense_page_30(
8391 	sata_drive_info_t *sdinfo,
8392 	uint8_t *buf,
8393 	sata_hba_inst_t *sata_hba_inst)
8394 {
8395 	struct smart_data *smart_data = (struct smart_data *)buf;
8396 	int rval;
8397 
8398 	/* Now do the SMART READ DATA */
8399 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8400 	if (rval == -1)
8401 		return (0);
8402 
8403 	return (sizeof (struct smart_data));
8404 }
8405 
8406 /*
8407  * sata_build_lsense_page_0e() is used to create the
8408  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8409  *
8410  * Date of Manufacture (0x0001)
8411  *	YEAR = "0000"
8412  *	WEEK = "00"
8413  * Accounting Date (0x0002)
8414  *	6 ASCII space character(20h)
8415  * Specified cycle count over device lifetime
8416  *	VALUE - THRESH - the delta between max and min;
8417  * Accumulated start-stop cycles
8418  *	VALUE - WORST - the accumulated cycles;
8419  *
8420  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8421  *
8422  * Takes a sata_drive_info t * and the address of a buffer
8423  * in which to create the page information as well as a sata_hba_inst_t *.
8424  *
8425  * Returns the number of bytes valid in the buffer.
8426  */
8427 static	int
8428 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8429 	sata_pkt_txlate_t *spx)
8430 {
8431 	struct start_stop_cycle_counter_log *log_page;
8432 	int i, rval, index;
8433 	uint8_t smart_data[512], id, value, worst, thresh;
8434 	uint32_t max_count, cycles;
8435 
8436 	/* Now do the SMART READ DATA */
8437 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8438 	    (struct smart_data *)smart_data);
8439 	if (rval == -1)
8440 		return (0);
8441 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8442 		index = (i * 12) + 2;
8443 		id = smart_data[index];
8444 		if (id != SMART_START_STOP_COUNT_ID)
8445 			continue;
8446 		else {
8447 			thresh = smart_data[index + 2];
8448 			value = smart_data[index + 3];
8449 			worst = smart_data[index + 4];
8450 			break;
8451 		}
8452 	}
8453 	if (id != SMART_START_STOP_COUNT_ID)
8454 		return (0);
8455 	max_count = value - thresh;
8456 	cycles = value - worst;
8457 
8458 	log_page = (struct start_stop_cycle_counter_log *)buf;
8459 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8460 	log_page->code = 0x0e;
8461 	log_page->page_len_low = 0x24;
8462 
8463 	log_page->manufactor_date_low = 0x1;
8464 	log_page->param_1.fmt_link = 0x1; /* 01b */
8465 	log_page->param_len_1 = 0x06;
8466 	for (i = 0; i < 4; i++) {
8467 		log_page->year_manu[i] = 0x30;
8468 		if (i < 2)
8469 			log_page->week_manu[i] = 0x30;
8470 	}
8471 
8472 	log_page->account_date_low = 0x02;
8473 	log_page->param_2.fmt_link = 0x01; /* 01b */
8474 	log_page->param_len_2 = 0x06;
8475 	for (i = 0; i < 4; i++) {
8476 		log_page->year_account[i] = 0x20;
8477 		if (i < 2)
8478 			log_page->week_account[i] = 0x20;
8479 	}
8480 
8481 	log_page->lifetime_code_low = 0x03;
8482 	log_page->param_3.fmt_link = 0x03; /* 11b */
8483 	log_page->param_len_3 = 0x04;
8484 	/* VALUE - THRESH - the delta between max and min */
8485 	log_page->cycle_code_low = 0x04;
8486 	log_page->param_4.fmt_link = 0x03; /* 11b */
8487 	log_page->param_len_4 = 0x04;
8488 	/* WORST - THRESH - the distance from 'now' to min */
8489 
8490 	for (i = 0; i < 4; i++) {
8491 		log_page->cycle_lifetime[i] =
8492 		    (max_count >> (8 * (3 - i))) & 0xff;
8493 		log_page->cycle_accumulated[i] =
8494 		    (cycles >> (8 * (3 - i))) & 0xff;
8495 	}
8496 
8497 	return (sizeof (struct start_stop_cycle_counter_log));
8498 }
8499 
8500 /*
8501  * This function was used for build a ATA read verify sector command
8502  */
8503 static void
8504 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8505 {
8506 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8507 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8508 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8509 
8510 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8511 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8512 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8513 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8514 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8515 	scmd->satacmd_features_reg = 0;
8516 	scmd->satacmd_status_reg = 0;
8517 	scmd->satacmd_error_reg = 0;
8518 }
8519 
8520 /*
8521  * This function was used for building an ATA
8522  * command, and only command register need to
8523  * be defined, other register will be zero or na.
8524  */
8525 static void
8526 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8527 {
8528 	scmd->satacmd_addr_type = 0;
8529 	scmd->satacmd_cmd_reg = cmd;
8530 	scmd->satacmd_device_reg = 0;
8531 	scmd->satacmd_sec_count_lsb = 0;
8532 	scmd->satacmd_lba_low_lsb = 0;
8533 	scmd->satacmd_lba_mid_lsb = 0;
8534 	scmd->satacmd_lba_high_lsb = 0;
8535 	scmd->satacmd_features_reg = 0;
8536 	scmd->satacmd_status_reg = 0;
8537 	scmd->satacmd_error_reg = 0;
8538 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8539 }
8540 
8541 /*
8542  * This function was used for changing the standby
8543  * timer format from SCSI to ATA.
8544  */
8545 static uint8_t
8546 sata_get_standby_timer(uint8_t *timer)
8547 {
8548 	uint32_t i = 0, count = 0;
8549 	uint8_t ata_count;
8550 
8551 	for (i = 0; i < 4; i++) {
8552 		count = count << 8 | timer[i];
8553 	}
8554 
8555 	if (count == 0)
8556 		return (0);
8557 
8558 	if (count >= 1 && count <= 12000)
8559 		ata_count = (count -1) / 50 + 1;
8560 	else if (count > 12000 && count <= 12600)
8561 		ata_count = 0xfc;
8562 	else if (count > 12601 && count <= 12750)
8563 		ata_count = 0xff;
8564 	else if (count > 12750 && count <= 17999)
8565 		ata_count = 0xf1;
8566 	else if (count > 18000 && count <= 198000)
8567 		ata_count = count / 18000 + 240;
8568 	else
8569 		ata_count = 0xfd;
8570 	return (ata_count);
8571 }
8572 
8573 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8574 
8575 /*
8576  * Start command for ATAPI device.
8577  * This function processes scsi_pkt requests.
8578  * Now CD/DVD, tape and ATAPI disk devices are supported.
8579  * Most commands are packet without any translation into Packet Command.
8580  * Some may be trapped and executed as SATA commands (not clear which one).
8581  *
8582  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8583  * execution).
8584  * Returns other TRAN_XXXX codes if command is not accepted or completed
8585  * (see return values for sata_hba_start()).
8586  *
8587  * Note:
8588  * Inquiry cdb format differs between transport version 2 and 3.
8589  * However, the transport version 3 devices that were checked did not adhere
8590  * to the specification (ignored MSB of the allocation length). Therefore,
8591  * the transport version is not checked, but Inquiry allocation length is
8592  * truncated to 255 bytes if the original allocation length set-up by the
8593  * target driver is greater than 255 bytes.
8594  */
8595 static int
8596 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8597 {
8598 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8599 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8600 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8601 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8602 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8603 	    &spx->txlt_sata_pkt->satapkt_device);
8604 	int cport = SATA_TXLT_CPORT(spx);
8605 	int cdblen;
8606 	int rval, reason;
8607 	int synch;
8608 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8609 
8610 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8611 
8612 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
8613 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8614 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8615 		return (rval);
8616 	}
8617 
8618 	/*
8619 	 * ATAPI device executes some ATA commands in addition to those
8620 	 * commands sent via PACKET command. These ATA commands may be
8621 	 * executed by the regular SATA translation functions. None needs
8622 	 * to be captured now.
8623 	 *
8624 	 * Commands sent via PACKET command include:
8625 	 *	MMC command set for ATAPI CD/DVD device
8626 	 *	SSC command set for ATAPI TAPE device
8627 	 *	SBC command set for ATAPI disk device
8628 	 *
8629 	 */
8630 
8631 	/* Check the size of cdb */
8632 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8633 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
8634 		sata_log(NULL, CE_WARN,
8635 		    "sata: invalid ATAPI cdb length %d",
8636 		    scsipkt->pkt_cdblen);
8637 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8638 		return (TRAN_BADPKT);
8639 	}
8640 
8641 	SATAATAPITRACE(spx, cdblen);
8642 
8643 	/*
8644 	 * For non-read/write commands we need to
8645 	 * map buffer
8646 	 */
8647 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8648 	case SCMD_READ:
8649 	case SCMD_READ_G1:
8650 	case SCMD_READ_G5:
8651 	case SCMD_READ_G4:
8652 	case SCMD_WRITE:
8653 	case SCMD_WRITE_G1:
8654 	case SCMD_WRITE_G5:
8655 	case SCMD_WRITE_G4:
8656 		break;
8657 	default:
8658 		if (bp != NULL) {
8659 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8660 				bp_mapin(bp);
8661 		}
8662 		break;
8663 	}
8664 	/*
8665 	 * scmd->satacmd_flags.sata_data_direction default -
8666 	 * SATA_DIR_NODATA_XFER - is set by
8667 	 * sata_txlt_generic_pkt_info().
8668 	 */
8669 	if (scmd->satacmd_bp) {
8670 		if (scmd->satacmd_bp->b_flags & B_READ) {
8671 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8672 		} else {
8673 			scmd->satacmd_flags.sata_data_direction =
8674 			    SATA_DIR_WRITE;
8675 		}
8676 	}
8677 
8678 	/*
8679 	 * Set up ATAPI packet command.
8680 	 */
8681 
8682 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8683 
8684 	/* Copy cdb into sata_cmd */
8685 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8686 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8687 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8688 
8689 	/* See note in the command header */
8690 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8691 		if (scmd->satacmd_acdb[3] != 0)
8692 			scmd->satacmd_acdb[4] = 255;
8693 	}
8694 
8695 #ifdef SATA_DEBUG
8696 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8697 		uint8_t *p = scmd->satacmd_acdb;
8698 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8699 
8700 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8701 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8702 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8703 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8704 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8705 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8706 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8707 	}
8708 #endif
8709 
8710 	/*
8711 	 * Preset request sense data to NO SENSE.
8712 	 * If there is no way to get error information via Request Sense,
8713 	 * the packet request sense data would not have to be modified by HBA,
8714 	 * but it could be returned as is.
8715 	 */
8716 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8717 	sata_fixed_sense_data_preset(
8718 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8719 
8720 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8721 		/* Need callback function */
8722 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8723 		synch = FALSE;
8724 	} else
8725 		synch = TRUE;
8726 
8727 	/* Transfer command to HBA */
8728 	if (sata_hba_start(spx, &rval) != 0) {
8729 		/* Pkt not accepted for execution */
8730 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8731 		return (rval);
8732 	}
8733 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8734 	/*
8735 	 * If execution is non-synchronous,
8736 	 * a callback function will handle potential errors, translate
8737 	 * the response and will do a callback to a target driver.
8738 	 * If it was synchronous, use the same framework callback to check
8739 	 * an execution status.
8740 	 */
8741 	if (synch) {
8742 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8743 		    "synchronous execution status %x\n",
8744 		    spx->txlt_sata_pkt->satapkt_reason);
8745 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8746 	}
8747 	return (TRAN_ACCEPT);
8748 }
8749 
8750 
8751 /*
8752  * ATAPI Packet command completion.
8753  *
8754  * Failure of the command passed via Packet command are considered device
8755  * error. SATA HBA driver would have to retrieve error data (via Request
8756  * Sense command delivered via error retrieval sata packet) and copy it
8757  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8758  */
8759 static void
8760 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8761 {
8762 	sata_pkt_txlate_t *spx =
8763 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8764 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8765 	struct scsi_extended_sense *sense;
8766 	struct buf *bp;
8767 	int rval;
8768 
8769 #ifdef SATA_DEBUG
8770 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8771 #endif
8772 
8773 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8774 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8775 
8776 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8777 		/* Normal completion */
8778 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8779 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8780 		scsipkt->pkt_reason = CMD_CMPLT;
8781 		*scsipkt->pkt_scbp = STATUS_GOOD;
8782 		if (spx->txlt_tmp_buf != NULL) {
8783 			/* Temporary buffer was used */
8784 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8785 			if (bp->b_flags & B_READ) {
8786 				rval = ddi_dma_sync(
8787 				    spx->txlt_buf_dma_handle, 0, 0,
8788 				    DDI_DMA_SYNC_FORCPU);
8789 				ASSERT(rval == DDI_SUCCESS);
8790 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8791 				    bp->b_bcount);
8792 			}
8793 		}
8794 	} else {
8795 		/*
8796 		 * Something went wrong - analyze return
8797 		 */
8798 		*scsipkt->pkt_scbp = STATUS_CHECK;
8799 		sense = sata_arq_sense(spx);
8800 
8801 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8802 			/*
8803 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8804 			 * Under this condition ERR bit is set for ATA command,
8805 			 * and CHK bit set for ATAPI command.
8806 			 *
8807 			 * Please check st_intr & sdintr about how pkt_reason
8808 			 * is used.
8809 			 */
8810 			scsipkt->pkt_reason = CMD_CMPLT;
8811 
8812 			/*
8813 			 * We may not have ARQ data if there was a double
8814 			 * error. But sense data in sata packet was pre-set
8815 			 * with NO SENSE so it is valid even if HBA could
8816 			 * not retrieve a real sense data.
8817 			 * Just copy this sense data into scsi pkt sense area.
8818 			 */
8819 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8820 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8821 #ifdef SATA_DEBUG
8822 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8823 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8824 				    "sata_txlt_atapi_completion: %02x\n"
8825 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8826 				    "          %02x %02x %02x %02x %02x %02x "
8827 				    "          %02x %02x %02x %02x %02x %02x\n",
8828 				    scsipkt->pkt_reason,
8829 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8830 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8831 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8832 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8833 				    rqsp[16], rqsp[17]);
8834 			}
8835 #endif
8836 		} else {
8837 			switch (sata_pkt->satapkt_reason) {
8838 			case SATA_PKT_PORT_ERROR:
8839 				/*
8840 				 * We have no device data.
8841 				 */
8842 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8843 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8844 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8845 				    STATE_GOT_STATUS);
8846 				sense->es_key = KEY_HARDWARE_ERROR;
8847 				break;
8848 
8849 			case SATA_PKT_TIMEOUT:
8850 				scsipkt->pkt_reason = CMD_TIMEOUT;
8851 				scsipkt->pkt_statistics |=
8852 				    STAT_TIMEOUT | STAT_DEV_RESET;
8853 				/*
8854 				 * Need to check if HARDWARE_ERROR/
8855 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8856 				 * appropriate.
8857 				 */
8858 				break;
8859 
8860 			case SATA_PKT_ABORTED:
8861 				scsipkt->pkt_reason = CMD_ABORTED;
8862 				scsipkt->pkt_statistics |= STAT_ABORTED;
8863 				/* Should we set key COMMAND_ABPRTED? */
8864 				break;
8865 
8866 			case SATA_PKT_RESET:
8867 				scsipkt->pkt_reason = CMD_RESET;
8868 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
8869 				/*
8870 				 * May be we should set Unit Attention /
8871 				 * Reset. Perhaps the same should be
8872 				 * returned for disks....
8873 				 */
8874 				sense->es_key = KEY_UNIT_ATTENTION;
8875 				sense->es_add_code = SD_SCSI_ASC_RESET;
8876 				break;
8877 
8878 			default:
8879 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8880 				    "sata_txlt_atapi_completion: "
8881 				    "invalid packet completion reason"));
8882 				scsipkt->pkt_reason = CMD_TRAN_ERR;
8883 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8884 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8885 				    STATE_GOT_STATUS);
8886 				break;
8887 			}
8888 		}
8889 	}
8890 
8891 	SATAATAPITRACE(spx, 0);
8892 
8893 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
8894 	    scsipkt->pkt_comp != NULL) {
8895 		/* scsi callback required */
8896 		(*scsipkt->pkt_comp)(scsipkt);
8897 	}
8898 }
8899 
8900 /*
8901  * Set up error retrieval sata command for ATAPI Packet Command error data
8902  * recovery.
8903  *
8904  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
8905  * returns SATA_FAILURE otherwise.
8906  */
8907 
8908 static int
8909 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
8910 {
8911 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
8912 	sata_cmd_t *scmd;
8913 	struct buf *bp;
8914 
8915 	/*
8916 	 * Allocate dma-able buffer error data.
8917 	 * Buffer allocation will take care of buffer alignment and other DMA
8918 	 * attributes.
8919 	 */
8920 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
8921 	if (bp == NULL) {
8922 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
8923 		    "sata_get_err_retrieval_pkt: "
8924 		    "cannot allocate buffer for error data", NULL);
8925 		return (SATA_FAILURE);
8926 	}
8927 	bp_mapin(bp); /* make data buffer accessible */
8928 
8929 	/* Operation modes are up to the caller */
8930 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8931 
8932 	/* Synchronous mode, no callback - may be changed by the caller */
8933 	spkt->satapkt_comp = NULL;
8934 	spkt->satapkt_time = sata_default_pkt_time;
8935 
8936 	scmd = &spkt->satapkt_cmd;
8937 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8938 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8939 
8940 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8941 
8942 	/*
8943 	 * Set-up acdb. Request Sense CDB (packet command content) is
8944 	 * not in DMA-able buffer. Its handling is HBA-specific (how
8945 	 * it is transfered into packet FIS).
8946 	 */
8947 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8948 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
8949 	/* Following zeroing of pad bytes may not be necessary */
8950 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
8951 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
8952 
8953 	/*
8954 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
8955 	 * before accessing it. Handle is in usual place in translate struct.
8956 	 */
8957 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
8958 
8959 	/*
8960 	 * Preset request sense data to NO SENSE.
8961 	 * Here it is redundant, only for a symetry with scsi-originated
8962 	 * packets. It should not be used for anything but debugging.
8963 	 */
8964 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8965 	sata_fixed_sense_data_preset(
8966 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8967 
8968 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8969 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8970 
8971 	return (SATA_SUCCESS);
8972 }
8973 
8974 /*
8975  * Set-up ATAPI packet command.
8976  * Data transfer direction has to be set-up in sata_cmd structure prior to
8977  * calling this function.
8978  *
8979  * Returns void
8980  */
8981 
8982 static void
8983 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
8984 {
8985 	scmd->satacmd_addr_type = 0;		/* N/A */
8986 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
8987 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8988 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
8989 	scmd->satacmd_lba_high_lsb =
8990 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
8991 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
8992 
8993 	/*
8994 	 * We want all data to be transfered via DMA.
8995 	 * But specify it only if drive supports DMA and DMA mode is
8996 	 * selected - some drives are sensitive about it.
8997 	 * Hopefully it wil work for all drives....
8998 	 */
8999 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9000 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9001 
9002 	/*
9003 	 * Features register requires special care for devices that use
9004 	 * Serial ATA bridge - they need an explicit specification of
9005 	 * the data transfer direction for Packet DMA commands.
9006 	 * Setting this bit is harmless if DMA is not used.
9007 	 *
9008 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9009 	 * spec they follow.
9010 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9011 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9012 	 * ATA/ATAPI-7 support is explicitly indicated.
9013 	 */
9014 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9015 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9016 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9017 		/*
9018 		 * Specification of major version is valid and version 7
9019 		 * is supported. It does automatically imply that all
9020 		 * spec features are supported. For now, we assume that
9021 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9022 		 */
9023 		if ((sdinfo->satadrv_id.ai_dirdma &
9024 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9025 			if (scmd->satacmd_flags.sata_data_direction ==
9026 			    SATA_DIR_READ)
9027 			scmd->satacmd_features_reg |=
9028 			    SATA_ATAPI_F_DATA_DIR_READ;
9029 		}
9030 	}
9031 }
9032 
9033 
9034 #ifdef SATA_DEBUG
9035 
9036 /* Display 18 bytes of Inquiry data */
9037 static void
9038 sata_show_inqry_data(uint8_t *buf)
9039 {
9040 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9041 	uint8_t *p;
9042 
9043 	cmn_err(CE_NOTE, "Inquiry data:");
9044 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9045 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9046 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9047 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9048 	    SATA_ATAPI_TRANS_VERSION(inq));
9049 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9050 	    inq->inq_rdf, inq->inq_aenc);
9051 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9052 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9053 	p = (uint8_t *)inq->inq_vid;
9054 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9055 	    "%02x %02x %02x %02x",
9056 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9057 	p = (uint8_t *)inq->inq_vid;
9058 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9059 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9060 
9061 	p = (uint8_t *)inq->inq_pid;
9062 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9063 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9064 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9065 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9066 	p = (uint8_t *)inq->inq_pid;
9067 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9068 	    "%c %c %c %c %c %c %c %c",
9069 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9070 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9071 
9072 	p = (uint8_t *)inq->inq_revision;
9073 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9074 	    p[0], p[1], p[2], p[3]);
9075 	p = (uint8_t *)inq->inq_revision;
9076 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9077 	    p[0], p[1], p[2], p[3]);
9078 
9079 }
9080 
9081 
9082 static void
9083 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9084 {
9085 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9086 
9087 	if (scsi_pkt == NULL)
9088 		return;
9089 	if (count != 0) {
9090 		/* saving cdb */
9091 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9092 		    SATA_ATAPI_MAX_CDB_LEN);
9093 		bcopy(scsi_pkt->pkt_cdbp,
9094 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9095 	} else {
9096 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9097 		    sts_sensedata,
9098 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9099 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9100 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9101 		    scsi_pkt->pkt_reason;
9102 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9103 		    spx->txlt_sata_pkt->satapkt_reason;
9104 
9105 		if (++sata_atapi_trace_index >= 64)
9106 			sata_atapi_trace_index = 0;
9107 	}
9108 }
9109 
9110 #endif
9111 
9112 /*
9113  * Fetch inquiry data from ATAPI device
9114  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9115  *
9116  * Note:
9117  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9118  * where the caller expects to see the inquiry data.
9119  *
9120  */
9121 
9122 static int
9123 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9124     sata_address_t *saddr, struct scsi_inquiry *inq)
9125 {
9126 	sata_pkt_txlate_t *spx;
9127 	sata_pkt_t *spkt;
9128 	struct buf *bp;
9129 	sata_drive_info_t *sdinfo;
9130 	sata_cmd_t *scmd;
9131 	int rval;
9132 	uint8_t *rqsp;
9133 #ifdef SATA_DEBUG
9134 	char msg_buf[MAXPATHLEN];
9135 #endif
9136 
9137 	ASSERT(sata_hba != NULL);
9138 
9139 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9140 	spx->txlt_sata_hba_inst = sata_hba;
9141 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9142 	spkt = sata_pkt_alloc(spx, NULL);
9143 	if (spkt == NULL) {
9144 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9145 		return (SATA_FAILURE);
9146 	}
9147 	/* address is needed now */
9148 	spkt->satapkt_device.satadev_addr = *saddr;
9149 
9150 	/* scsi_inquiry size buffer */
9151 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9152 	if (bp == NULL) {
9153 		sata_pkt_free(spx);
9154 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9155 		SATA_LOG_D((sata_hba, CE_WARN,
9156 		    "sata_get_atapi_inquiry_data: "
9157 		    "cannot allocate data buffer"));
9158 		return (SATA_FAILURE);
9159 	}
9160 	bp_mapin(bp); /* make data buffer accessible */
9161 
9162 	scmd = &spkt->satapkt_cmd;
9163 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9164 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9165 
9166 	/* Use synchronous mode */
9167 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9168 	spkt->satapkt_comp = NULL;
9169 	spkt->satapkt_time = sata_default_pkt_time;
9170 
9171 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9172 
9173 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9174 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9175 
9176 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9177 	sdinfo = sata_get_device_info(sata_hba,
9178 	    &spx->txlt_sata_pkt->satapkt_device);
9179 	if (sdinfo == NULL) {
9180 		/* we have to be carefull about the disapearing device */
9181 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9182 		rval = SATA_FAILURE;
9183 		goto cleanup;
9184 	}
9185 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9186 
9187 	/*
9188 	 * Set-up acdb. This works for atapi transport version 2 and later.
9189 	 */
9190 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9191 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9192 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9193 	scmd->satacmd_acdb[1] = 0x00;
9194 	scmd->satacmd_acdb[2] = 0x00;
9195 	scmd->satacmd_acdb[3] = 0x00;
9196 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9197 	scmd->satacmd_acdb[5] = 0x00;
9198 
9199 	sata_fixed_sense_data_preset(
9200 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9201 
9202 	/* Transfer command to HBA */
9203 	if (sata_hba_start(spx, &rval) != 0) {
9204 		/* Pkt not accepted for execution */
9205 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9206 		    "sata_get_atapi_inquiry_data: "
9207 		    "Packet not accepted for execution - ret: %02x", rval);
9208 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9209 		rval = SATA_FAILURE;
9210 		goto cleanup;
9211 	}
9212 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9213 
9214 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9215 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9216 		    "sata_get_atapi_inquiry_data: "
9217 		    "Packet completed successfully - ret: %02x", rval);
9218 		if (spx->txlt_buf_dma_handle != NULL) {
9219 			/*
9220 			 * Sync buffer. Handle is in usual place in translate
9221 			 * struct.
9222 			 */
9223 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9224 			    DDI_DMA_SYNC_FORCPU);
9225 			ASSERT(rval == DDI_SUCCESS);
9226 		}
9227 		/*
9228 		 * Normal completion - copy data into caller's buffer
9229 		 */
9230 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9231 		    sizeof (struct scsi_inquiry));
9232 #ifdef SATA_DEBUG
9233 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9234 			sata_show_inqry_data((uint8_t *)inq);
9235 		}
9236 #endif
9237 		rval = SATA_SUCCESS;
9238 	} else {
9239 		/*
9240 		 * Something went wrong - analyze return - check rqsense data
9241 		 */
9242 		rval = SATA_FAILURE;
9243 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9244 			/*
9245 			 * ARQ data hopefull show something other than NO SENSE
9246 			 */
9247 			rqsp = scmd->satacmd_rqsense;
9248 #ifdef SATA_DEBUG
9249 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9250 				msg_buf[0] = '\0';
9251 				(void) snprintf(msg_buf, MAXPATHLEN,
9252 				    "ATAPI packet completion reason: %02x\n"
9253 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9254 				    "          %02x %02x %02x %02x %02x %02x\n"
9255 				    "          %02x %02x %02x %02x %02x %02x",
9256 				    spkt->satapkt_reason,
9257 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9258 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9259 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9260 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9261 				    rqsp[16], rqsp[17]);
9262 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9263 				    "%s", msg_buf);
9264 			}
9265 #endif
9266 		} else {
9267 			switch (spkt->satapkt_reason) {
9268 			case SATA_PKT_PORT_ERROR:
9269 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9270 				    "sata_get_atapi_inquiry_data: "
9271 				    "packet reason: port error", NULL);
9272 				break;
9273 
9274 			case SATA_PKT_TIMEOUT:
9275 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9276 				    "sata_get_atapi_inquiry_data: "
9277 				    "packet reason: timeout", NULL);
9278 				break;
9279 
9280 			case SATA_PKT_ABORTED:
9281 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9282 				    "sata_get_atapi_inquiry_data: "
9283 				    "packet reason: aborted", NULL);
9284 				break;
9285 
9286 			case SATA_PKT_RESET:
9287 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9288 				    "sata_get_atapi_inquiry_data: "
9289 				    "packet reason: reset\n", NULL);
9290 				break;
9291 			default:
9292 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9293 				    "sata_get_atapi_inquiry_data: "
9294 				    "invalid packet reason: %02x\n",
9295 				    spkt->satapkt_reason);
9296 				break;
9297 			}
9298 		}
9299 	}
9300 cleanup:
9301 	sata_free_local_buffer(spx);
9302 	sata_pkt_free(spx);
9303 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9304 	return (rval);
9305 }
9306 
9307 
9308 
9309 
9310 
9311 #if 0
9312 #ifdef SATA_DEBUG
9313 
9314 /*
9315  * Test ATAPI packet command.
9316  * Single threaded test: send packet command in synch mode, process completion
9317  *
9318  */
9319 static void
9320 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9321 {
9322 	sata_pkt_txlate_t *spx;
9323 	sata_pkt_t *spkt;
9324 	struct buf *bp;
9325 	sata_device_t sata_device;
9326 	sata_drive_info_t *sdinfo;
9327 	sata_cmd_t *scmd;
9328 	int rval;
9329 	uint8_t *rqsp;
9330 
9331 	ASSERT(sata_hba_inst != NULL);
9332 	sata_device.satadev_addr.cport = cport;
9333 	sata_device.satadev_addr.pmport = 0;
9334 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9335 	sata_device.satadev_rev = SATA_DEVICE_REV;
9336 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9337 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9338 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9339 	if (sdinfo == NULL) {
9340 		sata_log(sata_hba_inst, CE_WARN,
9341 		    "sata_test_atapi_packet_command: "
9342 		    "no device info for cport %d",
9343 		    sata_device.satadev_addr.cport);
9344 		return;
9345 	}
9346 
9347 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9348 	spx->txlt_sata_hba_inst = sata_hba_inst;
9349 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9350 	spkt = sata_pkt_alloc(spx, NULL);
9351 	if (spkt == NULL) {
9352 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9353 		return;
9354 	}
9355 	/* address is needed now */
9356 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9357 
9358 	/* 1024k buffer */
9359 	bp = sata_alloc_local_buffer(spx, 1024);
9360 	if (bp == NULL) {
9361 		sata_pkt_free(spx);
9362 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9363 		sata_log(sata_hba_inst, CE_WARN,
9364 		    "sata_test_atapi_packet_command: "
9365 		    "cannot allocate data buffer");
9366 		return;
9367 	}
9368 	bp_mapin(bp); /* make data buffer accessible */
9369 
9370 	scmd = &spkt->satapkt_cmd;
9371 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9372 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9373 
9374 	/* Use synchronous mode */
9375 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9376 
9377 	/* Synchronous mode, no callback - may be changed by the caller */
9378 	spkt->satapkt_comp = NULL;
9379 	spkt->satapkt_time = sata_default_pkt_time;
9380 
9381 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9382 
9383 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9384 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9385 
9386 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9387 
9388 	/* Set-up acdb. */
9389 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9390 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9391 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9392 	scmd->satacmd_acdb[1] = 0x00;
9393 	scmd->satacmd_acdb[2] = 0x00;
9394 	scmd->satacmd_acdb[3] = 0x00;
9395 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9396 	scmd->satacmd_acdb[5] = 0x00;
9397 
9398 	sata_fixed_sense_data_preset(
9399 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9400 
9401 	/* Transfer command to HBA */
9402 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9403 	if (sata_hba_start(spx, &rval) != 0) {
9404 		/* Pkt not accepted for execution */
9405 		sata_log(sata_hba_inst, CE_WARN,
9406 		    "sata_test_atapi_packet_command: "
9407 		    "Packet not accepted for execution - ret: %02x", rval);
9408 		mutex_exit(
9409 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9410 		goto cleanup;
9411 	}
9412 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9413 
9414 	if (spx->txlt_buf_dma_handle != NULL) {
9415 		/*
9416 		 * Sync buffer. Handle is in usual place in translate struct.
9417 		 */
9418 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9419 		    DDI_DMA_SYNC_FORCPU);
9420 		ASSERT(rval == DDI_SUCCESS);
9421 	}
9422 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9423 		sata_log(sata_hba_inst, CE_WARN,
9424 		    "sata_test_atapi_packet_command: "
9425 		    "Packet completed successfully");
9426 		/*
9427 		 * Normal completion - show inquiry data
9428 		 */
9429 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9430 	} else {
9431 		/*
9432 		 * Something went wrong - analyze return - check rqsense data
9433 		 */
9434 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9435 			/*
9436 			 * ARQ data hopefull show something other than NO SENSE
9437 			 */
9438 			rqsp = scmd->satacmd_rqsense;
9439 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9440 			    "ATAPI packet completion reason: %02x\n"
9441 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9442 			    "          %02x %02x %02x %02x %02x %02x "
9443 			    "          %02x %02x %02x %02x %02x %02x\n",
9444 			    spkt->satapkt_reason,
9445 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9446 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9447 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9448 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9449 			    rqsp[16], rqsp[17]);
9450 		} else {
9451 			switch (spkt->satapkt_reason) {
9452 			case SATA_PKT_PORT_ERROR:
9453 				sata_log(sata_hba_inst, CE_WARN,
9454 				    "sata_test_atapi_packet_command: "
9455 				    "packet reason: port error\n");
9456 				break;
9457 
9458 			case SATA_PKT_TIMEOUT:
9459 				sata_log(sata_hba_inst, CE_WARN,
9460 				    "sata_test_atapi_packet_command: "
9461 				    "packet reason: timeout\n");
9462 				break;
9463 
9464 			case SATA_PKT_ABORTED:
9465 				sata_log(sata_hba_inst, CE_WARN,
9466 				    "sata_test_atapi_packet_command: "
9467 				    "packet reason: aborted\n");
9468 				break;
9469 
9470 			case SATA_PKT_RESET:
9471 				sata_log(sata_hba_inst, CE_WARN,
9472 				    "sata_test_atapi_packet_command: "
9473 				    "packet reason: reset\n");
9474 				break;
9475 			default:
9476 				sata_log(sata_hba_inst, CE_WARN,
9477 				    "sata_test_atapi_packet_command: "
9478 				    "invalid packet reason: %02x\n",
9479 				    spkt->satapkt_reason);
9480 				break;
9481 			}
9482 		}
9483 	}
9484 cleanup:
9485 	sata_free_local_buffer(spx);
9486 	sata_pkt_free(spx);
9487 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9488 }
9489 
9490 #endif /* SATA_DEBUG */
9491 #endif /* 1 */
9492 
9493 
9494 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9495 
9496 /*
9497  * Validate sata_tran info
9498  * SATA_FAILURE returns if structure is inconsistent or structure revision
9499  * does not match one used by the framework.
9500  *
9501  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9502  * required function pointers.
9503  * Returns SATA_FAILURE otherwise.
9504  */
9505 static int
9506 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9507 {
9508 	/*
9509 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9510 	 * of the SATA interface.
9511 	 */
9512 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9513 		sata_log(NULL, CE_WARN,
9514 		    "sata: invalid sata_hba_tran version %d for driver %s",
9515 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9516 		return (SATA_FAILURE);
9517 	}
9518 
9519 	if (dip != sata_tran->sata_tran_hba_dip) {
9520 		SATA_LOG_D((NULL, CE_WARN,
9521 		    "sata: inconsistent sata_tran_hba_dip "
9522 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9523 		return (SATA_FAILURE);
9524 	}
9525 
9526 	if (sata_tran->sata_tran_probe_port == NULL ||
9527 	    sata_tran->sata_tran_start == NULL ||
9528 	    sata_tran->sata_tran_abort == NULL ||
9529 	    sata_tran->sata_tran_reset_dport == NULL ||
9530 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9531 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9532 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9533 	    NULL) {
9534 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9535 		    "required functions"));
9536 	}
9537 	return (SATA_SUCCESS);
9538 }
9539 
9540 /*
9541  * Remove HBA instance from sata_hba_list.
9542  */
9543 static void
9544 sata_remove_hba_instance(dev_info_t *dip)
9545 {
9546 	sata_hba_inst_t	*sata_hba_inst;
9547 
9548 	mutex_enter(&sata_mutex);
9549 	for (sata_hba_inst = sata_hba_list;
9550 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9551 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9552 		if (sata_hba_inst->satahba_dip == dip)
9553 			break;
9554 	}
9555 
9556 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9557 #ifdef SATA_DEBUG
9558 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9559 		    "unknown HBA instance\n");
9560 #endif
9561 		ASSERT(FALSE);
9562 	}
9563 	if (sata_hba_inst == sata_hba_list) {
9564 		sata_hba_list = sata_hba_inst->satahba_next;
9565 		if (sata_hba_list) {
9566 			sata_hba_list->satahba_prev =
9567 			    (struct sata_hba_inst *)NULL;
9568 		}
9569 		if (sata_hba_inst == sata_hba_list_tail) {
9570 			sata_hba_list_tail = NULL;
9571 		}
9572 	} else if (sata_hba_inst == sata_hba_list_tail) {
9573 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9574 		if (sata_hba_list_tail) {
9575 			sata_hba_list_tail->satahba_next =
9576 			    (struct sata_hba_inst *)NULL;
9577 		}
9578 	} else {
9579 		sata_hba_inst->satahba_prev->satahba_next =
9580 		    sata_hba_inst->satahba_next;
9581 		sata_hba_inst->satahba_next->satahba_prev =
9582 		    sata_hba_inst->satahba_prev;
9583 	}
9584 	mutex_exit(&sata_mutex);
9585 }
9586 
9587 /*
9588  * Probe all SATA ports of the specified HBA instance.
9589  * The assumption is that there are no target and attachment point minor nodes
9590  * created by the boot subsystems, so we do not need to prune device tree.
9591  *
9592  * This function is called only from sata_hba_attach(). It does not have to
9593  * be protected by controller mutex, because the hba_attached flag is not set
9594  * yet and no one would be touching this HBA instance other than this thread.
9595  * Determines if port is active and what type of the device is attached
9596  * (if any). Allocates necessary structures for each port.
9597  *
9598  * An AP (Attachement Point) node is created for each SATA device port even
9599  * when there is no device attached.
9600  */
9601 
9602 static 	void
9603 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9604 {
9605 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9606 	int			ncport;
9607 	sata_cport_info_t 	*cportinfo;
9608 	sata_drive_info_t	*drive;
9609 	sata_device_t		sata_device;
9610 	int			rval;
9611 	dev_t			minor_number;
9612 	char			name[16];
9613 	clock_t			start_time, cur_time;
9614 
9615 	/*
9616 	 * Probe controller ports first, to find port status and
9617 	 * any port multiplier attached.
9618 	 */
9619 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9620 		/* allocate cport structure */
9621 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9622 		ASSERT(cportinfo != NULL);
9623 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9624 
9625 		mutex_enter(&cportinfo->cport_mutex);
9626 
9627 		cportinfo->cport_addr.cport = ncport;
9628 		cportinfo->cport_addr.pmport = 0;
9629 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9630 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9631 		cportinfo->cport_state |= SATA_STATE_PROBING;
9632 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9633 
9634 		/*
9635 		 * Regardless if a port is usable or not, create
9636 		 * an attachment point
9637 		 */
9638 		mutex_exit(&cportinfo->cport_mutex);
9639 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9640 		    ncport, 0, SATA_ADDR_CPORT);
9641 		(void) sprintf(name, "%d", ncport);
9642 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9643 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9644 		    DDI_SUCCESS) {
9645 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9646 			    "cannot create SATA attachment point for port %d",
9647 			    ncport);
9648 		}
9649 
9650 		/* Probe port */
9651 		start_time = ddi_get_lbolt();
9652 	reprobe_cport:
9653 		sata_device.satadev_addr.cport = ncport;
9654 		sata_device.satadev_addr.pmport = 0;
9655 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9656 		sata_device.satadev_rev = SATA_DEVICE_REV;
9657 
9658 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9659 		    (dip, &sata_device);
9660 
9661 		mutex_enter(&cportinfo->cport_mutex);
9662 		cportinfo->cport_scr = sata_device.satadev_scr;
9663 		if (rval != SATA_SUCCESS) {
9664 			/* Something went wrong? Fail the port */
9665 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9666 			mutex_exit(&cportinfo->cport_mutex);
9667 			continue;
9668 		}
9669 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9670 		cportinfo->cport_state |= SATA_STATE_PROBED;
9671 		cportinfo->cport_dev_type = sata_device.satadev_type;
9672 
9673 		cportinfo->cport_state |= SATA_STATE_READY;
9674 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9675 			mutex_exit(&cportinfo->cport_mutex);
9676 			continue;
9677 		}
9678 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9679 			/*
9680 			 * There is some device attached.
9681 			 * Allocate device info structure
9682 			 */
9683 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9684 				mutex_exit(&cportinfo->cport_mutex);
9685 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9686 				    kmem_zalloc(sizeof (sata_drive_info_t),
9687 				    KM_SLEEP);
9688 				mutex_enter(&cportinfo->cport_mutex);
9689 			}
9690 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9691 			drive->satadrv_addr = cportinfo->cport_addr;
9692 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9693 			drive->satadrv_type = cportinfo->cport_dev_type;
9694 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9695 
9696 			mutex_exit(&cportinfo->cport_mutex);
9697 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9698 			    SATA_SUCCESS) {
9699 				/*
9700 				 * Plugged device was not correctly identified.
9701 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9702 				 */
9703 				cur_time = ddi_get_lbolt();
9704 				if ((cur_time - start_time) <
9705 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9706 					/* sleep for a while */
9707 					delay(drv_usectohz(
9708 					    SATA_DEV_RETRY_DLY));
9709 					goto reprobe_cport;
9710 				}
9711 			}
9712 		} else { /* SATA_DTYPE_PMULT */
9713 			mutex_exit(&cportinfo->cport_mutex);
9714 
9715 			/* Allocate sata_pmult_info and sata_pmport_info */
9716 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9717 			    SATA_SUCCESS)
9718 				continue;
9719 
9720 			/* Log the information of the port multiplier */
9721 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9722 
9723 			/* Probe its pmports */
9724 			sata_probe_pmports(sata_hba_inst, ncport);
9725 		}
9726 	}
9727 }
9728 
9729 /*
9730  * Probe all device ports behind a port multiplier.
9731  *
9732  * PMult-related structure should be allocated before by sata_alloc_pmult().
9733  *
9734  * NOTE1: Only called from sata_probe_ports()
9735  * NOTE2: No mutex should be hold.
9736  */
9737 static void
9738 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9739 {
9740 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9741 	sata_pmult_info_t	*pmultinfo = NULL;
9742 	sata_pmport_info_t 	*pmportinfo = NULL;
9743 	sata_drive_info_t	*drive = NULL;
9744 	sata_device_t		sata_device;
9745 
9746 	clock_t			start_time, cur_time;
9747 	int			npmport;
9748 	int			rval;
9749 
9750 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9751 
9752 	/* Probe Port Multiplier ports */
9753 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9754 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9755 		start_time = ddi_get_lbolt();
9756 reprobe_pmport:
9757 		sata_device.satadev_addr.cport = ncport;
9758 		sata_device.satadev_addr.pmport = npmport;
9759 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9760 		sata_device.satadev_rev = SATA_DEVICE_REV;
9761 
9762 		/* Let HBA driver probe it. */
9763 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9764 		    (dip, &sata_device);
9765 		mutex_enter(&pmportinfo->pmport_mutex);
9766 
9767 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9768 
9769 		if (rval != SATA_SUCCESS) {
9770 			pmportinfo->pmport_state =
9771 			    SATA_PSTATE_FAILED;
9772 			mutex_exit(&pmportinfo->pmport_mutex);
9773 			continue;
9774 		}
9775 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9776 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9777 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9778 
9779 		pmportinfo->pmport_state |= SATA_STATE_READY;
9780 		if (pmportinfo->pmport_dev_type ==
9781 		    SATA_DTYPE_NONE) {
9782 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9783 			    "no device found at port %d:%d", ncport, npmport);
9784 			mutex_exit(&pmportinfo->pmport_mutex);
9785 			continue;
9786 		}
9787 		/* Port multipliers cannot be chained */
9788 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9789 		/*
9790 		 * There is something attached to Port
9791 		 * Multiplier device port
9792 		 * Allocate device info structure
9793 		 */
9794 		if (pmportinfo->pmport_sata_drive == NULL) {
9795 			mutex_exit(&pmportinfo->pmport_mutex);
9796 			pmportinfo->pmport_sata_drive =
9797 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9798 			mutex_enter(&pmportinfo->pmport_mutex);
9799 		}
9800 		drive = pmportinfo->pmport_sata_drive;
9801 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9802 		drive->satadrv_addr.pmport = npmport;
9803 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9804 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9805 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9806 
9807 		mutex_exit(&pmportinfo->pmport_mutex);
9808 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9809 
9810 		if (rval != SATA_SUCCESS) {
9811 			/*
9812 			 * Plugged device was not correctly identified.
9813 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9814 			 */
9815 			cur_time = ddi_get_lbolt();
9816 			if ((cur_time - start_time) < drv_usectohz(
9817 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9818 				/* sleep for a while */
9819 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9820 				goto reprobe_pmport;
9821 			}
9822 		}
9823 	}
9824 }
9825 
9826 /*
9827  * Add SATA device for specified HBA instance & port (SCSI target
9828  * device nodes).
9829  * This function is called (indirectly) only from sata_hba_attach().
9830  * A target node is created when there is a supported type device attached,
9831  * but may be removed if it cannot be put online.
9832  *
9833  * This function cannot be called from an interrupt context.
9834  *
9835  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9836  *
9837  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9838  * device identification failed - adding a device could be retried.
9839  *
9840  */
9841 static 	int
9842 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9843     sata_device_t *sata_device)
9844 {
9845 	sata_cport_info_t 	*cportinfo;
9846 	sata_pmult_info_t	*pminfo;
9847 	sata_pmport_info_t	*pmportinfo;
9848 	dev_info_t		*cdip;		/* child dip */
9849 	sata_address_t		*saddr = &sata_device->satadev_addr;
9850 	uint8_t			cport, pmport;
9851 	int			rval;
9852 
9853 	cport = saddr->cport;
9854 	pmport = saddr->pmport;
9855 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9856 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9857 
9858 	/*
9859 	 * Some device is attached to a controller port.
9860 	 * We rely on controllers distinquishing between no-device,
9861 	 * attached port multiplier and other kind of attached device.
9862 	 * We need to get Identify Device data and determine
9863 	 * positively the dev type before trying to attach
9864 	 * the target driver.
9865 	 */
9866 	sata_device->satadev_rev = SATA_DEVICE_REV;
9867 	switch (saddr->qual) {
9868 	case SATA_ADDR_CPORT:
9869 		/*
9870 		 * Add a non-port-multiplier device at controller port.
9871 		 */
9872 		saddr->qual = SATA_ADDR_DCPORT;
9873 
9874 		rval = sata_probe_device(sata_hba_inst, sata_device);
9875 		if (rval != SATA_SUCCESS ||
9876 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
9877 			return (SATA_FAILURE);
9878 
9879 		mutex_enter(&cportinfo->cport_mutex);
9880 		sata_show_drive_info(sata_hba_inst,
9881 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
9882 
9883 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9884 			/*
9885 			 * Could not determine device type or
9886 			 * a device is not supported.
9887 			 * Degrade this device to unknown.
9888 			 */
9889 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
9890 			mutex_exit(&cportinfo->cport_mutex);
9891 			return (SATA_SUCCESS);
9892 		}
9893 		cportinfo->cport_dev_type = sata_device->satadev_type;
9894 		cportinfo->cport_tgtnode_clean = B_TRUE;
9895 		mutex_exit(&cportinfo->cport_mutex);
9896 
9897 		/*
9898 		 * Initialize device to the desired state. Even if it
9899 		 * fails, the device will still attach but syslog
9900 		 * will show the warning.
9901 		 */
9902 		if (sata_initialize_device(sata_hba_inst,
9903 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
9904 			/* Retry */
9905 			rval = sata_initialize_device(sata_hba_inst,
9906 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
9907 
9908 			if (rval == SATA_RETRY)
9909 				sata_log(sata_hba_inst, CE_WARN,
9910 				    "SATA device at port %d - "
9911 				    "default device features could not be set."
9912 				    " Device may not operate as expected.",
9913 				    cport);
9914 		}
9915 
9916 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9917 		if (cdip == NULL) {
9918 			/*
9919 			 * Attaching target node failed.
9920 			 * We retain sata_drive_info structure...
9921 			 */
9922 			return (SATA_SUCCESS);
9923 		}
9924 
9925 		mutex_enter(&cportinfo->cport_mutex);
9926 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
9927 		    satadrv_state = SATA_STATE_READY;
9928 		mutex_exit(&cportinfo->cport_mutex);
9929 
9930 		break;
9931 
9932 	case SATA_ADDR_PMPORT:
9933 		saddr->qual = SATA_ADDR_DPMPORT;
9934 
9935 		mutex_enter(&cportinfo->cport_mutex);
9936 		/* It must be a Port Multiplier at the controller port */
9937 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
9938 
9939 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9940 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
9941 		mutex_exit(&cportinfo->cport_mutex);
9942 
9943 		rval = sata_probe_device(sata_hba_inst, sata_device);
9944 		if (rval != SATA_SUCCESS ||
9945 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
9946 			return (SATA_FAILURE);
9947 		}
9948 
9949 		mutex_enter(&pmportinfo->pmport_mutex);
9950 		sata_show_drive_info(sata_hba_inst,
9951 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
9952 
9953 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9954 			/*
9955 			 * Could not determine device type.
9956 			 * Degrade this device to unknown.
9957 			 */
9958 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
9959 			mutex_exit(&pmportinfo->pmport_mutex);
9960 			return (SATA_SUCCESS);
9961 		}
9962 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
9963 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
9964 		mutex_exit(&pmportinfo->pmport_mutex);
9965 
9966 		/*
9967 		 * Initialize device to the desired state.
9968 		 * Even if it fails, the device will still
9969 		 * attach but syslog will show the warning.
9970 		 */
9971 		if (sata_initialize_device(sata_hba_inst,
9972 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
9973 			/* Retry */
9974 			rval = sata_initialize_device(sata_hba_inst,
9975 			    pmportinfo->pmport_sata_drive);
9976 
9977 			if (rval == SATA_RETRY)
9978 				sata_log(sata_hba_inst, CE_WARN,
9979 				    "SATA device at port %d:%d - "
9980 				    "default device features could not be set."
9981 				    " Device may not operate as expected.",
9982 				    cport, pmport);
9983 		}
9984 
9985 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9986 		if (cdip == NULL) {
9987 			/*
9988 			 * Attaching target node failed.
9989 			 * We retain sata_drive_info structure...
9990 			 */
9991 			return (SATA_SUCCESS);
9992 		}
9993 		mutex_enter(&pmportinfo->pmport_mutex);
9994 		pmportinfo->pmport_sata_drive->satadrv_state |=
9995 		    SATA_STATE_READY;
9996 		mutex_exit(&pmportinfo->pmport_mutex);
9997 
9998 		break;
9999 
10000 	default:
10001 		return (SATA_FAILURE);
10002 	}
10003 
10004 	return (SATA_SUCCESS);
10005 }
10006 
10007 /*
10008  * Clean up target node at specific address.
10009  *
10010  * NOTE: No Mutex should be hold.
10011  */
10012 static int
10013 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10014     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10015 {
10016 	uint8_t cport, pmport, qual;
10017 	dev_info_t *tdip;
10018 
10019 	cport = sata_device->satadev_addr.cport;
10020 	pmport = sata_device->satadev_addr.pmport;
10021 	qual = sata_device->satadev_addr.qual;
10022 
10023 	if (qual == SATA_ADDR_DCPORT) {
10024 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10025 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10026 	} else {
10027 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10028 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10029 		    cport, pmport));
10030 	}
10031 
10032 	/* We are addressing attached device, not a port */
10033 	sata_device->satadev_addr.qual =
10034 	    sdinfo->satadrv_addr.qual;
10035 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10036 	    &sata_device->satadev_addr);
10037 	if (tdip != NULL && ndi_devi_offline(tdip,
10038 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10039 		/*
10040 		 * Problem :
10041 		 * The target node remained attached.
10042 		 * This happens when the device file was open
10043 		 * or a node was waiting for resources.
10044 		 * Cannot do anything about it.
10045 		 */
10046 		if (qual == SATA_ADDR_DCPORT) {
10047 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10048 			    "sata_hba_ioctl: disconnect: could "
10049 			    "not unconfigure device before "
10050 			    "disconnecting the SATA port %d",
10051 			    cport));
10052 		} else {
10053 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10054 			    "sata_hba_ioctl: disconnect: could "
10055 			    "not unconfigure device before "
10056 			    "disconnecting the SATA port %d:%d",
10057 			    cport, pmport));
10058 		}
10059 		/*
10060 		 * Set DEVICE REMOVED state in the target
10061 		 * node. It will prevent access to the device
10062 		 * even when a new device is attached, until
10063 		 * the old target node is released, removed and
10064 		 * recreated for a new  device.
10065 		 */
10066 		sata_set_device_removed(tdip);
10067 
10068 		/*
10069 		 * Instruct event daemon to try the target
10070 		 * node cleanup later.
10071 		 */
10072 		sata_set_target_node_cleanup(
10073 		    sata_hba_inst, &sata_device->satadev_addr);
10074 	}
10075 
10076 
10077 	return (SATA_SUCCESS);
10078 }
10079 
10080 
10081 /*
10082  * Create scsi target node for attached device, create node properties and
10083  * attach the node.
10084  * The node could be removed if the device onlining fails.
10085  *
10086  * A dev_info_t pointer is returned if operation is successful, NULL is
10087  * returned otherwise.
10088  */
10089 
10090 static dev_info_t *
10091 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10092 			sata_address_t *sata_addr)
10093 {
10094 	dev_info_t *cdip = NULL;
10095 	int rval;
10096 	char *nname = NULL;
10097 	char **compatible = NULL;
10098 	int ncompatible;
10099 	struct scsi_inquiry inq;
10100 	sata_device_t sata_device;
10101 	sata_drive_info_t *sdinfo;
10102 	int target;
10103 	int i;
10104 
10105 	sata_device.satadev_rev = SATA_DEVICE_REV;
10106 	sata_device.satadev_addr = *sata_addr;
10107 
10108 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10109 
10110 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10111 
10112 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10113 	    sata_addr->pmport, sata_addr->qual);
10114 
10115 	if (sdinfo == NULL) {
10116 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10117 		    sata_addr->cport)));
10118 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10119 		    "sata_create_target_node: no sdinfo for target %x",
10120 		    target));
10121 		return (NULL);
10122 	}
10123 
10124 	/*
10125 	 * create or get scsi inquiry data, expected by
10126 	 * scsi_hba_nodename_compatible_get()
10127 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10128 	 * ATAPI devices respond directly to Inquiry request.
10129 	 */
10130 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10131 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10132 		    (uint8_t *)&inq);
10133 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10134 		    sata_addr->cport)));
10135 	} else { /* Assume supported ATAPI device */
10136 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10137 		    sata_addr->cport)));
10138 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10139 		    &inq) == SATA_FAILURE)
10140 			return (NULL);
10141 		/*
10142 		 * Save supported ATAPI transport version
10143 		 */
10144 		sdinfo->satadrv_atapi_trans_ver =
10145 		    SATA_ATAPI_TRANS_VERSION(&inq);
10146 	}
10147 
10148 	/* determine the node name and compatible */
10149 	scsi_hba_nodename_compatible_get(&inq, NULL,
10150 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10151 
10152 #ifdef SATA_DEBUG
10153 	if (sata_debug_flags & SATA_DBG_NODES) {
10154 		if (nname == NULL) {
10155 			cmn_err(CE_NOTE, "sata_create_target_node: "
10156 			    "cannot determine nodename for target %d\n",
10157 			    target);
10158 		} else {
10159 			cmn_err(CE_WARN, "sata_create_target_node: "
10160 			    "target %d nodename: %s\n", target, nname);
10161 		}
10162 		if (compatible == NULL) {
10163 			cmn_err(CE_WARN,
10164 			    "sata_create_target_node: no compatible name\n");
10165 		} else {
10166 			for (i = 0; i < ncompatible; i++) {
10167 				cmn_err(CE_WARN, "sata_create_target_node: "
10168 				    "compatible name: %s\n", compatible[i]);
10169 			}
10170 		}
10171 	}
10172 #endif
10173 
10174 	/* if nodename can't be determined, log error and exit */
10175 	if (nname == NULL) {
10176 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10177 		    "sata_create_target_node: cannot determine nodename "
10178 		    "for target %d\n", target));
10179 		scsi_hba_nodename_compatible_free(nname, compatible);
10180 		return (NULL);
10181 	}
10182 	/*
10183 	 * Create scsi target node
10184 	 */
10185 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10186 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10187 	    "device-type", "scsi");
10188 
10189 	if (rval != DDI_PROP_SUCCESS) {
10190 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10191 		    "updating device_type prop failed %d", rval));
10192 		goto fail;
10193 	}
10194 
10195 	/*
10196 	 * Create target node properties: target & lun
10197 	 */
10198 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10199 	if (rval != DDI_PROP_SUCCESS) {
10200 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10201 		    "updating target prop failed %d", rval));
10202 		goto fail;
10203 	}
10204 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10205 	if (rval != DDI_PROP_SUCCESS) {
10206 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10207 		    "updating target prop failed %d", rval));
10208 		goto fail;
10209 	}
10210 
10211 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10212 		/*
10213 		 * Add "variant" property
10214 		 */
10215 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10216 		    "variant", "atapi");
10217 		if (rval != DDI_PROP_SUCCESS) {
10218 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10219 			    "sata_create_target_node: variant atapi "
10220 			    "property could not be created: %d", rval));
10221 			goto fail;
10222 		}
10223 	}
10224 	/* decorate the node with compatible */
10225 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10226 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10227 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10228 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10229 		    (void *)cdip));
10230 		goto fail;
10231 	}
10232 
10233 
10234 	/*
10235 	 * Now, try to attach the driver. If probing of the device fails,
10236 	 * the target node may be removed
10237 	 */
10238 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10239 
10240 	scsi_hba_nodename_compatible_free(nname, compatible);
10241 
10242 	if (rval == NDI_SUCCESS)
10243 		return (cdip);
10244 
10245 	/* target node was removed - are we sure? */
10246 	return (NULL);
10247 
10248 fail:
10249 	scsi_hba_nodename_compatible_free(nname, compatible);
10250 	ddi_prop_remove_all(cdip);
10251 	rval = ndi_devi_free(cdip);
10252 	if (rval != NDI_SUCCESS) {
10253 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10254 		    "node removal failed %d", rval));
10255 	}
10256 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10257 	    "cannot create target node for SATA device at port %d",
10258 	    sata_addr->cport);
10259 	return (NULL);
10260 }
10261 
10262 /*
10263  * Remove a target node.
10264  */
10265 static void
10266 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10267 			sata_address_t *sata_addr)
10268 {
10269 	dev_info_t *tdip;
10270 	uint8_t cport = sata_addr->cport;
10271 	uint8_t pmport = sata_addr->pmport;
10272 	uint8_t qual = sata_addr->qual;
10273 
10274 	/* Note the sata daemon uses the address of the port/pmport */
10275 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10276 
10277 	/* Remove target node */
10278 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10279 	if (tdip != NULL) {
10280 		/*
10281 		 * Target node exists.  Unconfigure device
10282 		 * then remove the target node (one ndi
10283 		 * operation).
10284 		 */
10285 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10286 			/*
10287 			 * PROBLEM - no device, but target node remained. This
10288 			 * happens when the file was open or node was waiting
10289 			 * for resources.
10290 			 */
10291 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10292 			    "sata_remove_target_node: "
10293 			    "Failed to remove target node for "
10294 			    "detached SATA device."));
10295 			/*
10296 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10297 			 * re-check first that the node still exists.
10298 			 */
10299 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10300 			    cport, pmport);
10301 			if (tdip != NULL) {
10302 				sata_set_device_removed(tdip);
10303 				/*
10304 				 * Instruct event daemon to retry the cleanup
10305 				 * later.
10306 				 */
10307 				sata_set_target_node_cleanup(sata_hba_inst,
10308 				    sata_addr);
10309 			}
10310 		}
10311 
10312 		if (qual == SATA_ADDR_CPORT)
10313 			sata_log(sata_hba_inst, CE_WARN,
10314 			    "SATA device detached at port %d", cport);
10315 		else
10316 			sata_log(sata_hba_inst, CE_WARN,
10317 			    "SATA device detached at port %d:%d",
10318 			    cport, pmport);
10319 	}
10320 #ifdef SATA_DEBUG
10321 	else {
10322 		if (qual == SATA_ADDR_CPORT)
10323 			sata_log(sata_hba_inst, CE_WARN,
10324 			    "target node not found at port %d", cport);
10325 		else
10326 			sata_log(sata_hba_inst, CE_WARN,
10327 			    "target node not found at port %d:%d",
10328 			    cport, pmport);
10329 	}
10330 #endif
10331 }
10332 
10333 
10334 /*
10335  * Re-probe sata port, check for a device and attach info
10336  * structures when necessary. Identify Device data is fetched, if possible.
10337  * Assumption: sata address is already validated.
10338  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10339  * the presence of a device and its type.
10340  *
10341  * flag arg specifies that the function should try multiple times to identify
10342  * device type and to initialize it, or it should return immediately on failure.
10343  * SATA_DEV_IDENTIFY_RETRY - retry
10344  * SATA_DEV_IDENTIFY_NORETRY - no retry
10345  *
10346  * SATA_FAILURE is returned if one of the operations failed.
10347  *
10348  * This function cannot be called in interrupt context - it may sleep.
10349  *
10350  * Note: Port multiplier is supported.
10351  */
10352 static int
10353 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10354     int flag)
10355 {
10356 	sata_cport_info_t *cportinfo;
10357 	sata_pmult_info_t *pmultinfo;
10358 	sata_drive_info_t *sdinfo, *osdinfo;
10359 	boolean_t init_device = B_FALSE;
10360 	int prev_device_type = SATA_DTYPE_NONE;
10361 	int prev_device_settings = 0;
10362 	int prev_device_state = 0;
10363 	clock_t start_time;
10364 	int retry = B_FALSE;
10365 	uint8_t cport = sata_device->satadev_addr.cport;
10366 	int rval_probe, rval_init;
10367 
10368 	/*
10369 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10370 	 */
10371 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10372 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10373 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10374 
10375 	/* We only care about host sata cport for now */
10376 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10377 	    sata_device->satadev_addr.cport);
10378 
10379 	/*
10380 	 * If a port multiplier was previously attached (we have no idea it
10381 	 * still there or not), sata_reprobe_pmult() will handle it.
10382 	 */
10383 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10384 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10385 
10386 	/* Store sata_drive_info when a non-pmult device was attached. */
10387 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10388 	if (osdinfo != NULL) {
10389 		/*
10390 		 * We are re-probing port with a previously attached device.
10391 		 * Save previous device type and settings.
10392 		 */
10393 		prev_device_type = cportinfo->cport_dev_type;
10394 		prev_device_settings = osdinfo->satadrv_settings;
10395 		prev_device_state = osdinfo->satadrv_state;
10396 	}
10397 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10398 		start_time = ddi_get_lbolt();
10399 		retry = B_TRUE;
10400 	}
10401 retry_probe:
10402 
10403 	/* probe port */
10404 	mutex_enter(&cportinfo->cport_mutex);
10405 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10406 	cportinfo->cport_state |= SATA_STATE_PROBING;
10407 	mutex_exit(&cportinfo->cport_mutex);
10408 
10409 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10410 	    (SATA_DIP(sata_hba_inst), sata_device);
10411 
10412 	mutex_enter(&cportinfo->cport_mutex);
10413 	if (rval_probe != SATA_SUCCESS) {
10414 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10415 		mutex_exit(&cportinfo->cport_mutex);
10416 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10417 		    "SATA port %d probing failed",
10418 		    cportinfo->cport_addr.cport));
10419 		return (SATA_FAILURE);
10420 	}
10421 
10422 	/*
10423 	 * update sata port state and set device type
10424 	 */
10425 	sata_update_port_info(sata_hba_inst, sata_device);
10426 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10427 
10428 	/*
10429 	 * Sanity check - Port is active? Is the link active?
10430 	 * Is there any device attached?
10431 	 */
10432 	if ((cportinfo->cport_state &
10433 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10434 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10435 	    SATA_PORT_DEVLINK_UP) {
10436 		/*
10437 		 * Port in non-usable state or no link active/no device.
10438 		 * Free info structure if necessary (direct attached drive
10439 		 * only, for now!
10440 		 */
10441 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10442 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10443 		/* Add here differentiation for device attached or not */
10444 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10445 		mutex_exit(&cportinfo->cport_mutex);
10446 		if (sdinfo != NULL)
10447 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10448 		return (SATA_SUCCESS);
10449 	}
10450 
10451 	cportinfo->cport_state |= SATA_STATE_READY;
10452 	cportinfo->cport_state |= SATA_STATE_PROBED;
10453 
10454 	cportinfo->cport_dev_type = sata_device->satadev_type;
10455 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10456 
10457 	/*
10458 	 * If we are re-probing the port, there may be
10459 	 * sata_drive_info structure attached
10460 	 */
10461 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10462 
10463 		/*
10464 		 * There is no device, so remove device info structure,
10465 		 * if necessary.
10466 		 */
10467 		/* Device change: Drive -> None */
10468 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10469 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10470 		if (sdinfo != NULL) {
10471 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10472 			sata_log(sata_hba_inst, CE_WARN,
10473 			    "SATA device detached "
10474 			    "from port %d", cportinfo->cport_addr.cport);
10475 		}
10476 		mutex_exit(&cportinfo->cport_mutex);
10477 		return (SATA_SUCCESS);
10478 
10479 	}
10480 
10481 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10482 
10483 		/* Device (may) change: Drive -> Drive */
10484 		if (sdinfo == NULL) {
10485 			/*
10486 			 * There is some device attached, but there is
10487 			 * no sata_drive_info structure - allocate one
10488 			 */
10489 			mutex_exit(&cportinfo->cport_mutex);
10490 			sdinfo = kmem_zalloc(
10491 			    sizeof (sata_drive_info_t), KM_SLEEP);
10492 			mutex_enter(&cportinfo->cport_mutex);
10493 			/*
10494 			 * Recheck, that the port state did not change when we
10495 			 * released mutex.
10496 			 */
10497 			if (cportinfo->cport_state & SATA_STATE_READY) {
10498 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10499 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10500 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10501 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10502 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10503 			} else {
10504 				/*
10505 				 * Port is not in ready state, we
10506 				 * cannot attach a device.
10507 				 */
10508 				mutex_exit(&cportinfo->cport_mutex);
10509 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10510 				return (SATA_SUCCESS);
10511 			}
10512 			/*
10513 			 * Since we are adding device, presumably new one,
10514 			 * indicate that it  should be initalized,
10515 			 * as well as some internal framework states).
10516 			 */
10517 			init_device = B_TRUE;
10518 		}
10519 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10520 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10521 	} else {
10522 		/* Device change: Drive -> PMult */
10523 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10524 		if (sdinfo != NULL) {
10525 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10526 			sata_log(sata_hba_inst, CE_WARN,
10527 			    "SATA device detached "
10528 			    "from port %d", cportinfo->cport_addr.cport);
10529 		}
10530 
10531 		sata_log(sata_hba_inst, CE_WARN,
10532 		    "SATA port multiplier detected at port %d",
10533 		    cportinfo->cport_addr.cport);
10534 
10535 		mutex_exit(&cportinfo->cport_mutex);
10536 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10537 		    SATA_SUCCESS)
10538 			return (SATA_FAILURE);
10539 		sata_show_pmult_info(sata_hba_inst, sata_device);
10540 		mutex_enter(&cportinfo->cport_mutex);
10541 
10542 		/*
10543 		 * Mark all the port multiplier port behind the port
10544 		 * multiplier behind with link events, so that the sata daemon
10545 		 * will update their status.
10546 		 */
10547 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10548 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10549 		mutex_exit(&cportinfo->cport_mutex);
10550 		return (SATA_SUCCESS);
10551 	}
10552 	mutex_exit(&cportinfo->cport_mutex);
10553 
10554 	/*
10555 	 * Figure out what kind of device we are really
10556 	 * dealing with. Failure of identifying device does not fail this
10557 	 * function.
10558 	 */
10559 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10560 	rval_init = SATA_FAILURE;
10561 	mutex_enter(&cportinfo->cport_mutex);
10562 	if (rval_probe == SATA_SUCCESS) {
10563 		/*
10564 		 * If we are dealing with the same type of a device as before,
10565 		 * restore its settings flags.
10566 		 */
10567 		if (osdinfo != NULL &&
10568 		    sata_device->satadev_type == prev_device_type)
10569 			sdinfo->satadrv_settings = prev_device_settings;
10570 
10571 		mutex_exit(&cportinfo->cport_mutex);
10572 		rval_init = SATA_SUCCESS;
10573 		/* Set initial device features, if necessary */
10574 		if (init_device == B_TRUE) {
10575 			rval_init = sata_initialize_device(sata_hba_inst,
10576 			    sdinfo);
10577 		}
10578 		if (rval_init == SATA_SUCCESS)
10579 			return (rval_init);
10580 		/* else we will retry if retry was asked for */
10581 
10582 	} else {
10583 		/*
10584 		 * If there was some device info before we probe the device,
10585 		 * restore previous device setting, so we can retry from scratch
10586 		 * later. Providing, of course, that device has not disapear
10587 		 * during probing process.
10588 		 */
10589 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10590 			if (osdinfo != NULL) {
10591 				cportinfo->cport_dev_type = prev_device_type;
10592 				sdinfo->satadrv_type = prev_device_type;
10593 				sdinfo->satadrv_state = prev_device_state;
10594 			}
10595 		} else {
10596 			/* device is gone */
10597 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10598 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10599 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10600 			mutex_exit(&cportinfo->cport_mutex);
10601 			return (SATA_SUCCESS);
10602 		}
10603 		mutex_exit(&cportinfo->cport_mutex);
10604 	}
10605 
10606 	if (retry) {
10607 		clock_t cur_time = ddi_get_lbolt();
10608 		/*
10609 		 * A device was not successfully identified or initialized.
10610 		 * Track retry time for device identification.
10611 		 */
10612 		if ((cur_time - start_time) <
10613 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10614 			/* sleep for a while */
10615 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10616 			goto retry_probe;
10617 		}
10618 		/* else no more retries */
10619 		mutex_enter(&cportinfo->cport_mutex);
10620 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10621 			if (rval_init == SATA_RETRY) {
10622 				/*
10623 				 * Setting drive features have failed, but
10624 				 * because the drive is still accessible,
10625 				 * keep it and emit a warning message.
10626 				 */
10627 				sata_log(sata_hba_inst, CE_WARN,
10628 				    "SATA device at port %d - desired "
10629 				    "drive features could not be set. "
10630 				    "Device may not operate as expected.",
10631 				    cportinfo->cport_addr.cport);
10632 			} else {
10633 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10634 				    satadrv_state = SATA_DSTATE_FAILED;
10635 			}
10636 		}
10637 		mutex_exit(&cportinfo->cport_mutex);
10638 	}
10639 	return (SATA_SUCCESS);
10640 }
10641 
10642 /*
10643  * Reprobe a controller port that connected to a port multiplier.
10644  *
10645  * NOTE: No Mutex should be hold.
10646  */
10647 static int
10648 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10649     int flag)
10650 {
10651 	_NOTE(ARGUNUSED(flag))
10652 	sata_cport_info_t *cportinfo;
10653 	sata_pmult_info_t *pmultinfo;
10654 	uint8_t cport = sata_device->satadev_addr.cport;
10655 	int rval_probe;
10656 
10657 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10658 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10659 
10660 	/* probe port */
10661 	mutex_enter(&cportinfo->cport_mutex);
10662 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10663 	cportinfo->cport_state |= SATA_STATE_PROBING;
10664 	mutex_exit(&cportinfo->cport_mutex);
10665 
10666 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10667 	    (SATA_DIP(sata_hba_inst), sata_device);
10668 
10669 	mutex_enter(&cportinfo->cport_mutex);
10670 	if (rval_probe != SATA_SUCCESS) {
10671 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10672 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10673 		    "SATA port %d probing failed", cport));
10674 		sata_log(sata_hba_inst, CE_WARN,
10675 		    "SATA port multiplier detached at port %d", cport);
10676 		mutex_exit(&cportinfo->cport_mutex);
10677 		sata_free_pmult(sata_hba_inst, sata_device);
10678 		return (SATA_FAILURE);
10679 	}
10680 
10681 	/*
10682 	 * update sata port state and set device type
10683 	 */
10684 	sata_update_port_info(sata_hba_inst, sata_device);
10685 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10686 	cportinfo->cport_state |= SATA_STATE_PROBED;
10687 
10688 	/*
10689 	 * Sanity check - Port is active? Is the link active?
10690 	 * Is there any device attached?
10691 	 */
10692 	if ((cportinfo->cport_state &
10693 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10694 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10695 	    SATA_PORT_DEVLINK_UP ||
10696 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10697 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10698 		mutex_exit(&cportinfo->cport_mutex);
10699 		sata_free_pmult(sata_hba_inst, sata_device);
10700 		sata_log(sata_hba_inst, CE_WARN,
10701 		    "SATA port multiplier detached at port %d", cport);
10702 		return (SATA_SUCCESS);
10703 	}
10704 
10705 	/*
10706 	 * Device changed: PMult -> Non-PMult
10707 	 *
10708 	 * This situation is uncommon, most possibly being caused by errors
10709 	 * after which the port multiplier is not correct initialized and
10710 	 * recognized. In that case the new device will be marked as unknown
10711 	 * and will not be automatically probed in this routine. Instead
10712 	 * system administrator could manually restart it via cfgadm(1M).
10713 	 */
10714 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10715 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10716 		mutex_exit(&cportinfo->cport_mutex);
10717 		sata_free_pmult(sata_hba_inst, sata_device);
10718 		sata_log(sata_hba_inst, CE_WARN,
10719 		    "SATA port multiplier detached at port %d", cport);
10720 		return (SATA_FAILURE);
10721 	}
10722 
10723 	/*
10724 	 * Now we know it is a port multiplier. However, if this is not the
10725 	 * previously attached port multiplier - they may have different
10726 	 * pmport numbers - we need to re-allocate data structures for every
10727 	 * pmport and drive.
10728 	 *
10729 	 * Port multipliers of the same model have identical values in these
10730 	 * registers, so it is still necessary to update the information of
10731 	 * all drives attached to the previous port multiplier afterwards.
10732 	 */
10733 	/* Device changed: PMult -> another PMult */
10734 	mutex_exit(&cportinfo->cport_mutex);
10735 	sata_free_pmult(sata_hba_inst, sata_device);
10736 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10737 		return (SATA_FAILURE);
10738 	mutex_enter(&cportinfo->cport_mutex);
10739 
10740 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10741 	    "SATA port multiplier [changed] at port %d", cport);
10742 	sata_log(sata_hba_inst, CE_WARN,
10743 	    "SATA port multiplier detected at port %d", cport);
10744 
10745 	/*
10746 	 * Mark all the port multiplier port behind the port
10747 	 * multiplier behind with link events, so that the sata daemon
10748 	 * will update their status.
10749 	 */
10750 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10751 	mutex_exit(&cportinfo->cport_mutex);
10752 
10753 	return (SATA_SUCCESS);
10754 }
10755 
10756 /*
10757  * Re-probe a port multiplier port, check for a device and attach info
10758  * structures when necessary. Identify Device data is fetched, if possible.
10759  * Assumption: sata address is already validated as port multiplier port.
10760  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10761  * the presence of a device and its type.
10762  *
10763  * flag arg specifies that the function should try multiple times to identify
10764  * device type and to initialize it, or it should return immediately on failure.
10765  * SATA_DEV_IDENTIFY_RETRY - retry
10766  * SATA_DEV_IDENTIFY_NORETRY - no retry
10767  *
10768  * SATA_FAILURE is returned if one of the operations failed.
10769  *
10770  * This function cannot be called in interrupt context - it may sleep.
10771  *
10772  * NOTE: Should be only called by sata_probe_port() in case target port is a
10773  *       port multiplier port.
10774  * NOTE: No Mutex should be hold.
10775  */
10776 static int
10777 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10778     int flag)
10779 {
10780 	sata_cport_info_t *cportinfo = NULL;
10781 	sata_pmport_info_t *pmportinfo = NULL;
10782 	sata_drive_info_t *sdinfo, *osdinfo;
10783 	sata_device_t sdevice;
10784 	boolean_t init_device = B_FALSE;
10785 	int prev_device_type = SATA_DTYPE_NONE;
10786 	int prev_device_settings = 0;
10787 	int prev_device_state = 0;
10788 	clock_t start_time;
10789 	uint8_t cport = sata_device->satadev_addr.cport;
10790 	uint8_t pmport = sata_device->satadev_addr.pmport;
10791 	int rval;
10792 
10793 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10794 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10795 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10796 
10797 	if (osdinfo != NULL) {
10798 		/*
10799 		 * We are re-probing port with a previously attached device.
10800 		 * Save previous device type and settings.
10801 		 */
10802 		prev_device_type = pmportinfo->pmport_dev_type;
10803 		prev_device_settings = osdinfo->satadrv_settings;
10804 		prev_device_state = osdinfo->satadrv_state;
10805 	}
10806 
10807 	start_time = ddi_get_lbolt();
10808 
10809 	/* check parent status */
10810 	mutex_enter(&cportinfo->cport_mutex);
10811 	if ((cportinfo->cport_state &
10812 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10813 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10814 	    SATA_PORT_DEVLINK_UP) {
10815 		mutex_exit(&cportinfo->cport_mutex);
10816 		return (SATA_FAILURE);
10817 	}
10818 	mutex_exit(&cportinfo->cport_mutex);
10819 
10820 retry_probe_pmport:
10821 
10822 	/* probe port */
10823 	mutex_enter(&pmportinfo->pmport_mutex);
10824 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10825 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10826 	mutex_exit(&pmportinfo->pmport_mutex);
10827 
10828 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10829 	    (SATA_DIP(sata_hba_inst), sata_device);
10830 
10831 	/* might need retry because we cannot touch registers. */
10832 	if (rval == SATA_FAILURE) {
10833 		mutex_enter(&pmportinfo->pmport_mutex);
10834 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10835 		mutex_exit(&pmportinfo->pmport_mutex);
10836 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10837 		    "SATA port %d:%d probing failed",
10838 		    cport, pmport));
10839 		return (SATA_FAILURE);
10840 	} else if (rval == SATA_RETRY) {
10841 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10842 		    "SATA port %d:%d probing failed, retrying...",
10843 		    cport, pmport));
10844 		clock_t cur_time = ddi_get_lbolt();
10845 		/*
10846 		 * A device was not successfully identified or initialized.
10847 		 * Track retry time for device identification.
10848 		 */
10849 		if ((cur_time - start_time) <
10850 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10851 			/* sleep for a while */
10852 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10853 			goto retry_probe_pmport;
10854 		} else {
10855 			mutex_enter(&pmportinfo->pmport_mutex);
10856 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10857 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10858 				    satadrv_state = SATA_DSTATE_FAILED;
10859 			mutex_exit(&pmportinfo->pmport_mutex);
10860 			return (SATA_SUCCESS);
10861 		}
10862 	}
10863 
10864 	/*
10865 	 * Sanity check - Controller port is active? Is the link active?
10866 	 * Is it still a port multiplier?
10867 	 */
10868 	if ((cportinfo->cport_state &
10869 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10870 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10871 	    SATA_PORT_DEVLINK_UP ||
10872 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
10873 		/*
10874 		 * Port in non-usable state or no link active/no
10875 		 * device. Free info structure.
10876 		 */
10877 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10878 
10879 		sdevice.satadev_addr.cport = cport;
10880 		sdevice.satadev_addr.pmport = pmport;
10881 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
10882 		mutex_exit(&cportinfo->cport_mutex);
10883 
10884 		sata_free_pmult(sata_hba_inst, &sdevice);
10885 		return (SATA_FAILURE);
10886 	}
10887 
10888 	/* SATA_SUCCESS NOW */
10889 	/*
10890 	 * update sata port state and set device type
10891 	 */
10892 	mutex_enter(&pmportinfo->pmport_mutex);
10893 	sata_update_pmport_info(sata_hba_inst, sata_device);
10894 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10895 
10896 	/*
10897 	 * Sanity check - Port is active? Is the link active?
10898 	 * Is there any device attached?
10899 	 */
10900 	if ((pmportinfo->pmport_state &
10901 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10902 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10903 	    SATA_PORT_DEVLINK_UP) {
10904 		/*
10905 		 * Port in non-usable state or no link active/no device.
10906 		 * Free info structure if necessary (direct attached drive
10907 		 * only, for now!
10908 		 */
10909 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10910 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10911 		/* Add here differentiation for device attached or not */
10912 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10913 		mutex_exit(&pmportinfo->pmport_mutex);
10914 		if (sdinfo != NULL)
10915 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10916 		return (SATA_SUCCESS);
10917 	}
10918 
10919 	pmportinfo->pmport_state |= SATA_STATE_READY;
10920 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
10921 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10922 
10923 	/*
10924 	 * If we are re-probing the port, there may be
10925 	 * sata_drive_info structure attached
10926 	 * (or sata_pm_info, if PMult is supported).
10927 	 */
10928 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10929 		/*
10930 		 * There is no device, so remove device info structure,
10931 		 * if necessary.
10932 		 */
10933 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10934 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10935 		if (sdinfo != NULL) {
10936 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10937 			sata_log(sata_hba_inst, CE_WARN,
10938 			    "SATA device detached from port %d:%d",
10939 			    cport, pmport);
10940 		}
10941 		mutex_exit(&pmportinfo->pmport_mutex);
10942 		return (SATA_SUCCESS);
10943 	}
10944 
10945 	/* this should not be a pmult */
10946 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
10947 	if (sdinfo == NULL) {
10948 		/*
10949 		 * There is some device attached, but there is
10950 		 * no sata_drive_info structure - allocate one
10951 		 */
10952 		mutex_exit(&pmportinfo->pmport_mutex);
10953 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
10954 		    KM_SLEEP);
10955 		mutex_enter(&pmportinfo->pmport_mutex);
10956 		/*
10957 		 * Recheck, that the port state did not change when we
10958 		 * released mutex.
10959 		 */
10960 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
10961 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
10962 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
10963 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10964 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10965 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10966 		} else {
10967 			/*
10968 			 * Port is not in ready state, we
10969 			 * cannot attach a device.
10970 			 */
10971 			mutex_exit(&pmportinfo->pmport_mutex);
10972 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10973 			return (SATA_SUCCESS);
10974 		}
10975 		/*
10976 		 * Since we are adding device, presumably new one,
10977 		 * indicate that it  should be initalized,
10978 		 * as well as some internal framework states).
10979 		 */
10980 		init_device = B_TRUE;
10981 	}
10982 
10983 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10984 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10985 
10986 	mutex_exit(&pmportinfo->pmport_mutex);
10987 	/*
10988 	 * Figure out what kind of device we are really
10989 	 * dealing with.
10990 	 */
10991 	rval = sata_probe_device(sata_hba_inst, sata_device);
10992 
10993 	mutex_enter(&pmportinfo->pmport_mutex);
10994 	if (rval == SATA_SUCCESS) {
10995 		/*
10996 		 * If we are dealing with the same type of a device as before,
10997 		 * restore its settings flags.
10998 		 */
10999 		if (osdinfo != NULL &&
11000 		    sata_device->satadev_type == prev_device_type)
11001 			sdinfo->satadrv_settings = prev_device_settings;
11002 
11003 		mutex_exit(&pmportinfo->pmport_mutex);
11004 		/* Set initial device features, if necessary */
11005 		if (init_device == B_TRUE) {
11006 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11007 		}
11008 		if (rval == SATA_SUCCESS)
11009 			return (rval);
11010 	} else {
11011 		/*
11012 		 * If there was some device info before we probe the device,
11013 		 * restore previous device setting, so we can retry from scratch
11014 		 * later. Providing, of course, that device has not disappeared
11015 		 * during probing process.
11016 		 */
11017 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11018 			if (osdinfo != NULL) {
11019 				pmportinfo->pmport_dev_type = prev_device_type;
11020 				sdinfo->satadrv_type = prev_device_type;
11021 				sdinfo->satadrv_state = prev_device_state;
11022 			}
11023 		} else {
11024 			/* device is gone */
11025 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11026 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11027 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11028 			mutex_exit(&pmportinfo->pmport_mutex);
11029 			return (SATA_SUCCESS);
11030 		}
11031 		mutex_exit(&pmportinfo->pmport_mutex);
11032 	}
11033 
11034 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11035 		clock_t cur_time = ddi_get_lbolt();
11036 		/*
11037 		 * A device was not successfully identified or initialized.
11038 		 * Track retry time for device identification.
11039 		 */
11040 		if ((cur_time - start_time) <
11041 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11042 			/* sleep for a while */
11043 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11044 			goto retry_probe_pmport;
11045 		} else {
11046 			mutex_enter(&pmportinfo->pmport_mutex);
11047 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11048 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11049 				    satadrv_state = SATA_DSTATE_FAILED;
11050 			mutex_exit(&pmportinfo->pmport_mutex);
11051 		}
11052 	}
11053 	return (SATA_SUCCESS);
11054 }
11055 
11056 /*
11057  * Allocated related structure for a port multiplier and its device ports
11058  *
11059  * Port multiplier should be ready and probed, and related information like
11060  * the number of the device ports should be store in sata_device_t.
11061  *
11062  * NOTE: No Mutex should be hold.
11063  */
11064 static int
11065 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11066 {
11067 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11068 	sata_cport_info_t *cportinfo = NULL;
11069 	sata_pmult_info_t *pmultinfo = NULL;
11070 	sata_pmport_info_t *pmportinfo = NULL;
11071 	sata_device_t sd;
11072 	dev_t minor_number;
11073 	char name[16];
11074 	uint8_t cport = sata_device->satadev_addr.cport;
11075 	int rval;
11076 	int npmport;
11077 
11078 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11079 
11080 	/* This function might be called while a port-mult is hot-plugged. */
11081 	mutex_enter(&cportinfo->cport_mutex);
11082 
11083 	/* dev_type's not updated when get called from sata_reprobe_port() */
11084 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11085 		/* Create a pmult_info structure */
11086 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11087 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11088 	}
11089 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11090 
11091 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11092 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11093 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11094 
11095 	/*
11096 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11097 	 * The HBA driver should initialize and register the port multiplier,
11098 	 * sata_register_pmult() will fill following fields,
11099 	 *   + sata_pmult_info.pmult_gscr
11100 	 *   + sata_pmult_info.pmult_num_dev_ports
11101 	 */
11102 	sd.satadev_addr = sata_device->satadev_addr;
11103 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11104 	mutex_exit(&cportinfo->cport_mutex);
11105 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11106 	    (SATA_DIP(sata_hba_inst), &sd);
11107 	mutex_enter(&cportinfo->cport_mutex);
11108 
11109 	if (rval != SATA_SUCCESS ||
11110 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11111 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11112 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11113 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11114 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11115 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11116 		mutex_exit(&cportinfo->cport_mutex);
11117 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11118 		    "sata_alloc_pmult: failed to initialize pmult "
11119 		    "at port %d.", cport)
11120 		return (SATA_FAILURE);
11121 	}
11122 
11123 	/* Initialize pmport_info structure */
11124 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11125 	    npmport++) {
11126 
11127 		/* if everything is allocated, skip */
11128 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11129 			continue;
11130 
11131 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11132 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11133 		mutex_exit(&cportinfo->cport_mutex);
11134 
11135 		mutex_enter(&pmportinfo->pmport_mutex);
11136 		pmportinfo->pmport_addr.cport = cport;
11137 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11138 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11139 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11140 		mutex_exit(&pmportinfo->pmport_mutex);
11141 
11142 		mutex_enter(&cportinfo->cport_mutex);
11143 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11144 
11145 		/* Create an attachment point */
11146 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11147 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11148 		(void) sprintf(name, "%d.%d", cport, npmport);
11149 
11150 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11151 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11152 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11153 			    "cannot create SATA attachment point for "
11154 			    "port %d:%d", cport, npmport);
11155 		}
11156 	}
11157 
11158 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11159 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11160 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11161 
11162 	mutex_exit(&cportinfo->cport_mutex);
11163 	return (SATA_SUCCESS);
11164 }
11165 
11166 /*
11167  * Free data structures when a port multiplier is removed.
11168  *
11169  * NOTE: No Mutex should be hold.
11170  */
11171 static void
11172 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11173 {
11174 	sata_cport_info_t *cportinfo;
11175 	sata_pmult_info_t *pmultinfo;
11176 	sata_pmport_info_t *pmportinfo;
11177 	sata_device_t pmport_device;
11178 	sata_drive_info_t *sdinfo;
11179 	dev_info_t *tdip;
11180 	char name[16];
11181 	uint8_t cport = sata_device->satadev_addr.cport;
11182 	int npmport;
11183 
11184 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11185 
11186 	/* This function might be called while port-mult is hot plugged. */
11187 	mutex_enter(&cportinfo->cport_mutex);
11188 
11189 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11190 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11191 	ASSERT(pmultinfo != NULL);
11192 
11193 	/* Free pmport_info structure */
11194 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11195 	    npmport++) {
11196 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11197 		if (pmportinfo == NULL)
11198 			continue;
11199 		mutex_exit(&cportinfo->cport_mutex);
11200 
11201 		mutex_enter(&pmportinfo->pmport_mutex);
11202 		sdinfo = pmportinfo->pmport_sata_drive;
11203 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11204 		mutex_exit(&pmportinfo->pmport_mutex);
11205 
11206 		/* Remove attachment point. */
11207 		name[0] = '\0';
11208 		(void) sprintf(name, "%d.%d", cport, npmport);
11209 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11210 		sata_log(sata_hba_inst, CE_NOTE,
11211 		    "Remove attachment point of port %d:%d",
11212 		    cport, npmport);
11213 
11214 		/*
11215 		 * Rumove target node
11216 		 */
11217 		bzero(&pmport_device, sizeof (sata_device_t));
11218 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11219 		pmport_device.satadev_addr.cport = cport;
11220 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11221 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11222 
11223 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11224 		    &(pmport_device.satadev_addr));
11225 		if (tdip != NULL && ndi_devi_offline(tdip,
11226 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11227 			/*
11228 			 * Problem :
11229 			 * The target node remained attached.
11230 			 * This happens when the device file was open
11231 			 * or a node was waiting for resources.
11232 			 * Cannot do anything about it.
11233 			 */
11234 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11235 			    "sata_free_pmult: could not unconfigure device "
11236 			    "before disconnecting the SATA port %d:%d",
11237 			    cport, npmport));
11238 
11239 			/*
11240 			 * Set DEVICE REMOVED state in the target
11241 			 * node. It will prevent access to the device
11242 			 * even when a new device is attached, until
11243 			 * the old target node is released, removed and
11244 			 * recreated for a new  device.
11245 			 */
11246 			sata_set_device_removed(tdip);
11247 
11248 			/*
11249 			 * Instruct event daemon to try the target
11250 			 * node cleanup later.
11251 			 */
11252 			sata_set_target_node_cleanup(
11253 			    sata_hba_inst, &(pmport_device.satadev_addr));
11254 
11255 		}
11256 		mutex_enter(&cportinfo->cport_mutex);
11257 
11258 		/*
11259 		 * Add here differentiation for device attached or not
11260 		 */
11261 		if (sdinfo != NULL)  {
11262 			sata_log(sata_hba_inst, CE_WARN,
11263 			    "SATA device detached from port %d:%d",
11264 			    cport, npmport);
11265 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11266 		}
11267 
11268 		mutex_destroy(&pmportinfo->pmport_mutex);
11269 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11270 	}
11271 
11272 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11273 
11274 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11275 
11276 	sata_log(sata_hba_inst, CE_WARN,
11277 	    "SATA port multiplier detached at port %d", cport);
11278 
11279 	mutex_exit(&cportinfo->cport_mutex);
11280 }
11281 
11282 /*
11283  * Initialize device
11284  * Specified device is initialized to a default state.
11285  *
11286  * Returns SATA_SUCCESS if all device features are set successfully,
11287  * SATA_RETRY if device is accessible but device features were not set
11288  * successfully, and SATA_FAILURE otherwise.
11289  */
11290 static int
11291 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11292     sata_drive_info_t *sdinfo)
11293 {
11294 	int rval;
11295 
11296 	sata_save_drive_settings(sdinfo);
11297 
11298 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11299 
11300 	sata_init_write_cache_mode(sdinfo);
11301 
11302 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11303 
11304 	/* Determine current data transfer mode */
11305 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11306 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11307 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11308 	    SATA_VALIDINFO_88) != 0 &&
11309 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11310 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11311 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11312 	    SATA_MDMA_SEL_MASK) != 0) {
11313 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11314 	} else
11315 		/* DMA supported, not no DMA transfer mode is selected !? */
11316 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11317 
11318 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11319 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11320 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11321 	else
11322 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11323 
11324 	return (rval);
11325 }
11326 
11327 
11328 /*
11329  * Initialize write cache mode.
11330  *
11331  * The default write cache setting for SATA HDD is provided by sata_write_cache
11332  * static variable. ATAPI CD/DVDs devices have write cache default is
11333  * determined by sata_atapicdvd_write_cache static variable.
11334  * ATAPI tape devices have write cache default is determined by
11335  * sata_atapitape_write_cache static variable.
11336  * ATAPI disk devices have write cache default is determined by
11337  * sata_atapidisk_write_cache static variable.
11338  * 1 - enable
11339  * 0 - disable
11340  * any other value - current drive setting
11341  *
11342  * Although there is not reason to disable write cache on CD/DVD devices,
11343  * tape devices and ATAPI disk devices, the default setting control is provided
11344  * for the maximun flexibility.
11345  *
11346  * In the future, it may be overridden by the
11347  * disk-write-cache-enable property setting, if it is defined.
11348  * Returns SATA_SUCCESS if all device features are set successfully,
11349  * SATA_FAILURE otherwise.
11350  */
11351 static void
11352 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11353 {
11354 	switch (sdinfo->satadrv_type) {
11355 	case SATA_DTYPE_ATADISK:
11356 		if (sata_write_cache == 1)
11357 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11358 		else if (sata_write_cache == 0)
11359 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11360 		/*
11361 		 * When sata_write_cache value is not 0 or 1,
11362 		 * a current setting of the drive's write cache is used.
11363 		 */
11364 		break;
11365 	case SATA_DTYPE_ATAPICD:
11366 		if (sata_atapicdvd_write_cache == 1)
11367 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11368 		else if (sata_atapicdvd_write_cache == 0)
11369 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11370 		/*
11371 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11372 		 * a current setting of the drive's write cache is used.
11373 		 */
11374 		break;
11375 	case SATA_DTYPE_ATAPITAPE:
11376 		if (sata_atapitape_write_cache == 1)
11377 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11378 		else if (sata_atapitape_write_cache == 0)
11379 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11380 		/*
11381 		 * When sata_atapitape_write_cache value is not 0 or 1,
11382 		 * a current setting of the drive's write cache is used.
11383 		 */
11384 		break;
11385 	case SATA_DTYPE_ATAPIDISK:
11386 		if (sata_atapidisk_write_cache == 1)
11387 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11388 		else if (sata_atapidisk_write_cache == 0)
11389 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11390 		/*
11391 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11392 		 * a current setting of the drive's write cache is used.
11393 		 */
11394 		break;
11395 	}
11396 }
11397 
11398 
11399 /*
11400  * Validate sata address.
11401  * Specified cport, pmport and qualifier has to match
11402  * passed sata_scsi configuration info.
11403  * The presence of an attached device is not verified.
11404  *
11405  * Returns 0 when address is valid, -1 otherwise.
11406  */
11407 static int
11408 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11409 	int pmport, int qual)
11410 {
11411 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11412 		goto invalid_address;
11413 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11414 		goto invalid_address;
11415 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11416 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11417 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11418 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11419 		goto invalid_address;
11420 
11421 	return (0);
11422 
11423 invalid_address:
11424 	return (-1);
11425 
11426 }
11427 
11428 /*
11429  * Validate scsi address
11430  * SCSI target address is translated into SATA cport/pmport and compared
11431  * with a controller port/device configuration. LUN has to be 0.
11432  * Returns 0 if a scsi target refers to an attached device,
11433  * returns 1 if address is valid but no valid device is attached,
11434  * returns 2 if address is valid but device type is unknown (not valid device),
11435  * returns -1 if bad address or device is of an unsupported type.
11436  * Upon return sata_device argument is set.
11437  *
11438  * Port multiplier is supported now.
11439  */
11440 static int
11441 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11442 	struct scsi_address *ap, sata_device_t *sata_device)
11443 {
11444 	int cport, pmport, qual, rval;
11445 
11446 	rval = -1;	/* Invalid address */
11447 	if (ap->a_lun != 0)
11448 		goto out;
11449 
11450 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11451 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11452 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11453 
11454 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11455 		goto out;
11456 
11457 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11458 	    0) {
11459 
11460 		sata_cport_info_t *cportinfo;
11461 		sata_pmult_info_t *pmultinfo;
11462 		sata_drive_info_t *sdinfo = NULL;
11463 
11464 		sata_device->satadev_addr.qual = qual;
11465 		sata_device->satadev_addr.cport = cport;
11466 		sata_device->satadev_addr.pmport = pmport;
11467 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11468 
11469 		rval = 1;	/* Valid sata address */
11470 
11471 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11472 		if (qual == SATA_ADDR_DCPORT) {
11473 			if (cportinfo == NULL ||
11474 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11475 				goto out;
11476 
11477 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11478 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11479 			    sdinfo != NULL) {
11480 				rval = 2;
11481 				goto out;
11482 			}
11483 
11484 			if ((cportinfo->cport_dev_type &
11485 			    SATA_VALID_DEV_TYPE) == 0) {
11486 				rval = -1;
11487 				goto out;
11488 			}
11489 
11490 		} else if (qual == SATA_ADDR_DPMPORT) {
11491 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11492 			if (pmultinfo == NULL) {
11493 				rval = -1;
11494 				goto out;
11495 			}
11496 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11497 			    NULL ||
11498 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11499 			    pmport) == SATA_DTYPE_NONE)
11500 				goto out;
11501 
11502 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11503 			    pmport);
11504 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11505 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11506 				rval = 2;
11507 				goto out;
11508 			}
11509 
11510 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11511 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11512 				rval = -1;
11513 				goto out;
11514 			}
11515 
11516 		} else {
11517 			rval = -1;
11518 			goto out;
11519 		}
11520 		if ((sdinfo == NULL) ||
11521 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11522 			goto out;
11523 
11524 		sata_device->satadev_type = sdinfo->satadrv_type;
11525 
11526 		return (0);
11527 	}
11528 out:
11529 	if (rval > 0) {
11530 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11531 		    "sata_validate_scsi_address: no valid target %x lun %x",
11532 		    ap->a_target, ap->a_lun);
11533 	}
11534 	return (rval);
11535 }
11536 
11537 /*
11538  * Find dip corresponding to passed device number
11539  *
11540  * Returns NULL if invalid device number is passed or device cannot be found,
11541  * Returns dip is device is found.
11542  */
11543 static dev_info_t *
11544 sata_devt_to_devinfo(dev_t dev)
11545 {
11546 	dev_info_t *dip;
11547 #ifndef __lock_lint
11548 	struct devnames *dnp;
11549 	major_t major = getmajor(dev);
11550 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11551 
11552 	if (major >= devcnt)
11553 		return (NULL);
11554 
11555 	dnp = &devnamesp[major];
11556 	LOCK_DEV_OPS(&(dnp->dn_lock));
11557 	dip = dnp->dn_head;
11558 	while (dip && (ddi_get_instance(dip) != instance)) {
11559 		dip = ddi_get_next(dip);
11560 	}
11561 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11562 #endif
11563 
11564 	return (dip);
11565 }
11566 
11567 
11568 /*
11569  * Probe device.
11570  * This function issues Identify Device command and initializes local
11571  * sata_drive_info structure if the device can be identified.
11572  * The device type is determined by examining Identify Device
11573  * command response.
11574  * If the sata_hba_inst has linked drive info structure for this
11575  * device address, the Identify Device data is stored into sata_drive_info
11576  * structure linked to the port info structure.
11577  *
11578  * sata_device has to refer to the valid sata port(s) for HBA described
11579  * by sata_hba_inst structure.
11580  *
11581  * Returns:
11582  *	SATA_SUCCESS if device type was successfully probed and port-linked
11583  *		drive info structure was updated;
11584  * 	SATA_FAILURE if there is no device, or device was not probed
11585  *		successully;
11586  *	SATA_RETRY if device probe can be retried later.
11587  * If a device cannot be identified, sata_device's dev_state and dev_type
11588  * fields are set to unknown.
11589  * There are no retries in this function. Any retries should be managed by
11590  * the caller.
11591  */
11592 
11593 
11594 static int
11595 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11596 {
11597 	sata_pmport_info_t *pmportinfo;
11598 	sata_drive_info_t *sdinfo;
11599 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11600 	int rval;
11601 
11602 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11603 	    sata_device->satadev_addr.cport) &
11604 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11605 
11606 	sata_device->satadev_type = SATA_DTYPE_NONE;
11607 
11608 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11609 	    sata_device->satadev_addr.cport)));
11610 
11611 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11612 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11613 		    sata_device->satadev_addr.cport,
11614 		    sata_device->satadev_addr.pmport);
11615 		ASSERT(pmportinfo != NULL);
11616 	}
11617 
11618 	/* Get pointer to port-linked sata device info structure */
11619 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11620 	if (sdinfo != NULL) {
11621 		sdinfo->satadrv_state &=
11622 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11623 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11624 	} else {
11625 		/* No device to probe */
11626 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11627 		    sata_device->satadev_addr.cport)));
11628 		sata_device->satadev_type = SATA_DTYPE_NONE;
11629 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11630 		return (SATA_FAILURE);
11631 	}
11632 	/*
11633 	 * Need to issue both types of identify device command and
11634 	 * determine device type by examining retreived data/status.
11635 	 * First, ATA Identify Device.
11636 	 */
11637 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11638 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11639 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11640 	    sata_device->satadev_addr.cport)));
11641 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11642 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11643 	if (rval == SATA_RETRY) {
11644 		/* We may try to check for ATAPI device */
11645 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11646 			/*
11647 			 * HBA supports ATAPI - try to issue Identify Packet
11648 			 * Device command.
11649 			 */
11650 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11651 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11652 		}
11653 	}
11654 	if (rval == SATA_SUCCESS) {
11655 		/*
11656 		 * Got something responding positively to ATA Identify Device
11657 		 * or to Identify Packet Device cmd.
11658 		 * Save last used device type.
11659 		 */
11660 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11661 
11662 		/* save device info, if possible */
11663 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11664 		    sata_device->satadev_addr.cport)));
11665 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11666 		if (sdinfo == NULL) {
11667 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11668 			    sata_device->satadev_addr.cport)));
11669 			return (SATA_FAILURE);
11670 		}
11671 		/*
11672 		 * Copy drive info into the port-linked drive info structure.
11673 		 */
11674 		*sdinfo = new_sdinfo;
11675 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11676 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11677 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11678 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11679 			    sata_device->satadev_addr.cport) =
11680 			    sdinfo->satadrv_type;
11681 		else { /* SATA_ADDR_DPMPORT */
11682 			mutex_enter(&pmportinfo->pmport_mutex);
11683 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11684 			    sata_device->satadev_addr.cport,
11685 			    sata_device->satadev_addr.pmport) =
11686 			    sdinfo->satadrv_type;
11687 			mutex_exit(&pmportinfo->pmport_mutex);
11688 		}
11689 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11690 		    sata_device->satadev_addr.cport)));
11691 		return (SATA_SUCCESS);
11692 	}
11693 
11694 	/*
11695 	 * It may be SATA_RETRY or SATA_FAILURE return.
11696 	 * Looks like we cannot determine the device type at this time.
11697 	 */
11698 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11699 	    sata_device->satadev_addr.cport)));
11700 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11701 	if (sdinfo != NULL) {
11702 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11703 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11704 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11705 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11706 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11707 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11708 			    sata_device->satadev_addr.cport) =
11709 			    SATA_DTYPE_UNKNOWN;
11710 		else {
11711 			/* SATA_ADDR_DPMPORT */
11712 			mutex_enter(&pmportinfo->pmport_mutex);
11713 			if ((SATA_PMULT_INFO(sata_hba_inst,
11714 			    sata_device->satadev_addr.cport) != NULL) &&
11715 			    (SATA_PMPORT_INFO(sata_hba_inst,
11716 			    sata_device->satadev_addr.cport,
11717 			    sata_device->satadev_addr.pmport) != NULL))
11718 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11719 				    sata_device->satadev_addr.cport,
11720 				    sata_device->satadev_addr.pmport) =
11721 				    SATA_DTYPE_UNKNOWN;
11722 			mutex_exit(&pmportinfo->pmport_mutex);
11723 		}
11724 	}
11725 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11726 	    sata_device->satadev_addr.cport)));
11727 	return (rval);
11728 }
11729 
11730 
11731 /*
11732  * Get pointer to sata_drive_info structure.
11733  *
11734  * The sata_device has to contain address (cport, pmport and qualifier) for
11735  * specified sata_scsi structure.
11736  *
11737  * Returns NULL if device address is not valid for this HBA configuration.
11738  * Otherwise, returns a pointer to sata_drive_info structure.
11739  *
11740  * This function should be called with a port mutex held.
11741  */
11742 static sata_drive_info_t *
11743 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11744     sata_device_t *sata_device)
11745 {
11746 	uint8_t cport = sata_device->satadev_addr.cport;
11747 	uint8_t pmport = sata_device->satadev_addr.pmport;
11748 	uint8_t qual = sata_device->satadev_addr.qual;
11749 
11750 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11751 		return (NULL);
11752 
11753 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11754 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11755 		/* Port not probed yet */
11756 		return (NULL);
11757 
11758 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11759 		return (NULL);
11760 
11761 	if (qual == SATA_ADDR_DCPORT) {
11762 		/* Request for a device on a controller port */
11763 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11764 		    SATA_DTYPE_PMULT)
11765 			/* Port multiplier attached */
11766 			return (NULL);
11767 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11768 	}
11769 	if (qual == SATA_ADDR_DPMPORT) {
11770 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11771 		    SATA_DTYPE_PMULT)
11772 			return (NULL);
11773 
11774 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11775 			return (NULL);
11776 
11777 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11778 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11779 			/* Port multiplier port not probed yet */
11780 			return (NULL);
11781 
11782 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11783 	}
11784 
11785 	/* we should not get here */
11786 	return (NULL);
11787 }
11788 
11789 
11790 /*
11791  * sata_identify_device.
11792  * Send Identify Device command to SATA HBA driver.
11793  * If command executes successfully, update sata_drive_info structure pointed
11794  * to by sdinfo argument, including Identify Device data.
11795  * If command fails, invalidate data in sata_drive_info.
11796  *
11797  * Cannot be called from interrupt level.
11798  *
11799  * Returns:
11800  * SATA_SUCCESS if the device was identified as a supported device,
11801  * SATA_RETRY if the device was not identified but could be retried,
11802  * SATA_FAILURE if the device was not identified and identify attempt
11803  *	should not be retried.
11804  */
11805 static int
11806 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11807     sata_drive_info_t *sdinfo)
11808 {
11809 	uint16_t cfg_word;
11810 	int rval;
11811 
11812 	/* fetch device identify data */
11813 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11814 	    sdinfo)) != SATA_SUCCESS)
11815 		goto fail_unknown;
11816 
11817 	cfg_word = sdinfo->satadrv_id.ai_config;
11818 
11819 	/* Set the correct device type */
11820 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11821 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11822 	} else if (cfg_word == SATA_CFA_TYPE) {
11823 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11824 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11825 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11826 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11827 		case SATA_ATAPI_CDROM_DEV:
11828 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11829 			break;
11830 		case SATA_ATAPI_SQACC_DEV:
11831 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11832 			break;
11833 		case SATA_ATAPI_DIRACC_DEV:
11834 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11835 			break;
11836 		default:
11837 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11838 		}
11839 	} else {
11840 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11841 	}
11842 
11843 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11844 		if (sdinfo->satadrv_capacity == 0) {
11845 			/* Non-LBA disk. Too bad... */
11846 			sata_log(sata_hba_inst, CE_WARN,
11847 			    "SATA disk device at port %d does not support LBA",
11848 			    sdinfo->satadrv_addr.cport);
11849 			rval = SATA_FAILURE;
11850 			goto fail_unknown;
11851 		}
11852 	}
11853 #if 0
11854 	/* Left for historical reason */
11855 	/*
11856 	 * Some initial version of SATA spec indicated that at least
11857 	 * UDMA mode 4 has to be supported. It is not metioned in
11858 	 * SerialATA 2.6, so this restriction is removed.
11859 	 */
11860 	/* Check for Ultra DMA modes 6 through 0 being supported */
11861 	for (i = 6; i >= 0; --i) {
11862 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
11863 			break;
11864 	}
11865 
11866 	/*
11867 	 * At least UDMA 4 mode has to be supported. If mode 4 or
11868 	 * higher are not supported by the device, fail this
11869 	 * device.
11870 	 */
11871 	if (i < 4) {
11872 		/* No required Ultra DMA mode supported */
11873 		sata_log(sata_hba_inst, CE_WARN,
11874 		    "SATA disk device at port %d does not support UDMA "
11875 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
11876 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11877 		    "mode 4 or higher required, %d supported", i));
11878 		rval = SATA_FAILURE;
11879 		goto fail_unknown;
11880 	}
11881 #endif
11882 
11883 	/*
11884 	 * For Disk devices, if it doesn't support UDMA mode, we would
11885 	 * like to return failure directly.
11886 	 */
11887 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
11888 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
11889 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
11890 		sata_log(sata_hba_inst, CE_WARN,
11891 		    "SATA disk device at port %d does not support UDMA",
11892 		    sdinfo->satadrv_addr.cport);
11893 		rval = SATA_FAILURE;
11894 		goto fail_unknown;
11895 	}
11896 
11897 	return (SATA_SUCCESS);
11898 
11899 fail_unknown:
11900 	/* Invalidate sata_drive_info ? */
11901 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11902 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11903 	return (rval);
11904 }
11905 
11906 /*
11907  * Log/display device information
11908  */
11909 static void
11910 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
11911     sata_drive_info_t *sdinfo)
11912 {
11913 	int valid_version;
11914 	char msg_buf[MAXPATHLEN];
11915 	int i;
11916 
11917 	/* Show HBA path */
11918 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
11919 
11920 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
11921 
11922 	switch (sdinfo->satadrv_type) {
11923 	case SATA_DTYPE_ATADISK:
11924 		(void) sprintf(msg_buf, "SATA disk device at");
11925 		break;
11926 
11927 	case SATA_DTYPE_ATAPICD:
11928 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
11929 		break;
11930 
11931 	case SATA_DTYPE_ATAPITAPE:
11932 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
11933 		break;
11934 
11935 	case SATA_DTYPE_ATAPIDISK:
11936 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
11937 		break;
11938 
11939 	case SATA_DTYPE_UNKNOWN:
11940 		(void) sprintf(msg_buf,
11941 		    "Unsupported SATA device type (cfg 0x%x) at ",
11942 		    sdinfo->satadrv_id.ai_config);
11943 		break;
11944 	}
11945 
11946 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
11947 		cmn_err(CE_CONT, "?\t%s port %d\n",
11948 		    msg_buf, sdinfo->satadrv_addr.cport);
11949 	else
11950 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
11951 		    msg_buf, sdinfo->satadrv_addr.cport,
11952 		    sdinfo->satadrv_addr.pmport);
11953 
11954 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
11955 	    sizeof (sdinfo->satadrv_id.ai_model));
11956 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
11957 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
11958 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
11959 
11960 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
11961 	    sizeof (sdinfo->satadrv_id.ai_fw));
11962 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
11963 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
11964 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
11965 
11966 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
11967 	    sizeof (sdinfo->satadrv_id.ai_drvser));
11968 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
11969 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
11970 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11971 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11972 	} else {
11973 		/*
11974 		 * Some drives do not implement serial number and may
11975 		 * violate the spec by providing spaces rather than zeros
11976 		 * in serial number field. Scan the buffer to detect it.
11977 		 */
11978 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
11979 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
11980 				break;
11981 		}
11982 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
11983 			cmn_err(CE_CONT, "?\tserial number - none\n");
11984 		} else {
11985 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11986 		}
11987 	}
11988 
11989 #ifdef SATA_DEBUG
11990 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
11991 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
11992 		int i;
11993 		for (i = 14; i >= 2; i--) {
11994 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
11995 				valid_version = i;
11996 				break;
11997 			}
11998 		}
11999 		cmn_err(CE_CONT,
12000 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12001 		    valid_version,
12002 		    sdinfo->satadrv_id.ai_majorversion,
12003 		    sdinfo->satadrv_id.ai_minorversion);
12004 	}
12005 #endif
12006 	/* Log some info */
12007 	cmn_err(CE_CONT, "?\tsupported features:\n");
12008 	msg_buf[0] = '\0';
12009 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12010 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12011 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12012 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12013 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12014 	}
12015 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12016 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12017 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12018 		(void) strlcat(msg_buf, ", Native Command Queueing",
12019 		    MAXPATHLEN);
12020 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12021 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12022 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12023 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12024 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12025 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12026 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12027 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12028 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12029 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12030 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12031 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12032 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12033 	if (sdinfo->satadrv_features_support &
12034 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12035 		msg_buf[0] = '\0';
12036 		(void) snprintf(msg_buf, MAXPATHLEN,
12037 		    "Supported queue depth %d",
12038 		    sdinfo->satadrv_queue_depth);
12039 		if (!(sata_func_enable &
12040 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12041 			(void) strlcat(msg_buf,
12042 			    " - queueing disabled globally", MAXPATHLEN);
12043 		else if (sdinfo->satadrv_queue_depth >
12044 		    sdinfo->satadrv_max_queue_depth) {
12045 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12046 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12047 			    (int)sdinfo->satadrv_max_queue_depth);
12048 		}
12049 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12050 	}
12051 
12052 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12053 #ifdef __i386
12054 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12055 		    sdinfo->satadrv_capacity);
12056 #else
12057 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12058 		    sdinfo->satadrv_capacity);
12059 #endif
12060 		cmn_err(CE_CONT, "?%s", msg_buf);
12061 	}
12062 }
12063 
12064 /*
12065  * Log/display port multiplier information
12066  * No Mutex should be hold.
12067  */
12068 static void
12069 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12070     sata_device_t *sata_device)
12071 {
12072 	_NOTE(ARGUNUSED(sata_hba_inst))
12073 
12074 	int cport = sata_device->satadev_addr.cport;
12075 	sata_pmult_info_t *pmultinfo;
12076 	char msg_buf[MAXPATHLEN];
12077 	uint32_t gscr0, gscr1, gscr2, gscr64;
12078 
12079 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12080 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12081 	if (pmultinfo == NULL) {
12082 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12083 		return;
12084 	}
12085 
12086 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12087 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12088 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12089 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12090 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12091 
12092 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12093 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12094 
12095 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12096 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12097 	cmn_err(CE_CONT, "?%s", msg_buf);
12098 
12099 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12100 	if (gscr1 & (1 << 3))
12101 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12102 	else if (gscr1 & (1 << 2))
12103 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12104 	else if (gscr1 & (1 << 1))
12105 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12106 	else
12107 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12108 	cmn_err(CE_CONT, "?%s", msg_buf);
12109 
12110 	(void) strcpy(msg_buf, "\tSupport ");
12111 	if (gscr64 & (1 << 3))
12112 		(void) strlcat(msg_buf, "Asy-Notif, ",
12113 		    MAXPATHLEN);
12114 	if (gscr64 & (1 << 2))
12115 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12116 	if (gscr64 & (1 << 1))
12117 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12118 	if (gscr64 & (1 << 0))
12119 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12120 	if ((gscr64 & 0xf) == 0)
12121 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12122 	cmn_err(CE_CONT, "?%s", msg_buf);
12123 
12124 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12125 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12126 	cmn_err(CE_CONT, "?%s", msg_buf);
12127 }
12128 
12129 /*
12130  * sata_save_drive_settings extracts current setting of the device and stores
12131  * it for future reference, in case the device setup would need to be restored
12132  * after the device reset.
12133  *
12134  * For all devices read ahead and write cache settings are saved, if the
12135  * device supports these features at all.
12136  * For ATAPI devices the Removable Media Status Notification setting is saved.
12137  */
12138 static void
12139 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12140 {
12141 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12142 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12143 
12144 		/* Current setting of Read Ahead (and Read Cache) */
12145 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12146 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12147 		else
12148 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12149 
12150 		/* Current setting of Write Cache */
12151 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12152 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12153 		else
12154 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12155 	}
12156 
12157 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12158 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12159 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12160 		else
12161 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12162 	}
12163 }
12164 
12165 
12166 /*
12167  * sata_check_capacity function determines a disk capacity
12168  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12169  *
12170  * NOTE: CHS mode is not supported! If a device does not support LBA,
12171  * this function is not called.
12172  *
12173  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12174  */
12175 static uint64_t
12176 sata_check_capacity(sata_drive_info_t *sdinfo)
12177 {
12178 	uint64_t capacity = 0;
12179 	int i;
12180 
12181 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12182 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12183 		/* Capacity valid only for LBA-addressable disk devices */
12184 		return (0);
12185 
12186 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12187 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12188 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12189 		/* LBA48 mode supported and enabled */
12190 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12191 		    SATA_DEV_F_LBA28;
12192 		for (i = 3;  i >= 0;  --i) {
12193 			capacity <<= 16;
12194 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12195 		}
12196 	} else {
12197 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12198 		capacity <<= 16;
12199 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12200 		if (capacity >= 0x1000000)
12201 			/* LBA28 mode */
12202 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12203 	}
12204 	return (capacity);
12205 }
12206 
12207 
12208 /*
12209  * Allocate consistent buffer for DMA transfer
12210  *
12211  * Cannot be called from interrupt level or with mutex held - it may sleep.
12212  *
12213  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12214  */
12215 static struct buf *
12216 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12217 {
12218 	struct scsi_address ap;
12219 	struct buf *bp;
12220 	ddi_dma_attr_t	cur_dma_attr;
12221 
12222 	ASSERT(spx->txlt_sata_pkt != NULL);
12223 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12224 	ap.a_target = SATA_TO_SCSI_TARGET(
12225 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12226 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12227 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12228 	ap.a_lun = 0;
12229 
12230 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12231 	    B_READ, SLEEP_FUNC, NULL);
12232 
12233 	if (bp != NULL) {
12234 		/* Allocate DMA resources for this buffer */
12235 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12236 		/*
12237 		 * We use a local version of the dma_attr, to account
12238 		 * for a device addressing limitations.
12239 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12240 		 * will cause dma attributes to be adjusted to a lowest
12241 		 * acceptable level.
12242 		 */
12243 		sata_adjust_dma_attr(NULL,
12244 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12245 
12246 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12247 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12248 			scsi_free_consistent_buf(bp);
12249 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12250 			bp = NULL;
12251 		}
12252 	}
12253 	return (bp);
12254 }
12255 
12256 /*
12257  * Release local buffer (consistent buffer for DMA transfer) allocated
12258  * via sata_alloc_local_buffer().
12259  */
12260 static void
12261 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12262 {
12263 	ASSERT(spx->txlt_sata_pkt != NULL);
12264 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12265 
12266 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12267 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12268 
12269 	sata_common_free_dma_rsrcs(spx);
12270 
12271 	/* Free buffer */
12272 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12273 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12274 }
12275 
12276 /*
12277  * Allocate sata_pkt
12278  * Pkt structure version and embedded strcutures version are initialized.
12279  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12280  *
12281  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12282  * callback argument determines if it can sleep or not.
12283  * Hence, it should not be called from interrupt context.
12284  *
12285  * If successful, non-NULL pointer to a sata pkt is returned.
12286  * Upon failure, NULL pointer is returned.
12287  */
12288 static sata_pkt_t *
12289 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12290 {
12291 	sata_pkt_t *spkt;
12292 	int kmsflag;
12293 
12294 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12295 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12296 	if (spkt == NULL) {
12297 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12298 		    "sata_pkt_alloc: failed"));
12299 		return (NULL);
12300 	}
12301 	spkt->satapkt_rev = SATA_PKT_REV;
12302 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12303 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12304 	spkt->satapkt_framework_private = spx;
12305 	spx->txlt_sata_pkt = spkt;
12306 	return (spkt);
12307 }
12308 
12309 /*
12310  * Free sata pkt allocated via sata_pkt_alloc()
12311  */
12312 static void
12313 sata_pkt_free(sata_pkt_txlate_t *spx)
12314 {
12315 	ASSERT(spx->txlt_sata_pkt != NULL);
12316 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12317 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12318 	spx->txlt_sata_pkt = NULL;
12319 }
12320 
12321 
12322 /*
12323  * Adjust DMA attributes.
12324  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12325  * from 8 bits to 16 bits, depending on a command being used.
12326  * Limiting max block count arbitrarily to 256 for all read/write
12327  * commands may affects performance, so check both the device and
12328  * controller capability before adjusting dma attributes.
12329  */
12330 void
12331 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12332     ddi_dma_attr_t *adj_dma_attr)
12333 {
12334 	uint32_t count_max;
12335 
12336 	/* Copy original attributes */
12337 	*adj_dma_attr = *dma_attr;
12338 	/*
12339 	 * Things to consider: device addressing capability,
12340 	 * "excessive" controller DMA capabilities.
12341 	 * If a device is being probed/initialized, there are
12342 	 * no device info - use default limits then.
12343 	 */
12344 	if (sdinfo == NULL) {
12345 		count_max = dma_attr->dma_attr_granular * 0x100;
12346 		if (dma_attr->dma_attr_count_max > count_max)
12347 			adj_dma_attr->dma_attr_count_max = count_max;
12348 		if (dma_attr->dma_attr_maxxfer > count_max)
12349 			adj_dma_attr->dma_attr_maxxfer = count_max;
12350 		return;
12351 	}
12352 
12353 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12354 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12355 			/*
12356 			 * 16-bit sector count may be used - we rely on
12357 			 * the assumption that only read and write cmds
12358 			 * will request more than 256 sectors worth of data
12359 			 */
12360 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12361 		} else {
12362 			/*
12363 			 * 8-bit sector count will be used - default limits
12364 			 * for dma attributes
12365 			 */
12366 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12367 		}
12368 		/*
12369 		 * Adjust controler dma attributes, if necessary
12370 		 */
12371 		if (dma_attr->dma_attr_count_max > count_max)
12372 			adj_dma_attr->dma_attr_count_max = count_max;
12373 		if (dma_attr->dma_attr_maxxfer > count_max)
12374 			adj_dma_attr->dma_attr_maxxfer = count_max;
12375 	}
12376 }
12377 
12378 
12379 /*
12380  * Allocate DMA resources for the buffer
12381  * This function handles initial DMA resource allocation as well as
12382  * DMA window shift and may be called repeatedly for the same DMA window
12383  * until all DMA cookies in the DMA window are processed.
12384  * To guarantee that there is always a coherent set of cookies to process
12385  * by SATA HBA driver (observing alignment, device granularity, etc.),
12386  * the number of slots for DMA cookies is equal to lesser of  a number of
12387  * cookies in a DMA window and a max number of scatter/gather entries.
12388  *
12389  * Returns DDI_SUCCESS upon successful operation.
12390  * Return failure code of a failing command or DDI_FAILURE when
12391  * internal cleanup failed.
12392  */
12393 static int
12394 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12395     int (*callback)(caddr_t), caddr_t arg,
12396     ddi_dma_attr_t *cur_dma_attr)
12397 {
12398 	int	rval;
12399 	off_t	offset;
12400 	size_t	size;
12401 	int	max_sg_len, req_len, i;
12402 	uint_t	dma_flags;
12403 	struct buf	*bp;
12404 	uint64_t	cur_txfer_len;
12405 
12406 
12407 	ASSERT(spx->txlt_sata_pkt != NULL);
12408 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12409 	ASSERT(bp != NULL);
12410 
12411 
12412 	if (spx->txlt_buf_dma_handle == NULL) {
12413 		/*
12414 		 * No DMA resources allocated so far - this is a first call
12415 		 * for this sata pkt.
12416 		 */
12417 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12418 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12419 
12420 		if (rval != DDI_SUCCESS) {
12421 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12422 			    "sata_dma_buf_setup: no buf DMA resources %x",
12423 			    rval));
12424 			return (rval);
12425 		}
12426 
12427 		if (bp->b_flags & B_READ)
12428 			dma_flags = DDI_DMA_READ;
12429 		else
12430 			dma_flags = DDI_DMA_WRITE;
12431 
12432 		if (flags & PKT_CONSISTENT)
12433 			dma_flags |= DDI_DMA_CONSISTENT;
12434 
12435 		if (flags & PKT_DMA_PARTIAL)
12436 			dma_flags |= DDI_DMA_PARTIAL;
12437 
12438 		/*
12439 		 * Check buffer alignment and size against dma attributes
12440 		 * Consider dma_attr_align only. There may be requests
12441 		 * with the size lower than device granularity, but they
12442 		 * will not read/write from/to the device, so no adjustment
12443 		 * is necessary. The dma_attr_minxfer theoretically should
12444 		 * be considered, but no HBA driver is checking it.
12445 		 */
12446 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12447 		    cur_dma_attr->dma_attr_align)) {
12448 			rval = ddi_dma_buf_bind_handle(
12449 			    spx->txlt_buf_dma_handle,
12450 			    bp, dma_flags, callback, arg,
12451 			    &spx->txlt_dma_cookie,
12452 			    &spx->txlt_curwin_num_dma_cookies);
12453 		} else { /* Buffer is not aligned */
12454 
12455 			int	(*ddicallback)(caddr_t);
12456 			size_t	bufsz;
12457 
12458 			/* Check id sleeping is allowed */
12459 			ddicallback = (callback == NULL_FUNC) ?
12460 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12461 
12462 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12463 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12464 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12465 
12466 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12467 				/*
12468 				 * CPU will need to access data in the buffer
12469 				 * (for copying) so map it.
12470 				 */
12471 				bp_mapin(bp);
12472 
12473 			ASSERT(spx->txlt_tmp_buf == NULL);
12474 
12475 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12476 			rval = ddi_dma_mem_alloc(
12477 			    spx->txlt_buf_dma_handle,
12478 			    bp->b_bcount,
12479 			    &sata_acc_attr,
12480 			    DDI_DMA_STREAMING,
12481 			    ddicallback, NULL,
12482 			    &spx->txlt_tmp_buf,
12483 			    &bufsz,
12484 			    &spx->txlt_tmp_buf_handle);
12485 
12486 			if (rval != DDI_SUCCESS) {
12487 				/* DMA mapping failed */
12488 				(void) ddi_dma_free_handle(
12489 				    &spx->txlt_buf_dma_handle);
12490 				spx->txlt_buf_dma_handle = NULL;
12491 #ifdef SATA_DEBUG
12492 				mbuffail_count++;
12493 #endif
12494 				SATADBG1(SATA_DBG_DMA_SETUP,
12495 				    spx->txlt_sata_hba_inst,
12496 				    "sata_dma_buf_setup: "
12497 				    "buf dma mem alloc failed %x\n", rval);
12498 				return (rval);
12499 			}
12500 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12501 			    cur_dma_attr->dma_attr_align));
12502 
12503 #ifdef SATA_DEBUG
12504 			mbuf_count++;
12505 
12506 			if (bp->b_bcount != bufsz)
12507 				/*
12508 				 * This will require special handling, because
12509 				 * DMA cookies will be based on the temporary
12510 				 * buffer size, not the original buffer
12511 				 * b_bcount, so the residue may have to
12512 				 * be counted differently.
12513 				 */
12514 				SATADBG2(SATA_DBG_DMA_SETUP,
12515 				    spx->txlt_sata_hba_inst,
12516 				    "sata_dma_buf_setup: bp size %x != "
12517 				    "bufsz %x\n", bp->b_bcount, bufsz);
12518 #endif
12519 			if (dma_flags & DDI_DMA_WRITE) {
12520 				/*
12521 				 * Write operation - copy data into
12522 				 * an aligned temporary buffer. Buffer will be
12523 				 * synced for device by ddi_dma_addr_bind_handle
12524 				 */
12525 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12526 				    bp->b_bcount);
12527 			}
12528 
12529 			rval = ddi_dma_addr_bind_handle(
12530 			    spx->txlt_buf_dma_handle,
12531 			    NULL,
12532 			    spx->txlt_tmp_buf,
12533 			    bufsz, dma_flags, ddicallback, 0,
12534 			    &spx->txlt_dma_cookie,
12535 			    &spx->txlt_curwin_num_dma_cookies);
12536 		}
12537 
12538 		switch (rval) {
12539 		case DDI_DMA_PARTIAL_MAP:
12540 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12541 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12542 			/*
12543 			 * Partial DMA mapping.
12544 			 * Retrieve number of DMA windows for this request.
12545 			 */
12546 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12547 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12548 				if (spx->txlt_tmp_buf != NULL) {
12549 					ddi_dma_mem_free(
12550 					    &spx->txlt_tmp_buf_handle);
12551 					spx->txlt_tmp_buf = NULL;
12552 				}
12553 				(void) ddi_dma_unbind_handle(
12554 				    spx->txlt_buf_dma_handle);
12555 				(void) ddi_dma_free_handle(
12556 				    &spx->txlt_buf_dma_handle);
12557 				spx->txlt_buf_dma_handle = NULL;
12558 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12559 				    "sata_dma_buf_setup: numwin failed\n"));
12560 				return (DDI_FAILURE);
12561 			}
12562 			SATADBG2(SATA_DBG_DMA_SETUP,
12563 			    spx->txlt_sata_hba_inst,
12564 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12565 			    spx->txlt_num_dma_win,
12566 			    spx->txlt_curwin_num_dma_cookies);
12567 			spx->txlt_cur_dma_win = 0;
12568 			break;
12569 
12570 		case DDI_DMA_MAPPED:
12571 			/* DMA fully mapped */
12572 			spx->txlt_num_dma_win = 1;
12573 			spx->txlt_cur_dma_win = 0;
12574 			SATADBG1(SATA_DBG_DMA_SETUP,
12575 			    spx->txlt_sata_hba_inst,
12576 			    "sata_dma_buf_setup: windows: 1 "
12577 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12578 			break;
12579 
12580 		default:
12581 			/* DMA mapping failed */
12582 			if (spx->txlt_tmp_buf != NULL) {
12583 				ddi_dma_mem_free(
12584 				    &spx->txlt_tmp_buf_handle);
12585 				spx->txlt_tmp_buf = NULL;
12586 			}
12587 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12588 			spx->txlt_buf_dma_handle = NULL;
12589 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12590 			    "sata_dma_buf_setup: buf dma handle binding "
12591 			    "failed %x\n", rval));
12592 			return (rval);
12593 		}
12594 		spx->txlt_curwin_processed_dma_cookies = 0;
12595 		spx->txlt_dma_cookie_list = NULL;
12596 	} else {
12597 		/*
12598 		 * DMA setup is reused. Check if we need to process more
12599 		 * cookies in current window, or to get next window, if any.
12600 		 */
12601 
12602 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12603 		    spx->txlt_curwin_num_dma_cookies);
12604 
12605 		if (spx->txlt_curwin_processed_dma_cookies ==
12606 		    spx->txlt_curwin_num_dma_cookies) {
12607 			/*
12608 			 * All cookies from current DMA window were processed.
12609 			 * Get next DMA window.
12610 			 */
12611 			spx->txlt_cur_dma_win++;
12612 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12613 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12614 				    spx->txlt_cur_dma_win, &offset, &size,
12615 				    &spx->txlt_dma_cookie,
12616 				    &spx->txlt_curwin_num_dma_cookies);
12617 				spx->txlt_curwin_processed_dma_cookies = 0;
12618 			} else {
12619 				/* No more windows! End of request! */
12620 				/* What to do? - panic for now */
12621 				ASSERT(spx->txlt_cur_dma_win >=
12622 				    spx->txlt_num_dma_win);
12623 
12624 				spx->txlt_curwin_num_dma_cookies = 0;
12625 				spx->txlt_curwin_processed_dma_cookies = 0;
12626 				spx->txlt_sata_pkt->
12627 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12628 				return (DDI_SUCCESS);
12629 			}
12630 		}
12631 	}
12632 	/* There better be at least one DMA cookie outstanding */
12633 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12634 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12635 
12636 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12637 		/* The default cookie slot was used in previous run */
12638 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12639 		spx->txlt_dma_cookie_list = NULL;
12640 		spx->txlt_dma_cookie_list_len = 0;
12641 	}
12642 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12643 		/*
12644 		 * Processing a new DMA window - set-up dma cookies list.
12645 		 * We may reuse previously allocated cookie array if it is
12646 		 * possible.
12647 		 */
12648 		if (spx->txlt_dma_cookie_list != NULL &&
12649 		    spx->txlt_dma_cookie_list_len <
12650 		    spx->txlt_curwin_num_dma_cookies) {
12651 			/*
12652 			 * New DMA window contains more cookies than
12653 			 * the previous one. We need larger cookie list - free
12654 			 * the old one.
12655 			 */
12656 			(void) kmem_free(spx->txlt_dma_cookie_list,
12657 			    spx->txlt_dma_cookie_list_len *
12658 			    sizeof (ddi_dma_cookie_t));
12659 			spx->txlt_dma_cookie_list = NULL;
12660 			spx->txlt_dma_cookie_list_len = 0;
12661 		}
12662 		if (spx->txlt_dma_cookie_list == NULL) {
12663 			/*
12664 			 * Calculate lesser of number of cookies in this
12665 			 * DMA window and number of s/g entries.
12666 			 */
12667 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12668 			req_len = MIN(max_sg_len,
12669 			    spx->txlt_curwin_num_dma_cookies);
12670 
12671 			/* Allocate new dma cookie array if necessary */
12672 			if (req_len == 1) {
12673 				/* Only one cookie - no need for a list */
12674 				spx->txlt_dma_cookie_list =
12675 				    &spx->txlt_dma_cookie;
12676 				spx->txlt_dma_cookie_list_len = 1;
12677 			} else {
12678 				/*
12679 				 * More than one cookie - try to allocate space.
12680 				 */
12681 				spx->txlt_dma_cookie_list = kmem_zalloc(
12682 				    sizeof (ddi_dma_cookie_t) * req_len,
12683 				    callback == NULL_FUNC ? KM_NOSLEEP :
12684 				    KM_SLEEP);
12685 				if (spx->txlt_dma_cookie_list == NULL) {
12686 					SATADBG1(SATA_DBG_DMA_SETUP,
12687 					    spx->txlt_sata_hba_inst,
12688 					    "sata_dma_buf_setup: cookie list "
12689 					    "allocation failed\n", NULL);
12690 					/*
12691 					 * We could not allocate space for
12692 					 * neccessary number of dma cookies in
12693 					 * this window, so we fail this request.
12694 					 * Next invocation would try again to
12695 					 * allocate space for cookie list.
12696 					 * Note:Packet residue was not modified.
12697 					 */
12698 					return (DDI_DMA_NORESOURCES);
12699 				} else {
12700 					spx->txlt_dma_cookie_list_len = req_len;
12701 				}
12702 			}
12703 		}
12704 		/*
12705 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12706 		 * First cookie was already fetched.
12707 		 */
12708 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12709 		cur_txfer_len =
12710 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12711 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12712 		spx->txlt_curwin_processed_dma_cookies++;
12713 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12714 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12715 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12716 			    &spx->txlt_dma_cookie_list[i]);
12717 			cur_txfer_len +=
12718 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12719 			spx->txlt_curwin_processed_dma_cookies++;
12720 			spx->txlt_sata_pkt->
12721 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12722 		}
12723 	} else {
12724 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12725 		    "sata_dma_buf_setup: sliding within DMA window, "
12726 		    "cur cookie %d, total cookies %d\n",
12727 		    spx->txlt_curwin_processed_dma_cookies,
12728 		    spx->txlt_curwin_num_dma_cookies);
12729 
12730 		/*
12731 		 * Not all cookies from the current dma window were used because
12732 		 * of s/g limitation.
12733 		 * There is no need to re-size the list - it was set at
12734 		 * optimal size, or only default entry is used (s/g = 1).
12735 		 */
12736 		if (spx->txlt_dma_cookie_list == NULL) {
12737 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12738 			spx->txlt_dma_cookie_list_len = 1;
12739 		}
12740 		/*
12741 		 * Since we are processing remaining cookies in a DMA window,
12742 		 * there may be less of them than the number of entries in the
12743 		 * current dma cookie list.
12744 		 */
12745 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12746 		    (spx->txlt_curwin_num_dma_cookies -
12747 		    spx->txlt_curwin_processed_dma_cookies));
12748 
12749 		/* Fetch the next batch of cookies */
12750 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12751 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12752 			    &spx->txlt_dma_cookie_list[i]);
12753 			cur_txfer_len +=
12754 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12755 			spx->txlt_sata_pkt->
12756 			    satapkt_cmd.satacmd_num_dma_cookies++;
12757 			spx->txlt_curwin_processed_dma_cookies++;
12758 		}
12759 	}
12760 
12761 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12762 
12763 	/* Point sata_cmd to the cookie list */
12764 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12765 	    &spx->txlt_dma_cookie_list[0];
12766 
12767 	/* Remember number of DMA cookies passed in sata packet */
12768 	spx->txlt_num_dma_cookies =
12769 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12770 
12771 	ASSERT(cur_txfer_len != 0);
12772 	if (cur_txfer_len <= bp->b_bcount)
12773 		spx->txlt_total_residue -= cur_txfer_len;
12774 	else {
12775 		/*
12776 		 * Temporary DMA buffer has been padded by
12777 		 * ddi_dma_mem_alloc()!
12778 		 * This requires special handling, because DMA cookies are
12779 		 * based on the temporary buffer size, not the b_bcount,
12780 		 * and we have extra bytes to transfer - but the packet
12781 		 * residue has to stay correct because we will copy only
12782 		 * the requested number of bytes.
12783 		 */
12784 		spx->txlt_total_residue -= bp->b_bcount;
12785 	}
12786 
12787 	return (DDI_SUCCESS);
12788 }
12789 
12790 /*
12791  * Common routine for releasing DMA resources
12792  */
12793 static void
12794 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12795 {
12796 	if (spx->txlt_buf_dma_handle != NULL) {
12797 		if (spx->txlt_tmp_buf != NULL)  {
12798 			/*
12799 			 * Intermediate DMA buffer was allocated.
12800 			 * Free allocated buffer and associated access handle.
12801 			 */
12802 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12803 			spx->txlt_tmp_buf = NULL;
12804 		}
12805 		/*
12806 		 * Free DMA resources - cookies and handles
12807 		 */
12808 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12809 		if (spx->txlt_dma_cookie_list != NULL) {
12810 			if (spx->txlt_dma_cookie_list !=
12811 			    &spx->txlt_dma_cookie) {
12812 				(void) kmem_free(spx->txlt_dma_cookie_list,
12813 				    spx->txlt_dma_cookie_list_len *
12814 				    sizeof (ddi_dma_cookie_t));
12815 				spx->txlt_dma_cookie_list = NULL;
12816 			}
12817 		}
12818 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12819 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12820 		spx->txlt_buf_dma_handle = NULL;
12821 	}
12822 }
12823 
12824 /*
12825  * Free DMA resources
12826  * Used by the HBA driver to release DMA resources that it does not use.
12827  *
12828  * Returns Void
12829  */
12830 void
12831 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12832 {
12833 	sata_pkt_txlate_t *spx;
12834 
12835 	if (sata_pkt == NULL)
12836 		return;
12837 
12838 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12839 
12840 	sata_common_free_dma_rsrcs(spx);
12841 }
12842 
12843 /*
12844  * Fetch Device Identify data.
12845  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12846  * command to a device and get the device identify data.
12847  * The device_info structure has to be set to device type (for selecting proper
12848  * device identify command).
12849  *
12850  * Returns:
12851  * SATA_SUCCESS if cmd succeeded
12852  * SATA_RETRY if cmd was rejected and could be retried,
12853  * SATA_FAILURE if cmd failed and should not be retried (port error)
12854  *
12855  * Cannot be called in an interrupt context.
12856  */
12857 
12858 static int
12859 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
12860     sata_drive_info_t *sdinfo)
12861 {
12862 	struct buf *bp;
12863 	sata_pkt_t *spkt;
12864 	sata_cmd_t *scmd;
12865 	sata_pkt_txlate_t *spx;
12866 	int rval;
12867 
12868 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12869 	spx->txlt_sata_hba_inst = sata_hba_inst;
12870 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12871 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12872 	if (spkt == NULL) {
12873 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12874 		return (SATA_RETRY); /* may retry later */
12875 	}
12876 	/* address is needed now */
12877 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12878 
12879 	/*
12880 	 * Allocate buffer for Identify Data return data
12881 	 */
12882 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
12883 	if (bp == NULL) {
12884 		sata_pkt_free(spx);
12885 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12886 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12887 		    "sata_fetch_device_identify_data: "
12888 		    "cannot allocate buffer for ID"));
12889 		return (SATA_RETRY); /* may retry later */
12890 	}
12891 
12892 	/* Fill sata_pkt */
12893 	sdinfo->satadrv_state = SATA_STATE_PROBING;
12894 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12895 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12896 	/* Synchronous mode, no callback */
12897 	spkt->satapkt_comp = NULL;
12898 	/* Timeout 30s */
12899 	spkt->satapkt_time = sata_default_pkt_time;
12900 
12901 	scmd = &spkt->satapkt_cmd;
12902 	scmd->satacmd_bp = bp;
12903 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12904 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12905 
12906 	/* Build Identify Device cmd in the sata_pkt */
12907 	scmd->satacmd_addr_type = 0;		/* N/A */
12908 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12909 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12910 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
12911 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
12912 	scmd->satacmd_features_reg = 0;		/* N/A */
12913 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12914 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
12915 		/* Identify Packet Device cmd */
12916 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
12917 	} else {
12918 		/* Identify Device cmd - mandatory for all other devices */
12919 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
12920 	}
12921 
12922 	/* Send pkt to SATA HBA driver */
12923 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
12924 
12925 #ifdef SATA_INJECT_FAULTS
12926 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12927 #endif
12928 
12929 	if (rval == SATA_TRAN_ACCEPTED &&
12930 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
12931 		if (spx->txlt_buf_dma_handle != NULL) {
12932 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12933 			    DDI_DMA_SYNC_FORKERNEL);
12934 			ASSERT(rval == DDI_SUCCESS);
12935 		}
12936 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
12937 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
12938 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12939 			    "SATA disk device at port %d - "
12940 			    "partial Identify Data",
12941 			    sdinfo->satadrv_addr.cport));
12942 			rval = SATA_RETRY; /* may retry later */
12943 			goto fail;
12944 		}
12945 		/* Update sata_drive_info */
12946 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
12947 		    sizeof (sata_id_t));
12948 
12949 		sdinfo->satadrv_features_support = 0;
12950 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12951 			/*
12952 			 * Retrieve capacity (disks only) and addressing mode
12953 			 */
12954 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
12955 		} else {
12956 			/*
12957 			 * For ATAPI devices one would have to issue
12958 			 * Get Capacity cmd for media capacity. Not here.
12959 			 */
12960 			sdinfo->satadrv_capacity = 0;
12961 			/*
12962 			 * Check what cdb length is supported
12963 			 */
12964 			if ((sdinfo->satadrv_id.ai_config &
12965 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
12966 				sdinfo->satadrv_atapi_cdb_len = 16;
12967 			else
12968 				sdinfo->satadrv_atapi_cdb_len = 12;
12969 		}
12970 		/* Setup supported features flags */
12971 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
12972 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
12973 
12974 		/* Check for SATA GEN and NCQ support */
12975 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
12976 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
12977 			/* SATA compliance */
12978 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
12979 				sdinfo->satadrv_features_support |=
12980 				    SATA_DEV_F_NCQ;
12981 			if (sdinfo->satadrv_id.ai_satacap &
12982 			    (SATA_1_SPEED | SATA_2_SPEED)) {
12983 				if (sdinfo->satadrv_id.ai_satacap &
12984 				    SATA_2_SPEED)
12985 					sdinfo->satadrv_features_support |=
12986 					    SATA_DEV_F_SATA2;
12987 				if (sdinfo->satadrv_id.ai_satacap &
12988 				    SATA_1_SPEED)
12989 					sdinfo->satadrv_features_support |=
12990 					    SATA_DEV_F_SATA1;
12991 			} else {
12992 				sdinfo->satadrv_features_support |=
12993 				    SATA_DEV_F_SATA1;
12994 			}
12995 		}
12996 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
12997 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
12998 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
12999 
13000 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13001 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13002 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13003 			++sdinfo->satadrv_queue_depth;
13004 			/* Adjust according to controller capabilities */
13005 			sdinfo->satadrv_max_queue_depth = MIN(
13006 			    sdinfo->satadrv_queue_depth,
13007 			    SATA_QDEPTH(sata_hba_inst));
13008 			/* Adjust according to global queue depth limit */
13009 			sdinfo->satadrv_max_queue_depth = MIN(
13010 			    sdinfo->satadrv_max_queue_depth,
13011 			    sata_current_max_qdepth);
13012 			if (sdinfo->satadrv_max_queue_depth == 0)
13013 				sdinfo->satadrv_max_queue_depth = 1;
13014 		} else
13015 			sdinfo->satadrv_max_queue_depth = 1;
13016 
13017 		rval = SATA_SUCCESS;
13018 	} else {
13019 		/*
13020 		 * Woops, no Identify Data.
13021 		 */
13022 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13023 			rval = SATA_RETRY; /* may retry later */
13024 		} else if (rval == SATA_TRAN_ACCEPTED) {
13025 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13026 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13027 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13028 			    spkt->satapkt_reason == SATA_PKT_RESET)
13029 				rval = SATA_RETRY; /* may retry later */
13030 			else
13031 				rval = SATA_FAILURE;
13032 		} else {
13033 			rval = SATA_FAILURE;
13034 		}
13035 	}
13036 fail:
13037 	/* Free allocated resources */
13038 	sata_free_local_buffer(spx);
13039 	sata_pkt_free(spx);
13040 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13041 
13042 	return (rval);
13043 }
13044 
13045 
13046 /*
13047  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13048  * UDMA mode is checked first, followed by MWDMA mode.
13049  * set correctly, so this function is setting it to the highest supported level.
13050  * Older SATA spec required that the device supports at least DMA 4 mode and
13051  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13052  * restriction has been removed.
13053  *
13054  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13055  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13056  *
13057  * NOTE: This function should be called only if DMA mode is supported.
13058  */
13059 static int
13060 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13061 {
13062 	sata_pkt_t *spkt;
13063 	sata_cmd_t *scmd;
13064 	sata_pkt_txlate_t *spx;
13065 	int mode;
13066 	uint8_t subcmd;
13067 	int rval = SATA_SUCCESS;
13068 
13069 	ASSERT(sdinfo != NULL);
13070 	ASSERT(sata_hba_inst != NULL);
13071 
13072 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13073 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13074 		/* Find highest Ultra DMA mode supported */
13075 		for (mode = 6; mode >= 0; --mode) {
13076 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13077 				break;
13078 		}
13079 #if 0
13080 		/* Left for historical reasons */
13081 		/*
13082 		 * Some initial version of SATA spec indicated that at least
13083 		 * UDMA mode 4 has to be supported. It is not mentioned in
13084 		 * SerialATA 2.6, so this restriction is removed.
13085 		 */
13086 		if (mode < 4)
13087 			return (SATA_FAILURE);
13088 #endif
13089 
13090 		/*
13091 		 * We're still going to set DMA mode whatever is selected
13092 		 * by default
13093 		 *
13094 		 * We saw an old maxtor sata drive will select Ultra DMA and
13095 		 * Multi-Word DMA simultaneouly by default, which is going
13096 		 * to cause DMA command timed out, so we need to select DMA
13097 		 * mode even when it's already done by default
13098 		 */
13099 
13100 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13101 
13102 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13103 		/* Find highest MultiWord DMA mode supported */
13104 		for (mode = 2; mode >= 0; --mode) {
13105 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13106 				break;
13107 		}
13108 
13109 		/*
13110 		 * We're still going to set DMA mode whatever is selected
13111 		 * by default
13112 		 *
13113 		 * We saw an old maxtor sata drive will select Ultra DMA and
13114 		 * Multi-Word DMA simultaneouly by default, which is going
13115 		 * to cause DMA command timed out, so we need to select DMA
13116 		 * mode even when it's already done by default
13117 		 */
13118 
13119 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13120 	} else
13121 		return (SATA_SUCCESS);
13122 
13123 	/*
13124 	 * Set DMA mode via SET FEATURES COMMAND.
13125 	 * Prepare packet for SET FEATURES COMMAND.
13126 	 */
13127 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13128 	spx->txlt_sata_hba_inst = sata_hba_inst;
13129 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13130 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13131 	if (spkt == NULL) {
13132 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13133 		    "sata_set_dma_mode: could not set DMA mode %", mode));
13134 		rval = SATA_FAILURE;
13135 		goto done;
13136 	}
13137 	/* Fill sata_pkt */
13138 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13139 	/* Timeout 30s */
13140 	spkt->satapkt_time = sata_default_pkt_time;
13141 	/* Synchronous mode, no callback, interrupts */
13142 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13143 	spkt->satapkt_comp = NULL;
13144 	scmd = &spkt->satapkt_cmd;
13145 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13146 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13147 	scmd->satacmd_addr_type = 0;
13148 	scmd->satacmd_device_reg = 0;
13149 	scmd->satacmd_status_reg = 0;
13150 	scmd->satacmd_error_reg = 0;
13151 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13152 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13153 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13154 
13155 	/* Transfer command to HBA */
13156 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13157 	    spkt) != SATA_TRAN_ACCEPTED ||
13158 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13159 		/* Pkt execution failed */
13160 		rval = SATA_FAILURE;
13161 	}
13162 done:
13163 
13164 	/* Free allocated resources */
13165 	if (spkt != NULL)
13166 		sata_pkt_free(spx);
13167 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13168 
13169 	return (rval);
13170 }
13171 
13172 
13173 /*
13174  * Set device caching mode.
13175  * One of the following operations should be specified:
13176  * SATAC_SF_ENABLE_READ_AHEAD
13177  * SATAC_SF_DISABLE_READ_AHEAD
13178  * SATAC_SF_ENABLE_WRITE_CACHE
13179  * SATAC_SF_DISABLE_WRITE_CACHE
13180  *
13181  * If operation fails, system log messgage is emitted.
13182  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13183  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13184  */
13185 
13186 static int
13187 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13188     int cache_op)
13189 {
13190 	sata_pkt_t *spkt;
13191 	sata_cmd_t *scmd;
13192 	sata_pkt_txlate_t *spx;
13193 	int rval = SATA_SUCCESS;
13194 	int hba_rval;
13195 	char *infop;
13196 
13197 	ASSERT(sdinfo != NULL);
13198 	ASSERT(sata_hba_inst != NULL);
13199 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13200 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13201 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13202 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13203 
13204 
13205 	/* Prepare packet for SET FEATURES COMMAND */
13206 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13207 	spx->txlt_sata_hba_inst = sata_hba_inst;
13208 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13209 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13210 	if (spkt == NULL) {
13211 		rval = SATA_FAILURE;
13212 		goto failure;
13213 	}
13214 	/* Fill sata_pkt */
13215 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13216 	/* Timeout 30s */
13217 	spkt->satapkt_time = sata_default_pkt_time;
13218 	/* Synchronous mode, no callback, interrupts */
13219 	spkt->satapkt_op_mode =
13220 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13221 	spkt->satapkt_comp = NULL;
13222 	scmd = &spkt->satapkt_cmd;
13223 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13224 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13225 	scmd->satacmd_addr_type = 0;
13226 	scmd->satacmd_device_reg = 0;
13227 	scmd->satacmd_status_reg = 0;
13228 	scmd->satacmd_error_reg = 0;
13229 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13230 	scmd->satacmd_features_reg = cache_op;
13231 
13232 	/* Transfer command to HBA */
13233 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13234 	    SATA_DIP(sata_hba_inst), spkt);
13235 
13236 #ifdef SATA_INJECT_FAULTS
13237 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13238 #endif
13239 
13240 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13241 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13242 		/* Pkt execution failed */
13243 		switch (cache_op) {
13244 		case SATAC_SF_ENABLE_READ_AHEAD:
13245 			infop = "enabling read ahead failed";
13246 			break;
13247 		case SATAC_SF_DISABLE_READ_AHEAD:
13248 			infop = "disabling read ahead failed";
13249 			break;
13250 		case SATAC_SF_ENABLE_WRITE_CACHE:
13251 			infop = "enabling write cache failed";
13252 			break;
13253 		case SATAC_SF_DISABLE_WRITE_CACHE:
13254 			infop = "disabling write cache failed";
13255 			break;
13256 		}
13257 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13258 		rval = SATA_RETRY;
13259 	}
13260 failure:
13261 	/* Free allocated resources */
13262 	if (spkt != NULL)
13263 		sata_pkt_free(spx);
13264 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13265 	return (rval);
13266 }
13267 
13268 /*
13269  * Set Removable Media Status Notification (enable/disable)
13270  * state == 0 , disable
13271  * state != 0 , enable
13272  *
13273  * If operation fails, system log messgage is emitted.
13274  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13275  */
13276 
13277 static int
13278 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13279     int state)
13280 {
13281 	sata_pkt_t *spkt;
13282 	sata_cmd_t *scmd;
13283 	sata_pkt_txlate_t *spx;
13284 	int rval = SATA_SUCCESS;
13285 	char *infop;
13286 
13287 	ASSERT(sdinfo != NULL);
13288 	ASSERT(sata_hba_inst != NULL);
13289 
13290 	/* Prepare packet for SET FEATURES COMMAND */
13291 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13292 	spx->txlt_sata_hba_inst = sata_hba_inst;
13293 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13294 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13295 	if (spkt == NULL) {
13296 		rval = SATA_FAILURE;
13297 		goto failure;
13298 	}
13299 	/* Fill sata_pkt */
13300 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13301 	/* Timeout 30s */
13302 	spkt->satapkt_time = sata_default_pkt_time;
13303 	/* Synchronous mode, no callback, interrupts */
13304 	spkt->satapkt_op_mode =
13305 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13306 	spkt->satapkt_comp = NULL;
13307 	scmd = &spkt->satapkt_cmd;
13308 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13309 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13310 	scmd->satacmd_addr_type = 0;
13311 	scmd->satacmd_device_reg = 0;
13312 	scmd->satacmd_status_reg = 0;
13313 	scmd->satacmd_error_reg = 0;
13314 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13315 	if (state == 0)
13316 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13317 	else
13318 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13319 
13320 	/* Transfer command to HBA */
13321 	if (((*SATA_START_FUNC(sata_hba_inst))(
13322 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13323 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13324 		/* Pkt execution failed */
13325 		if (state == 0)
13326 			infop = "disabling Removable Media Status "
13327 			    "Notification failed";
13328 		else
13329 			infop = "enabling Removable Media Status "
13330 			    "Notification failed";
13331 
13332 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13333 		rval = SATA_FAILURE;
13334 	}
13335 failure:
13336 	/* Free allocated resources */
13337 	if (spkt != NULL)
13338 		sata_pkt_free(spx);
13339 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13340 	return (rval);
13341 }
13342 
13343 
13344 /*
13345  * Update state and copy port ss* values from passed sata_device structure.
13346  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13347  * configuration struct.
13348  *
13349  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13350  * regardless of the state in device argument.
13351  *
13352  * Port mutex should be held while calling this function.
13353  */
13354 static void
13355 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13356     sata_device_t *sata_device)
13357 {
13358 	sata_cport_info_t *cportinfo;
13359 
13360 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13361 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13362 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13363 		    sata_device->satadev_addr.cport)
13364 			return;
13365 
13366 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13367 		    sata_device->satadev_addr.cport);
13368 
13369 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13370 		cportinfo->cport_scr = sata_device->satadev_scr;
13371 
13372 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13373 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13374 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13375 		cportinfo->cport_state |=
13376 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13377 	}
13378 }
13379 
13380 void
13381 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13382     sata_device_t *sata_device)
13383 {
13384 	sata_pmport_info_t *pmportinfo;
13385 
13386 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13387 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13388 	    SATA_NUM_PMPORTS(sata_hba_inst,
13389 	    sata_device->satadev_addr.cport) <
13390 	    sata_device->satadev_addr.pmport) {
13391 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13392 		    "sata_update_port_info: error address %p.",
13393 		    &sata_device->satadev_addr);
13394 		return;
13395 	}
13396 
13397 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13398 	    sata_device->satadev_addr.cport,
13399 	    sata_device->satadev_addr.pmport);
13400 
13401 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13402 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13403 
13404 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13405 	pmportinfo->pmport_state &=
13406 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13407 	pmportinfo->pmport_state |=
13408 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13409 }
13410 
13411 /*
13412  * Extract SATA port specification from an IOCTL argument.
13413  *
13414  * This function return the port the user land send us as is, unless it
13415  * cannot retrieve port spec, then -1 is returned.
13416  *
13417  * Support port multiplier.
13418  */
13419 static int32_t
13420 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13421 {
13422 	int32_t port;
13423 
13424 	/* Extract port number from nvpair in dca structure  */
13425 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13426 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13427 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13428 		    port));
13429 		port = -1;
13430 	}
13431 
13432 	return (port);
13433 }
13434 
13435 /*
13436  * Get dev_info_t pointer to the device node pointed to by port argument.
13437  * NOTE: target argument is a value used in ioctls to identify
13438  * the AP - it is not a sata_address.
13439  * It is a combination of cport, pmport and address qualifier, encodded same
13440  * way as a scsi target number.
13441  * At this moment it carries only cport number.
13442  *
13443  * PMult hotplug is supported now.
13444  *
13445  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13446  */
13447 
13448 static dev_info_t *
13449 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13450 {
13451 	dev_info_t	*cdip = NULL;
13452 	int		target, tgt;
13453 	int 		circ;
13454 	uint8_t		qual;
13455 
13456 	sata_hba_inst_t	*sata_hba_inst;
13457 	scsi_hba_tran_t *scsi_hba_tran;
13458 
13459 	/* Get target id */
13460 	scsi_hba_tran = ddi_get_driver_private(dip);
13461 	if (scsi_hba_tran == NULL)
13462 		return (NULL);
13463 
13464 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13465 
13466 	if (sata_hba_inst == NULL)
13467 		return (NULL);
13468 
13469 	/* Identify a port-mult by cport_info.cport_dev_type */
13470 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13471 		qual = SATA_ADDR_DPMPORT;
13472 	else
13473 		qual = SATA_ADDR_DCPORT;
13474 
13475 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13476 
13477 	/* Retrieve target dip */
13478 	ndi_devi_enter(dip, &circ);
13479 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13480 		dev_info_t *next = ddi_get_next_sibling(cdip);
13481 
13482 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13483 		    DDI_PROP_DONTPASS, "target", -1);
13484 		if (tgt == -1) {
13485 			/*
13486 			 * This is actually an error condition, but not
13487 			 * a fatal one. Just continue the search.
13488 			 */
13489 			cdip = next;
13490 			continue;
13491 		}
13492 
13493 		if (tgt == target)
13494 			break;
13495 
13496 		cdip = next;
13497 	}
13498 	ndi_devi_exit(dip, circ);
13499 
13500 	return (cdip);
13501 }
13502 
13503 /*
13504  * Get dev_info_t pointer to the device node pointed to by port argument.
13505  * NOTE: target argument is a value used in ioctls to identify
13506  * the AP - it is not a sata_address.
13507  * It is a combination of cport, pmport and address qualifier, encoded same
13508  * way as a scsi target number.
13509  *
13510  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13511  */
13512 
13513 static dev_info_t *
13514 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13515 {
13516 	dev_info_t	*cdip = NULL;
13517 	int		target, tgt;
13518 	int 		circ;
13519 
13520 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13521 
13522 	ndi_devi_enter(dip, &circ);
13523 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13524 		dev_info_t *next = ddi_get_next_sibling(cdip);
13525 
13526 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13527 		    DDI_PROP_DONTPASS, "target", -1);
13528 		if (tgt == -1) {
13529 			/*
13530 			 * This is actually an error condition, but not
13531 			 * a fatal one. Just continue the search.
13532 			 */
13533 			cdip = next;
13534 			continue;
13535 		}
13536 
13537 		if (tgt == target)
13538 			break;
13539 
13540 		cdip = next;
13541 	}
13542 	ndi_devi_exit(dip, circ);
13543 
13544 	return (cdip);
13545 }
13546 
13547 /*
13548  * Process sata port disconnect request.
13549  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13550  * before this request. Nevertheless, if a device is still configured,
13551  * we need to attempt to offline and unconfigure device.
13552  * Regardless of the unconfigure operation results the port is marked as
13553  * deactivated and no access to the attached device is possible.
13554  * If the target node remains because unconfigure operation failed, its state
13555  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13556  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13557  * the device and remove old target node.
13558  *
13559  * This function invokes sata_hba_inst->satahba_tran->
13560  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13561  * If successful, the device structure (if any) attached to the specified port
13562  * is removed and state of the port marked appropriately.
13563  * Failure of the port_deactivate may keep port in the physically active state,
13564  * or may fail the port.
13565  *
13566  * NOTE: Port multiplier is supported.
13567  */
13568 
13569 static int
13570 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13571     sata_device_t *sata_device)
13572 {
13573 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13574 	sata_cport_info_t *cportinfo = NULL;
13575 	sata_pmport_info_t *pmportinfo = NULL;
13576 	sata_pmult_info_t *pmultinfo = NULL;
13577 	sata_device_t subsdevice;
13578 	int cport, pmport, qual;
13579 	int rval = SATA_SUCCESS;
13580 	int npmport = 0;
13581 	int rv = 0;
13582 
13583 	cport = sata_device->satadev_addr.cport;
13584 	pmport = sata_device->satadev_addr.pmport;
13585 	qual = sata_device->satadev_addr.qual;
13586 
13587 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13588 	if (qual == SATA_ADDR_DCPORT)
13589 		qual = SATA_ADDR_CPORT;
13590 	else
13591 		qual = SATA_ADDR_PMPORT;
13592 
13593 	/*
13594 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13595 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13596 	 * Do the sanity check.
13597 	 */
13598 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13599 		/* No physical port deactivation supported. */
13600 		return (EINVAL);
13601 	}
13602 
13603 	/* Check the current state of the port */
13604 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13605 	    (SATA_DIP(sata_hba_inst), sata_device);
13606 
13607 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13608 
13609 	/*
13610 	 * Processing port mulitiplier
13611 	 */
13612 	if (qual == SATA_ADDR_CPORT &&
13613 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13614 		mutex_enter(&cportinfo->cport_mutex);
13615 
13616 		/* Check controller port status */
13617 		sata_update_port_info(sata_hba_inst, sata_device);
13618 		if (rval != SATA_SUCCESS ||
13619 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13620 			/*
13621 			 * Device port status is unknown or it is in failed
13622 			 * state
13623 			 */
13624 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13625 			    SATA_PSTATE_FAILED;
13626 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13627 			    "sata_hba_ioctl: connect: failed to deactivate "
13628 			    "SATA port %d", cport);
13629 			mutex_exit(&cportinfo->cport_mutex);
13630 			return (EIO);
13631 		}
13632 
13633 		/* Disconnect all sub-devices. */
13634 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13635 		if (pmultinfo != NULL) {
13636 
13637 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13638 			    sata_hba_inst, cport); npmport ++) {
13639 				subsdinfo = SATA_PMPORT_DRV_INFO(
13640 				    sata_hba_inst, cport, npmport);
13641 				if (subsdinfo == NULL)
13642 					continue;
13643 
13644 				subsdevice.satadev_addr = subsdinfo->
13645 				    satadrv_addr;
13646 
13647 				mutex_exit(&cportinfo->cport_mutex);
13648 				if (sata_ioctl_disconnect(sata_hba_inst,
13649 				    &subsdevice) == SATA_SUCCESS) {
13650 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13651 					"[Remove] device at port %d:%d "
13652 					"successfully.", cport, npmport);
13653 				}
13654 				mutex_enter(&cportinfo->cport_mutex);
13655 			}
13656 		}
13657 
13658 		/* Disconnect the port multiplier */
13659 		cportinfo->cport_state &= ~SATA_STATE_READY;
13660 		mutex_exit(&cportinfo->cport_mutex);
13661 
13662 		sata_device->satadev_addr.qual = qual;
13663 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13664 		    (SATA_DIP(sata_hba_inst), sata_device);
13665 
13666 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13667 		    SE_NO_HINT);
13668 
13669 		mutex_enter(&cportinfo->cport_mutex);
13670 		sata_update_port_info(sata_hba_inst, sata_device);
13671 		if (rval != SATA_SUCCESS &&
13672 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13673 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13674 			rv = EIO;
13675 		} else {
13676 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13677 		}
13678 		mutex_exit(&cportinfo->cport_mutex);
13679 
13680 		return (rv);
13681 	}
13682 
13683 	/*
13684 	 * Process non-port-multiplier device - it could be a drive connected
13685 	 * to a port multiplier port or a controller port.
13686 	 */
13687 	if (qual == SATA_ADDR_PMPORT) {
13688 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13689 		mutex_enter(&pmportinfo->pmport_mutex);
13690 		sata_update_pmport_info(sata_hba_inst, sata_device);
13691 		if (rval != SATA_SUCCESS ||
13692 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13693 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13694 			    SATA_PSTATE_FAILED;
13695 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13696 			    "sata_hba_ioctl: connect: failed to deactivate "
13697 			    "SATA port %d:%d", cport, pmport);
13698 			mutex_exit(&pmportinfo->pmport_mutex);
13699 			return (EIO);
13700 		}
13701 
13702 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13703 			sdinfo = pmportinfo->pmport_sata_drive;
13704 			ASSERT(sdinfo != NULL);
13705 		}
13706 
13707 		/*
13708 		 * Set port's dev_state to not ready - this will disable
13709 		 * an access to a potentially attached device.
13710 		 */
13711 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13712 
13713 		/* Remove and release sata_drive info structure. */
13714 		if (sdinfo != NULL) {
13715 			if ((sdinfo->satadrv_type &
13716 			    SATA_VALID_DEV_TYPE) != 0) {
13717 				/*
13718 				 * If a target node exists, try to offline
13719 				 * a device and remove target node.
13720 				 */
13721 				mutex_exit(&pmportinfo->pmport_mutex);
13722 				(void) sata_offline_device(sata_hba_inst,
13723 				    sata_device, sdinfo);
13724 				mutex_enter(&pmportinfo->pmport_mutex);
13725 			}
13726 
13727 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13728 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13729 			(void) kmem_free((void *)sdinfo,
13730 			    sizeof (sata_drive_info_t));
13731 		}
13732 		mutex_exit(&pmportinfo->pmport_mutex);
13733 
13734 	} else if (qual == SATA_ADDR_CPORT) {
13735 		mutex_enter(&cportinfo->cport_mutex);
13736 		sata_update_port_info(sata_hba_inst, sata_device);
13737 		if (rval != SATA_SUCCESS ||
13738 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13739 			/*
13740 			 * Device port status is unknown or it is in failed
13741 			 * state
13742 			 */
13743 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13744 			    SATA_PSTATE_FAILED;
13745 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13746 			    "sata_hba_ioctl: connect: failed to deactivate "
13747 			    "SATA port %d", cport);
13748 			mutex_exit(&cportinfo->cport_mutex);
13749 			return (EIO);
13750 		}
13751 
13752 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13753 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13754 			ASSERT(pmultinfo != NULL);
13755 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13756 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13757 			ASSERT(sdinfo != NULL);
13758 		}
13759 		cportinfo->cport_state &= ~SATA_STATE_READY;
13760 
13761 		if (sdinfo != NULL) {
13762 			if ((sdinfo->satadrv_type &
13763 			    SATA_VALID_DEV_TYPE) != 0) {
13764 				/*
13765 				 * If a target node exists, try to offline
13766 				 * a device and remove target node.
13767 				 */
13768 				mutex_exit(&cportinfo->cport_mutex);
13769 				(void) sata_offline_device(sata_hba_inst,
13770 				    sata_device, sdinfo);
13771 				mutex_enter(&cportinfo->cport_mutex);
13772 			}
13773 
13774 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13775 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13776 			(void) kmem_free((void *)sdinfo,
13777 			    sizeof (sata_drive_info_t));
13778 		}
13779 		mutex_exit(&cportinfo->cport_mutex);
13780 	}
13781 
13782 	/* Just ask HBA driver to deactivate port */
13783 	sata_device->satadev_addr.qual = qual;
13784 
13785 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13786 	    (SATA_DIP(sata_hba_inst), sata_device);
13787 
13788 	/*
13789 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13790 	 * without the hint (to force listener to investivate the state).
13791 	 */
13792 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13793 	    SE_NO_HINT);
13794 
13795 	if (qual == SATA_ADDR_PMPORT) {
13796 		mutex_enter(&pmportinfo->pmport_mutex);
13797 		sata_update_pmport_info(sata_hba_inst, sata_device);
13798 
13799 		if (rval != SATA_SUCCESS &&
13800 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13801 			/*
13802 			 * Port deactivation failure - do not change port
13803 			 * state unless the state returned by HBA indicates a
13804 			 * port failure.
13805 			 *
13806 			 * NOTE: device structures were released, so devices
13807 			 * now are invisible! Port reset is needed to
13808 			 * re-enumerate devices.
13809 			 */
13810 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13811 			rv = EIO;
13812 		} else {
13813 			/*
13814 			 * Deactivation succeded. From now on the sata framework
13815 			 * will not care what is happening to the device, until
13816 			 * the port is activated again.
13817 			 */
13818 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13819 		}
13820 		mutex_exit(&pmportinfo->pmport_mutex);
13821 	} else if (qual == SATA_ADDR_CPORT) {
13822 		mutex_enter(&cportinfo->cport_mutex);
13823 		sata_update_port_info(sata_hba_inst, sata_device);
13824 
13825 		if (rval != SATA_SUCCESS &&
13826 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13827 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13828 			rv = EIO;
13829 		} else {
13830 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13831 		}
13832 		mutex_exit(&cportinfo->cport_mutex);
13833 	}
13834 
13835 	return (rv);
13836 }
13837 
13838 
13839 
13840 /*
13841  * Process sata port connect request
13842  * The sata cfgadm pluging will invoke this operation only if port was found
13843  * in the disconnect state (failed state is also treated as the disconnected
13844  * state).
13845  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
13846  * sata_tran_hotplug_ops->sata_tran_port_activate().
13847  * If successful and a device is found attached to the port,
13848  * the initialization sequence is executed to attach a device structure to
13849  * a port structure. The state of the port and a device would be set
13850  * appropriately.
13851  * The device is not set in configured state (system-wise) by this operation.
13852  *
13853  * Note, that activating the port may generate link events,
13854  * so it is important that following processing and the
13855  * event processing does not interfere with each other!
13856  *
13857  * This operation may remove port failed state and will
13858  * try to make port active and in good standing.
13859  *
13860  * NOTE: Port multiplier is supported.
13861  */
13862 
13863 static int
13864 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
13865     sata_device_t *sata_device)
13866 {
13867 	sata_pmport_info_t	*pmportinfo = NULL;
13868 	uint8_t cport, pmport, qual;
13869 	int rv = 0;
13870 
13871 	cport = sata_device->satadev_addr.cport;
13872 	pmport = sata_device->satadev_addr.pmport;
13873 	qual = sata_device->satadev_addr.qual;
13874 
13875 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13876 	if (qual == SATA_ADDR_DCPORT)
13877 		qual = SATA_ADDR_CPORT;
13878 	else
13879 		qual = SATA_ADDR_PMPORT;
13880 
13881 	if (qual == SATA_ADDR_PMPORT)
13882 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13883 
13884 	/*
13885 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
13886 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
13887 	 * Perform sanity check now.
13888 	 */
13889 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
13890 		/* No physical port activation supported. */
13891 		return (EINVAL);
13892 	}
13893 
13894 	/* Just ask HBA driver to activate port */
13895 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13896 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13897 		/*
13898 		 * Port activation failure.
13899 		 */
13900 		if (qual == SATA_ADDR_CPORT) {
13901 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13902 			    cport)->cport_mutex);
13903 			sata_update_port_info(sata_hba_inst, sata_device);
13904 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13905 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13906 				    SATA_PSTATE_FAILED;
13907 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13908 				    "sata_hba_ioctl: connect: failed to "
13909 				    "activate SATA port %d", cport);
13910 			}
13911 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13912 			    cport)->cport_mutex);
13913 		} else { /* port multiplier device port */
13914 			mutex_enter(&pmportinfo->pmport_mutex);
13915 			sata_update_pmport_info(sata_hba_inst, sata_device);
13916 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13917 				SATA_PMPORT_STATE(sata_hba_inst, cport,
13918 				    pmport) = SATA_PSTATE_FAILED;
13919 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13920 				    "sata_hba_ioctl: connect: failed to "
13921 				    "activate SATA port %d:%d", cport, pmport);
13922 			}
13923 			mutex_exit(&pmportinfo->pmport_mutex);
13924 		}
13925 		return (EIO);
13926 	}
13927 
13928 	/* Virgin port state - will be updated by the port re-probe. */
13929 	if (qual == SATA_ADDR_CPORT) {
13930 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13931 		    cport)->cport_mutex);
13932 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
13933 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13934 		    cport)->cport_mutex);
13935 	} else { /* port multiplier device port */
13936 		mutex_enter(&pmportinfo->pmport_mutex);
13937 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
13938 		mutex_exit(&pmportinfo->pmport_mutex);
13939 	}
13940 
13941 	/*
13942 	 * Probe the port to find its state and attached device.
13943 	 */
13944 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13945 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
13946 		rv = EIO;
13947 
13948 	/*
13949 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13950 	 * without the hint
13951 	 */
13952 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13953 	    SE_NO_HINT);
13954 
13955 	/*
13956 	 * If there is a device attached to the port, emit
13957 	 * a message.
13958 	 */
13959 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
13960 
13961 		if (qual == SATA_ADDR_CPORT) {
13962 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
13963 				sata_log(sata_hba_inst, CE_WARN,
13964 				    "SATA port multiplier detected "
13965 				    "at port %d", cport);
13966 			} else {
13967 				sata_log(sata_hba_inst, CE_WARN,
13968 				    "SATA device detected at port %d", cport);
13969 				if (sata_device->satadev_type ==
13970 				    SATA_DTYPE_UNKNOWN) {
13971 				/*
13972 				 * A device was not successfully identified
13973 				 */
13974 				sata_log(sata_hba_inst, CE_WARN,
13975 				    "Could not identify SATA "
13976 				    "device at port %d", cport);
13977 				}
13978 			}
13979 		} else { /* port multiplier device port */
13980 			sata_log(sata_hba_inst, CE_WARN,
13981 			    "SATA device detected at port %d:%d",
13982 			    cport, pmport);
13983 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13984 				/*
13985 				 * A device was not successfully identified
13986 				 */
13987 				sata_log(sata_hba_inst, CE_WARN,
13988 				    "Could not identify SATA "
13989 				    "device at port %d:%d", cport, pmport);
13990 			}
13991 		}
13992 	}
13993 
13994 	return (rv);
13995 }
13996 
13997 
13998 /*
13999  * Process sata device unconfigure request.
14000  * The unconfigure operation uses generic nexus operation to
14001  * offline a device. It leaves a target device node attached.
14002  * and obviously sata_drive_info attached as well, because
14003  * from the hardware point of view nothing has changed.
14004  */
14005 static int
14006 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14007     sata_device_t *sata_device)
14008 {
14009 	int rv = 0;
14010 	dev_info_t *tdip;
14011 
14012 	/* We are addressing attached device, not a port */
14013 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14014 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14015 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14016 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14017 
14018 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14019 	    &sata_device->satadev_addr)) != NULL) {
14020 
14021 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14022 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14023 			    "sata_hba_ioctl: unconfigure: "
14024 			    "failed to unconfigure device at SATA port %d:%d",
14025 			    sata_device->satadev_addr.cport,
14026 			    sata_device->satadev_addr.pmport));
14027 			rv = EIO;
14028 		}
14029 		/*
14030 		 * The target node devi_state should be marked with
14031 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14032 		 * This would be the indication for cfgadm that
14033 		 * the AP node occupant state is 'unconfigured'.
14034 		 */
14035 
14036 	} else {
14037 		/*
14038 		 * This would indicate a failure on the part of cfgadm
14039 		 * to detect correct state of the node prior to this
14040 		 * call - one cannot unconfigure non-existing device.
14041 		 */
14042 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14043 		    "sata_hba_ioctl: unconfigure: "
14044 		    "attempt to unconfigure non-existing device "
14045 		    "at SATA port %d:%d",
14046 		    sata_device->satadev_addr.cport,
14047 		    sata_device->satadev_addr.pmport));
14048 		rv = ENXIO;
14049 	}
14050 	return (rv);
14051 }
14052 
14053 /*
14054  * Process sata device configure request
14055  * If port is in a failed state, operation is aborted - one has to use
14056  * an explicit connect or port activate request to try to get a port into
14057  * non-failed mode. Port reset wil also work in such situation.
14058  * If the port is in disconnected (shutdown) state, the connect operation is
14059  * attempted prior to any other action.
14060  * When port is in the active state, there is a device attached and the target
14061  * node exists, a device was most likely offlined.
14062  * If target node does not exist, a new target node is created. In both cases
14063  * an attempt is made to online (configure) the device.
14064  *
14065  * NOTE: Port multiplier is supported.
14066  */
14067 static int
14068 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14069     sata_device_t *sata_device)
14070 {
14071 	int cport, pmport, qual;
14072 	int rval;
14073 	boolean_t target = TRUE;
14074 	sata_cport_info_t *cportinfo;
14075 	sata_pmport_info_t *pmportinfo = NULL;
14076 	dev_info_t *tdip;
14077 	sata_drive_info_t *sdinfo;
14078 
14079 	cport = sata_device->satadev_addr.cport;
14080 	pmport = sata_device->satadev_addr.pmport;
14081 	qual = sata_device->satadev_addr.qual;
14082 
14083 	/* Get current port state */
14084 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14085 	    (SATA_DIP(sata_hba_inst), sata_device);
14086 
14087 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14088 	if (qual == SATA_ADDR_DPMPORT) {
14089 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14090 		mutex_enter(&pmportinfo->pmport_mutex);
14091 		sata_update_pmport_info(sata_hba_inst, sata_device);
14092 		if (rval != SATA_SUCCESS ||
14093 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14094 			/*
14095 			 * Obviously, device on a failed port is not visible
14096 			 */
14097 			mutex_exit(&pmportinfo->pmport_mutex);
14098 			return (ENXIO);
14099 		}
14100 		mutex_exit(&pmportinfo->pmport_mutex);
14101 	} else {
14102 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14103 		    cport)->cport_mutex);
14104 		sata_update_port_info(sata_hba_inst, sata_device);
14105 		if (rval != SATA_SUCCESS ||
14106 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14107 			/*
14108 			 * Obviously, device on a failed port is not visible
14109 			 */
14110 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14111 			    cport)->cport_mutex);
14112 			return (ENXIO);
14113 		}
14114 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14115 		    cport)->cport_mutex);
14116 	}
14117 
14118 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14119 		/* need to activate port */
14120 		target = FALSE;
14121 
14122 		/* Sanity check */
14123 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14124 			return (ENXIO);
14125 
14126 		/* Just let HBA driver to activate port */
14127 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14128 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14129 			/*
14130 			 * Port activation failure - do not change port state
14131 			 * unless the state returned by HBA indicates a port
14132 			 * failure.
14133 			 */
14134 			if (qual == SATA_ADDR_DPMPORT) {
14135 				mutex_enter(&pmportinfo->pmport_mutex);
14136 				sata_update_pmport_info(sata_hba_inst,
14137 				    sata_device);
14138 				if (sata_device->satadev_state &
14139 				    SATA_PSTATE_FAILED)
14140 					pmportinfo->pmport_state =
14141 					    SATA_PSTATE_FAILED;
14142 				mutex_exit(&pmportinfo->pmport_mutex);
14143 			} else {
14144 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14145 				    cport)->cport_mutex);
14146 				sata_update_port_info(sata_hba_inst,
14147 				    sata_device);
14148 				if (sata_device->satadev_state &
14149 				    SATA_PSTATE_FAILED)
14150 					cportinfo->cport_state =
14151 					    SATA_PSTATE_FAILED;
14152 				mutex_exit(&SATA_CPORT_INFO(
14153 				    sata_hba_inst, cport)->cport_mutex);
14154 			}
14155 		}
14156 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14157 		    "sata_hba_ioctl: configure: "
14158 		    "failed to activate SATA port %d:%d",
14159 		    cport, pmport));
14160 		return (EIO);
14161 	}
14162 	/*
14163 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14164 	 * without the hint.
14165 	 */
14166 	sata_gen_sysevent(sata_hba_inst,
14167 	    &sata_device->satadev_addr, SE_NO_HINT);
14168 
14169 	/* Virgin port state */
14170 	if (qual == SATA_ADDR_DPMPORT) {
14171 		mutex_enter(&pmportinfo->pmport_mutex);
14172 		pmportinfo->pmport_state = 0;
14173 		mutex_exit(&pmportinfo->pmport_mutex);
14174 	} else {
14175 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14176 		    cport)-> cport_mutex);
14177 		cportinfo->cport_state = 0;
14178 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14179 		    cport)->cport_mutex);
14180 	}
14181 	/*
14182 	 * Always reprobe port, to get current device info.
14183 	 */
14184 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14185 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14186 		return (EIO);
14187 
14188 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14189 		if (qual == SATA_ADDR_DPMPORT) {
14190 			/*
14191 			 * That's the transition from "inactive" port
14192 			 * to active one with device attached.
14193 			 */
14194 			sata_log(sata_hba_inst, CE_WARN,
14195 			    "SATA device detected at port %d:%d",
14196 			    cport, pmport);
14197 		} else {
14198 			/*
14199 			 * When PM is attached to the cport and cport is
14200 			 * activated, every PM device port needs to be reprobed.
14201 			 * We need to emit message for all devices detected
14202 			 * at port multiplier's device ports.
14203 			 * Add such code here.
14204 			 * For now, just inform about device attached to
14205 			 * cport.
14206 			 */
14207 			sata_log(sata_hba_inst, CE_WARN,
14208 			    "SATA device detected at port %d", cport);
14209 		}
14210 	}
14211 
14212 	/*
14213 	 * This is where real configuration operation starts.
14214 	 *
14215 	 * When PM is attached to the cport and cport is activated,
14216 	 * devices attached PM device ports may have to be configured
14217 	 * explicitly. This may change when port multiplier is supported.
14218 	 * For now, configure only disks and other valid target devices.
14219 	 */
14220 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14221 		if (qual == SATA_ADDR_DCPORT) {
14222 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14223 				/*
14224 				 * A device was not successfully identified
14225 				 */
14226 				sata_log(sata_hba_inst, CE_WARN,
14227 				    "Could not identify SATA "
14228 				    "device at port %d", cport);
14229 			}
14230 		} else { /* port multiplier device port */
14231 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14232 				/*
14233 				 * A device was not successfully identified
14234 				 */
14235 				sata_log(sata_hba_inst, CE_WARN,
14236 				    "Could not identify SATA "
14237 				    "device at port %d:%d", cport, pmport);
14238 			}
14239 		}
14240 		return (ENXIO);		/* No device to configure */
14241 	}
14242 
14243 	/*
14244 	 * Here we may have a device in reset condition,
14245 	 * but because we are just configuring it, there is
14246 	 * no need to process the reset other than just
14247 	 * to clear device reset condition in the HBA driver.
14248 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14249 	 * cause a first command sent the HBA driver with the request
14250 	 * to clear device reset condition.
14251 	 */
14252 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14253 	if (qual == SATA_ADDR_DPMPORT)
14254 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14255 	else
14256 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14257 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14258 	if (sdinfo == NULL) {
14259 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14260 		return (ENXIO);
14261 	}
14262 	if (sdinfo->satadrv_event_flags &
14263 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14264 		sdinfo->satadrv_event_flags = 0;
14265 	}
14266 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14267 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14268 
14269 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14270 	    &sata_device->satadev_addr)) != NULL) {
14271 		/*
14272 		 * Target node exists. Verify, that it belongs
14273 		 * to existing, attached device and not to
14274 		 * a removed device.
14275 		 */
14276 		if (sata_check_device_removed(tdip) == B_TRUE) {
14277 			if (qual == SATA_ADDR_DPMPORT)
14278 				sata_log(sata_hba_inst, CE_WARN,
14279 				    "SATA device at port %d cannot be "
14280 				    "configured. "
14281 				    "Application(s) accessing "
14282 				    "previously attached device "
14283 				    "have to release it before newly "
14284 				    "inserted device can be made accessible.",
14285 				    cport);
14286 			else
14287 				sata_log(sata_hba_inst, CE_WARN,
14288 				    "SATA device at port %d:%d cannot be"
14289 				    "configured. "
14290 				    "Application(s) accessing "
14291 				    "previously attached device "
14292 				    "have to release it before newly "
14293 				    "inserted device can be made accessible.",
14294 				    cport, pmport);
14295 			return (EIO);
14296 		}
14297 		/*
14298 		 * Device was not removed and re-inserted.
14299 		 * Try to online it.
14300 		 */
14301 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14302 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14303 			    "sata_hba_ioctl: configure: "
14304 			    "onlining device at SATA port "
14305 			    "%d:%d failed", cport, pmport));
14306 			return (EIO);
14307 		}
14308 
14309 		if (qual == SATA_ADDR_DPMPORT) {
14310 			mutex_enter(&pmportinfo->pmport_mutex);
14311 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14312 			mutex_exit(&pmportinfo->pmport_mutex);
14313 		} else {
14314 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14315 			    cport)->cport_mutex);
14316 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14317 			mutex_exit(&SATA_CPORT_INFO(
14318 			    sata_hba_inst, cport)->cport_mutex);
14319 		}
14320 	} else {
14321 		/*
14322 		 * No target node - need to create a new target node.
14323 		 */
14324 		if (qual == SATA_ADDR_DPMPORT) {
14325 			mutex_enter(&pmportinfo->pmport_mutex);
14326 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14327 			mutex_exit(&pmportinfo->pmport_mutex);
14328 		} else {
14329 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14330 			    cport_mutex);
14331 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14332 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14333 			    cport_mutex);
14334 		}
14335 
14336 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14337 		    sata_hba_inst, &sata_device->satadev_addr);
14338 		if (tdip == NULL) {
14339 			/* Configure operation failed */
14340 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14341 			    "sata_hba_ioctl: configure: "
14342 			    "configuring SATA device at port %d:%d "
14343 			    "failed", cport, pmport));
14344 			return (EIO);
14345 		}
14346 	}
14347 	return (0);
14348 }
14349 
14350 
14351 /*
14352  * Process ioctl deactivate port request.
14353  * Arbitrarily unconfigure attached device, if any.
14354  * Even if the unconfigure fails, proceed with the
14355  * port deactivation.
14356  *
14357  * NOTE: Port Multiplier is supported now.
14358  */
14359 
14360 static int
14361 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14362     sata_device_t *sata_device)
14363 {
14364 	int cport, pmport, qual;
14365 	int rval, rv = 0;
14366 	int npmport;
14367 	sata_cport_info_t *cportinfo;
14368 	sata_pmport_info_t *pmportinfo;
14369 	sata_pmult_info_t *pmultinfo;
14370 	dev_info_t *tdip;
14371 	sata_drive_info_t *sdinfo = NULL;
14372 	sata_device_t subsdevice;
14373 
14374 	/* Sanity check */
14375 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14376 		return (ENOTSUP);
14377 
14378 	cport = sata_device->satadev_addr.cport;
14379 	pmport = sata_device->satadev_addr.pmport;
14380 	qual = sata_device->satadev_addr.qual;
14381 
14382 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14383 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14384 	if (qual == SATA_ADDR_DCPORT)
14385 		qual = SATA_ADDR_CPORT;
14386 	else
14387 		qual = SATA_ADDR_PMPORT;
14388 
14389 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14390 	if (qual == SATA_ADDR_PMPORT)
14391 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14392 
14393 	/*
14394 	 * Processing port multiplier
14395 	 */
14396 	if (qual == SATA_ADDR_CPORT &&
14397 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14398 		mutex_enter(&cportinfo->cport_mutex);
14399 
14400 		/* Deactivate all sub-deices */
14401 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14402 		if (pmultinfo != NULL) {
14403 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14404 			    sata_hba_inst, cport); npmport++) {
14405 
14406 				subsdevice.satadev_addr.cport = cport;
14407 				subsdevice.satadev_addr.pmport =
14408 				    (uint8_t)npmport;
14409 				subsdevice.satadev_addr.qual =
14410 				    SATA_ADDR_DPMPORT;
14411 
14412 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14413 				    "sata_hba_ioctl: deactivate: trying to "
14414 				    "deactivate SATA port %d:%d",
14415 				    cport, npmport);
14416 
14417 				mutex_exit(&cportinfo->cport_mutex);
14418 				if (sata_ioctl_deactivate(sata_hba_inst,
14419 				    &subsdevice) == SATA_SUCCESS) {
14420 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14421 					    "[Deactivate] device at port %d:%d "
14422 					    "successfully.", cport, npmport);
14423 				}
14424 				mutex_enter(&cportinfo->cport_mutex);
14425 			}
14426 		}
14427 
14428 		/* Deactivate the port multiplier now. */
14429 		cportinfo->cport_state &= ~SATA_STATE_READY;
14430 		mutex_exit(&cportinfo->cport_mutex);
14431 
14432 		sata_device->satadev_addr.qual = qual;
14433 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14434 		    (SATA_DIP(sata_hba_inst), sata_device);
14435 
14436 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14437 		    SE_NO_HINT);
14438 
14439 		mutex_enter(&cportinfo->cport_mutex);
14440 		sata_update_port_info(sata_hba_inst, sata_device);
14441 		if (rval != SATA_SUCCESS) {
14442 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14443 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14444 			}
14445 			rv = EIO;
14446 		} else {
14447 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14448 		}
14449 		mutex_exit(&cportinfo->cport_mutex);
14450 
14451 		return (rv);
14452 	}
14453 
14454 	/*
14455 	 * Process non-port-multiplier device - it could be a drive connected
14456 	 * to a port multiplier port or a controller port.
14457 	 */
14458 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14459 	if (qual == SATA_ADDR_CPORT) {
14460 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14461 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14462 			/* deal only with valid devices */
14463 			if ((cportinfo->cport_dev_type &
14464 			    SATA_VALID_DEV_TYPE) != 0)
14465 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14466 		}
14467 		cportinfo->cport_state &= ~SATA_STATE_READY;
14468 	} else {
14469 		/* Port multiplier device port */
14470 		mutex_enter(&pmportinfo->pmport_mutex);
14471 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14472 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14473 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14474 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14475 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14476 		mutex_exit(&pmportinfo->pmport_mutex);
14477 	}
14478 
14479 	if (sdinfo != NULL) {
14480 		/*
14481 		 * If a target node exists, try to offline a device and
14482 		 * to remove a target node.
14483 		 */
14484 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14485 		    cport_mutex);
14486 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14487 		    &sata_device->satadev_addr);
14488 		if (tdip != NULL) {
14489 			/* target node exist */
14490 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14491 			    "sata_hba_ioctl: port deactivate: "
14492 			    "target node exists.", NULL);
14493 
14494 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14495 			    NDI_SUCCESS) {
14496 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14497 				    "sata_hba_ioctl: port deactivate: "
14498 				    "failed to unconfigure device at port "
14499 				    "%d:%d before deactivating the port",
14500 				    cport, pmport));
14501 				/*
14502 				 * Set DEVICE REMOVED state in the target
14503 				 * node. It will prevent an access to
14504 				 * the device even when a new device is
14505 				 * attached, until the old target node is
14506 				 * released, removed and recreated for a new
14507 				 * device.
14508 				 */
14509 				sata_set_device_removed(tdip);
14510 
14511 				/*
14512 				 * Instruct the event daemon to try the
14513 				 * target node cleanup later.
14514 				 */
14515 				sata_set_target_node_cleanup(sata_hba_inst,
14516 				    &sata_device->satadev_addr);
14517 			}
14518 		}
14519 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14520 		    cport_mutex);
14521 		/*
14522 		 * In any case, remove and release sata_drive_info
14523 		 * structure.
14524 		 */
14525 		if (qual == SATA_ADDR_CPORT) {
14526 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14527 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14528 		} else { /* port multiplier device port */
14529 			mutex_enter(&pmportinfo->pmport_mutex);
14530 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14531 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14532 			mutex_exit(&pmportinfo->pmport_mutex);
14533 		}
14534 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14535 	}
14536 
14537 	if (qual == SATA_ADDR_CPORT) {
14538 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14539 		    SATA_STATE_PROBING);
14540 	} else if (qual == SATA_ADDR_PMPORT) {
14541 		mutex_enter(&pmportinfo->pmport_mutex);
14542 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14543 		    SATA_STATE_PROBING);
14544 		mutex_exit(&pmportinfo->pmport_mutex);
14545 	}
14546 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14547 
14548 	/* Just let HBA driver to deactivate port */
14549 	sata_device->satadev_addr.qual = qual;
14550 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14551 	    (SATA_DIP(sata_hba_inst), sata_device);
14552 
14553 	/*
14554 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14555 	 * without the hint
14556 	 */
14557 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14558 	    SE_NO_HINT);
14559 
14560 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14561 	sata_update_port_info(sata_hba_inst, sata_device);
14562 	if (qual == SATA_ADDR_CPORT) {
14563 		if (rval != SATA_SUCCESS) {
14564 			/*
14565 			 * Port deactivation failure - do not change port state
14566 			 * unless the state returned by HBA indicates a port
14567 			 * failure.
14568 			 */
14569 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14570 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14571 				    SATA_PSTATE_FAILED;
14572 			}
14573 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14574 			    "sata_hba_ioctl: port deactivate: "
14575 			    "cannot deactivate SATA port %d", cport));
14576 			rv = EIO;
14577 		} else {
14578 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14579 		}
14580 	} else {
14581 		mutex_enter(&pmportinfo->pmport_mutex);
14582 		if (rval != SATA_SUCCESS) {
14583 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14584 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14585 				    pmport) = SATA_PSTATE_FAILED;
14586 			}
14587 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14588 			    "sata_hba_ioctl: port deactivate: "
14589 			    "cannot deactivate SATA port %d:%d",
14590 			    cport, pmport));
14591 			rv = EIO;
14592 		} else {
14593 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14594 		}
14595 		mutex_exit(&pmportinfo->pmport_mutex);
14596 	}
14597 
14598 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14599 
14600 	return (rv);
14601 }
14602 
14603 /*
14604  * Process ioctl port activate request.
14605  *
14606  * NOTE: Port multiplier is supported now.
14607  */
14608 static int
14609 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14610     sata_device_t *sata_device)
14611 {
14612 	int cport, pmport, qual;
14613 	sata_cport_info_t *cportinfo;
14614 	sata_pmport_info_t *pmportinfo = NULL;
14615 	boolean_t dev_existed = TRUE;
14616 
14617 	/* Sanity check */
14618 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14619 		return (ENOTSUP);
14620 
14621 	cport = sata_device->satadev_addr.cport;
14622 	pmport = sata_device->satadev_addr.pmport;
14623 	qual = sata_device->satadev_addr.qual;
14624 
14625 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14626 
14627 	/*
14628 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14629 	 * is a device. But what we are dealing with is port/pmport.
14630 	 */
14631 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14632 	if (qual == SATA_ADDR_DCPORT)
14633 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14634 	else
14635 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14636 
14637 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14638 	if (qual == SATA_ADDR_PMPORT) {
14639 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14640 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14641 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14642 			dev_existed = FALSE;
14643 	} else { /* cport */
14644 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14645 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14646 			dev_existed = FALSE;
14647 	}
14648 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14649 
14650 	/* Just let HBA driver to activate port, if necessary */
14651 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14652 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14653 		/*
14654 		 * Port activation failure - do not change port state unless
14655 		 * the state returned by HBA indicates a port failure.
14656 		 */
14657 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14658 		    cport)->cport_mutex);
14659 		sata_update_port_info(sata_hba_inst, sata_device);
14660 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14661 			if (qual == SATA_ADDR_PMPORT) {
14662 				mutex_enter(&pmportinfo->pmport_mutex);
14663 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14664 				mutex_exit(&pmportinfo->pmport_mutex);
14665 			} else
14666 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14667 
14668 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14669 			    cport)->cport_mutex);
14670 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14671 			    "sata_hba_ioctl: port activate: cannot activate "
14672 			    "SATA port %d:%d", cport, pmport));
14673 			return (EIO);
14674 		}
14675 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14676 	}
14677 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14678 	if (qual == SATA_ADDR_PMPORT) {
14679 		mutex_enter(&pmportinfo->pmport_mutex);
14680 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14681 		mutex_exit(&pmportinfo->pmport_mutex);
14682 	} else
14683 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14684 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14685 
14686 	/*
14687 	 * Re-probe port to find its current state and possibly attached device.
14688 	 * Port re-probing may change the cportinfo device type if device is
14689 	 * found attached.
14690 	 * If port probing failed, the device type would be set to
14691 	 * SATA_DTYPE_NONE.
14692 	 */
14693 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14694 	    SATA_DEV_IDENTIFY_RETRY);
14695 
14696 	/*
14697 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14698 	 * without the hint.
14699 	 */
14700 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14701 	    SE_NO_HINT);
14702 
14703 	if (dev_existed == FALSE) {
14704 		if (qual == SATA_ADDR_PMPORT &&
14705 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14706 			/*
14707 			 * That's the transition from the "inactive" port state
14708 			 * or the active port without a device attached to the
14709 			 * active port state with a device attached.
14710 			 */
14711 			sata_log(sata_hba_inst, CE_WARN,
14712 			    "SATA device detected at port %d:%d",
14713 			    cport, pmport);
14714 		} else if (qual == SATA_ADDR_CPORT &&
14715 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14716 			/*
14717 			 * That's the transition from the "inactive" port state
14718 			 * or the active port without a device attached to the
14719 			 * active port state with a device attached.
14720 			 */
14721 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14722 				sata_log(sata_hba_inst, CE_WARN,
14723 				    "SATA device detected at port %d", cport);
14724 			} else {
14725 				sata_log(sata_hba_inst, CE_WARN,
14726 				    "SATA port multiplier detected at port %d",
14727 				    cport);
14728 			}
14729 		}
14730 	}
14731 	return (0);
14732 }
14733 
14734 
14735 
14736 /*
14737  * Process ioctl reset port request.
14738  *
14739  * NOTE: Port-Multiplier is supported.
14740  */
14741 static int
14742 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14743     sata_device_t *sata_device)
14744 {
14745 	int cport, pmport, qual;
14746 	int rv = 0;
14747 
14748 	cport = sata_device->satadev_addr.cport;
14749 	pmport = sata_device->satadev_addr.pmport;
14750 	qual = sata_device->satadev_addr.qual;
14751 
14752 	/*
14753 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14754 	 * is a device. But what we are dealing with is port/pmport.
14755 	 */
14756 	if (qual == SATA_ADDR_DCPORT)
14757 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14758 	else
14759 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14760 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14761 
14762 	/* Sanity check */
14763 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14764 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14765 		    "sata_hba_ioctl: sata_hba_tran missing required "
14766 		    "function sata_tran_reset_dport"));
14767 		return (ENOTSUP);
14768 	}
14769 
14770 	/* Ask HBA to reset port */
14771 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14772 	    sata_device) != SATA_SUCCESS) {
14773 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14774 		    "sata_hba_ioctl: reset port: failed %d:%d",
14775 		    cport, pmport));
14776 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14777 		    cport_mutex);
14778 		sata_update_port_info(sata_hba_inst, sata_device);
14779 		if (qual == SATA_ADDR_CPORT)
14780 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14781 			    SATA_PSTATE_FAILED;
14782 		else {
14783 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14784 			    pmport));
14785 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14786 			    SATA_PSTATE_FAILED;
14787 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14788 			    pmport));
14789 		}
14790 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14791 		    cport_mutex);
14792 		rv = EIO;
14793 	}
14794 	/*
14795 	 * Beacuse the port was reset, it should be probed and
14796 	 * attached device reinitialized. At this point the
14797 	 * port state is unknown - it's state is HBA-specific.
14798 	 * Re-probe port to get its state.
14799 	 */
14800 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14801 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14802 		rv = EIO;
14803 	}
14804 	return (rv);
14805 }
14806 
14807 /*
14808  * Process ioctl reset device request.
14809  *
14810  * NOTE: Port multiplier is supported.
14811  */
14812 static int
14813 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14814     sata_device_t *sata_device)
14815 {
14816 	sata_drive_info_t *sdinfo = NULL;
14817 	sata_pmult_info_t *pmultinfo = NULL;
14818 	int cport, pmport;
14819 	int rv = 0;
14820 
14821 	/* Sanity check */
14822 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14823 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14824 		    "sata_hba_ioctl: sata_hba_tran missing required "
14825 		    "function sata_tran_reset_dport"));
14826 		return (ENOTSUP);
14827 	}
14828 
14829 	cport = sata_device->satadev_addr.cport;
14830 	pmport = sata_device->satadev_addr.pmport;
14831 
14832 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14833 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14834 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14835 		    SATA_DTYPE_PMULT)
14836 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
14837 			    cport_devp.cport_sata_pmult;
14838 		else
14839 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14840 			    sata_device->satadev_addr.cport);
14841 	} else { /* port multiplier */
14842 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14843 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14844 		    sata_device->satadev_addr.cport,
14845 		    sata_device->satadev_addr.pmport);
14846 	}
14847 	if (sdinfo == NULL && pmultinfo == NULL) {
14848 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14849 		return (EINVAL);
14850 	}
14851 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14852 
14853 	/* Ask HBA to reset device */
14854 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14855 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14856 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14857 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
14858 		    cport, pmport));
14859 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14860 		    cport_mutex);
14861 		sata_update_port_info(sata_hba_inst, sata_device);
14862 		/*
14863 		 * Device info structure remains attached. Another device reset
14864 		 * or port disconnect/connect and re-probing is
14865 		 * needed to change it's state
14866 		 */
14867 		if (sdinfo != NULL) {
14868 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
14869 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
14870 		} else if (pmultinfo != NULL) {
14871 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
14872 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
14873 		}
14874 
14875 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14876 		rv = EIO;
14877 	}
14878 	/*
14879 	 * If attached device was a port multiplier, some extra processing
14880 	 * may be needed to bring it back. SATA specification requies a
14881 	 * mandatory software reset on host port to reliably enumerate a port
14882 	 * multiplier, the HBA driver should handle that after reset
14883 	 * operation.
14884 	 */
14885 	return (rv);
14886 }
14887 
14888 
14889 /*
14890  * Process ioctl reset all request.
14891  */
14892 static int
14893 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
14894 {
14895 	sata_device_t sata_device;
14896 	int rv = 0;
14897 	int tcport;
14898 	int tpmport = 0;
14899 
14900 	sata_device.satadev_rev = SATA_DEVICE_REV;
14901 
14902 	/*
14903 	 * There is no protection here for configured devices.
14904 	 */
14905 	/* Sanity check */
14906 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14907 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14908 		    "sata_hba_ioctl: sata_hba_tran missing required "
14909 		    "function sata_tran_reset_dport"));
14910 		return (ENOTSUP);
14911 	}
14912 
14913 	/*
14914 	 * Need to lock all ports, not just one.
14915 	 * If any port is locked by event processing, fail the whole operation.
14916 	 * One port is already locked, but for simplicity lock it again.
14917 	 */
14918 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14919 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14920 		    cport_mutex);
14921 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
14922 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
14923 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14924 			    cport_mutex);
14925 			rv = EBUSY;
14926 			break;
14927 		} else {
14928 			/*
14929 			 * It is enough to lock cport in command-based
14930 			 * switching mode.
14931 			 */
14932 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
14933 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
14934 		}
14935 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14936 		    cport_mutex);
14937 	}
14938 
14939 	if (rv == 0) {
14940 		/*
14941 		 * All cports were successfully locked.
14942 		 * Reset main SATA controller.
14943 		 * Set the device address to port 0, to have a valid device
14944 		 * address.
14945 		 */
14946 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
14947 		sata_device.satadev_addr.cport = 0;
14948 		sata_device.satadev_addr.pmport = 0;
14949 
14950 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14951 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
14952 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14953 			    "sata_hba_ioctl: reset controller failed"));
14954 			return (EIO);
14955 		}
14956 		/*
14957 		 * Because ports were reset, port states are unknown.
14958 		 * They should be re-probed to get their state and
14959 		 * attached devices should be reinitialized.
14960 		 */
14961 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
14962 		    tcport++) {
14963 			sata_device.satadev_addr.cport = tcport;
14964 			sata_device.satadev_addr.pmport = tpmport;
14965 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14966 
14967 			/*
14968 			 * The sata_reprobe_port() will mark a
14969 			 * SATA_EVNT_DEVICE_RESET event on the port
14970 			 * multiplier, all its sub-ports will be probed by
14971 			 * sata daemon afterwards.
14972 			 */
14973 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
14974 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14975 				rv = EIO;
14976 		}
14977 	}
14978 	/*
14979 	 * Unlock all ports
14980 	 */
14981 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14982 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14983 		    cport_mutex);
14984 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
14985 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
14986 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14987 		    cport_mutex);
14988 	}
14989 
14990 	/*
14991 	 * This operation returns EFAULT if either reset
14992 	 * controller failed or a re-probing of any port failed.
14993 	 */
14994 	return (rv);
14995 }
14996 
14997 
14998 /*
14999  * Process ioctl port self test request.
15000  *
15001  * NOTE: Port multiplier code is not completed nor tested.
15002  */
15003 static int
15004 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15005     sata_device_t *sata_device)
15006 {
15007 	int cport, pmport, qual;
15008 	int rv = 0;
15009 
15010 	/* Sanity check */
15011 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15012 		return (ENOTSUP);
15013 
15014 	cport = sata_device->satadev_addr.cport;
15015 	pmport = sata_device->satadev_addr.pmport;
15016 	qual = sata_device->satadev_addr.qual;
15017 
15018 	/*
15019 	 * There is no protection here for a configured
15020 	 * device attached to this port.
15021 	 */
15022 
15023 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15024 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15025 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15026 		    "sata_hba_ioctl: port selftest: "
15027 		    "failed port %d:%d", cport, pmport));
15028 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15029 		    cport_mutex);
15030 		sata_update_port_info(sata_hba_inst, sata_device);
15031 		if (qual == SATA_ADDR_CPORT)
15032 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15033 			    SATA_PSTATE_FAILED;
15034 		else { /* port multiplier device port */
15035 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15036 			    cport, pmport));
15037 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15038 			    SATA_PSTATE_FAILED;
15039 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15040 			    cport, pmport));
15041 		}
15042 
15043 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15044 		    cport_mutex);
15045 		return (EIO);
15046 	}
15047 	/*
15048 	 * Beacuse the port was reset in the course of testing, it should be
15049 	 * re-probed and attached device state should be restored. At this
15050 	 * point the port state is unknown - it's state is HBA-specific.
15051 	 * Force port re-probing to get it into a known state.
15052 	 */
15053 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15054 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15055 		rv = EIO;
15056 	return (rv);
15057 }
15058 
15059 
15060 /*
15061  * sata_cfgadm_state:
15062  * Use the sata port state and state of the target node to figure out
15063  * the cfgadm_state.
15064  *
15065  * The port argument is a value with encoded cport,
15066  * pmport and address qualifier, in the same manner as a scsi target number.
15067  * SCSI_TO_SATA_CPORT macro extracts cport number,
15068  * SCSI_TO_SATA_PMPORT extracts pmport number and
15069  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15070  *
15071  * Port multiplier is supported.
15072  */
15073 
15074 static void
15075 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15076     devctl_ap_state_t *ap_state)
15077 {
15078 	uint8_t		cport, pmport, qual;
15079 	uint32_t	port_state, pmult_state;
15080 	uint32_t	dev_type;
15081 	sata_drive_info_t *sdinfo;
15082 
15083 	cport = SCSI_TO_SATA_CPORT(port);
15084 	pmport = SCSI_TO_SATA_PMPORT(port);
15085 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15086 
15087 	/* Check cport state */
15088 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15089 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15090 	    port_state & SATA_PSTATE_FAILED) {
15091 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15092 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15093 		if (port_state & SATA_PSTATE_FAILED)
15094 			ap_state->ap_condition = AP_COND_FAILED;
15095 		else
15096 			ap_state->ap_condition = AP_COND_UNKNOWN;
15097 
15098 		return;
15099 	}
15100 
15101 	/* cport state is okay. Now check pmport state */
15102 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15103 		/* Sanity check */
15104 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15105 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15106 		    cport, pmport) == NULL)
15107 			return;
15108 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15109 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15110 		    port_state & SATA_PSTATE_FAILED) {
15111 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15112 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15113 			if (port_state & SATA_PSTATE_FAILED)
15114 				ap_state->ap_condition = AP_COND_FAILED;
15115 			else
15116 				ap_state->ap_condition = AP_COND_UNKNOWN;
15117 
15118 			return;
15119 		}
15120 	}
15121 
15122 	/* Port is enabled and ready */
15123 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15124 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15125 	else
15126 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15127 
15128 	switch (dev_type) {
15129 	case SATA_DTYPE_NONE:
15130 	{
15131 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15132 		ap_state->ap_condition = AP_COND_OK;
15133 		/* No device attached */
15134 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15135 		break;
15136 	}
15137 	case SATA_DTYPE_PMULT:
15138 	{
15139 		/* Need to check port multiplier state */
15140 		ASSERT(qual == SATA_ADDR_DCPORT);
15141 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15142 		    pmult_state;
15143 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15144 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15145 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15146 			if (pmult_state & SATA_PSTATE_FAILED)
15147 				ap_state->ap_condition = AP_COND_FAILED;
15148 			else
15149 				ap_state->ap_condition = AP_COND_UNKNOWN;
15150 
15151 			return;
15152 		}
15153 
15154 		/* Port multiplier is not configurable */
15155 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15156 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15157 		ap_state->ap_condition = AP_COND_OK;
15158 		break;
15159 	}
15160 
15161 	case SATA_DTYPE_ATADISK:
15162 	case SATA_DTYPE_ATAPICD:
15163 	case SATA_DTYPE_ATAPITAPE:
15164 	case SATA_DTYPE_ATAPIDISK:
15165 	{
15166 		dev_info_t *tdip = NULL;
15167 		dev_info_t *dip = NULL;
15168 		int circ;
15169 
15170 		dip = SATA_DIP(sata_hba_inst);
15171 		tdip = sata_get_target_dip(dip, cport, pmport);
15172 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15173 		if (tdip != NULL) {
15174 			ndi_devi_enter(dip, &circ);
15175 			mutex_enter(&(DEVI(tdip)->devi_lock));
15176 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15177 				/*
15178 				 * There could be the case where previously
15179 				 * configured and opened device was removed
15180 				 * and unknown device was plugged.
15181 				 * In such case we want to show a device, and
15182 				 * its configured or unconfigured state but
15183 				 * indicate unusable condition untill the
15184 				 * old target node is released and removed.
15185 				 */
15186 				ap_state->ap_condition = AP_COND_UNUSABLE;
15187 			} else {
15188 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15189 				    cport));
15190 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15191 				    cport);
15192 				if (sdinfo != NULL) {
15193 					if ((sdinfo->satadrv_state &
15194 					    SATA_DSTATE_FAILED) != 0)
15195 						ap_state->ap_condition =
15196 						    AP_COND_FAILED;
15197 					else
15198 						ap_state->ap_condition =
15199 						    AP_COND_OK;
15200 				} else {
15201 					ap_state->ap_condition =
15202 					    AP_COND_UNKNOWN;
15203 				}
15204 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15205 				    cport));
15206 			}
15207 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15208 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15209 				ap_state->ap_ostate =
15210 				    AP_OSTATE_UNCONFIGURED;
15211 			} else {
15212 				ap_state->ap_ostate =
15213 				    AP_OSTATE_CONFIGURED;
15214 			}
15215 			mutex_exit(&(DEVI(tdip)->devi_lock));
15216 			ndi_devi_exit(dip, circ);
15217 		} else {
15218 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15219 			ap_state->ap_condition = AP_COND_UNKNOWN;
15220 		}
15221 		break;
15222 	}
15223 	default:
15224 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15225 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15226 		ap_state->ap_condition = AP_COND_UNKNOWN;
15227 		/*
15228 		 * This is actually internal error condition (non fatal),
15229 		 * because we have already checked all defined device types.
15230 		 */
15231 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15232 		    "sata_cfgadm_state: Internal error: "
15233 		    "unknown device type"));
15234 		break;
15235 	}
15236 }
15237 
15238 
15239 /*
15240  * Process ioctl get device path request.
15241  *
15242  * NOTE: Port multiplier has no target dip. Devices connected to port
15243  * multiplier have target node attached to the HBA node. The only difference
15244  * between them and the directly-attached device node is a target address.
15245  */
15246 static int
15247 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15248     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15249 {
15250 	char path[MAXPATHLEN];
15251 	uint32_t size;
15252 	dev_info_t *tdip;
15253 
15254 	(void) strcpy(path, "/devices");
15255 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15256 	    &sata_device->satadev_addr)) == NULL) {
15257 		/*
15258 		 * No such device. If this is a request for a size, do not
15259 		 * return EINVAL for non-existing target, because cfgadm
15260 		 * will then indicate a meaningless ioctl failure.
15261 		 * If this is a request for a path, indicate invalid
15262 		 * argument.
15263 		 */
15264 		if (ioc->get_size == 0)
15265 			return (EINVAL);
15266 	} else {
15267 		(void) ddi_pathname(tdip, path + strlen(path));
15268 	}
15269 	size = strlen(path) + 1;
15270 
15271 	if (ioc->get_size != 0) {
15272 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15273 		    mode) != 0)
15274 			return (EFAULT);
15275 	} else {
15276 		if (ioc->bufsiz != size)
15277 			return (EINVAL);
15278 
15279 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15280 		    mode) != 0)
15281 			return (EFAULT);
15282 	}
15283 	return (0);
15284 }
15285 
15286 /*
15287  * Process ioctl get attachment point type request.
15288  *
15289  * NOTE: Port multiplier is supported.
15290  */
15291 static	int
15292 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15293     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15294 {
15295 	uint32_t	type_len;
15296 	const char	*ap_type;
15297 	int		dev_type;
15298 
15299 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15300 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15301 		    sata_device->satadev_addr.cport);
15302 	else /* pmport */
15303 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15304 		    sata_device->satadev_addr.cport,
15305 		    sata_device->satadev_addr.pmport);
15306 
15307 	switch (dev_type) {
15308 	case SATA_DTYPE_NONE:
15309 		ap_type = "port";
15310 		break;
15311 
15312 	case SATA_DTYPE_ATADISK:
15313 	case SATA_DTYPE_ATAPIDISK:
15314 		ap_type = "disk";
15315 		break;
15316 
15317 	case SATA_DTYPE_ATAPICD:
15318 		ap_type = "cd/dvd";
15319 		break;
15320 
15321 	case SATA_DTYPE_ATAPITAPE:
15322 		ap_type = "tape";
15323 		break;
15324 
15325 	case SATA_DTYPE_PMULT:
15326 		ap_type = "sata-pmult";
15327 		break;
15328 
15329 	case SATA_DTYPE_UNKNOWN:
15330 		ap_type = "unknown";
15331 		break;
15332 
15333 	default:
15334 		ap_type = "unsupported";
15335 		break;
15336 
15337 	} /* end of dev_type switch */
15338 
15339 	type_len = strlen(ap_type) + 1;
15340 
15341 	if (ioc->get_size) {
15342 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15343 		    mode) != 0)
15344 			return (EFAULT);
15345 	} else {
15346 		if (ioc->bufsiz != type_len)
15347 			return (EINVAL);
15348 
15349 		if (ddi_copyout((void *)ap_type, ioc->buf,
15350 		    ioc->bufsiz, mode) != 0)
15351 			return (EFAULT);
15352 	}
15353 	return (0);
15354 
15355 }
15356 
15357 /*
15358  * Process ioctl get device model info request.
15359  * This operation should return to cfgadm the device model
15360  * information string
15361  *
15362  * NOTE: Port multiplier is supported.
15363  */
15364 static	int
15365 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15366     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15367 {
15368 	sata_drive_info_t *sdinfo;
15369 	uint32_t info_len;
15370 	char ap_info[SATA_ID_MODEL_LEN + 1];
15371 
15372 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15373 	    sata_device->satadev_addr.cport)->cport_mutex);
15374 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15375 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15376 		    sata_device->satadev_addr.cport);
15377 	else /* port multiplier */
15378 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15379 		    sata_device->satadev_addr.cport,
15380 		    sata_device->satadev_addr.pmport);
15381 	if (sdinfo == NULL) {
15382 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15383 		    sata_device->satadev_addr.cport)->cport_mutex);
15384 		return (EINVAL);
15385 	}
15386 
15387 #ifdef	_LITTLE_ENDIAN
15388 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15389 #else	/* _LITTLE_ENDIAN */
15390 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15391 #endif	/* _LITTLE_ENDIAN */
15392 
15393 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15394 	    sata_device->satadev_addr.cport)->cport_mutex);
15395 
15396 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15397 
15398 	info_len = strlen(ap_info) + 1;
15399 
15400 	if (ioc->get_size) {
15401 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15402 		    mode) != 0)
15403 			return (EFAULT);
15404 	} else {
15405 		if (ioc->bufsiz < info_len)
15406 			return (EINVAL);
15407 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15408 		    mode) != 0)
15409 			return (EFAULT);
15410 	}
15411 	return (0);
15412 }
15413 
15414 
15415 /*
15416  * Process ioctl get device firmware revision info request.
15417  * This operation should return to cfgadm the device firmware revision
15418  * information string
15419  *
15420  * Port multiplier is supported.
15421  */
15422 static	int
15423 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15424     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15425 {
15426 	sata_drive_info_t *sdinfo;
15427 	uint32_t info_len;
15428 	char ap_info[SATA_ID_FW_LEN + 1];
15429 
15430 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15431 	    sata_device->satadev_addr.cport)->cport_mutex);
15432 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15433 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15434 		    sata_device->satadev_addr.cport);
15435 	else /* port multiplier */
15436 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15437 		    sata_device->satadev_addr.cport,
15438 		    sata_device->satadev_addr.pmport);
15439 	if (sdinfo == NULL) {
15440 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15441 		    sata_device->satadev_addr.cport)->cport_mutex);
15442 		return (EINVAL);
15443 	}
15444 
15445 #ifdef	_LITTLE_ENDIAN
15446 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15447 #else	/* _LITTLE_ENDIAN */
15448 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15449 #endif	/* _LITTLE_ENDIAN */
15450 
15451 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15452 	    sata_device->satadev_addr.cport)->cport_mutex);
15453 
15454 	ap_info[SATA_ID_FW_LEN] = '\0';
15455 
15456 	info_len = strlen(ap_info) + 1;
15457 
15458 	if (ioc->get_size) {
15459 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15460 		    mode) != 0)
15461 			return (EFAULT);
15462 	} else {
15463 		if (ioc->bufsiz < info_len)
15464 			return (EINVAL);
15465 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15466 		    mode) != 0)
15467 			return (EFAULT);
15468 	}
15469 	return (0);
15470 }
15471 
15472 
15473 /*
15474  * Process ioctl get device serial number info request.
15475  * This operation should return to cfgadm the device serial number string.
15476  *
15477  * NOTE: Port multiplier is supported.
15478  */
15479 static	int
15480 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15481     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15482 {
15483 	sata_drive_info_t *sdinfo;
15484 	uint32_t info_len;
15485 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15486 
15487 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15488 	    sata_device->satadev_addr.cport)->cport_mutex);
15489 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15490 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15491 		    sata_device->satadev_addr.cport);
15492 	else /* port multiplier */
15493 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15494 		    sata_device->satadev_addr.cport,
15495 		    sata_device->satadev_addr.pmport);
15496 	if (sdinfo == NULL) {
15497 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15498 		    sata_device->satadev_addr.cport)->cport_mutex);
15499 		return (EINVAL);
15500 	}
15501 
15502 #ifdef	_LITTLE_ENDIAN
15503 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15504 #else	/* _LITTLE_ENDIAN */
15505 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15506 #endif	/* _LITTLE_ENDIAN */
15507 
15508 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15509 	    sata_device->satadev_addr.cport)->cport_mutex);
15510 
15511 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15512 
15513 	info_len = strlen(ap_info) + 1;
15514 
15515 	if (ioc->get_size) {
15516 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15517 		    mode) != 0)
15518 			return (EFAULT);
15519 	} else {
15520 		if (ioc->bufsiz < info_len)
15521 			return (EINVAL);
15522 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15523 		    mode) != 0)
15524 			return (EFAULT);
15525 	}
15526 	return (0);
15527 }
15528 
15529 
15530 /*
15531  * Preset scsi extended sense data (to NO SENSE)
15532  * First 18 bytes of the sense data are preset to current valid sense
15533  * with a key NO SENSE data.
15534  *
15535  * Returns void
15536  */
15537 static void
15538 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15539 {
15540 	sense->es_valid = 1;		/* Valid sense */
15541 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15542 	sense->es_key = KEY_NO_SENSE;
15543 	sense->es_info_1 = 0;
15544 	sense->es_info_2 = 0;
15545 	sense->es_info_3 = 0;
15546 	sense->es_info_4 = 0;
15547 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15548 	sense->es_cmd_info[0] = 0;
15549 	sense->es_cmd_info[1] = 0;
15550 	sense->es_cmd_info[2] = 0;
15551 	sense->es_cmd_info[3] = 0;
15552 	sense->es_add_code = 0;
15553 	sense->es_qual_code = 0;
15554 }
15555 
15556 /*
15557  * Register a legacy cmdk-style devid for the target (disk) device.
15558  *
15559  * Note: This function is called only when the HBA devinfo node has the
15560  * property "use-cmdk-devid-format" set. This property indicates that
15561  * devid compatible with old cmdk (target) driver is to be generated
15562  * for any target device attached to this controller. This will take
15563  * precedence over the devid generated by sd (target) driver.
15564  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15565  */
15566 static void
15567 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15568 {
15569 	char	*hwid;
15570 	int	modlen;
15571 	int	serlen;
15572 	int	rval;
15573 	ddi_devid_t	devid;
15574 
15575 	/*
15576 	 * device ID is a concatanation of model number, "=", serial number.
15577 	 */
15578 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15579 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15580 	    sizeof (sdinfo->satadrv_id.ai_model));
15581 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15582 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15583 	if (modlen == 0)
15584 		goto err;
15585 	hwid[modlen++] = '=';
15586 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15587 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15588 	swab(&hwid[modlen], &hwid[modlen],
15589 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15590 	serlen = sata_check_modser(&hwid[modlen],
15591 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15592 	if (serlen == 0)
15593 		goto err;
15594 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15595 
15596 	/* initialize/register devid */
15597 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15598 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15599 		rval = ddi_devid_register(dip, devid);
15600 		/*
15601 		 * Free up the allocated devid buffer.
15602 		 * NOTE: This doesn't mean unregistering devid.
15603 		 */
15604 		ddi_devid_free(devid);
15605 	}
15606 
15607 	if (rval != DDI_SUCCESS)
15608 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15609 		    " on port %d", sdinfo->satadrv_addr.cport);
15610 err:
15611 	kmem_free(hwid, LEGACY_HWID_LEN);
15612 }
15613 
15614 /*
15615  * valid model/serial string must contain a non-zero non-space characters.
15616  * trim trailing spaces/NULLs.
15617  */
15618 static int
15619 sata_check_modser(char *buf, int buf_len)
15620 {
15621 	boolean_t ret;
15622 	char *s;
15623 	int i;
15624 	int tb;
15625 	char ch;
15626 
15627 	ret = B_FALSE;
15628 	s = buf;
15629 	for (i = 0; i < buf_len; i++) {
15630 		ch = *s++;
15631 		if (ch != ' ' && ch != '\0')
15632 			tb = i + 1;
15633 		if (ch != ' ' && ch != '\0' && ch != '0')
15634 			ret = B_TRUE;
15635 	}
15636 
15637 	if (ret == B_FALSE)
15638 		return (0); /* invalid string */
15639 
15640 	return (tb); /* return length */
15641 }
15642 
15643 /*
15644  * sata_set_drive_features function compares current device features setting
15645  * with the saved device features settings and, if there is a difference,
15646  * it restores device features setting to the previously saved state.
15647  * It also arbitrarily tries to select the highest supported DMA mode.
15648  * Device Identify or Identify Packet Device data has to be current.
15649  * At the moment read ahead and write cache are considered for all devices.
15650  * For atapi devices, Removable Media Status Notification is set in addition
15651  * to common features.
15652  *
15653  * This function cannot be called in the interrupt context (it may sleep).
15654  *
15655  * The input argument sdinfo should point to the drive info structure
15656  * to be updated after features are set. Note, that only
15657  * device (packet) identify data is updated, not the flags indicating the
15658  * supported features.
15659  *
15660  * Returns SATA_SUCCESS if successful or there was nothing to do.
15661  * Device Identify data in the drive info structure pointed to by the sdinfo
15662  * arguments is updated even when no features were set or changed.
15663  *
15664  * Returns SATA_FAILURE if device features could not be set or DMA mode
15665  * for a disk cannot be set and device identify data cannot be fetched.
15666  *
15667  * Returns SATA_RETRY if device features could not be set (other than disk
15668  * DMA mode) but the device identify data was fetched successfully.
15669  *
15670  * Note: This function may fail the port, making it inaccessible.
15671  * In such case the explicit port disconnect/connect or physical device
15672  * detach/attach is required to re-evaluate port state again.
15673  */
15674 
15675 static int
15676 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15677     sata_drive_info_t *sdinfo, int restore)
15678 {
15679 	int rval = SATA_SUCCESS;
15680 	int rval_set;
15681 	sata_drive_info_t new_sdinfo;
15682 	char *finfo = "sata_set_drive_features: cannot";
15683 	char *finfox;
15684 	int cache_op;
15685 
15686 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15687 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15688 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15689 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15690 		/*
15691 		 * Cannot get device identification - caller may retry later
15692 		 */
15693 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15694 		    "%s fetch device identify data\n", finfo);
15695 		return (SATA_FAILURE);
15696 	}
15697 	finfox = (restore != 0) ? " restore device features" :
15698 	    " initialize device features\n";
15699 
15700 	switch (sdinfo->satadrv_type) {
15701 	case SATA_DTYPE_ATADISK:
15702 		/* Arbitrarily set UDMA mode */
15703 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15704 		    SATA_SUCCESS) {
15705 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15706 			    "%s set UDMA mode\n", finfo));
15707 			return (SATA_FAILURE);
15708 		}
15709 		break;
15710 	case SATA_DTYPE_ATAPICD:
15711 	case SATA_DTYPE_ATAPITAPE:
15712 	case SATA_DTYPE_ATAPIDISK:
15713 		/*  Set Removable Media Status Notification, if necessary */
15714 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15715 		    restore != 0) {
15716 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15717 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15718 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15719 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15720 				/* Current setting does not match saved one */
15721 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15722 				    sdinfo->satadrv_settings &
15723 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15724 					rval = SATA_FAILURE;
15725 			}
15726 		}
15727 		/*
15728 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15729 		 * we want to use DMA transfer mode whenever possible.
15730 		 * Some devices require explicit setting of the DMA mode.
15731 		 */
15732 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15733 			/* Set highest supported DMA mode */
15734 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15735 			    SATA_SUCCESS) {
15736 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15737 				    "%s set UDMA mode\n", finfo));
15738 				rval = SATA_FAILURE;
15739 			}
15740 		}
15741 		break;
15742 	}
15743 
15744 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15745 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15746 		/*
15747 		 * neither READ AHEAD nor WRITE CACHE is supported
15748 		 * - do nothing
15749 		 */
15750 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15751 		    "settable features not supported\n", NULL);
15752 		goto update_sdinfo;
15753 	}
15754 
15755 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15756 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15757 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15758 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15759 		/*
15760 		 * both READ AHEAD and WRITE CACHE are enabled
15761 		 * - Nothing to do
15762 		 */
15763 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15764 		    "no device features to set\n", NULL);
15765 		goto update_sdinfo;
15766 	}
15767 
15768 	cache_op = 0;
15769 
15770 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15771 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15772 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15773 			/* Enable read ahead / read cache */
15774 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15775 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15776 			    "enabling read cache\n", NULL);
15777 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15778 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15779 			/* Disable read ahead  / read cache */
15780 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15781 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15782 			    "disabling read cache\n", NULL);
15783 		}
15784 
15785 		if (cache_op != 0) {
15786 			/* Try to set read cache mode */
15787 			rval_set = sata_set_cache_mode(sata_hba_inst,
15788 			    &new_sdinfo, cache_op);
15789 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15790 				rval = rval_set;
15791 		}
15792 	}
15793 
15794 	cache_op = 0;
15795 
15796 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15797 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15798 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15799 			/* Enable write cache */
15800 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15801 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15802 			    "enabling write cache\n", NULL);
15803 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15804 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15805 			/* Disable write cache */
15806 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15807 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15808 			    "disabling write cache\n", NULL);
15809 		}
15810 
15811 		if (cache_op != 0) {
15812 			/* Try to set write cache mode */
15813 			rval_set = sata_set_cache_mode(sata_hba_inst,
15814 			    &new_sdinfo, cache_op);
15815 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15816 				rval = rval_set;
15817 		}
15818 	}
15819 	if (rval != SATA_SUCCESS)
15820 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15821 		    "%s %s", finfo, finfox));
15822 
15823 update_sdinfo:
15824 	/*
15825 	 * We need to fetch Device Identify data again
15826 	 */
15827 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15828 		/*
15829 		 * Cannot get device identification - retry later
15830 		 */
15831 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15832 		    "%s re-fetch device identify data\n", finfo));
15833 		rval = SATA_FAILURE;
15834 	}
15835 	/* Copy device sata info. */
15836 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
15837 
15838 	return (rval);
15839 }
15840 
15841 
15842 /*
15843  *
15844  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
15845  * unable to determine.
15846  *
15847  * Cannot be called in an interrupt context.
15848  *
15849  * Called by sata_build_lsense_page_2f()
15850  */
15851 
15852 static int
15853 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
15854     sata_drive_info_t *sdinfo)
15855 {
15856 	sata_pkt_t *spkt;
15857 	sata_cmd_t *scmd;
15858 	sata_pkt_txlate_t *spx;
15859 	int rval;
15860 
15861 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15862 	spx->txlt_sata_hba_inst = sata_hba_inst;
15863 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15864 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15865 	if (spkt == NULL) {
15866 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15867 		return (-1);
15868 	}
15869 	/* address is needed now */
15870 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15871 
15872 
15873 	/* Fill sata_pkt */
15874 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15875 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15876 	/* Synchronous mode, no callback */
15877 	spkt->satapkt_comp = NULL;
15878 	/* Timeout 30s */
15879 	spkt->satapkt_time = sata_default_pkt_time;
15880 
15881 	scmd = &spkt->satapkt_cmd;
15882 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
15883 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
15884 
15885 	/* Set up which registers need to be returned */
15886 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
15887 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
15888 
15889 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
15890 	scmd->satacmd_addr_type = 0;		/* N/A */
15891 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15892 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15893 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15894 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15895 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
15896 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15897 	scmd->satacmd_cmd_reg = SATAC_SMART;
15898 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15899 	    sdinfo->satadrv_addr.cport)));
15900 
15901 
15902 	/* Send pkt to SATA HBA driver */
15903 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15904 	    SATA_TRAN_ACCEPTED ||
15905 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15906 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15907 		    sdinfo->satadrv_addr.cport)));
15908 		/*
15909 		 * Whoops, no SMART RETURN STATUS
15910 		 */
15911 		rval = -1;
15912 	} else {
15913 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15914 		    sdinfo->satadrv_addr.cport)));
15915 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
15916 			rval = -1;
15917 			goto fail;
15918 		}
15919 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
15920 			rval = -1;
15921 			goto fail;
15922 		}
15923 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
15924 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
15925 			rval = 0;
15926 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
15927 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
15928 			rval = 1;
15929 		else {
15930 			rval = -1;
15931 			goto fail;
15932 		}
15933 	}
15934 fail:
15935 	/* Free allocated resources */
15936 	sata_pkt_free(spx);
15937 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15938 
15939 	return (rval);
15940 }
15941 
15942 /*
15943  *
15944  * Returns 0 if succeeded, -1 otherwise
15945  *
15946  * Cannot be called in an interrupt context.
15947  *
15948  */
15949 static int
15950 sata_fetch_smart_data(
15951 	sata_hba_inst_t *sata_hba_inst,
15952 	sata_drive_info_t *sdinfo,
15953 	struct smart_data *smart_data)
15954 {
15955 	sata_pkt_t *spkt;
15956 	sata_cmd_t *scmd;
15957 	sata_pkt_txlate_t *spx;
15958 	int rval;
15959 
15960 #if ! defined(lint)
15961 	ASSERT(sizeof (struct smart_data) == 512);
15962 #endif
15963 
15964 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15965 	spx->txlt_sata_hba_inst = sata_hba_inst;
15966 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15967 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15968 	if (spkt == NULL) {
15969 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15970 		return (-1);
15971 	}
15972 	/* address is needed now */
15973 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15974 
15975 
15976 	/* Fill sata_pkt */
15977 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15978 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15979 	/* Synchronous mode, no callback */
15980 	spkt->satapkt_comp = NULL;
15981 	/* Timeout 30s */
15982 	spkt->satapkt_time = sata_default_pkt_time;
15983 
15984 	scmd = &spkt->satapkt_cmd;
15985 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15986 
15987 	/*
15988 	 * Allocate buffer for SMART data
15989 	 */
15990 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15991 	    sizeof (struct smart_data));
15992 	if (scmd->satacmd_bp == NULL) {
15993 		sata_pkt_free(spx);
15994 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15995 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15996 		    "sata_fetch_smart_data: "
15997 		    "cannot allocate buffer"));
15998 		return (-1);
15999 	}
16000 
16001 
16002 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16003 	scmd->satacmd_addr_type = 0;		/* N/A */
16004 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16005 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16006 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16007 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16008 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16009 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16010 	scmd->satacmd_cmd_reg = SATAC_SMART;
16011 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16012 	    sdinfo->satadrv_addr.cport)));
16013 
16014 	/* Send pkt to SATA HBA driver */
16015 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16016 	    SATA_TRAN_ACCEPTED ||
16017 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16018 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16019 		    sdinfo->satadrv_addr.cport)));
16020 		/*
16021 		 * Whoops, no SMART DATA available
16022 		 */
16023 		rval = -1;
16024 		goto fail;
16025 	} else {
16026 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16027 		    sdinfo->satadrv_addr.cport)));
16028 		if (spx->txlt_buf_dma_handle != NULL) {
16029 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16030 			    DDI_DMA_SYNC_FORKERNEL);
16031 			ASSERT(rval == DDI_SUCCESS);
16032 		}
16033 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16034 		    sizeof (struct smart_data));
16035 	}
16036 
16037 fail:
16038 	/* Free allocated resources */
16039 	sata_free_local_buffer(spx);
16040 	sata_pkt_free(spx);
16041 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16042 
16043 	return (rval);
16044 }
16045 
16046 /*
16047  * Used by LOG SENSE page 0x10
16048  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16049  * Note: cannot be called in the interrupt context.
16050  *
16051  * return 0 for success, -1 otherwise
16052  *
16053  */
16054 static int
16055 sata_ext_smart_selftest_read_log(
16056 	sata_hba_inst_t *sata_hba_inst,
16057 	sata_drive_info_t *sdinfo,
16058 	struct smart_ext_selftest_log *ext_selftest_log,
16059 	uint16_t block_num)
16060 {
16061 	sata_pkt_txlate_t *spx;
16062 	sata_pkt_t *spkt;
16063 	sata_cmd_t *scmd;
16064 	int rval;
16065 
16066 #if ! defined(lint)
16067 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16068 #endif
16069 
16070 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16071 	spx->txlt_sata_hba_inst = sata_hba_inst;
16072 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16073 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16074 	if (spkt == NULL) {
16075 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16076 		return (-1);
16077 	}
16078 	/* address is needed now */
16079 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16080 
16081 
16082 	/* Fill sata_pkt */
16083 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16084 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16085 	/* Synchronous mode, no callback */
16086 	spkt->satapkt_comp = NULL;
16087 	/* Timeout 30s */
16088 	spkt->satapkt_time = sata_default_pkt_time;
16089 
16090 	scmd = &spkt->satapkt_cmd;
16091 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16092 
16093 	/*
16094 	 * Allocate buffer for SMART extended self-test log
16095 	 */
16096 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16097 	    sizeof (struct smart_ext_selftest_log));
16098 	if (scmd->satacmd_bp == NULL) {
16099 		sata_pkt_free(spx);
16100 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16101 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16102 		    "sata_ext_smart_selftest_log: "
16103 		    "cannot allocate buffer"));
16104 		return (-1);
16105 	}
16106 
16107 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16108 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16109 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16110 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16111 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16112 	scmd->satacmd_lba_low_msb = 0;
16113 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16114 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16115 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16116 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16117 
16118 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16119 	    sdinfo->satadrv_addr.cport)));
16120 
16121 	/* Send pkt to SATA HBA driver */
16122 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16123 	    SATA_TRAN_ACCEPTED ||
16124 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16125 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16126 		    sdinfo->satadrv_addr.cport)));
16127 
16128 		/*
16129 		 * Whoops, no SMART selftest log info available
16130 		 */
16131 		rval = -1;
16132 		goto fail;
16133 	} else {
16134 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16135 		    sdinfo->satadrv_addr.cport)));
16136 
16137 		if (spx->txlt_buf_dma_handle != NULL) {
16138 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16139 			    DDI_DMA_SYNC_FORKERNEL);
16140 			ASSERT(rval == DDI_SUCCESS);
16141 		}
16142 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16143 		    (uint8_t *)ext_selftest_log,
16144 		    sizeof (struct smart_ext_selftest_log));
16145 		rval = 0;
16146 	}
16147 
16148 fail:
16149 	/* Free allocated resources */
16150 	sata_free_local_buffer(spx);
16151 	sata_pkt_free(spx);
16152 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16153 
16154 	return (rval);
16155 }
16156 
16157 /*
16158  * Returns 0 for success, -1 otherwise
16159  *
16160  * SMART self-test log data is returned in buffer pointed to by selftest_log
16161  */
16162 static int
16163 sata_smart_selftest_log(
16164 	sata_hba_inst_t *sata_hba_inst,
16165 	sata_drive_info_t *sdinfo,
16166 	struct smart_selftest_log *selftest_log)
16167 {
16168 	sata_pkt_t *spkt;
16169 	sata_cmd_t *scmd;
16170 	sata_pkt_txlate_t *spx;
16171 	int rval;
16172 
16173 #if ! defined(lint)
16174 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16175 #endif
16176 
16177 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16178 	spx->txlt_sata_hba_inst = sata_hba_inst;
16179 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16180 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16181 	if (spkt == NULL) {
16182 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16183 		return (-1);
16184 	}
16185 	/* address is needed now */
16186 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16187 
16188 
16189 	/* Fill sata_pkt */
16190 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16191 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16192 	/* Synchronous mode, no callback */
16193 	spkt->satapkt_comp = NULL;
16194 	/* Timeout 30s */
16195 	spkt->satapkt_time = sata_default_pkt_time;
16196 
16197 	scmd = &spkt->satapkt_cmd;
16198 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16199 
16200 	/*
16201 	 * Allocate buffer for SMART SELFTEST LOG
16202 	 */
16203 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16204 	    sizeof (struct smart_selftest_log));
16205 	if (scmd->satacmd_bp == NULL) {
16206 		sata_pkt_free(spx);
16207 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16208 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16209 		    "sata_smart_selftest_log: "
16210 		    "cannot allocate buffer"));
16211 		return (-1);
16212 	}
16213 
16214 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16215 	scmd->satacmd_addr_type = 0;		/* N/A */
16216 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16217 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16218 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16219 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16220 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16221 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16222 	scmd->satacmd_cmd_reg = SATAC_SMART;
16223 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16224 	    sdinfo->satadrv_addr.cport)));
16225 
16226 	/* Send pkt to SATA HBA driver */
16227 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16228 	    SATA_TRAN_ACCEPTED ||
16229 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16230 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16231 		    sdinfo->satadrv_addr.cport)));
16232 		/*
16233 		 * Whoops, no SMART DATA available
16234 		 */
16235 		rval = -1;
16236 		goto fail;
16237 	} else {
16238 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16239 		    sdinfo->satadrv_addr.cport)));
16240 		if (spx->txlt_buf_dma_handle != NULL) {
16241 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16242 			    DDI_DMA_SYNC_FORKERNEL);
16243 			ASSERT(rval == DDI_SUCCESS);
16244 		}
16245 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16246 		    sizeof (struct smart_selftest_log));
16247 		rval = 0;
16248 	}
16249 
16250 fail:
16251 	/* Free allocated resources */
16252 	sata_free_local_buffer(spx);
16253 	sata_pkt_free(spx);
16254 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16255 
16256 	return (rval);
16257 }
16258 
16259 
16260 /*
16261  * Returns 0 for success, -1 otherwise
16262  *
16263  * SMART READ LOG data is returned in buffer pointed to by smart_log
16264  */
16265 static int
16266 sata_smart_read_log(
16267 	sata_hba_inst_t *sata_hba_inst,
16268 	sata_drive_info_t *sdinfo,
16269 	uint8_t *smart_log,		/* where the data should be returned */
16270 	uint8_t which_log,		/* which log should be returned */
16271 	uint8_t log_size)		/* # of 512 bytes in log */
16272 {
16273 	sata_pkt_t *spkt;
16274 	sata_cmd_t *scmd;
16275 	sata_pkt_txlate_t *spx;
16276 	int rval;
16277 
16278 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16279 	spx->txlt_sata_hba_inst = sata_hba_inst;
16280 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16281 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16282 	if (spkt == NULL) {
16283 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16284 		return (-1);
16285 	}
16286 	/* address is needed now */
16287 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16288 
16289 
16290 	/* Fill sata_pkt */
16291 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16292 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16293 	/* Synchronous mode, no callback */
16294 	spkt->satapkt_comp = NULL;
16295 	/* Timeout 30s */
16296 	spkt->satapkt_time = sata_default_pkt_time;
16297 
16298 	scmd = &spkt->satapkt_cmd;
16299 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16300 
16301 	/*
16302 	 * Allocate buffer for SMART READ LOG
16303 	 */
16304 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16305 	if (scmd->satacmd_bp == NULL) {
16306 		sata_pkt_free(spx);
16307 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16308 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16309 		    "sata_smart_read_log: " "cannot allocate buffer"));
16310 		return (-1);
16311 	}
16312 
16313 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16314 	scmd->satacmd_addr_type = 0;		/* N/A */
16315 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16316 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16317 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16318 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16319 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16320 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16321 	scmd->satacmd_cmd_reg = SATAC_SMART;
16322 
16323 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16324 	    sdinfo->satadrv_addr.cport)));
16325 
16326 	/* Send pkt to SATA HBA driver */
16327 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16328 	    SATA_TRAN_ACCEPTED ||
16329 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16330 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16331 		    sdinfo->satadrv_addr.cport)));
16332 
16333 		/*
16334 		 * Whoops, no SMART DATA available
16335 		 */
16336 		rval = -1;
16337 		goto fail;
16338 	} else {
16339 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16340 		    sdinfo->satadrv_addr.cport)));
16341 
16342 		if (spx->txlt_buf_dma_handle != NULL) {
16343 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16344 			    DDI_DMA_SYNC_FORKERNEL);
16345 			ASSERT(rval == DDI_SUCCESS);
16346 		}
16347 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16348 		rval = 0;
16349 	}
16350 
16351 fail:
16352 	/* Free allocated resources */
16353 	sata_free_local_buffer(spx);
16354 	sata_pkt_free(spx);
16355 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16356 
16357 	return (rval);
16358 }
16359 
16360 /*
16361  * Used by LOG SENSE page 0x10
16362  *
16363  * return 0 for success, -1 otherwise
16364  *
16365  */
16366 static int
16367 sata_read_log_ext_directory(
16368 	sata_hba_inst_t *sata_hba_inst,
16369 	sata_drive_info_t *sdinfo,
16370 	struct read_log_ext_directory *logdir)
16371 {
16372 	sata_pkt_txlate_t *spx;
16373 	sata_pkt_t *spkt;
16374 	sata_cmd_t *scmd;
16375 	int rval;
16376 
16377 #if ! defined(lint)
16378 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16379 #endif
16380 
16381 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16382 	spx->txlt_sata_hba_inst = sata_hba_inst;
16383 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16384 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16385 	if (spkt == NULL) {
16386 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16387 		return (-1);
16388 	}
16389 
16390 	/* Fill sata_pkt */
16391 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16392 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16393 	/* Synchronous mode, no callback */
16394 	spkt->satapkt_comp = NULL;
16395 	/* Timeout 30s */
16396 	spkt->satapkt_time = sata_default_pkt_time;
16397 
16398 	scmd = &spkt->satapkt_cmd;
16399 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16400 
16401 	/*
16402 	 * Allocate buffer for SMART READ LOG EXTENDED command
16403 	 */
16404 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16405 	    sizeof (struct read_log_ext_directory));
16406 	if (scmd->satacmd_bp == NULL) {
16407 		sata_pkt_free(spx);
16408 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16409 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16410 		    "sata_read_log_ext_directory: "
16411 		    "cannot allocate buffer"));
16412 		return (-1);
16413 	}
16414 
16415 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16416 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16417 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16418 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16419 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16420 	scmd->satacmd_lba_low_msb = 0;
16421 	scmd->satacmd_lba_mid_lsb = 0;
16422 	scmd->satacmd_lba_mid_msb = 0;
16423 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16424 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16425 
16426 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16427 	    sdinfo->satadrv_addr.cport)));
16428 
16429 	/* Send pkt to SATA HBA driver */
16430 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16431 	    SATA_TRAN_ACCEPTED ||
16432 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16433 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16434 		    sdinfo->satadrv_addr.cport)));
16435 		/*
16436 		 * Whoops, no SMART selftest log info available
16437 		 */
16438 		rval = -1;
16439 		goto fail;
16440 	} else {
16441 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16442 		    sdinfo->satadrv_addr.cport)));
16443 		if (spx->txlt_buf_dma_handle != NULL) {
16444 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16445 			    DDI_DMA_SYNC_FORKERNEL);
16446 			ASSERT(rval == DDI_SUCCESS);
16447 		}
16448 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16449 		    sizeof (struct read_log_ext_directory));
16450 		rval = 0;
16451 	}
16452 
16453 fail:
16454 	/* Free allocated resources */
16455 	sata_free_local_buffer(spx);
16456 	sata_pkt_free(spx);
16457 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16458 
16459 	return (rval);
16460 }
16461 
16462 /*
16463  * Set up error retrieval sata command for NCQ command error data
16464  * recovery.
16465  *
16466  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16467  * returns SATA_FAILURE otherwise.
16468  */
16469 static int
16470 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16471 {
16472 #ifndef __lock_lint
16473 	_NOTE(ARGUNUSED(sdinfo))
16474 #endif
16475 
16476 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16477 	sata_cmd_t *scmd;
16478 	struct buf *bp;
16479 
16480 	/* Operation modes are up to the caller */
16481 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16482 
16483 	/* Synchronous mode, no callback - may be changed by the caller */
16484 	spkt->satapkt_comp = NULL;
16485 	spkt->satapkt_time = sata_default_pkt_time;
16486 
16487 	scmd = &spkt->satapkt_cmd;
16488 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16489 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16490 
16491 	/*
16492 	 * Allocate dma_able buffer error data.
16493 	 * Buffer allocation will take care of buffer alignment and other DMA
16494 	 * attributes.
16495 	 */
16496 	bp = sata_alloc_local_buffer(spx,
16497 	    sizeof (struct sata_ncq_error_recovery_page));
16498 	if (bp == NULL)
16499 		return (SATA_FAILURE);
16500 
16501 	bp_mapin(bp); /* make data buffer accessible */
16502 	scmd->satacmd_bp = bp;
16503 
16504 	/*
16505 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16506 	 * before accessing it. Handle is in usual place in translate struct.
16507 	 */
16508 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16509 
16510 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16511 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16512 
16513 	return (SATA_SUCCESS);
16514 }
16515 
16516 /*
16517  * sata_xlate_errors() is used to translate (S)ATA error
16518  * information to SCSI information returned in the SCSI
16519  * packet.
16520  */
16521 static void
16522 sata_xlate_errors(sata_pkt_txlate_t *spx)
16523 {
16524 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16525 	struct scsi_extended_sense *sense;
16526 
16527 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16528 	*scsipkt->pkt_scbp = STATUS_CHECK;
16529 	sense = sata_arq_sense(spx);
16530 
16531 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16532 	case SATA_PKT_PORT_ERROR:
16533 		/*
16534 		 * We have no device data. Assume no data transfered.
16535 		 */
16536 		sense->es_key = KEY_HARDWARE_ERROR;
16537 		break;
16538 
16539 	case SATA_PKT_DEV_ERROR:
16540 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16541 		    SATA_STATUS_ERR) {
16542 			/*
16543 			 * determine dev error reason from error
16544 			 * reg content
16545 			 */
16546 			sata_decode_device_error(spx, sense);
16547 			break;
16548 		}
16549 		/* No extended sense key - no info available */
16550 		break;
16551 
16552 	case SATA_PKT_TIMEOUT:
16553 		scsipkt->pkt_reason = CMD_TIMEOUT;
16554 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16555 		/* No extended sense key */
16556 		break;
16557 
16558 	case SATA_PKT_ABORTED:
16559 		scsipkt->pkt_reason = CMD_ABORTED;
16560 		scsipkt->pkt_statistics |= STAT_ABORTED;
16561 		/* No extended sense key */
16562 		break;
16563 
16564 	case SATA_PKT_RESET:
16565 		/*
16566 		 * pkt aborted either by an explicit reset request from
16567 		 * a host, or due to error recovery
16568 		 */
16569 		scsipkt->pkt_reason = CMD_RESET;
16570 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16571 		break;
16572 
16573 	default:
16574 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16575 		break;
16576 	}
16577 }
16578 
16579 
16580 
16581 
16582 /*
16583  * Log sata message
16584  * dev pathname msg line preceeds the logged message.
16585  */
16586 
16587 static	void
16588 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16589 {
16590 	char pathname[128];
16591 	dev_info_t *dip = NULL;
16592 	va_list ap;
16593 
16594 	mutex_enter(&sata_log_mutex);
16595 
16596 	va_start(ap, fmt);
16597 	(void) vsprintf(sata_log_buf, fmt, ap);
16598 	va_end(ap);
16599 
16600 	if (sata_hba_inst != NULL) {
16601 		dip = SATA_DIP(sata_hba_inst);
16602 		(void) ddi_pathname(dip, pathname);
16603 	} else {
16604 		pathname[0] = 0;
16605 	}
16606 	if (level == CE_CONT) {
16607 		if (sata_debug_flags == 0)
16608 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16609 		else
16610 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16611 	} else {
16612 		if (level != CE_NOTE) {
16613 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16614 		} else if (sata_msg) {
16615 			cmn_err(level, "%s:\n %s", pathname,
16616 			    sata_log_buf);
16617 		}
16618 	}
16619 
16620 	/* sata trace debug */
16621 	sata_trace_debug(dip, sata_log_buf);
16622 
16623 	mutex_exit(&sata_log_mutex);
16624 }
16625 
16626 
16627 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16628 
16629 /*
16630  * Start or terminate the thread, depending on flag arg and current state
16631  */
16632 static void
16633 sata_event_thread_control(int startstop)
16634 {
16635 	static 	int sata_event_thread_terminating = 0;
16636 	static 	int sata_event_thread_starting = 0;
16637 	int i;
16638 
16639 	mutex_enter(&sata_event_mutex);
16640 
16641 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16642 	    sata_event_thread_terminating == 1)) {
16643 		mutex_exit(&sata_event_mutex);
16644 		return;
16645 	}
16646 	if (startstop == 1 && sata_event_thread_starting == 1) {
16647 		mutex_exit(&sata_event_mutex);
16648 		return;
16649 	}
16650 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16651 		sata_event_thread_starting = 1;
16652 		/* wait til terminate operation completes */
16653 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16654 		while (sata_event_thread_terminating == 1) {
16655 			if (i-- <= 0) {
16656 				sata_event_thread_starting = 0;
16657 				mutex_exit(&sata_event_mutex);
16658 #ifdef SATA_DEBUG
16659 				cmn_err(CE_WARN, "sata_event_thread_control: "
16660 				    "timeout waiting for thread to terminate");
16661 #endif
16662 				return;
16663 			}
16664 			mutex_exit(&sata_event_mutex);
16665 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16666 			mutex_enter(&sata_event_mutex);
16667 		}
16668 	}
16669 	if (startstop == 1) {
16670 		if (sata_event_thread == NULL) {
16671 			sata_event_thread = thread_create(NULL, 0,
16672 			    (void (*)())sata_event_daemon,
16673 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16674 		}
16675 		sata_event_thread_starting = 0;
16676 		mutex_exit(&sata_event_mutex);
16677 		return;
16678 	}
16679 
16680 	/*
16681 	 * If we got here, thread may need to be terminated
16682 	 */
16683 	if (sata_event_thread != NULL) {
16684 		int i;
16685 		/* Signal event thread to go away */
16686 		sata_event_thread_terminating = 1;
16687 		sata_event_thread_terminate = 1;
16688 		cv_signal(&sata_event_cv);
16689 		/*
16690 		 * Wait til daemon terminates.
16691 		 */
16692 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16693 		while (sata_event_thread_terminate == 1) {
16694 			mutex_exit(&sata_event_mutex);
16695 			if (i-- <= 0) {
16696 				/* Daemon did not go away !!! */
16697 #ifdef SATA_DEBUG
16698 				cmn_err(CE_WARN, "sata_event_thread_control: "
16699 				    "cannot terminate event daemon thread");
16700 #endif
16701 				mutex_enter(&sata_event_mutex);
16702 				break;
16703 			}
16704 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16705 			mutex_enter(&sata_event_mutex);
16706 		}
16707 		sata_event_thread_terminating = 0;
16708 	}
16709 	ASSERT(sata_event_thread_terminating == 0);
16710 	ASSERT(sata_event_thread_starting == 0);
16711 	mutex_exit(&sata_event_mutex);
16712 }
16713 
16714 
16715 /*
16716  * SATA HBA event notification function.
16717  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16718  * a port and/or device state or a controller itself.
16719  * Events for different addresses/addr types cannot be combined.
16720  * A warning message is generated for each event type.
16721  * Events are not processed by this function, so only the
16722  * event flag(s)is set for an affected entity and the event thread is
16723  * waken up. Event daemon thread processes all events.
16724  *
16725  * NOTE: Since more than one event may be reported at the same time, one
16726  * cannot determine a sequence of events when opposite event are reported, eg.
16727  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16728  * is taking precedence over reported events, i.e. may cause ignoring some
16729  * events.
16730  */
16731 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16732 
16733 void
16734 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16735 {
16736 	sata_hba_inst_t *sata_hba_inst = NULL;
16737 	sata_address_t *saddr;
16738 	sata_pmult_info_t *pmultinfo;
16739 	sata_drive_info_t *sdinfo;
16740 	sata_port_stats_t *pstats;
16741 	sata_cport_info_t *cportinfo;
16742 	sata_pmport_info_t *pmportinfo;
16743 	int cport, pmport;
16744 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16745 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16746 	char *lcp;
16747 	static char *err_msg_evnt_1 =
16748 	    "sata_hba_event_notify: invalid port event 0x%x ";
16749 	static char *err_msg_evnt_2 =
16750 	    "sata_hba_event_notify: invalid device event 0x%x ";
16751 	int linkevent;
16752 
16753 	/*
16754 	 * There is a possibility that an event will be generated on HBA
16755 	 * that has not completed attachment or is detaching. We still want
16756 	 * to process events until HBA is detached.
16757 	 */
16758 	mutex_enter(&sata_mutex);
16759 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16760 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16761 		if (SATA_DIP(sata_hba_inst) == dip)
16762 			if (sata_hba_inst->satahba_attached == 1)
16763 				break;
16764 	}
16765 	mutex_exit(&sata_mutex);
16766 	if (sata_hba_inst == NULL)
16767 		/* HBA not attached */
16768 		return;
16769 
16770 	ASSERT(sata_device != NULL);
16771 
16772 	/*
16773 	 * Validate address before - do not proceed with invalid address.
16774 	 */
16775 	saddr = &sata_device->satadev_addr;
16776 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16777 		return;
16778 
16779 	cport = saddr->cport;
16780 	pmport = saddr->pmport;
16781 
16782 	buf1[0] = buf2[0] = '\0';
16783 
16784 	/*
16785 	 * If event relates to port or device, check port state.
16786 	 * Port has to be initialized, or we cannot accept an event.
16787 	 */
16788 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16789 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16790 		mutex_enter(&sata_hba_inst->satahba_mutex);
16791 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16792 		mutex_exit(&sata_hba_inst->satahba_mutex);
16793 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16794 			return;
16795 	}
16796 
16797 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16798 	    SATA_ADDR_DPMPORT)) != 0) {
16799 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16800 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16801 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16802 			    "is attached to port %d, ignore pmult/pmport "
16803 			    "event 0x%x", cportinfo->cport_dev_type,
16804 			    cport, event));
16805 			return;
16806 		}
16807 
16808 		mutex_enter(&cportinfo->cport_mutex);
16809 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16810 		mutex_exit(&cportinfo->cport_mutex);
16811 
16812 		/*
16813 		 * The daemon might be processing attachment of port
16814 		 * multiplier, in that case we should ignore events on its
16815 		 * sub-devices.
16816 		 *
16817 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16818 		 * The pmport_state is checked by sata daemon.
16819 		 */
16820 		if (pmultinfo == NULL ||
16821 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16822 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16823 			    "sata_hba_event_notify: pmult is not"
16824 			    "available at port %d:%d, ignore event 0x%x",
16825 			    cport, pmport, event));
16826 			return;
16827 		}
16828 	}
16829 
16830 	if ((saddr->qual &
16831 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16832 
16833 		mutex_enter(&cportinfo->cport_mutex);
16834 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16835 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16836 			    "sata_hba_event_notify: invalid/"
16837 			    "un-implemented port %d:%d (%d ports), "
16838 			    "ignore event 0x%x", cport, pmport,
16839 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
16840 			mutex_exit(&cportinfo->cport_mutex);
16841 			return;
16842 		}
16843 		mutex_exit(&cportinfo->cport_mutex);
16844 
16845 		mutex_enter(&sata_hba_inst->satahba_mutex);
16846 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16847 		    cport, pmport);
16848 		mutex_exit(&sata_hba_inst->satahba_mutex);
16849 
16850 		/* pmport is implemented/valid? */
16851 		if (pmportinfo == NULL) {
16852 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16853 			    "sata_hba_event_notify: invalid/"
16854 			    "un-implemented port %d:%d, ignore "
16855 			    "event 0x%x", cport, pmport, event));
16856 			return;
16857 		}
16858 	}
16859 
16860 	/*
16861 	 * Events refer to devices, ports and controllers - each has
16862 	 * unique address. Events for different addresses cannot be combined.
16863 	 */
16864 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
16865 
16866 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16867 
16868 		/* qualify this event(s) */
16869 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
16870 			/* Invalid event for the device port */
16871 			(void) sprintf(buf2, err_msg_evnt_1,
16872 			    event & SATA_EVNT_PORT_EVENTS);
16873 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16874 			goto event_info;
16875 		}
16876 		if (saddr->qual == SATA_ADDR_CPORT) {
16877 			/* Controller's device port event */
16878 
16879 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
16880 			    cport_event_flags |=
16881 			    event & SATA_EVNT_PORT_EVENTS;
16882 			pstats =
16883 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
16884 			    cport_stats;
16885 		} else {
16886 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16887 			mutex_enter(&pmportinfo->pmport_mutex);
16888 			/* Port multiplier's device port event */
16889 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16890 			    pmport_event_flags |=
16891 			    event & SATA_EVNT_PORT_EVENTS;
16892 			pstats =
16893 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16894 			    pmport_stats;
16895 			mutex_exit(&pmportinfo->pmport_mutex);
16896 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16897 		}
16898 
16899 		/*
16900 		 * Add to statistics and log the message. We have to do it
16901 		 * here rather than in the event daemon, because there may be
16902 		 * multiple events occuring before they are processed.
16903 		 */
16904 		linkevent = event &
16905 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
16906 		if (linkevent) {
16907 			if (linkevent == (SATA_EVNT_LINK_LOST |
16908 			    SATA_EVNT_LINK_ESTABLISHED)) {
16909 				/* This is likely event combination */
16910 				(void) strlcat(buf1, "link lost/established, ",
16911 				    SATA_EVENT_MAX_MSG_LENGTH);
16912 
16913 				if (pstats->link_lost < 0xffffffffffffffffULL)
16914 					pstats->link_lost++;
16915 				if (pstats->link_established <
16916 				    0xffffffffffffffffULL)
16917 					pstats->link_established++;
16918 				linkevent = 0;
16919 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
16920 				(void) strlcat(buf1, "link lost, ",
16921 				    SATA_EVENT_MAX_MSG_LENGTH);
16922 
16923 				if (pstats->link_lost < 0xffffffffffffffffULL)
16924 					pstats->link_lost++;
16925 			} else {
16926 				(void) strlcat(buf1, "link established, ",
16927 				    SATA_EVENT_MAX_MSG_LENGTH);
16928 				if (pstats->link_established <
16929 				    0xffffffffffffffffULL)
16930 					pstats->link_established++;
16931 			}
16932 		}
16933 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
16934 			(void) strlcat(buf1, "device attached, ",
16935 			    SATA_EVENT_MAX_MSG_LENGTH);
16936 			if (pstats->device_attached < 0xffffffffffffffffULL)
16937 				pstats->device_attached++;
16938 		}
16939 		if (event & SATA_EVNT_DEVICE_DETACHED) {
16940 			(void) strlcat(buf1, "device detached, ",
16941 			    SATA_EVENT_MAX_MSG_LENGTH);
16942 			if (pstats->device_detached < 0xffffffffffffffffULL)
16943 				pstats->device_detached++;
16944 		}
16945 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
16946 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16947 			    "port %d power level changed", cport);
16948 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
16949 				pstats->port_pwr_changed++;
16950 		}
16951 
16952 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
16953 			/* There should be no other events for this address */
16954 			(void) sprintf(buf2, err_msg_evnt_1,
16955 			    event & ~SATA_EVNT_PORT_EVENTS);
16956 		}
16957 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16958 
16959 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
16960 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16961 
16962 		/* qualify this event */
16963 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
16964 			/* Invalid event for a device */
16965 			(void) sprintf(buf2, err_msg_evnt_2,
16966 			    event & SATA_EVNT_DEVICE_RESET);
16967 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16968 			goto event_info;
16969 		}
16970 		/* drive event */
16971 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
16972 		if (sdinfo != NULL) {
16973 			if (event & SATA_EVNT_DEVICE_RESET) {
16974 				(void) strlcat(buf1, "device reset, ",
16975 				    SATA_EVENT_MAX_MSG_LENGTH);
16976 				if (sdinfo->satadrv_stats.drive_reset <
16977 				    0xffffffffffffffffULL)
16978 					sdinfo->satadrv_stats.drive_reset++;
16979 				sdinfo->satadrv_event_flags |=
16980 				    SATA_EVNT_DEVICE_RESET;
16981 			}
16982 		}
16983 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
16984 			/* Invalid event for a device */
16985 			(void) sprintf(buf2, err_msg_evnt_2,
16986 			    event & ~SATA_EVNT_DRIVE_EVENTS);
16987 		}
16988 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16989 	} else if (saddr->qual == SATA_ADDR_PMULT) {
16990 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16991 
16992 		/* qualify this event */
16993 		if ((event & (SATA_EVNT_DEVICE_RESET |
16994 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
16995 			/* Invalid event for a port multiplier */
16996 			(void) sprintf(buf2, err_msg_evnt_2,
16997 			    event & SATA_EVNT_DEVICE_RESET);
16998 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16999 			goto event_info;
17000 		}
17001 
17002 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17003 
17004 		if (event & SATA_EVNT_DEVICE_RESET) {
17005 
17006 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17007 			    "[Reset] port-mult on cport %d", cport);
17008 			pmultinfo->pmult_event_flags |=
17009 			    SATA_EVNT_DEVICE_RESET;
17010 			(void) strlcat(buf1, "pmult reset, ",
17011 			    SATA_EVENT_MAX_MSG_LENGTH);
17012 		}
17013 
17014 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17015 
17016 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17017 			    "pmult link changed on cport %d", cport);
17018 			pmultinfo->pmult_event_flags |=
17019 			    SATA_EVNT_PMULT_LINK_CHANGED;
17020 			(void) strlcat(buf1, "pmult link changed, ",
17021 			    SATA_EVENT_MAX_MSG_LENGTH);
17022 		}
17023 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17024 
17025 	} else {
17026 		if (saddr->qual != SATA_ADDR_NULL) {
17027 			/* Wrong address qualifier */
17028 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17029 			    "sata_hba_event_notify: invalid address 0x%x",
17030 			    *(uint32_t *)saddr));
17031 			return;
17032 		}
17033 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17034 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17035 			/* Invalid event for the controller */
17036 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17037 			    "sata_hba_event_notify: invalid event 0x%x for "
17038 			    "controller",
17039 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17040 			return;
17041 		}
17042 		buf1[0] = '\0';
17043 		/* This may be a frequent and not interesting event */
17044 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17045 		    "controller power level changed\n", NULL);
17046 
17047 		mutex_enter(&sata_hba_inst->satahba_mutex);
17048 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17049 		    0xffffffffffffffffULL)
17050 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17051 
17052 		sata_hba_inst->satahba_event_flags |=
17053 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17054 		mutex_exit(&sata_hba_inst->satahba_mutex);
17055 	}
17056 	/*
17057 	 * If we got here, there is something to do with this HBA
17058 	 * instance.
17059 	 */
17060 	mutex_enter(&sata_hba_inst->satahba_mutex);
17061 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17062 	mutex_exit(&sata_hba_inst->satahba_mutex);
17063 	mutex_enter(&sata_mutex);
17064 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17065 	mutex_exit(&sata_mutex);
17066 
17067 	/* Tickle event thread */
17068 	mutex_enter(&sata_event_mutex);
17069 	if (sata_event_thread_active == 0)
17070 		cv_signal(&sata_event_cv);
17071 	mutex_exit(&sata_event_mutex);
17072 
17073 event_info:
17074 	if (buf1[0] != '\0') {
17075 		lcp = strrchr(buf1, ',');
17076 		if (lcp != NULL)
17077 			*lcp = '\0';
17078 	}
17079 	if (saddr->qual == SATA_ADDR_CPORT ||
17080 	    saddr->qual == SATA_ADDR_DCPORT) {
17081 		if (buf1[0] != '\0') {
17082 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17083 			    cport, buf1);
17084 		}
17085 		if (buf2[0] != '\0') {
17086 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17087 			    cport, buf2);
17088 		}
17089 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17090 	    saddr->qual == SATA_ADDR_DPMPORT) {
17091 		if (buf1[0] != '\0') {
17092 			sata_log(sata_hba_inst, CE_NOTE,
17093 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17094 		}
17095 		if (buf2[0] != '\0') {
17096 			sata_log(sata_hba_inst, CE_NOTE,
17097 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17098 		}
17099 	}
17100 }
17101 
17102 
17103 /*
17104  * Event processing thread.
17105  * Arg is a pointer to the sata_hba_list pointer.
17106  * It is not really needed, because sata_hba_list is global and static
17107  */
17108 static void
17109 sata_event_daemon(void *arg)
17110 {
17111 #ifndef __lock_lint
17112 	_NOTE(ARGUNUSED(arg))
17113 #endif
17114 	sata_hba_inst_t *sata_hba_inst;
17115 	clock_t delta;
17116 
17117 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17118 	    "SATA event daemon started\n", NULL);
17119 loop:
17120 	/*
17121 	 * Process events here. Walk through all registered HBAs
17122 	 */
17123 	mutex_enter(&sata_mutex);
17124 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17125 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17126 		ASSERT(sata_hba_inst != NULL);
17127 		mutex_enter(&sata_hba_inst->satahba_mutex);
17128 		if (sata_hba_inst->satahba_attached == 0 ||
17129 		    (sata_hba_inst->satahba_event_flags &
17130 		    SATA_EVNT_SKIP) != 0) {
17131 			mutex_exit(&sata_hba_inst->satahba_mutex);
17132 			continue;
17133 		}
17134 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17135 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17136 			mutex_exit(&sata_hba_inst->satahba_mutex);
17137 			mutex_exit(&sata_mutex);
17138 			/* Got the controller with pending event */
17139 			sata_process_controller_events(sata_hba_inst);
17140 			/*
17141 			 * Since global mutex was released, there is a
17142 			 * possibility that HBA list has changed, so start
17143 			 * over from the top. Just processed controller
17144 			 * will be passed-over because of the SKIP flag.
17145 			 */
17146 			goto loop;
17147 		}
17148 		mutex_exit(&sata_hba_inst->satahba_mutex);
17149 	}
17150 	/* Clear SKIP flag in all controllers */
17151 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17152 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17153 		mutex_enter(&sata_hba_inst->satahba_mutex);
17154 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17155 		mutex_exit(&sata_hba_inst->satahba_mutex);
17156 	}
17157 	mutex_exit(&sata_mutex);
17158 
17159 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17160 	    "SATA EVENT DAEMON suspending itself", NULL);
17161 
17162 #ifdef SATA_DEBUG
17163 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17164 		sata_log(sata_hba_inst, CE_WARN,
17165 		    "SATA EVENTS PROCESSING DISABLED\n");
17166 		thread_exit(); /* Daemon will not run again */
17167 	}
17168 #endif
17169 	mutex_enter(&sata_event_mutex);
17170 	sata_event_thread_active = 0;
17171 	mutex_exit(&sata_event_mutex);
17172 	/*
17173 	 * Go to sleep/suspend itself and wake up either because new event or
17174 	 * wait timeout. Exit if there is a termination request (driver
17175 	 * unload).
17176 	 */
17177 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17178 	do {
17179 		mutex_enter(&sata_event_mutex);
17180 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17181 		    delta, TR_CLOCK_TICK);
17182 
17183 		if (sata_event_thread_active != 0) {
17184 			mutex_exit(&sata_event_mutex);
17185 			continue;
17186 		}
17187 
17188 		/* Check if it is time to go away */
17189 		if (sata_event_thread_terminate == 1) {
17190 			/*
17191 			 * It is up to the thread setting above flag to make
17192 			 * sure that this thread is not killed prematurely.
17193 			 */
17194 			sata_event_thread_terminate = 0;
17195 			sata_event_thread = NULL;
17196 			mutex_exit(&sata_event_mutex);
17197 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17198 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17199 			thread_exit();  { _NOTE(NOT_REACHED) }
17200 		}
17201 		mutex_exit(&sata_event_mutex);
17202 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17203 
17204 	mutex_enter(&sata_event_mutex);
17205 	sata_event_thread_active = 1;
17206 	mutex_exit(&sata_event_mutex);
17207 
17208 	mutex_enter(&sata_mutex);
17209 	sata_event_pending &= ~SATA_EVNT_MAIN;
17210 	mutex_exit(&sata_mutex);
17211 
17212 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17213 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17214 
17215 	goto loop;
17216 }
17217 
17218 /*
17219  * Specific HBA instance event processing.
17220  *
17221  * NOTE: At the moment, device event processing is limited to hard disks
17222  * only.
17223  * Port multiplier is supported now.
17224  */
17225 static void
17226 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17227 {
17228 	int ncport;
17229 	uint32_t event_flags;
17230 	sata_address_t *saddr;
17231 	sata_cport_info_t *cportinfo;
17232 	sata_pmult_info_t *pmultinfo;
17233 
17234 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17235 	    "Processing controller %d event(s)",
17236 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17237 
17238 	mutex_enter(&sata_hba_inst->satahba_mutex);
17239 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17240 	event_flags = sata_hba_inst->satahba_event_flags;
17241 	mutex_exit(&sata_hba_inst->satahba_mutex);
17242 	/*
17243 	 * Process controller power change first
17244 	 * HERE
17245 	 */
17246 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17247 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17248 
17249 	/*
17250 	 * Search through ports/devices to identify affected port/device.
17251 	 * We may have to process events for more than one port/device.
17252 	 */
17253 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17254 		/*
17255 		 * Not all ports may be processed in attach by the time we
17256 		 * get an event. Check if port info is initialized.
17257 		 */
17258 		mutex_enter(&sata_hba_inst->satahba_mutex);
17259 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17260 		mutex_exit(&sata_hba_inst->satahba_mutex);
17261 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17262 			continue;
17263 
17264 		/* We have initialized controller port info */
17265 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17266 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17267 		    cport_event_flags;
17268 		/* Check if port was locked by IOCTL processing */
17269 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17270 			/*
17271 			 * We ignore port events because port is busy
17272 			 * with AP control processing. Set again
17273 			 * controller and main event flag, so that
17274 			 * events may be processed by the next daemon
17275 			 * run.
17276 			 */
17277 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17278 			mutex_enter(&sata_hba_inst->satahba_mutex);
17279 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17280 			mutex_exit(&sata_hba_inst->satahba_mutex);
17281 			mutex_enter(&sata_mutex);
17282 			sata_event_pending |= SATA_EVNT_MAIN;
17283 			mutex_exit(&sata_mutex);
17284 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17285 			    "Event processing postponed until "
17286 			    "AP control processing completes",
17287 			    NULL);
17288 			/* Check other ports */
17289 			continue;
17290 		} else {
17291 			/*
17292 			 * Set BSY flag so that AP control would not
17293 			 * interfere with events processing for
17294 			 * this port.
17295 			 */
17296 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17297 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17298 		}
17299 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17300 
17301 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17302 
17303 		if ((event_flags &
17304 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17305 			/*
17306 			 * Got port event.
17307 			 * We need some hierarchy of event processing as they
17308 			 * are affecting each other:
17309 			 * 1. port failed
17310 			 * 2. device detached/attached
17311 			 * 3. link events - link events may trigger device
17312 			 *    detached or device attached events in some
17313 			 *    circumstances.
17314 			 * 4. port power level changed
17315 			 */
17316 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17317 				sata_process_port_failed_event(sata_hba_inst,
17318 				    saddr);
17319 			}
17320 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17321 				sata_process_device_detached(sata_hba_inst,
17322 				    saddr);
17323 			}
17324 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17325 				sata_process_device_attached(sata_hba_inst,
17326 				    saddr);
17327 			}
17328 			if (event_flags &
17329 			    (SATA_EVNT_LINK_ESTABLISHED |
17330 			    SATA_EVNT_LINK_LOST)) {
17331 				sata_process_port_link_events(sata_hba_inst,
17332 				    saddr);
17333 			}
17334 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17335 				sata_process_port_pwr_change(sata_hba_inst,
17336 				    saddr);
17337 			}
17338 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17339 				sata_process_target_node_cleanup(
17340 				    sata_hba_inst, saddr);
17341 			}
17342 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17343 				sata_process_device_autoonline(
17344 				    sata_hba_inst, saddr);
17345 			}
17346 		}
17347 
17348 
17349 		/*
17350 		 * Scan port multiplier and all its sub-ports event flags.
17351 		 * The events are marked by
17352 		 * (1) sata_pmult_info.pmult_event_flags
17353 		 * (2) sata_pmport_info.pmport_event_flags
17354 		 */
17355 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17356 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17357 			/*
17358 			 * There should be another extra check: this
17359 			 * port multiplier still exists?
17360 			 */
17361 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17362 			    ncport);
17363 
17364 			if (pmultinfo != NULL) {
17365 				mutex_exit(&(SATA_CPORT_MUTEX(
17366 				    sata_hba_inst, ncport)));
17367 				sata_process_pmult_events(
17368 				    sata_hba_inst, ncport);
17369 				mutex_enter(&(SATA_CPORT_MUTEX(
17370 				    sata_hba_inst, ncport)));
17371 			} else {
17372 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17373 				    "Port-multiplier is gone. "
17374 				    "Ignore all sub-device events "
17375 				    "at port %d.", ncport);
17376 			}
17377 		}
17378 
17379 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17380 		    SATA_DTYPE_NONE) &&
17381 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17382 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17383 			    satadrv_event_flags &
17384 			    (SATA_EVNT_DEVICE_RESET |
17385 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17386 				/* Have device event */
17387 				sata_process_device_reset(sata_hba_inst,
17388 				    saddr);
17389 			}
17390 		}
17391 		/* Release PORT_BUSY flag */
17392 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17393 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17394 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17395 
17396 	} /* End of loop through the controller SATA ports */
17397 }
17398 
17399 /*
17400  * Specific port multiplier instance event processing. At the moment, device
17401  * event processing is limited to link/attach event only.
17402  *
17403  * NOTE: power management event is not supported yet.
17404  */
17405 static void
17406 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17407 {
17408 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17409 	sata_pmult_info_t *pmultinfo;
17410 	sata_pmport_info_t *pmportinfo;
17411 	sata_address_t *saddr;
17412 	sata_device_t sata_device;
17413 	uint32_t event_flags;
17414 	int npmport;
17415 	int rval;
17416 
17417 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17418 	    "Processing pmult event(s) on cport %d of controller %d",
17419 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17420 
17421 	/* First process events on port multiplier */
17422 	mutex_enter(&cportinfo->cport_mutex);
17423 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17424 	event_flags = pmultinfo->pmult_event_flags;
17425 
17426 	/*
17427 	 * Reset event (of port multiplier) has higher priority because the
17428 	 * port multiplier itself might be failed or removed after reset.
17429 	 */
17430 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17431 		/*
17432 		 * The status of the sub-links are uncertain,
17433 		 * so mark all sub-ports as RESET
17434 		 */
17435 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17436 		    sata_hba_inst, cport); npmport ++) {
17437 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17438 			    cport, npmport);
17439 			if (pmportinfo == NULL) {
17440 				/* That's weird. */
17441 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17442 				    "sata_hba_event_notify: "
17443 				    "invalid/un-implemented "
17444 				    "port %d:%d (%d ports), ",
17445 				    cport, npmport, SATA_NUM_PMPORTS(
17446 				    sata_hba_inst, cport)));
17447 				continue;
17448 			}
17449 
17450 			mutex_enter(&pmportinfo->pmport_mutex);
17451 
17452 			/* Mark all pmport to unknow state. */
17453 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17454 			/* Mark all pmports with link events. */
17455 			pmportinfo->pmport_event_flags =
17456 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17457 			mutex_exit(&pmportinfo->pmport_mutex);
17458 		}
17459 
17460 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17461 		/*
17462 		 * We need probe the port multiplier to know what has
17463 		 * happened.
17464 		 */
17465 		bzero(&sata_device, sizeof (sata_device_t));
17466 		sata_device.satadev_rev = SATA_DEVICE_REV;
17467 		sata_device.satadev_addr.cport = cport;
17468 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17469 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17470 
17471 		mutex_exit(&cportinfo->cport_mutex);
17472 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17473 		    (SATA_DIP(sata_hba_inst), &sata_device);
17474 		mutex_enter(&cportinfo->cport_mutex);
17475 		if (rval != SATA_SUCCESS) {
17476 			/* Something went wrong? Fail the port */
17477 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17478 			mutex_exit(&cportinfo->cport_mutex);
17479 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17480 			    "SATA port %d probing failed", cport));
17481 
17482 			/* PMult structure must be released.  */
17483 			sata_free_pmult(sata_hba_inst, &sata_device);
17484 			return;
17485 		}
17486 
17487 		sata_update_port_info(sata_hba_inst, &sata_device);
17488 
17489 		/*
17490 		 * Sanity check - Port is active? Is the link active?
17491 		 * The device is still a port multiplier?
17492 		 */
17493 		if ((cportinfo->cport_state &
17494 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17495 		    ((cportinfo->cport_scr.sstatus &
17496 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17497 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17498 			mutex_exit(&cportinfo->cport_mutex);
17499 
17500 			/* PMult structure must be released.  */
17501 			sata_free_pmult(sata_hba_inst, &sata_device);
17502 			return;
17503 		}
17504 
17505 		/* Probed succeed, set port ready. */
17506 		cportinfo->cport_state |=
17507 		    SATA_STATE_PROBED | SATA_STATE_READY;
17508 	}
17509 
17510 	/* Release port multiplier event flags. */
17511 	pmultinfo->pmult_event_flags &=
17512 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17513 	mutex_exit(&cportinfo->cport_mutex);
17514 
17515 	/*
17516 	 * Check all sub-links.
17517 	 */
17518 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17519 	    npmport ++) {
17520 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17521 		mutex_enter(&pmportinfo->pmport_mutex);
17522 		event_flags = pmportinfo->pmport_event_flags;
17523 		mutex_exit(&pmportinfo->pmport_mutex);
17524 		saddr = &pmportinfo->pmport_addr;
17525 
17526 		if ((event_flags &
17527 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17528 			/*
17529 			 * Got port multiplier port event.
17530 			 * We need some hierarchy of event processing as they
17531 			 * are affecting each other:
17532 			 * 1. device detached/attached
17533 			 * 2. link events - link events may trigger device
17534 			 *    detached or device attached events in some
17535 			 *    circumstances.
17536 			 */
17537 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17538 				sata_process_pmdevice_detached(sata_hba_inst,
17539 				    saddr);
17540 			}
17541 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17542 				sata_process_pmdevice_attached(sata_hba_inst,
17543 				    saddr);
17544 			}
17545 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17546 			    event_flags & SATA_EVNT_LINK_LOST) {
17547 				sata_process_pmport_link_events(sata_hba_inst,
17548 				    saddr);
17549 			}
17550 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17551 				sata_process_target_node_cleanup(
17552 				    sata_hba_inst, saddr);
17553 			}
17554 		}
17555 
17556 		/* Checking drive event(s). */
17557 		mutex_enter(&pmportinfo->pmport_mutex);
17558 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17559 		    pmportinfo->pmport_sata_drive != NULL) {
17560 			event_flags = pmportinfo->pmport_sata_drive->
17561 			    satadrv_event_flags;
17562 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17563 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17564 
17565 				/* Have device event */
17566 				sata_process_pmdevice_reset(sata_hba_inst,
17567 				    saddr);
17568 			}
17569 		}
17570 		mutex_exit(&pmportinfo->pmport_mutex);
17571 
17572 		/* Release PORT_BUSY flag */
17573 		mutex_enter(&cportinfo->cport_mutex);
17574 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17575 		mutex_exit(&cportinfo->cport_mutex);
17576 	}
17577 
17578 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17579 	    "[DONE] pmult event(s) on cport %d of controller %d",
17580 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17581 }
17582 
17583 /*
17584  * Process HBA power level change reported by HBA driver.
17585  * Not implemented at this time - event is ignored.
17586  */
17587 static void
17588 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17589 {
17590 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17591 	    "Processing controller power level change", NULL);
17592 
17593 	/* Ignoring it for now */
17594 	mutex_enter(&sata_hba_inst->satahba_mutex);
17595 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17596 	mutex_exit(&sata_hba_inst->satahba_mutex);
17597 }
17598 
17599 /*
17600  * Process port power level change reported by HBA driver.
17601  * Not implemented at this time - event is ignored.
17602  */
17603 static void
17604 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17605     sata_address_t *saddr)
17606 {
17607 	sata_cport_info_t *cportinfo;
17608 
17609 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17610 	    "Processing port power level change", NULL);
17611 
17612 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17613 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17614 	/* Reset event flag */
17615 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17616 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17617 }
17618 
17619 /*
17620  * Process port failure reported by HBA driver.
17621  * cports support only - no pmports.
17622  */
17623 static void
17624 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17625     sata_address_t *saddr)
17626 {
17627 	sata_cport_info_t *cportinfo;
17628 
17629 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17630 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17631 	/* Reset event flag first */
17632 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17633 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17634 	if ((cportinfo->cport_state &
17635 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17636 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17637 		    cport_mutex);
17638 		return;
17639 	}
17640 	/* Fail the port */
17641 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17642 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17643 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17644 }
17645 
17646 /*
17647  * Device Reset Event processing.
17648  * The seqeunce is managed by 3 stage flags:
17649  * - reset event reported,
17650  * - reset event being processed,
17651  * - request to clear device reset state.
17652  *
17653  * NOTE: This function has to be entered with cport mutex held. It exits with
17654  * mutex held as well, but can release mutex during the processing.
17655  */
17656 static void
17657 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17658     sata_address_t *saddr)
17659 {
17660 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17661 	sata_drive_info_t *sdinfo;
17662 	sata_cport_info_t *cportinfo;
17663 	sata_device_t sata_device;
17664 	int rval_probe, rval_set;
17665 
17666 	/* We only care about host sata cport for now */
17667 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17668 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17669 	/*
17670 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17671 	 * state, ignore reset event.
17672 	 */
17673 	if (((cportinfo->cport_state &
17674 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17675 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17676 		sdinfo->satadrv_event_flags &=
17677 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17678 		return;
17679 	}
17680 
17681 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17682 	    SATA_DTYPE_PMULT)) {
17683 		/*
17684 		 * Should not happened: this is already handled in
17685 		 * sata_hba_event_notify()
17686 		 */
17687 		mutex_exit(&cportinfo->cport_mutex);
17688 		goto done;
17689 	}
17690 
17691 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17692 	    SATA_VALID_DEV_TYPE) == 0) {
17693 		/*
17694 		 * This should not happen - coding error.
17695 		 * But we can recover, so do not panic, just clean up
17696 		 * and if in debug mode, log the message.
17697 		 */
17698 #ifdef SATA_DEBUG
17699 		sata_log(sata_hba_inst, CE_WARN,
17700 		    "sata_process_device_reset: "
17701 		    "Invalid device type with sdinfo!", NULL);
17702 #endif
17703 		sdinfo->satadrv_event_flags = 0;
17704 		return;
17705 	}
17706 
17707 #ifdef SATA_DEBUG
17708 	if ((sdinfo->satadrv_event_flags &
17709 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17710 		/* Nothing to do */
17711 		/* Something is weird - why we are processing dev reset? */
17712 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17713 		    "No device reset event!!!!", NULL);
17714 
17715 		return;
17716 	}
17717 	if ((sdinfo->satadrv_event_flags &
17718 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17719 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17720 		/* Something is weird - new device reset event */
17721 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17722 		    "Overlapping device reset events!", NULL);
17723 	}
17724 #endif
17725 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17726 	    "Processing port %d device reset", saddr->cport);
17727 
17728 	/* Clear event flag */
17729 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17730 
17731 	/* It seems that we always need to check the port state first */
17732 	sata_device.satadev_rev = SATA_DEVICE_REV;
17733 	sata_device.satadev_addr = *saddr;
17734 	/*
17735 	 * We have to exit mutex, because the HBA probe port function may
17736 	 * block on its own mutex.
17737 	 */
17738 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17739 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17740 	    (SATA_DIP(sata_hba_inst), &sata_device);
17741 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17742 	sata_update_port_info(sata_hba_inst, &sata_device);
17743 	if (rval_probe != SATA_SUCCESS) {
17744 		/* Something went wrong? Fail the port */
17745 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17746 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17747 		if (sdinfo != NULL)
17748 			sdinfo->satadrv_event_flags = 0;
17749 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17750 		    cport_mutex);
17751 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17752 		    "SATA port %d probing failed",
17753 		    saddr->cport));
17754 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17755 		    saddr->cport)->cport_mutex);
17756 		return;
17757 	}
17758 	if ((sata_device.satadev_scr.sstatus  &
17759 	    SATA_PORT_DEVLINK_UP_MASK) !=
17760 	    SATA_PORT_DEVLINK_UP ||
17761 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17762 		/*
17763 		 * No device to process, anymore. Some other event processing
17764 		 * would or have already performed port info cleanup.
17765 		 * To be safe (HBA may need it), request clearing device
17766 		 * reset condition.
17767 		 */
17768 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17769 		if (sdinfo != NULL) {
17770 			sdinfo->satadrv_event_flags &=
17771 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17772 			sdinfo->satadrv_event_flags |=
17773 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17774 		}
17775 		return;
17776 	}
17777 
17778 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17779 	if (sdinfo == NULL) {
17780 		return;
17781 	}
17782 	if ((sdinfo->satadrv_event_flags &
17783 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17784 		/*
17785 		 * Start tracking time for device feature restoration and
17786 		 * identification. Save current time (lbolt value).
17787 		 */
17788 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17789 	}
17790 	/* Mark device reset processing as active */
17791 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17792 
17793 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17794 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17795 
17796 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17797 
17798 	if (rval_set  != SATA_SUCCESS) {
17799 		/*
17800 		 * Restoring drive setting failed.
17801 		 * Probe the port first, to check if the port state has changed
17802 		 */
17803 		sata_device.satadev_rev = SATA_DEVICE_REV;
17804 		sata_device.satadev_addr = *saddr;
17805 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17806 		/* probe port */
17807 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17808 		    (SATA_DIP(sata_hba_inst), &sata_device);
17809 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17810 		    cport_mutex);
17811 		if (rval_probe == SATA_SUCCESS &&
17812 		    (sata_device.satadev_state &
17813 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17814 		    (sata_device.satadev_scr.sstatus  &
17815 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17816 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17817 			/*
17818 			 * We may retry this a bit later - in-process reset
17819 			 * condition should be already set.
17820 			 * Track retry time for device identification.
17821 			 */
17822 			if ((cportinfo->cport_dev_type &
17823 			    SATA_VALID_DEV_TYPE) != 0 &&
17824 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17825 			    sdinfo->satadrv_reset_time != 0) {
17826 				clock_t cur_time = ddi_get_lbolt();
17827 				/*
17828 				 * If the retry time limit was not
17829 				 * exceeded, retry.
17830 				 */
17831 				if ((cur_time - sdinfo->satadrv_reset_time) <
17832 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17833 					mutex_enter(
17834 					    &sata_hba_inst->satahba_mutex);
17835 					sata_hba_inst->satahba_event_flags |=
17836 					    SATA_EVNT_MAIN;
17837 					mutex_exit(
17838 					    &sata_hba_inst->satahba_mutex);
17839 					mutex_enter(&sata_mutex);
17840 					sata_event_pending |= SATA_EVNT_MAIN;
17841 					mutex_exit(&sata_mutex);
17842 					return;
17843 				}
17844 				if (rval_set == SATA_RETRY) {
17845 					/*
17846 					 * Setting drive features failed, but
17847 					 * the drive is still accessible,
17848 					 * so emit a warning message before
17849 					 * return.
17850 					 */
17851 					mutex_exit(&SATA_CPORT_INFO(
17852 					    sata_hba_inst,
17853 					    saddr->cport)->cport_mutex);
17854 					goto done;
17855 				}
17856 			}
17857 			/* Fail the drive */
17858 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17859 
17860 			sata_log(sata_hba_inst, CE_WARN,
17861 			    "SATA device at port %d - device failed",
17862 			    saddr->cport);
17863 		}
17864 		/*
17865 		 * No point of retrying - device failed or some other event
17866 		 * processing or already did or will do port info cleanup.
17867 		 * To be safe (HBA may need it),
17868 		 * request clearing device reset condition.
17869 		 */
17870 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
17871 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17872 		sdinfo->satadrv_reset_time = 0;
17873 		return;
17874 	}
17875 done:
17876 	/*
17877 	 * If setting of drive features failed, but the drive is still
17878 	 * accessible, emit a warning message.
17879 	 */
17880 	if (rval_set == SATA_RETRY) {
17881 		sata_log(sata_hba_inst, CE_WARN,
17882 		    "SATA device at port %d - desired setting could not be "
17883 		    "restored after reset. Device may not operate as expected.",
17884 		    saddr->cport);
17885 	}
17886 	/*
17887 	 * Raise the flag indicating that the next sata command could
17888 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17889 	 * reset is reported.
17890 	 */
17891 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17892 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
17893 		sdinfo->satadrv_reset_time = 0;
17894 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
17895 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17896 			sdinfo->satadrv_event_flags &=
17897 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17898 			sdinfo->satadrv_event_flags |=
17899 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17900 		}
17901 	}
17902 }
17903 
17904 
17905 /*
17906  * Port Multiplier Port Device Reset Event processing.
17907  *
17908  * NOTE: This function has to be entered with pmport mutex held. It exits with
17909  * mutex held as well, but can release mutex during the processing.
17910  */
17911 static void
17912 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
17913     sata_address_t *saddr)
17914 {
17915 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17916 	sata_drive_info_t *sdinfo = NULL;
17917 	sata_cport_info_t *cportinfo = NULL;
17918 	sata_pmport_info_t *pmportinfo = NULL;
17919 	sata_pmult_info_t *pminfo = NULL;
17920 	sata_device_t sata_device;
17921 	uint8_t cport = saddr->cport;
17922 	uint8_t pmport = saddr->pmport;
17923 	int rval;
17924 
17925 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17926 	    "Processing drive reset at port %d:%d", cport, pmport);
17927 
17928 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17929 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17930 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
17931 
17932 	/*
17933 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17934 	 * state, ignore reset event.
17935 	 */
17936 	if (((cportinfo->cport_state &
17937 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17938 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17939 		sdinfo->satadrv_event_flags &=
17940 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17941 		return;
17942 	}
17943 
17944 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
17945 		/*
17946 		 * This should not happen - coding error.
17947 		 * But we can recover, so do not panic, just clean up
17948 		 * and if in debug mode, log the message.
17949 		 */
17950 #ifdef SATA_DEBUG
17951 		sata_log(sata_hba_inst, CE_WARN,
17952 		    "sata_process_pmdevice_reset: "
17953 		    "Invalid device type with sdinfo!", NULL);
17954 #endif
17955 		sdinfo->satadrv_event_flags = 0;
17956 		return;
17957 	}
17958 
17959 #ifdef SATA_DEBUG
17960 	if ((sdinfo->satadrv_event_flags &
17961 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17962 		/* Nothing to do */
17963 		/* Something is weird - why we are processing dev reset? */
17964 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17965 		    "No device reset event!!!!", NULL);
17966 
17967 		return;
17968 	}
17969 	if ((sdinfo->satadrv_event_flags &
17970 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17971 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17972 		/* Something is weird - new device reset event */
17973 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17974 		    "Overlapping device reset events!", NULL);
17975 	}
17976 #endif
17977 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17978 	    "Processing port %d:%d device reset", cport, pmport);
17979 
17980 	/* Clear event flag */
17981 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17982 
17983 	/* It seems that we always need to check the port state first */
17984 	sata_device.satadev_rev = SATA_DEVICE_REV;
17985 	sata_device.satadev_addr = *saddr;
17986 	/*
17987 	 * We have to exit mutex, because the HBA probe port function may
17988 	 * block on its own mutex.
17989 	 */
17990 	mutex_exit(&pmportinfo->pmport_mutex);
17991 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17992 	    (SATA_DIP(sata_hba_inst), &sata_device);
17993 	mutex_enter(&pmportinfo->pmport_mutex);
17994 
17995 	sata_update_pmport_info(sata_hba_inst, &sata_device);
17996 	if (rval != SATA_SUCCESS) {
17997 		/* Something went wrong? Fail the port */
17998 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
17999 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18000 		    saddr->pmport);
18001 		if (sdinfo != NULL)
18002 			sdinfo->satadrv_event_flags = 0;
18003 		mutex_exit(&pmportinfo->pmport_mutex);
18004 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18005 		    "SATA port %d:%d probing failed",
18006 		    saddr->cport, saddr->pmport));
18007 		mutex_enter(&pmportinfo->pmport_mutex);
18008 		return;
18009 	}
18010 	if ((sata_device.satadev_scr.sstatus  &
18011 	    SATA_PORT_DEVLINK_UP_MASK) !=
18012 	    SATA_PORT_DEVLINK_UP ||
18013 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18014 		/*
18015 		 * No device to process, anymore. Some other event processing
18016 		 * would or have already performed port info cleanup.
18017 		 * To be safe (HBA may need it), request clearing device
18018 		 * reset condition.
18019 		 */
18020 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18021 		    saddr->pmport);
18022 		if (sdinfo != NULL) {
18023 			sdinfo->satadrv_event_flags &=
18024 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18025 			/* must clear flags on cport */
18026 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18027 			    saddr->cport);
18028 			pminfo->pmult_event_flags |=
18029 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18030 		}
18031 		return;
18032 	}
18033 
18034 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18035 	    saddr->pmport);
18036 	if (sdinfo == NULL) {
18037 		return;
18038 	}
18039 	if ((sdinfo->satadrv_event_flags &
18040 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18041 		/*
18042 		 * Start tracking time for device feature restoration and
18043 		 * identification. Save current time (lbolt value).
18044 		 */
18045 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18046 	}
18047 	/* Mark device reset processing as active */
18048 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18049 
18050 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18051 	mutex_exit(&pmportinfo->pmport_mutex);
18052 
18053 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18054 	    SATA_FAILURE) {
18055 		/*
18056 		 * Restoring drive setting failed.
18057 		 * Probe the port first, to check if the port state has changed
18058 		 */
18059 		sata_device.satadev_rev = SATA_DEVICE_REV;
18060 		sata_device.satadev_addr = *saddr;
18061 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18062 
18063 		/* probe port */
18064 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18065 		    (SATA_DIP(sata_hba_inst), &sata_device);
18066 		mutex_enter(&pmportinfo->pmport_mutex);
18067 		if (rval == SATA_SUCCESS &&
18068 		    (sata_device.satadev_state &
18069 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18070 		    (sata_device.satadev_scr.sstatus  &
18071 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18072 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18073 			/*
18074 			 * We may retry this a bit later - in-process reset
18075 			 * condition should be already set.
18076 			 * Track retry time for device identification.
18077 			 */
18078 			if ((pmportinfo->pmport_dev_type &
18079 			    SATA_VALID_DEV_TYPE) != 0 &&
18080 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18081 			    sdinfo->satadrv_reset_time != 0) {
18082 				clock_t cur_time = ddi_get_lbolt();
18083 				/*
18084 				 * If the retry time limit was not
18085 				 * exceeded, retry.
18086 				 */
18087 				if ((cur_time - sdinfo->satadrv_reset_time) <
18088 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18089 					mutex_enter(
18090 					    &sata_hba_inst->satahba_mutex);
18091 					sata_hba_inst->satahba_event_flags |=
18092 					    SATA_EVNT_MAIN;
18093 					mutex_exit(
18094 					    &sata_hba_inst->satahba_mutex);
18095 					mutex_enter(&sata_mutex);
18096 					sata_event_pending |= SATA_EVNT_MAIN;
18097 					mutex_exit(&sata_mutex);
18098 					return;
18099 				}
18100 			}
18101 			/* Fail the drive */
18102 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18103 
18104 			sata_log(sata_hba_inst, CE_WARN,
18105 			    "SATA device at port %d:%d - device failed",
18106 			    saddr->cport, saddr->pmport);
18107 		} else {
18108 			/*
18109 			 * No point of retrying - some other event processing
18110 			 * would or already did port info cleanup.
18111 			 * To be safe (HBA may need it),
18112 			 * request clearing device reset condition.
18113 			 */
18114 			sdinfo->satadrv_event_flags |=
18115 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18116 		}
18117 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18118 		sdinfo->satadrv_reset_time = 0;
18119 		return;
18120 	}
18121 	/*
18122 	 * Raise the flag indicating that the next sata command could
18123 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18124 	 * reset is reported.
18125 	 */
18126 	mutex_enter(&pmportinfo->pmport_mutex);
18127 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18128 		sdinfo->satadrv_reset_time = 0;
18129 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18130 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18131 			sdinfo->satadrv_event_flags &=
18132 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18133 			/* must clear flags on cport */
18134 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18135 			    saddr->cport);
18136 			pminfo->pmult_event_flags |=
18137 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18138 		}
18139 	}
18140 }
18141 
18142 /*
18143  * Port Link Events processing.
18144  * Every link established event may involve device reset (due to
18145  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18146  * set device reset event for an attached device (if any).
18147  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18148  *
18149  * The link established event processing varies, depending on the state
18150  * of the target node, HBA hotplugging capabilities, state of the port.
18151  * If the link is not active, the link established event is ignored.
18152  * If HBA cannot detect device attachment and there is no target node,
18153  * the link established event triggers device attach event processing.
18154  * Else, link established event triggers device reset event processing.
18155  *
18156  * The link lost event processing varies, depending on a HBA hotplugging
18157  * capability and the state of the port (link active or not active).
18158  * If the link is active, the lost link event is ignored.
18159  * If HBA cannot detect device removal, the lost link event triggers
18160  * device detached event processing after link lost timeout.
18161  * Else, the event is ignored.
18162  *
18163  * NOTE: Port multiplier ports events are handled by
18164  * sata_process_pmport_link_events();
18165  */
18166 static void
18167 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18168     sata_address_t *saddr)
18169 {
18170 	sata_device_t sata_device;
18171 	sata_cport_info_t *cportinfo;
18172 	sata_drive_info_t *sdinfo;
18173 	uint32_t event_flags;
18174 	int rval;
18175 
18176 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18177 	    "Processing port %d link event(s)", saddr->cport);
18178 
18179 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18180 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18181 	event_flags = cportinfo->cport_event_flags;
18182 
18183 	/* Reset event flags first */
18184 	cportinfo->cport_event_flags &=
18185 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18186 
18187 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18188 	if ((cportinfo->cport_state &
18189 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18190 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18191 		    cport_mutex);
18192 		return;
18193 	}
18194 
18195 	/*
18196 	 * For the sanity sake get current port state.
18197 	 * Set device address only. Other sata_device fields should be
18198 	 * set by HBA driver.
18199 	 */
18200 	sata_device.satadev_rev = SATA_DEVICE_REV;
18201 	sata_device.satadev_addr = *saddr;
18202 	/*
18203 	 * We have to exit mutex, because the HBA probe port function may
18204 	 * block on its own mutex.
18205 	 */
18206 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18207 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18208 	    (SATA_DIP(sata_hba_inst), &sata_device);
18209 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18210 	sata_update_port_info(sata_hba_inst, &sata_device);
18211 	if (rval != SATA_SUCCESS) {
18212 		/* Something went wrong? Fail the port */
18213 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18214 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18215 		    cport_mutex);
18216 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18217 		    "SATA port %d probing failed",
18218 		    saddr->cport));
18219 		/*
18220 		 * We may want to release device info structure, but
18221 		 * it is not necessary.
18222 		 */
18223 		return;
18224 	} else {
18225 		/* port probed successfully */
18226 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18227 	}
18228 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18229 
18230 		if ((sata_device.satadev_scr.sstatus &
18231 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18232 			/* Ignore event */
18233 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18234 			    "Ignoring port %d link established event - "
18235 			    "link down",
18236 			    saddr->cport);
18237 			goto linklost;
18238 		}
18239 
18240 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18241 		    "Processing port %d link established event",
18242 		    saddr->cport);
18243 
18244 		/*
18245 		 * For the sanity sake check if a device is attached - check
18246 		 * return state of a port probing.
18247 		 */
18248 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18249 			/*
18250 			 * HBA port probe indicated that there is a device
18251 			 * attached. Check if the framework had device info
18252 			 * structure attached for this device.
18253 			 */
18254 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18255 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18256 				    NULL);
18257 
18258 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18259 				if ((sdinfo->satadrv_type &
18260 				    SATA_VALID_DEV_TYPE) != 0) {
18261 					/*
18262 					 * Dev info structure is present.
18263 					 * If dev_type is set to known type in
18264 					 * the framework's drive info struct
18265 					 * then the device existed before and
18266 					 * the link was probably lost
18267 					 * momentarily - in such case
18268 					 * we may want to check device
18269 					 * identity.
18270 					 * Identity check is not supported now.
18271 					 *
18272 					 * Link established event
18273 					 * triggers device reset event.
18274 					 */
18275 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18276 					    satadrv_event_flags |=
18277 					    SATA_EVNT_DEVICE_RESET;
18278 				}
18279 			} else if (cportinfo->cport_dev_type ==
18280 			    SATA_DTYPE_NONE) {
18281 				/*
18282 				 * We got new device attached! If HBA does not
18283 				 * generate device attached events, trigger it
18284 				 * here.
18285 				 */
18286 				if (!(SATA_FEATURES(sata_hba_inst) &
18287 				    SATA_CTLF_HOTPLUG)) {
18288 					cportinfo->cport_event_flags |=
18289 					    SATA_EVNT_DEVICE_ATTACHED;
18290 				}
18291 			}
18292 			/* Reset link lost timeout */
18293 			cportinfo->cport_link_lost_time = 0;
18294 		}
18295 	}
18296 linklost:
18297 	if (event_flags & SATA_EVNT_LINK_LOST) {
18298 		if ((sata_device.satadev_scr.sstatus &
18299 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18300 			/* Ignore event */
18301 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18302 			    "Ignoring port %d link lost event - link is up",
18303 			    saddr->cport);
18304 			goto done;
18305 		}
18306 #ifdef SATA_DEBUG
18307 		if (cportinfo->cport_link_lost_time == 0) {
18308 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18309 			    "Processing port %d link lost event",
18310 			    saddr->cport);
18311 		}
18312 #endif
18313 		/*
18314 		 * When HBA cannot generate device attached/detached events,
18315 		 * we need to track link lost time and eventually generate
18316 		 * device detach event.
18317 		 */
18318 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18319 			/* We are tracking link lost time */
18320 			if (cportinfo->cport_link_lost_time == 0) {
18321 				/* save current time (lbolt value) */
18322 				cportinfo->cport_link_lost_time =
18323 				    ddi_get_lbolt();
18324 				/* just keep link lost event */
18325 				cportinfo->cport_event_flags |=
18326 				    SATA_EVNT_LINK_LOST;
18327 			} else {
18328 				clock_t cur_time = ddi_get_lbolt();
18329 				if ((cur_time -
18330 				    cportinfo->cport_link_lost_time) >=
18331 				    drv_usectohz(
18332 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18333 					/* trigger device detach event */
18334 					cportinfo->cport_event_flags |=
18335 					    SATA_EVNT_DEVICE_DETACHED;
18336 					cportinfo->cport_link_lost_time = 0;
18337 					SATADBG1(SATA_DBG_EVENTS,
18338 					    sata_hba_inst,
18339 					    "Triggering port %d "
18340 					    "device detached event",
18341 					    saddr->cport);
18342 				} else {
18343 					/* keep link lost event */
18344 					cportinfo->cport_event_flags |=
18345 					    SATA_EVNT_LINK_LOST;
18346 				}
18347 			}
18348 		}
18349 		/*
18350 		 * We could change port state to disable/delay access to
18351 		 * the attached device until the link is recovered.
18352 		 */
18353 	}
18354 done:
18355 	event_flags = cportinfo->cport_event_flags;
18356 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18357 	if (event_flags != 0) {
18358 		mutex_enter(&sata_hba_inst->satahba_mutex);
18359 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18360 		mutex_exit(&sata_hba_inst->satahba_mutex);
18361 		mutex_enter(&sata_mutex);
18362 		sata_event_pending |= SATA_EVNT_MAIN;
18363 		mutex_exit(&sata_mutex);
18364 	}
18365 }
18366 
18367 /*
18368  * Port Multiplier Port Link Events processing.
18369  */
18370 static void
18371 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18372     sata_address_t *saddr)
18373 {
18374 	sata_device_t sata_device;
18375 	sata_pmport_info_t *pmportinfo = NULL;
18376 	sata_drive_info_t *sdinfo = NULL;
18377 	uint32_t event_flags;
18378 	uint8_t cport = saddr->cport;
18379 	uint8_t pmport = saddr->pmport;
18380 	int rval;
18381 
18382 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18383 	    "Processing port %d:%d link event(s)",
18384 	    cport, pmport);
18385 
18386 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18387 	mutex_enter(&pmportinfo->pmport_mutex);
18388 	event_flags = pmportinfo->pmport_event_flags;
18389 
18390 	/* Reset event flags first */
18391 	pmportinfo->pmport_event_flags &=
18392 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18393 
18394 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18395 	if ((pmportinfo->pmport_state &
18396 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18397 		mutex_exit(&pmportinfo->pmport_mutex);
18398 		return;
18399 	}
18400 
18401 	/*
18402 	 * For the sanity sake get current port state.
18403 	 * Set device address only. Other sata_device fields should be
18404 	 * set by HBA driver.
18405 	 */
18406 	sata_device.satadev_rev = SATA_DEVICE_REV;
18407 	sata_device.satadev_addr = *saddr;
18408 	/*
18409 	 * We have to exit mutex, because the HBA probe port function may
18410 	 * block on its own mutex.
18411 	 */
18412 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18413 	    saddr->pmport));
18414 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18415 	    (SATA_DIP(sata_hba_inst), &sata_device);
18416 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18417 	    saddr->pmport));
18418 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18419 	if (rval != SATA_SUCCESS) {
18420 		/* Something went wrong? Fail the port */
18421 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18422 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18423 		    saddr->pmport));
18424 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18425 		    "SATA port %d:%d probing failed",
18426 		    saddr->cport, saddr->pmport));
18427 		/*
18428 		 * We may want to release device info structure, but
18429 		 * it is not necessary.
18430 		 */
18431 		return;
18432 	} else {
18433 		/* port probed successfully */
18434 		pmportinfo->pmport_state |=
18435 		    SATA_STATE_PROBED | SATA_STATE_READY;
18436 	}
18437 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18438 	    saddr->cport, saddr->pmport));
18439 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18440 	    saddr->cport, saddr->pmport));
18441 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18442 
18443 		if ((sata_device.satadev_scr.sstatus &
18444 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18445 			/* Ignore event */
18446 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18447 			    "Ignoring port %d:%d link established event - "
18448 			    "link down",
18449 			    saddr->cport, saddr->pmport);
18450 			goto linklost;
18451 		}
18452 
18453 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18454 		    "Processing port %d:%d link established event",
18455 		    cport, pmport);
18456 
18457 		/*
18458 		 * For the sanity sake check if a device is attached - check
18459 		 * return state of a port probing.
18460 		 */
18461 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18462 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18463 			/*
18464 			 * HBA port probe indicated that there is a device
18465 			 * attached. Check if the framework had device info
18466 			 * structure attached for this device.
18467 			 */
18468 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18469 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18470 				    NULL);
18471 
18472 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18473 				if ((sdinfo->satadrv_type &
18474 				    SATA_VALID_DEV_TYPE) != 0) {
18475 					/*
18476 					 * Dev info structure is present.
18477 					 * If dev_type is set to known type in
18478 					 * the framework's drive info struct
18479 					 * then the device existed before and
18480 					 * the link was probably lost
18481 					 * momentarily - in such case
18482 					 * we may want to check device
18483 					 * identity.
18484 					 * Identity check is not supported now.
18485 					 *
18486 					 * Link established event
18487 					 * triggers device reset event.
18488 					 */
18489 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18490 					    satadrv_event_flags |=
18491 					    SATA_EVNT_DEVICE_RESET;
18492 				}
18493 			} else if (pmportinfo->pmport_dev_type ==
18494 			    SATA_DTYPE_NONE) {
18495 				/*
18496 				 * We got new device attached! If HBA does not
18497 				 * generate device attached events, trigger it
18498 				 * here.
18499 				 */
18500 				if (!(SATA_FEATURES(sata_hba_inst) &
18501 				    SATA_CTLF_HOTPLUG)) {
18502 					pmportinfo->pmport_event_flags |=
18503 					    SATA_EVNT_DEVICE_ATTACHED;
18504 				}
18505 			}
18506 			/* Reset link lost timeout */
18507 			pmportinfo->pmport_link_lost_time = 0;
18508 		}
18509 	}
18510 linklost:
18511 	if (event_flags & SATA_EVNT_LINK_LOST) {
18512 #ifdef SATA_DEBUG
18513 		if (pmportinfo->pmport_link_lost_time == 0) {
18514 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18515 			    "Processing port %d:%d link lost event",
18516 			    saddr->cport, saddr->pmport);
18517 		}
18518 #endif
18519 		if ((sata_device.satadev_scr.sstatus &
18520 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18521 			/* Ignore event */
18522 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18523 			    "Ignoring port %d:%d link lost event - link is up",
18524 			    saddr->cport, saddr->pmport);
18525 			goto done;
18526 		}
18527 		/*
18528 		 * When HBA cannot generate device attached/detached events,
18529 		 * we need to track link lost time and eventually generate
18530 		 * device detach event.
18531 		 */
18532 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18533 			/* We are tracking link lost time */
18534 			if (pmportinfo->pmport_link_lost_time == 0) {
18535 				/* save current time (lbolt value) */
18536 				pmportinfo->pmport_link_lost_time =
18537 				    ddi_get_lbolt();
18538 				/* just keep link lost event */
18539 				pmportinfo->pmport_event_flags |=
18540 				    SATA_EVNT_LINK_LOST;
18541 			} else {
18542 				clock_t cur_time = ddi_get_lbolt();
18543 				if ((cur_time -
18544 				    pmportinfo->pmport_link_lost_time) >=
18545 				    drv_usectohz(
18546 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18547 					/* trigger device detach event */
18548 					pmportinfo->pmport_event_flags |=
18549 					    SATA_EVNT_DEVICE_DETACHED;
18550 					pmportinfo->pmport_link_lost_time = 0;
18551 					SATADBG2(SATA_DBG_EVENTS,
18552 					    sata_hba_inst,
18553 					    "Triggering port %d:%d "
18554 					    "device detached event",
18555 					    saddr->cport, saddr->pmport);
18556 				} else {
18557 					/* keep link lost event */
18558 					pmportinfo->pmport_event_flags |=
18559 					    SATA_EVNT_LINK_LOST;
18560 				}
18561 			}
18562 		}
18563 		/*
18564 		 * We could change port state to disable/delay access to
18565 		 * the attached device until the link is recovered.
18566 		 */
18567 	}
18568 done:
18569 	event_flags = pmportinfo->pmport_event_flags;
18570 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18571 	    saddr->pmport));
18572 	if (event_flags != 0) {
18573 		mutex_enter(&sata_hba_inst->satahba_mutex);
18574 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18575 		mutex_exit(&sata_hba_inst->satahba_mutex);
18576 		mutex_enter(&sata_mutex);
18577 		sata_event_pending |= SATA_EVNT_MAIN;
18578 		mutex_exit(&sata_mutex);
18579 	}
18580 }
18581 
18582 /*
18583  * Device Detached Event processing.
18584  * Port is probed to find if a device is really gone. If so,
18585  * the device info structure is detached from the SATA port info structure
18586  * and released.
18587  * Port status is updated.
18588  *
18589  * NOTE: Port multiplier ports events are handled by
18590  * sata_process_pmdevice_detached()
18591  */
18592 static void
18593 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18594     sata_address_t *saddr)
18595 {
18596 	sata_cport_info_t *cportinfo;
18597 	sata_pmport_info_t *pmportinfo;
18598 	sata_drive_info_t *sdevinfo;
18599 	sata_device_t sata_device;
18600 	sata_address_t pmport_addr;
18601 	char name[16];
18602 	uint8_t cport = saddr->cport;
18603 	int npmport;
18604 	int rval;
18605 
18606 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18607 	    "Processing port %d device detached", saddr->cport);
18608 
18609 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18610 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18611 	/* Clear event flag */
18612 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18613 
18614 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18615 	if ((cportinfo->cport_state &
18616 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18617 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18618 		    cport_mutex);
18619 		return;
18620 	}
18621 	/* For sanity, re-probe the port */
18622 	sata_device.satadev_rev = SATA_DEVICE_REV;
18623 	sata_device.satadev_addr = *saddr;
18624 
18625 	/*
18626 	 * We have to exit mutex, because the HBA probe port function may
18627 	 * block on its own mutex.
18628 	 */
18629 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18630 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18631 	    (SATA_DIP(sata_hba_inst), &sata_device);
18632 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18633 	sata_update_port_info(sata_hba_inst, &sata_device);
18634 	if (rval != SATA_SUCCESS) {
18635 		/* Something went wrong? Fail the port */
18636 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18637 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18638 		    cport_mutex);
18639 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18640 		    "SATA port %d probing failed",
18641 		    saddr->cport));
18642 		/*
18643 		 * We may want to release device info structure, but
18644 		 * it is not necessary.
18645 		 */
18646 		return;
18647 	} else {
18648 		/* port probed successfully */
18649 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18650 	}
18651 	/*
18652 	 * Check if a device is still attached. For sanity, check also
18653 	 * link status - if no link, there is no device.
18654 	 */
18655 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18656 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18657 	    SATA_DTYPE_NONE) {
18658 		/*
18659 		 * Device is still attached - ignore detach event.
18660 		 */
18661 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18662 		    cport_mutex);
18663 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18664 		    "Ignoring detach - device still attached to port %d",
18665 		    sata_device.satadev_addr.cport);
18666 		return;
18667 	}
18668 	/*
18669 	 * We need to detach and release device info structure here
18670 	 */
18671 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18672 		/*
18673 		 * A port-multiplier is removed.
18674 		 *
18675 		 * Calling sata_process_pmdevice_detached() does not work
18676 		 * here. The port multiplier is gone, so we cannot probe
18677 		 * sub-port any more and all pmult-related data structure must
18678 		 * be de-allocated immediately. Following structure of every
18679 		 * implemented sub-port behind the pmult are required to
18680 		 * released.
18681 		 *
18682 		 *   - attachment point
18683 		 *   - target node
18684 		 *   - sata_drive_info
18685 		 *   - sata_pmport_info
18686 		 */
18687 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18688 		    cport); npmport ++) {
18689 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18690 			    sata_hba_inst,
18691 			    "Detaching target node at port %d:%d",
18692 			    cport, npmport);
18693 
18694 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18695 
18696 			/* Remove attachment point. */
18697 			name[0] = '\0';
18698 			(void) sprintf(name, "%d.%d", cport, npmport);
18699 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18700 			sata_log(sata_hba_inst, CE_NOTE,
18701 			    "Remove attachment point of port %d:%d",
18702 			    cport, npmport);
18703 
18704 			/* Remove target node */
18705 			pmport_addr.cport = cport;
18706 			pmport_addr.pmport = (uint8_t)npmport;
18707 			pmport_addr.qual = SATA_ADDR_PMPORT;
18708 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18709 
18710 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18711 
18712 			/* Release sata_pmport_info & sata_drive_info. */
18713 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18714 			    cport, npmport);
18715 			ASSERT(pmportinfo != NULL);
18716 
18717 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18718 			if (sdevinfo != NULL) {
18719 				(void) kmem_free((void *) sdevinfo,
18720 				    sizeof (sata_drive_info_t));
18721 			}
18722 
18723 			/* Release sata_pmport_info at last */
18724 			(void) kmem_free((void *) pmportinfo,
18725 			    sizeof (sata_pmport_info_t));
18726 		}
18727 
18728 		/* Finally, release sata_pmult_info */
18729 		(void) kmem_free((void *)
18730 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18731 		    sizeof (sata_pmult_info_t));
18732 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18733 
18734 		sata_log(sata_hba_inst, CE_WARN,
18735 		    "SATA port-multiplier detached at port %d", cport);
18736 
18737 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18738 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18739 		    saddr->cport)->cport_mutex);
18740 	} else {
18741 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18742 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18743 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18744 			(void) kmem_free((void *)sdevinfo,
18745 			    sizeof (sata_drive_info_t));
18746 		}
18747 		sata_log(sata_hba_inst, CE_WARN,
18748 		    "SATA device detached at port %d", cport);
18749 
18750 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18751 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18752 		    saddr->cport)->cport_mutex);
18753 
18754 		/*
18755 		 * Try to offline a device and remove target node
18756 		 * if it still exists
18757 		 */
18758 		sata_remove_target_node(sata_hba_inst, saddr);
18759 	}
18760 
18761 
18762 	/*
18763 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18764 	 * with the hint: SE_HINT_REMOVE
18765 	 */
18766 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18767 }
18768 
18769 /*
18770  * Port Multiplier Port Device Deattached Event processing.
18771  *
18772  * NOTE: No Mutex should be hold.
18773  */
18774 static void
18775 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18776     sata_address_t *saddr)
18777 {
18778 	sata_pmport_info_t *pmportinfo;
18779 	sata_drive_info_t *sdevinfo;
18780 	sata_device_t sata_device;
18781 	int rval;
18782 	uint8_t cport, pmport;
18783 
18784 	cport = saddr->cport;
18785 	pmport = saddr->pmport;
18786 
18787 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18788 	    "Processing port %d:%d device detached",
18789 	    cport, pmport);
18790 
18791 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18792 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18793 
18794 	/* Clear event flag */
18795 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18796 
18797 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18798 	if ((pmportinfo->pmport_state &
18799 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18800 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18801 		return;
18802 	}
18803 	/* For sanity, re-probe the port */
18804 	sata_device.satadev_rev = SATA_DEVICE_REV;
18805 	sata_device.satadev_addr = *saddr;
18806 
18807 	/*
18808 	 * We have to exit mutex, because the HBA probe port function may
18809 	 * block on its own mutex.
18810 	 */
18811 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18812 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18813 	    (SATA_DIP(sata_hba_inst), &sata_device);
18814 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18815 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18816 	if (rval != SATA_SUCCESS) {
18817 		/* Something went wrong? Fail the port */
18818 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18819 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18820 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18821 		    "SATA port %d:%d probing failed",
18822 		    saddr->pmport));
18823 		/*
18824 		 * We may want to release device info structure, but
18825 		 * it is not necessary.
18826 		 */
18827 		return;
18828 	} else {
18829 		/* port probed successfully */
18830 		pmportinfo->pmport_state |=
18831 		    SATA_STATE_PROBED | SATA_STATE_READY;
18832 	}
18833 	/*
18834 	 * Check if a device is still attached. For sanity, check also
18835 	 * link status - if no link, there is no device.
18836 	 */
18837 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18838 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18839 	    SATA_DTYPE_NONE) {
18840 		/*
18841 		 * Device is still attached - ignore detach event.
18842 		 */
18843 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18844 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18845 		    "Ignoring detach - device still attached to port %d",
18846 		    sata_device.satadev_addr.pmport);
18847 		return;
18848 	}
18849 	/*
18850 	 * We need to detach and release device info structure here
18851 	 */
18852 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18853 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18854 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18855 		(void) kmem_free((void *)sdevinfo,
18856 		    sizeof (sata_drive_info_t));
18857 	}
18858 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18859 	/*
18860 	 * Device cannot be reached anymore, even if the target node may be
18861 	 * still present.
18862 	 */
18863 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18864 
18865 	/*
18866 	 * Try to offline a device and remove target node if it still exists
18867 	 */
18868 	sata_remove_target_node(sata_hba_inst, saddr);
18869 
18870 	/*
18871 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18872 	 * with the hint: SE_HINT_REMOVE
18873 	 */
18874 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18875 }
18876 
18877 
18878 /*
18879  * Device Attached Event processing.
18880  * Port state is checked to verify that a device is really attached. If so,
18881  * the device info structure is created and attached to the SATA port info
18882  * structure.
18883  *
18884  * If attached device cannot be identified or set-up, the retry for the
18885  * attach processing is set-up. Subsequent daemon run would try again to
18886  * identify the device, until the time limit is reached
18887  * (SATA_DEV_IDENTIFY_TIMEOUT).
18888  *
18889  * This function cannot be called in interrupt context (it may sleep).
18890  *
18891  * NOTE: Port multiplier ports events are handled by
18892  * sata_process_pmdevice_attached()
18893  */
18894 static void
18895 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
18896     sata_address_t *saddr)
18897 {
18898 	sata_cport_info_t *cportinfo = NULL;
18899 	sata_drive_info_t *sdevinfo = NULL;
18900 	sata_pmult_info_t *pmultinfo = NULL;
18901 	sata_pmport_info_t *pmportinfo = NULL;
18902 	sata_device_t sata_device;
18903 	dev_info_t *tdip;
18904 	uint32_t event_flags = 0, pmult_event_flags = 0;
18905 	int rval;
18906 	int npmport;
18907 
18908 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18909 	    "Processing port %d device attached", saddr->cport);
18910 
18911 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18912 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18913 
18914 	/* Clear attach event flag first */
18915 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18916 
18917 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18918 	if ((cportinfo->cport_state &
18919 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18920 		cportinfo->cport_dev_attach_time = 0;
18921 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18922 		    cport_mutex);
18923 		return;
18924 	}
18925 
18926 	/*
18927 	 * If the sata_drive_info structure is found attached to the port info,
18928 	 * despite the fact the device was removed and now it is re-attached,
18929 	 * the old drive info structure was not removed.
18930 	 * Arbitrarily release device info structure.
18931 	 */
18932 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18933 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18934 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18935 		(void) kmem_free((void *)sdevinfo,
18936 		    sizeof (sata_drive_info_t));
18937 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18938 		    "Arbitrarily detaching old device info.", NULL);
18939 	}
18940 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18941 
18942 	/* For sanity, re-probe the port */
18943 	sata_device.satadev_rev = SATA_DEVICE_REV;
18944 	sata_device.satadev_addr = *saddr;
18945 
18946 	/*
18947 	 * We have to exit mutex, because the HBA probe port function may
18948 	 * block on its own mutex.
18949 	 */
18950 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18951 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18952 	    (SATA_DIP(sata_hba_inst), &sata_device);
18953 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18954 	sata_update_port_info(sata_hba_inst, &sata_device);
18955 	if (rval != SATA_SUCCESS) {
18956 		/* Something went wrong? Fail the port */
18957 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18958 		cportinfo->cport_dev_attach_time = 0;
18959 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18960 		    cport_mutex);
18961 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18962 		    "SATA port %d probing failed",
18963 		    saddr->cport));
18964 		return;
18965 	} else {
18966 		/* port probed successfully */
18967 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18968 	}
18969 	/*
18970 	 * Check if a device is still attached. For sanity, check also
18971 	 * link status - if no link, there is no device.
18972 	 */
18973 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18974 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18975 	    SATA_DTYPE_NONE) {
18976 		/*
18977 		 * No device - ignore attach event.
18978 		 */
18979 		cportinfo->cport_dev_attach_time = 0;
18980 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18981 		    cport_mutex);
18982 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18983 		    "Ignoring attach - no device connected to port %d",
18984 		    sata_device.satadev_addr.cport);
18985 		return;
18986 	}
18987 
18988 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18989 	/*
18990 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18991 	 * with the hint: SE_HINT_INSERT
18992 	 */
18993 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
18994 
18995 	/*
18996 	 * Port reprobing will take care of the creation of the device
18997 	 * info structure and determination of the device type.
18998 	 */
18999 	sata_device.satadev_addr = *saddr;
19000 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19001 	    SATA_DEV_IDENTIFY_NORETRY);
19002 
19003 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19004 	    cport_mutex);
19005 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19006 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19007 		/* Some device is attached to the port */
19008 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19009 			/*
19010 			 * A device was not successfully attached.
19011 			 * Track retry time for device identification.
19012 			 */
19013 			if (cportinfo->cport_dev_attach_time != 0) {
19014 				clock_t cur_time = ddi_get_lbolt();
19015 				/*
19016 				 * If the retry time limit was not exceeded,
19017 				 * reinstate attach event.
19018 				 */
19019 				if ((cur_time -
19020 				    cportinfo->cport_dev_attach_time) <
19021 				    drv_usectohz(
19022 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19023 					/* OK, restore attach event */
19024 					cportinfo->cport_event_flags |=
19025 					    SATA_EVNT_DEVICE_ATTACHED;
19026 				} else {
19027 					/* Timeout - cannot identify device */
19028 					cportinfo->cport_dev_attach_time = 0;
19029 					sata_log(sata_hba_inst,
19030 					    CE_WARN,
19031 					    "Could not identify SATA device "
19032 					    "at port %d",
19033 					    saddr->cport);
19034 				}
19035 			} else {
19036 				/*
19037 				 * Start tracking time for device
19038 				 * identification.
19039 				 * Save current time (lbolt value).
19040 				 */
19041 				cportinfo->cport_dev_attach_time =
19042 				    ddi_get_lbolt();
19043 				/* Restore attach event */
19044 				cportinfo->cport_event_flags |=
19045 				    SATA_EVNT_DEVICE_ATTACHED;
19046 			}
19047 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19048 			cportinfo->cport_dev_attach_time = 0;
19049 			sata_log(sata_hba_inst, CE_NOTE,
19050 			    "SATA port-multiplier detected at port %d",
19051 			    saddr->cport);
19052 
19053 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19054 				/* Log the info of new port multiplier */
19055 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19056 				    saddr->cport)->cport_mutex);
19057 				sata_show_pmult_info(sata_hba_inst,
19058 				    &sata_device);
19059 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19060 				    saddr->cport)->cport_mutex);
19061 			}
19062 
19063 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19064 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19065 			for (npmport = 0; npmport <
19066 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19067 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19068 				    saddr->cport, npmport);
19069 				ASSERT(pmportinfo != NULL);
19070 
19071 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19072 				    saddr->cport)->cport_mutex);
19073 				mutex_enter(&pmportinfo->pmport_mutex);
19074 				/* Marked all pmports with link events. */
19075 				pmportinfo->pmport_event_flags =
19076 				    SATA_EVNT_LINK_ESTABLISHED;
19077 				pmult_event_flags |=
19078 				    pmportinfo->pmport_event_flags;
19079 				mutex_exit(&pmportinfo->pmport_mutex);
19080 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19081 				    saddr->cport)->cport_mutex);
19082 			}
19083 			/* Auto-online is not available for PMult now. */
19084 
19085 		} else {
19086 			/*
19087 			 * If device was successfully attached, the subsequent
19088 			 * action depends on a state of the
19089 			 * sata_auto_online variable. If it is set to zero.
19090 			 * an explicit 'configure' command will be needed to
19091 			 * configure it. If its value is non-zero, we will
19092 			 * attempt to online (configure) the device.
19093 			 * First, log the message indicating that a device
19094 			 * was attached.
19095 			 */
19096 			cportinfo->cport_dev_attach_time = 0;
19097 			sata_log(sata_hba_inst, CE_WARN,
19098 			    "SATA device detected at port %d", saddr->cport);
19099 
19100 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19101 				sata_drive_info_t new_sdinfo;
19102 
19103 				/* Log device info data */
19104 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19105 				    cportinfo));
19106 				sata_show_drive_info(sata_hba_inst,
19107 				    &new_sdinfo);
19108 			}
19109 
19110 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19111 			    saddr->cport)->cport_mutex);
19112 
19113 			/*
19114 			 * Make sure that there is no target node for that
19115 			 * device. If so, release it. It should not happen,
19116 			 * unless we had problem removing the node when
19117 			 * device was detached.
19118 			 */
19119 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19120 			    saddr->cport, saddr->pmport);
19121 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19122 			    saddr->cport)->cport_mutex);
19123 			if (tdip != NULL) {
19124 
19125 #ifdef SATA_DEBUG
19126 				if ((cportinfo->cport_event_flags &
19127 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19128 					sata_log(sata_hba_inst, CE_WARN,
19129 					    "sata_process_device_attached: "
19130 					    "old device target node exists!");
19131 #endif
19132 				/*
19133 				 * target node exists - try to unconfigure
19134 				 * device and remove the node.
19135 				 */
19136 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19137 				    saddr->cport)->cport_mutex);
19138 				rval = ndi_devi_offline(tdip,
19139 				    NDI_DEVI_REMOVE);
19140 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19141 				    saddr->cport)->cport_mutex);
19142 
19143 				if (rval == NDI_SUCCESS) {
19144 					cportinfo->cport_event_flags &=
19145 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19146 					cportinfo->cport_tgtnode_clean = B_TRUE;
19147 				} else {
19148 					/*
19149 					 * PROBLEM - the target node remained
19150 					 * and it belongs to a previously
19151 					 * attached device.
19152 					 * This happens when the file was open
19153 					 * or the node was waiting for
19154 					 * resources at the time the
19155 					 * associated device was removed.
19156 					 * Instruct event daemon to retry the
19157 					 * cleanup later.
19158 					 */
19159 					sata_log(sata_hba_inst,
19160 					    CE_WARN,
19161 					    "Application(s) accessing "
19162 					    "previously attached SATA "
19163 					    "device have to release "
19164 					    "it before newly inserted "
19165 					    "device can be made accessible.",
19166 					    saddr->cport);
19167 					cportinfo->cport_event_flags |=
19168 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19169 					cportinfo->cport_tgtnode_clean =
19170 					    B_FALSE;
19171 				}
19172 			}
19173 			if (sata_auto_online != 0) {
19174 				cportinfo->cport_event_flags |=
19175 				    SATA_EVNT_AUTOONLINE_DEVICE;
19176 			}
19177 
19178 		}
19179 	} else {
19180 		cportinfo->cport_dev_attach_time = 0;
19181 	}
19182 
19183 	event_flags = cportinfo->cport_event_flags;
19184 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19185 	if (event_flags != 0 || pmult_event_flags != 0) {
19186 		mutex_enter(&sata_hba_inst->satahba_mutex);
19187 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19188 		mutex_exit(&sata_hba_inst->satahba_mutex);
19189 		mutex_enter(&sata_mutex);
19190 		sata_event_pending |= SATA_EVNT_MAIN;
19191 		mutex_exit(&sata_mutex);
19192 	}
19193 }
19194 
19195 /*
19196  * Port Multiplier Port Device Attached Event processing.
19197  *
19198  * NOTE: No Mutex should be hold.
19199  */
19200 static void
19201 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19202     sata_address_t *saddr)
19203 {
19204 	sata_pmport_info_t *pmportinfo;
19205 	sata_drive_info_t *sdinfo;
19206 	sata_device_t sata_device;
19207 	dev_info_t *tdip;
19208 	uint32_t event_flags;
19209 	uint8_t cport = saddr->cport;
19210 	uint8_t pmport = saddr->pmport;
19211 	int rval;
19212 
19213 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19214 	    "Processing port %d:%d device attached", cport, pmport);
19215 
19216 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19217 
19218 	mutex_enter(&pmportinfo->pmport_mutex);
19219 
19220 	/* Clear attach event flag first */
19221 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19222 
19223 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19224 	if ((pmportinfo->pmport_state &
19225 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19226 		pmportinfo->pmport_dev_attach_time = 0;
19227 		mutex_exit(&pmportinfo->pmport_mutex);
19228 		return;
19229 	}
19230 
19231 	/*
19232 	 * If the sata_drive_info structure is found attached to the port info,
19233 	 * despite the fact the device was removed and now it is re-attached,
19234 	 * the old drive info structure was not removed.
19235 	 * Arbitrarily release device info structure.
19236 	 */
19237 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19238 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19239 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19240 		(void) kmem_free((void *)sdinfo,
19241 		    sizeof (sata_drive_info_t));
19242 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19243 		    "Arbitrarily detaching old device info.", NULL);
19244 	}
19245 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19246 
19247 	/* For sanity, re-probe the port */
19248 	sata_device.satadev_rev = SATA_DEVICE_REV;
19249 	sata_device.satadev_addr = *saddr;
19250 
19251 	/*
19252 	 * We have to exit mutex, because the HBA probe port function may
19253 	 * block on its own mutex.
19254 	 */
19255 	mutex_exit(&pmportinfo->pmport_mutex);
19256 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19257 	    (SATA_DIP(sata_hba_inst), &sata_device);
19258 	mutex_enter(&pmportinfo->pmport_mutex);
19259 
19260 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19261 	if (rval != SATA_SUCCESS) {
19262 		/* Something went wrong? Fail the port */
19263 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19264 		pmportinfo->pmport_dev_attach_time = 0;
19265 		mutex_exit(&pmportinfo->pmport_mutex);
19266 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19267 		    "SATA port %d:%d probing failed", cport, pmport));
19268 		return;
19269 	} else {
19270 		/* pmport probed successfully */
19271 		pmportinfo->pmport_state |=
19272 		    SATA_STATE_PROBED | SATA_STATE_READY;
19273 	}
19274 	/*
19275 	 * Check if a device is still attached. For sanity, check also
19276 	 * link status - if no link, there is no device.
19277 	 */
19278 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19279 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19280 	    SATA_DTYPE_NONE) {
19281 		/*
19282 		 * No device - ignore attach event.
19283 		 */
19284 		pmportinfo->pmport_dev_attach_time = 0;
19285 		mutex_exit(&pmportinfo->pmport_mutex);
19286 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19287 		    "Ignoring attach - no device connected to port %d:%d",
19288 		    cport, pmport);
19289 		return;
19290 	}
19291 
19292 	mutex_exit(&pmportinfo->pmport_mutex);
19293 	/*
19294 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19295 	 * with the hint: SE_HINT_INSERT
19296 	 */
19297 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19298 
19299 	/*
19300 	 * Port reprobing will take care of the creation of the device
19301 	 * info structure and determination of the device type.
19302 	 */
19303 	sata_device.satadev_addr = *saddr;
19304 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19305 	    SATA_DEV_IDENTIFY_NORETRY);
19306 
19307 	mutex_enter(&pmportinfo->pmport_mutex);
19308 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19309 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19310 		/* Some device is attached to the port */
19311 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19312 			/*
19313 			 * A device was not successfully attached.
19314 			 * Track retry time for device identification.
19315 			 */
19316 			if (pmportinfo->pmport_dev_attach_time != 0) {
19317 				clock_t cur_time = ddi_get_lbolt();
19318 				/*
19319 				 * If the retry time limit was not exceeded,
19320 				 * reinstate attach event.
19321 				 */
19322 				if ((cur_time -
19323 				    pmportinfo->pmport_dev_attach_time) <
19324 				    drv_usectohz(
19325 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19326 					/* OK, restore attach event */
19327 					pmportinfo->pmport_event_flags |=
19328 					    SATA_EVNT_DEVICE_ATTACHED;
19329 				} else {
19330 					/* Timeout - cannot identify device */
19331 					pmportinfo->pmport_dev_attach_time = 0;
19332 					sata_log(sata_hba_inst, CE_WARN,
19333 					    "Could not identify SATA device "
19334 					    "at port %d:%d",
19335 					    cport, pmport);
19336 				}
19337 			} else {
19338 				/*
19339 				 * Start tracking time for device
19340 				 * identification.
19341 				 * Save current time (lbolt value).
19342 				 */
19343 				pmportinfo->pmport_dev_attach_time =
19344 				    ddi_get_lbolt();
19345 				/* Restore attach event */
19346 				pmportinfo->pmport_event_flags |=
19347 				    SATA_EVNT_DEVICE_ATTACHED;
19348 			}
19349 		} else {
19350 			/*
19351 			 * If device was successfully attached, the subsequent
19352 			 * action depends on a state of the
19353 			 * sata_auto_online variable. If it is set to zero.
19354 			 * an explicit 'configure' command will be needed to
19355 			 * configure it. If its value is non-zero, we will
19356 			 * attempt to online (configure) the device.
19357 			 * First, log the message indicating that a device
19358 			 * was attached.
19359 			 */
19360 			pmportinfo->pmport_dev_attach_time = 0;
19361 			sata_log(sata_hba_inst, CE_WARN,
19362 			    "SATA device detected at port %d:%d",
19363 			    cport, pmport);
19364 
19365 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19366 				sata_drive_info_t new_sdinfo;
19367 
19368 				/* Log device info data */
19369 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19370 				    pmportinfo));
19371 				sata_show_drive_info(sata_hba_inst,
19372 				    &new_sdinfo);
19373 			}
19374 
19375 			mutex_exit(&pmportinfo->pmport_mutex);
19376 
19377 			/*
19378 			 * Make sure that there is no target node for that
19379 			 * device. If so, release it. It should not happen,
19380 			 * unless we had problem removing the node when
19381 			 * device was detached.
19382 			 */
19383 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19384 			    saddr->cport, saddr->pmport);
19385 			mutex_enter(&pmportinfo->pmport_mutex);
19386 			if (tdip != NULL) {
19387 
19388 #ifdef SATA_DEBUG
19389 				if ((pmportinfo->pmport_event_flags &
19390 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19391 					sata_log(sata_hba_inst, CE_WARN,
19392 					    "sata_process_device_attached: "
19393 					    "old device target node exists!");
19394 #endif
19395 				/*
19396 				 * target node exists - try to unconfigure
19397 				 * device and remove the node.
19398 				 */
19399 				mutex_exit(&pmportinfo->pmport_mutex);
19400 				rval = ndi_devi_offline(tdip,
19401 				    NDI_DEVI_REMOVE);
19402 				mutex_enter(&pmportinfo->pmport_mutex);
19403 
19404 				if (rval == NDI_SUCCESS) {
19405 					pmportinfo->pmport_event_flags &=
19406 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19407 					pmportinfo->pmport_tgtnode_clean =
19408 					    B_TRUE;
19409 				} else {
19410 					/*
19411 					 * PROBLEM - the target node remained
19412 					 * and it belongs to a previously
19413 					 * attached device.
19414 					 * This happens when the file was open
19415 					 * or the node was waiting for
19416 					 * resources at the time the
19417 					 * associated device was removed.
19418 					 * Instruct event daemon to retry the
19419 					 * cleanup later.
19420 					 */
19421 					sata_log(sata_hba_inst,
19422 					    CE_WARN,
19423 					    "Application(s) accessing "
19424 					    "previously attached SATA "
19425 					    "device have to release "
19426 					    "it before newly inserted "
19427 					    "device can be made accessible."
19428 					    "at port %d:%d",
19429 					    cport, pmport);
19430 					pmportinfo->pmport_event_flags |=
19431 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19432 					pmportinfo->pmport_tgtnode_clean =
19433 					    B_FALSE;
19434 				}
19435 			}
19436 			if (sata_auto_online != 0) {
19437 				pmportinfo->pmport_event_flags |=
19438 				    SATA_EVNT_AUTOONLINE_DEVICE;
19439 			}
19440 
19441 		}
19442 	} else {
19443 		pmportinfo->pmport_dev_attach_time = 0;
19444 	}
19445 
19446 	event_flags = pmportinfo->pmport_event_flags;
19447 	mutex_exit(&pmportinfo->pmport_mutex);
19448 	if (event_flags != 0) {
19449 		mutex_enter(&sata_hba_inst->satahba_mutex);
19450 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19451 		mutex_exit(&sata_hba_inst->satahba_mutex);
19452 		mutex_enter(&sata_mutex);
19453 		sata_event_pending |= SATA_EVNT_MAIN;
19454 		mutex_exit(&sata_mutex);
19455 	}
19456 
19457 	/* clear the reset_in_progress events */
19458 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19459 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19460 			/* must clear flags on cport */
19461 			sata_pmult_info_t *pminfo =
19462 			    SATA_PMULT_INFO(sata_hba_inst,
19463 			    saddr->cport);
19464 			pminfo->pmult_event_flags |=
19465 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19466 		}
19467 	}
19468 }
19469 
19470 /*
19471  * Device Target Node Cleanup Event processing.
19472  * If the target node associated with a sata port device is in
19473  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19474  * If the target node cannot be removed, the event flag is left intact,
19475  * so that event daemon may re-run this function later.
19476  *
19477  * This function cannot be called in interrupt context (it may sleep).
19478  *
19479  * NOTE: Processes cport events only, not port multiplier ports.
19480  */
19481 static void
19482 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19483     sata_address_t *saddr)
19484 {
19485 	sata_cport_info_t *cportinfo;
19486 	dev_info_t *tdip;
19487 
19488 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19489 	    "Processing port %d device target node cleanup", saddr->cport);
19490 
19491 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19492 
19493 	/*
19494 	 * Check if there is target node for that device and it is in the
19495 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19496 	 */
19497 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19498 	    saddr->pmport);
19499 	if (tdip != NULL) {
19500 		/*
19501 		 * target node exists - check if it is target node of
19502 		 * a removed device.
19503 		 */
19504 		if (sata_check_device_removed(tdip) == B_TRUE) {
19505 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19506 			    "sata_process_target_node_cleanup: "
19507 			    "old device target node exists!", NULL);
19508 			/*
19509 			 * Unconfigure and remove the target node
19510 			 */
19511 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19512 			    NDI_SUCCESS) {
19513 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19514 				    saddr->cport)->cport_mutex);
19515 				cportinfo->cport_event_flags &=
19516 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19517 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19518 				    saddr->cport)->cport_mutex);
19519 				return;
19520 			}
19521 			/*
19522 			 * Event daemon will retry the cleanup later.
19523 			 */
19524 			mutex_enter(&sata_hba_inst->satahba_mutex);
19525 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19526 			mutex_exit(&sata_hba_inst->satahba_mutex);
19527 			mutex_enter(&sata_mutex);
19528 			sata_event_pending |= SATA_EVNT_MAIN;
19529 			mutex_exit(&sata_mutex);
19530 		}
19531 	} else {
19532 		if (saddr->qual == SATA_ADDR_CPORT ||
19533 		    saddr->qual == SATA_ADDR_DCPORT) {
19534 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19535 			    saddr->cport)->cport_mutex);
19536 			cportinfo->cport_event_flags &=
19537 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19538 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19539 			    saddr->cport)->cport_mutex);
19540 		} else {
19541 			/* sanity check */
19542 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19543 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19544 			    saddr->cport) == NULL)
19545 				return;
19546 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19547 			    saddr->pmport) == NULL)
19548 				return;
19549 
19550 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19551 			    saddr->cport, saddr->pmport)->pmport_mutex);
19552 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19553 			    saddr->pmport)->pmport_event_flags &=
19554 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19555 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19556 			    saddr->cport, saddr->pmport)->pmport_mutex);
19557 		}
19558 	}
19559 }
19560 
19561 /*
19562  * Device AutoOnline Event processing.
19563  * If attached device is to be onlined, an attempt is made to online this
19564  * device, but only if there is no lingering (old) target node present.
19565  * If the device cannot be onlined, the event flag is left intact,
19566  * so that event daemon may re-run this function later.
19567  *
19568  * This function cannot be called in interrupt context (it may sleep).
19569  *
19570  * NOTE: Processes cport events only, not port multiplier ports.
19571  */
19572 static void
19573 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19574     sata_address_t *saddr)
19575 {
19576 	sata_cport_info_t *cportinfo;
19577 	sata_drive_info_t *sdinfo;
19578 	sata_device_t sata_device;
19579 	dev_info_t *tdip;
19580 
19581 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19582 	    "Processing port %d attached device auto-onlining", saddr->cport);
19583 
19584 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19585 
19586 	/*
19587 	 * Check if device is present and recognized. If not, reset event.
19588 	 */
19589 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19590 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19591 		/* Nothing to online */
19592 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19593 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19594 		    saddr->cport)->cport_mutex);
19595 		return;
19596 	}
19597 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19598 
19599 	/*
19600 	 * Check if there is target node for this device and if it is in the
19601 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19602 	 * the event for later processing.
19603 	 */
19604 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19605 	    saddr->pmport);
19606 	if (tdip != NULL) {
19607 		/*
19608 		 * target node exists - check if it is target node of
19609 		 * a removed device.
19610 		 */
19611 		if (sata_check_device_removed(tdip) == B_TRUE) {
19612 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19613 			    "sata_process_device_autoonline: "
19614 			    "old device target node exists!", NULL);
19615 			/*
19616 			 * Event daemon will retry device onlining later.
19617 			 */
19618 			mutex_enter(&sata_hba_inst->satahba_mutex);
19619 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19620 			mutex_exit(&sata_hba_inst->satahba_mutex);
19621 			mutex_enter(&sata_mutex);
19622 			sata_event_pending |= SATA_EVNT_MAIN;
19623 			mutex_exit(&sata_mutex);
19624 			return;
19625 		}
19626 		/*
19627 		 * If the target node is not in the 'removed" state, assume
19628 		 * that it belongs to this device. There is nothing more to do,
19629 		 * but reset the event.
19630 		 */
19631 	} else {
19632 
19633 		/*
19634 		 * Try to online the device
19635 		 * If there is any reset-related event, remove it. We are
19636 		 * configuring the device and no state restoring is needed.
19637 		 */
19638 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19639 		    saddr->cport)->cport_mutex);
19640 		sata_device.satadev_addr = *saddr;
19641 		if (saddr->qual == SATA_ADDR_CPORT)
19642 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19643 		else
19644 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19645 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19646 		if (sdinfo != NULL) {
19647 			if (sdinfo->satadrv_event_flags &
19648 			    (SATA_EVNT_DEVICE_RESET |
19649 			    SATA_EVNT_INPROC_DEVICE_RESET))
19650 				sdinfo->satadrv_event_flags = 0;
19651 			sdinfo->satadrv_event_flags |=
19652 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19653 
19654 			/* Need to create a new target node. */
19655 			cportinfo->cport_tgtnode_clean = B_TRUE;
19656 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19657 			    saddr->cport)->cport_mutex);
19658 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19659 			    sata_hba_inst, &sata_device.satadev_addr);
19660 			if (tdip == NULL) {
19661 				/*
19662 				 * Configure (onlining) failed.
19663 				 * We will NOT retry
19664 				 */
19665 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19666 				    "sata_process_device_autoonline: "
19667 				    "configuring SATA device at port %d failed",
19668 				    saddr->cport));
19669 			}
19670 		} else {
19671 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19672 			    saddr->cport)->cport_mutex);
19673 		}
19674 
19675 	}
19676 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19677 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19678 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19679 	    saddr->cport)->cport_mutex);
19680 }
19681 
19682 
19683 static void
19684 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19685     int hint)
19686 {
19687 	char ap[MAXPATHLEN];
19688 	nvlist_t *ev_attr_list = NULL;
19689 	int err;
19690 
19691 	/* Allocate and build sysevent attribute list */
19692 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19693 	if (err != 0) {
19694 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19695 		    "sata_gen_sysevent: "
19696 		    "cannot allocate memory for sysevent attributes\n"));
19697 		return;
19698 	}
19699 	/* Add hint attribute */
19700 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19701 	if (err != 0) {
19702 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19703 		    "sata_gen_sysevent: "
19704 		    "failed to add DR_HINT attr for sysevent"));
19705 		nvlist_free(ev_attr_list);
19706 		return;
19707 	}
19708 	/*
19709 	 * Add AP attribute.
19710 	 * Get controller pathname and convert it into AP pathname by adding
19711 	 * a target number.
19712 	 */
19713 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19714 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19715 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19716 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19717 
19718 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19719 	if (err != 0) {
19720 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19721 		    "sata_gen_sysevent: "
19722 		    "failed to add DR_AP_ID attr for sysevent"));
19723 		nvlist_free(ev_attr_list);
19724 		return;
19725 	}
19726 
19727 	/* Generate/log sysevent */
19728 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19729 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19730 	if (err != DDI_SUCCESS) {
19731 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19732 		    "sata_gen_sysevent: "
19733 		    "cannot log sysevent, err code %x\n", err));
19734 	}
19735 
19736 	nvlist_free(ev_attr_list);
19737 }
19738 
19739 
19740 
19741 
19742 /*
19743  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19744  */
19745 static void
19746 sata_set_device_removed(dev_info_t *tdip)
19747 {
19748 	int circ;
19749 
19750 	ASSERT(tdip != NULL);
19751 
19752 	ndi_devi_enter(tdip, &circ);
19753 	mutex_enter(&DEVI(tdip)->devi_lock);
19754 	DEVI_SET_DEVICE_REMOVED(tdip);
19755 	mutex_exit(&DEVI(tdip)->devi_lock);
19756 	ndi_devi_exit(tdip, circ);
19757 }
19758 
19759 
19760 /*
19761  * Set internal event instructing event daemon to try
19762  * to perform the target node cleanup.
19763  */
19764 static void
19765 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19766     sata_address_t *saddr)
19767 {
19768 	if (saddr->qual == SATA_ADDR_CPORT ||
19769 	    saddr->qual == SATA_ADDR_DCPORT) {
19770 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19771 		    saddr->cport)->cport_mutex);
19772 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19773 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19774 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19775 		    cport_tgtnode_clean = B_FALSE;
19776 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19777 		    saddr->cport)->cport_mutex);
19778 	} else {
19779 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19780 		    saddr->cport, saddr->pmport)->pmport_mutex);
19781 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19782 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19783 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19784 		    pmport_tgtnode_clean = B_FALSE;
19785 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19786 		    saddr->cport, saddr->pmport)->pmport_mutex);
19787 	}
19788 	mutex_enter(&sata_hba_inst->satahba_mutex);
19789 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19790 	mutex_exit(&sata_hba_inst->satahba_mutex);
19791 	mutex_enter(&sata_mutex);
19792 	sata_event_pending |= SATA_EVNT_MAIN;
19793 	mutex_exit(&sata_mutex);
19794 }
19795 
19796 
19797 /*
19798  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19799  * i.e. check if the target node state indicates that it belongs to a removed
19800  * device.
19801  *
19802  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19803  * B_FALSE otherwise.
19804  */
19805 static boolean_t
19806 sata_check_device_removed(dev_info_t *tdip)
19807 {
19808 	ASSERT(tdip != NULL);
19809 
19810 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19811 		return (B_TRUE);
19812 	else
19813 		return (B_FALSE);
19814 }
19815 
19816 /* ************************ FAULT INJECTTION **************************** */
19817 
19818 #ifdef SATA_INJECT_FAULTS
19819 
19820 static	uint32_t sata_fault_count = 0;
19821 static	uint32_t sata_fault_suspend_count = 0;
19822 
19823 /*
19824  * Inject sata pkt fault
19825  * It modifies returned values of the sata packet.
19826  * It returns immediately if:
19827  * pkt fault injection is not enabled (via sata_inject_fault,
19828  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19829  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19830  * pkt is not directed to specified fault controller/device
19831  * (sata_fault_ctrl_dev and sata_fault_device).
19832  * If fault controller is not specified, fault injection applies to all
19833  * controllers and devices.
19834  *
19835  * First argument is the pointer to the executed sata packet.
19836  * Second argument is a pointer to a value returned by the HBA tran_start
19837  * function.
19838  * Third argument specifies injected error. Injected sata packet faults
19839  * are the satapkt_reason values.
19840  * SATA_PKT_BUSY		-1	Not completed, busy
19841  * SATA_PKT_DEV_ERROR		1	Device reported error
19842  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
19843  * SATA_PKT_PORT_ERROR		3	Not completed, port error
19844  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
19845  * SATA_PKT_ABORTED		5	Aborted by request
19846  * SATA_PKT_TIMEOUT		6	Operation timeut
19847  * SATA_PKT_RESET		7	Aborted by reset request
19848  *
19849  * Additional global variables affecting the execution:
19850  *
19851  * sata_inject_fault_count variable specifies number of times in row the
19852  * error is injected. Value of -1 specifies permanent fault, ie. every time
19853  * the fault injection point is reached, the fault is injected and a pause
19854  * between fault injection specified by sata_inject_fault_pause_count is
19855  * ignored). Fault injection routine decrements sata_inject_fault_count
19856  * (if greater than zero) until it reaches 0. No fault is injected when
19857  * sata_inject_fault_count is 0 (zero).
19858  *
19859  * sata_inject_fault_pause_count variable specifies number of times a fault
19860  * injection is bypassed (pause between fault injections).
19861  * If set to 0, a fault is injected only a number of times specified by
19862  * sata_inject_fault_count.
19863  *
19864  * The fault counts are static, so for periodic errors they have to be manually
19865  * reset to start repetition sequence from scratch.
19866  * If the original value returned by the HBA tran_start function is not
19867  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
19868  * is injected (to avoid masking real problems);
19869  *
19870  * NOTE: In its current incarnation, this function should be invoked only for
19871  * commands executed in SYNCHRONOUS mode.
19872  */
19873 
19874 
19875 static void
19876 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
19877 {
19878 
19879 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
19880 		return;
19881 
19882 	if (sata_inject_fault_count == 0)
19883 		return;
19884 
19885 	if (fault == 0)
19886 		return;
19887 
19888 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
19889 		return;
19890 
19891 	if (sata_fault_ctrl != NULL) {
19892 		sata_pkt_txlate_t *spx =
19893 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
19894 
19895 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
19896 		    spx->txlt_sata_hba_inst->satahba_dip)
19897 			return;
19898 
19899 		if (sata_fault_device.satadev_addr.cport !=
19900 		    spkt->satapkt_device.satadev_addr.cport ||
19901 		    sata_fault_device.satadev_addr.pmport !=
19902 		    spkt->satapkt_device.satadev_addr.pmport ||
19903 		    sata_fault_device.satadev_addr.qual !=
19904 		    spkt->satapkt_device.satadev_addr.qual)
19905 			return;
19906 	}
19907 
19908 	/* Modify pkt return parameters */
19909 	if (*rval != SATA_TRAN_ACCEPTED ||
19910 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
19911 		sata_fault_count = 0;
19912 		sata_fault_suspend_count = 0;
19913 		return;
19914 	}
19915 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
19916 		/* Pause in the injection */
19917 		sata_fault_suspend_count -= 1;
19918 		return;
19919 	}
19920 
19921 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
19922 		/*
19923 		 * Init inject fault cycle. If fault count is set to -1,
19924 		 * it is a permanent fault.
19925 		 */
19926 		if (sata_inject_fault_count != -1) {
19927 			sata_fault_count = sata_inject_fault_count;
19928 			sata_fault_suspend_count =
19929 			    sata_inject_fault_pause_count;
19930 			if (sata_fault_suspend_count == 0)
19931 				sata_inject_fault_count = 0;
19932 		}
19933 	}
19934 
19935 	if (sata_fault_count != 0)
19936 		sata_fault_count -= 1;
19937 
19938 	switch (fault) {
19939 	case SATA_PKT_BUSY:
19940 		*rval = SATA_TRAN_BUSY;
19941 		spkt->satapkt_reason = SATA_PKT_BUSY;
19942 		break;
19943 
19944 	case SATA_PKT_QUEUE_FULL:
19945 		*rval = SATA_TRAN_QUEUE_FULL;
19946 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
19947 		break;
19948 
19949 	case SATA_PKT_CMD_UNSUPPORTED:
19950 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
19951 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
19952 		break;
19953 
19954 	case SATA_PKT_PORT_ERROR:
19955 		/* This is "rejected" command */
19956 		*rval = SATA_TRAN_PORT_ERROR;
19957 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
19958 		/* Additional error setup could be done here - port state */
19959 		break;
19960 
19961 	case SATA_PKT_DEV_ERROR:
19962 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
19963 		/*
19964 		 * Additional error setup could be done here
19965 		 */
19966 		break;
19967 
19968 	case SATA_PKT_ABORTED:
19969 		spkt->satapkt_reason = SATA_PKT_ABORTED;
19970 		break;
19971 
19972 	case SATA_PKT_TIMEOUT:
19973 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
19974 		/* Additional error setup could be done here */
19975 		break;
19976 
19977 	case SATA_PKT_RESET:
19978 		spkt->satapkt_reason = SATA_PKT_RESET;
19979 		/*
19980 		 * Additional error setup could be done here - device reset
19981 		 */
19982 		break;
19983 
19984 	default:
19985 		break;
19986 	}
19987 }
19988 
19989 #endif
19990 
19991 /*
19992  * SATA Trace Ring Buffer
19993  * ----------------------
19994  *
19995  * Overview
19996  *
19997  * The SATA trace ring buffer is a ring buffer created and managed by
19998  * the SATA framework module that can be used by any module or driver
19999  * within the SATA framework to store debug messages.
20000  *
20001  * Ring Buffer Interfaces:
20002  *
20003  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20004  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20005  *
20006  *	Note that the sata_trace_debug() interface was created to give
20007  *	consumers the flexibilty of sending debug messages to ring buffer
20008  *	as variable arguments.  Consumers can send type va_list debug
20009  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20010  *	and sata_vtrace_debug() relationship is similar to that of
20011  *	cmn_err(9F) and vcmn_err(9F).
20012  *
20013  * Below is a diagram of the SATA trace ring buffer interfaces and
20014  * sample consumers:
20015  *
20016  * +---------------------------------+
20017  * |    o  o  SATA Framework Module  |
20018  * | o  SATA  o     +------------------+      +------------------+
20019  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20020  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20021  * | o        o     +------------------+   |  +------------------+
20022  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20023  * |                        |        |        +------------------+
20024  * |           +------------------+  |
20025  * |           |SATA Debug Message|  |
20026  * |           +------------------+  |
20027  * +---------------------------------+
20028  *
20029  * Supporting Routines:
20030  *
20031  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20032  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20033  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20034  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20035  *
20036  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20037  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20038  * /etc/system to desired size in unit of bytes.
20039  *
20040  * The individual debug message size in the ring buffer is restricted
20041  * to DMSG_BUF_SIZE.
20042  */
20043 void
20044 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20045 {
20046 	sata_trace_dmsg_t *dmsg;
20047 
20048 	if (sata_debug_rbuf == NULL) {
20049 		return;
20050 	}
20051 
20052 	/*
20053 	 * If max size of ring buffer is smaller than size
20054 	 * required for one debug message then just return
20055 	 * since we have no room for the debug message.
20056 	 */
20057 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20058 		return;
20059 	}
20060 
20061 	mutex_enter(&sata_debug_rbuf->lock);
20062 
20063 	/* alloc or reuse on ring buffer */
20064 	dmsg = sata_trace_dmsg_alloc();
20065 
20066 	if (dmsg == NULL) {
20067 		/* resource allocation failed */
20068 		mutex_exit(&sata_debug_rbuf->lock);
20069 		return;
20070 	}
20071 
20072 	dmsg->dip = dip;
20073 	gethrestime(&dmsg->timestamp);
20074 
20075 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20076 
20077 	mutex_exit(&sata_debug_rbuf->lock);
20078 }
20079 
20080 void
20081 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20082 {
20083 	va_list ap;
20084 
20085 	va_start(ap, fmt);
20086 	sata_vtrace_debug(dip, fmt, ap);
20087 	va_end(ap);
20088 }
20089 
20090 /*
20091  * This routine is used to manage debug messages
20092  * on ring buffer.
20093  */
20094 static sata_trace_dmsg_t *
20095 sata_trace_dmsg_alloc(void)
20096 {
20097 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20098 
20099 	if (sata_debug_rbuf->looped == TRUE) {
20100 		sata_debug_rbuf->dmsgp = dmsg->next;
20101 		return (sata_debug_rbuf->dmsgp);
20102 	}
20103 
20104 	/*
20105 	 * If we're looping for the first time,
20106 	 * connect the ring.
20107 	 */
20108 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20109 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20110 		dmsg->next = sata_debug_rbuf->dmsgh;
20111 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20112 		sata_debug_rbuf->looped = TRUE;
20113 		return (sata_debug_rbuf->dmsgp);
20114 	}
20115 
20116 	/* If we've gotten this far then memory allocation is needed */
20117 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20118 	if (dmsg_alloc == NULL) {
20119 		sata_debug_rbuf->allocfailed++;
20120 		return (dmsg_alloc);
20121 	} else {
20122 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20123 	}
20124 
20125 	if (sata_debug_rbuf->dmsgp != NULL) {
20126 		dmsg->next = dmsg_alloc;
20127 		sata_debug_rbuf->dmsgp = dmsg->next;
20128 		return (sata_debug_rbuf->dmsgp);
20129 	} else {
20130 		/*
20131 		 * We should only be here if we're initializing
20132 		 * the ring buffer.
20133 		 */
20134 		if (sata_debug_rbuf->dmsgh == NULL) {
20135 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20136 		} else {
20137 			/* Something is wrong */
20138 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20139 			return (NULL);
20140 		}
20141 
20142 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20143 		return (sata_debug_rbuf->dmsgp);
20144 	}
20145 }
20146 
20147 
20148 /*
20149  * Free all messages on debug ring buffer.
20150  */
20151 static void
20152 sata_trace_dmsg_free(void)
20153 {
20154 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20155 
20156 	while (dmsg != NULL) {
20157 		dmsg_next = dmsg->next;
20158 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20159 
20160 		/*
20161 		 * If we've looped around the ring than we're done.
20162 		 */
20163 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20164 			break;
20165 		} else {
20166 			dmsg = dmsg_next;
20167 		}
20168 	}
20169 }
20170 
20171 
20172 /*
20173  * This function can block
20174  */
20175 static void
20176 sata_trace_rbuf_alloc(void)
20177 {
20178 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20179 
20180 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20181 
20182 	if (dmsg_ring_size > 0) {
20183 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20184 	}
20185 }
20186 
20187 
20188 static void
20189 sata_trace_rbuf_free(void)
20190 {
20191 	sata_trace_dmsg_free();
20192 	mutex_destroy(&sata_debug_rbuf->lock);
20193 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20194 }
20195 
20196 /*
20197  * If SATA_DEBUG is not defined then this routine is called instead
20198  * of sata_log() via the SATA_LOG_D macro.
20199  */
20200 static void
20201 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20202     const char *fmt, ...)
20203 {
20204 #ifndef __lock_lint
20205 	_NOTE(ARGUNUSED(level))
20206 #endif
20207 
20208 	dev_info_t *dip = NULL;
20209 	va_list ap;
20210 
20211 	if (sata_hba_inst != NULL) {
20212 		dip = SATA_DIP(sata_hba_inst);
20213 	}
20214 
20215 	va_start(ap, fmt);
20216 	sata_vtrace_debug(dip, fmt, ap);
20217 	va_end(ap);
20218 }
20219