xref: /titanic_52/usr/src/uts/common/io/sata/impl/sata.c (revision 005d3feb53a9a10272d4a24b03991575d6a9bcb3)
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 2010 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 (servicing_interrupt()) {
2443 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2444 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2445 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
2446 				    NULL) {
2447 					return (TRAN_BUSY);
2448 				}
2449 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2450 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2451 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
2452 				/* Scheduling the callback failed */
2453 				return (TRAN_BUSY);
2454 			}
2455 			return (TRAN_ACCEPT);
2456 		}
2457 		/* No callback available */
2458 		return (TRAN_FATAL_ERROR);
2459 	}
2460 
2461 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2462 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2463 		rval = sata_txlt_atapi(spx);
2464 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2465 		    "sata_scsi_start atapi: rval %d\n", rval);
2466 		return (rval);
2467 	}
2468 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2469 
2470 	/*
2471 	 * Checking for power state, if it was on
2472 	 * STOPPED state, then the drive is not capable
2473 	 * of processing media access command.  And
2474 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2475 	 * in the function for different power state.
2476 	 */
2477 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2478 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2479 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2480 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2481 		    SD_SCSI_ASC_LU_NOT_READY));
2482 	}
2483 
2484 	/* ATA Disk commands processing starts here */
2485 
2486 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2487 
2488 	switch (pkt->pkt_cdbp[0]) {
2489 
2490 	case SCMD_INQUIRY:
2491 		/* Mapped to identify device */
2492 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2493 			bp_mapin(bp);
2494 		rval = sata_txlt_inquiry(spx);
2495 		break;
2496 
2497 	case SCMD_TEST_UNIT_READY:
2498 		/*
2499 		 * SAT "SATA to ATA Translation" doc specifies translation
2500 		 * to ATA CHECK POWER MODE.
2501 		 */
2502 		rval = sata_txlt_test_unit_ready(spx);
2503 		break;
2504 
2505 	case SCMD_START_STOP:
2506 		/* Mapping depends on the command */
2507 		rval = sata_txlt_start_stop_unit(spx);
2508 		break;
2509 
2510 	case SCMD_READ_CAPACITY:
2511 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2512 			bp_mapin(bp);
2513 		rval = sata_txlt_read_capacity(spx);
2514 		break;
2515 
2516 	case SCMD_REQUEST_SENSE:
2517 		/*
2518 		 * Always No Sense, since we force ARQ
2519 		 */
2520 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2521 			bp_mapin(bp);
2522 		rval = sata_txlt_request_sense(spx);
2523 		break;
2524 
2525 	case SCMD_LOG_SENSE_G1:
2526 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2527 			bp_mapin(bp);
2528 		rval = sata_txlt_log_sense(spx);
2529 		break;
2530 
2531 	case SCMD_LOG_SELECT_G1:
2532 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2533 			bp_mapin(bp);
2534 		rval = sata_txlt_log_select(spx);
2535 		break;
2536 
2537 	case SCMD_MODE_SENSE:
2538 	case SCMD_MODE_SENSE_G1:
2539 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2540 			bp_mapin(bp);
2541 		rval = sata_txlt_mode_sense(spx);
2542 		break;
2543 
2544 
2545 	case SCMD_MODE_SELECT:
2546 	case SCMD_MODE_SELECT_G1:
2547 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2548 			bp_mapin(bp);
2549 		rval = sata_txlt_mode_select(spx);
2550 		break;
2551 
2552 	case SCMD_SYNCHRONIZE_CACHE:
2553 	case SCMD_SYNCHRONIZE_CACHE_G1:
2554 		rval = sata_txlt_synchronize_cache(spx);
2555 		break;
2556 
2557 	case SCMD_READ:
2558 	case SCMD_READ_G1:
2559 	case SCMD_READ_G4:
2560 	case SCMD_READ_G5:
2561 		rval = sata_txlt_read(spx);
2562 		break;
2563 	case SCMD_WRITE_BUFFER:
2564 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2565 			bp_mapin(bp);
2566 		rval = sata_txlt_write_buffer(spx);
2567 		break;
2568 
2569 	case SCMD_WRITE:
2570 	case SCMD_WRITE_G1:
2571 	case SCMD_WRITE_G4:
2572 	case SCMD_WRITE_G5:
2573 		rval = sata_txlt_write(spx);
2574 		break;
2575 
2576 	case SCMD_SEEK:
2577 		rval = sata_txlt_nodata_cmd_immediate(spx);
2578 		break;
2579 
2580 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2581 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2582 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2583 			bp_mapin(bp);
2584 		rval = sata_txlt_ata_pass_thru(spx);
2585 		break;
2586 
2587 		/* Other cases will be filed later */
2588 		/* postponed until phase 2 of the development */
2589 	default:
2590 		rval = sata_txlt_invalid_command(spx);
2591 		break;
2592 	}
2593 
2594 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2595 	    "sata_scsi_start: rval %d\n", rval);
2596 
2597 	return (rval);
2598 }
2599 
2600 /*
2601  * Implementation of scsi tran_abort.
2602  * Abort specific pkt or all packets.
2603  *
2604  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2605  *
2606  * May be called from an interrupt level.
2607  */
2608 static int
2609 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2610 {
2611 	sata_hba_inst_t *sata_hba_inst =
2612 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2613 	sata_device_t	sata_device;
2614 	sata_pkt_t	*sata_pkt;
2615 
2616 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2617 	    "sata_scsi_abort: %s at target: 0x%x\n",
2618 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2619 
2620 	/* Validate address */
2621 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2622 		/* Invalid address */
2623 		return (0);
2624 
2625 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2626 	    sata_device.satadev_addr.cport)));
2627 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2628 		/* invalid address */
2629 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2630 		    sata_device.satadev_addr.cport)));
2631 		return (0);
2632 	}
2633 	if (scsi_pkt == NULL) {
2634 		/*
2635 		 * Abort all packets.
2636 		 * Although we do not have specific packet, we still need
2637 		 * dummy packet structure to pass device address to HBA.
2638 		 * Allocate one, without sleeping. Fail if pkt cannot be
2639 		 * allocated.
2640 		 */
2641 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2642 		if (sata_pkt == NULL) {
2643 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2644 			    sata_device.satadev_addr.cport)));
2645 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2646 			    "could not allocate sata_pkt"));
2647 			return (0);
2648 		}
2649 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2650 		sata_pkt->satapkt_device = sata_device;
2651 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2652 	} else {
2653 		if (scsi_pkt->pkt_ha_private == NULL) {
2654 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2655 			    sata_device.satadev_addr.cport)));
2656 			return (0); /* Bad scsi pkt */
2657 		}
2658 		/* extract pointer to sata pkt */
2659 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2660 		    txlt_sata_pkt;
2661 	}
2662 
2663 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2664 	    sata_device.satadev_addr.cport)));
2665 	/* Send abort request to HBA */
2666 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2667 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2668 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2669 	    SATA_SUCCESS) {
2670 		if (scsi_pkt == NULL)
2671 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2672 		/* Success */
2673 		return (1);
2674 	}
2675 	/* Else, something did not go right */
2676 	if (scsi_pkt == NULL)
2677 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2678 	/* Failure */
2679 	return (0);
2680 }
2681 
2682 
2683 /*
2684  * Implementation of scsi tran_reset.
2685  * RESET_ALL request is translated into port reset.
2686  * RESET_TARGET requests is translated into a device reset,
2687  * RESET_LUN request is accepted only for LUN 0 and translated into
2688  * device reset.
2689  * The target reset should cause all HBA active and queued packets to
2690  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2691  * the return. HBA should report reset event for the device.
2692  *
2693  * Returns 1 upon success, 0 upon failure.
2694  */
2695 static int
2696 sata_scsi_reset(struct scsi_address *ap, int level)
2697 {
2698 	sata_hba_inst_t	*sata_hba_inst =
2699 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2700 	sata_device_t	sata_device;
2701 	int		val;
2702 
2703 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2704 	    "sata_scsi_reset: level %d target: 0x%x\n",
2705 	    level, ap->a_target);
2706 
2707 	/* Validate address */
2708 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2709 	if (val == -1)
2710 		/* Invalid address */
2711 		return (0);
2712 
2713 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2714 	    sata_device.satadev_addr.cport)));
2715 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2716 		/* invalid address */
2717 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2718 		    sata_device.satadev_addr.cport)));
2719 		return (0);
2720 	}
2721 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2722 	    sata_device.satadev_addr.cport)));
2723 	if (level == RESET_ALL) {
2724 		/* port reset */
2725 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2726 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2727 		else
2728 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2729 
2730 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2731 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2732 			return (1);
2733 		else
2734 			return (0);
2735 
2736 	} else if (val == 0 &&
2737 	    (level == RESET_TARGET || level == RESET_LUN)) {
2738 		/* reset device (device attached) */
2739 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2740 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2741 			return (1);
2742 		else
2743 			return (0);
2744 	}
2745 	return (0);
2746 }
2747 
2748 
2749 /*
2750  * Implementation of scsi tran_getcap (get transport/device capabilities).
2751  * Supported capabilities for SATA hard disks:
2752  * auto-rqsense		(always supported)
2753  * tagged-qing		(supported if HBA supports it)
2754  * untagged-qing	(could be supported if disk supports it, but because
2755  *			 caching behavior allowing untagged queuing actually
2756  *			 results in reduced performance.  sd tries to throttle
2757  *			 back to only 3 outstanding commands, which may
2758  *			 work for real SCSI disks, but with read ahead
2759  *			 caching, having more than 1 outstanding command
2760  *			 results in cache thrashing.)
2761  * sector_size
2762  * dma_max
2763  * interconnect-type	(INTERCONNECT_SATA)
2764  *
2765  * Supported capabilities for ATAPI CD/DVD devices:
2766  * auto-rqsense		(always supported)
2767  * sector_size
2768  * dma_max
2769  * max-cdb-length
2770  * interconnect-type	(INTERCONNECT_SATA)
2771  *
2772  * Supported capabilities for ATAPI TAPE devices:
2773  * auto-rqsense		(always supported)
2774  * dma_max
2775  * max-cdb-length
2776  *
2777  * Supported capabilities for SATA ATAPI hard disks:
2778  * auto-rqsense		(always supported)
2779  * interconnect-type	(INTERCONNECT_SATA)
2780  * max-cdb-length
2781  *
2782  * Request for other capabilities is rejected as unsupported.
2783  *
2784  * Returns supported capability value, or -1 if capability is unsuppported or
2785  * the address is invalid - no device.
2786  */
2787 
2788 static int
2789 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2790 {
2791 
2792 	sata_hba_inst_t 	*sata_hba_inst =
2793 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2794 	sata_device_t		sata_device;
2795 	sata_drive_info_t	*sdinfo;
2796 	ddi_dma_attr_t		adj_dma_attr;
2797 	int 			rval;
2798 
2799 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2800 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2801 	    ap->a_target, cap);
2802 
2803 	/*
2804 	 * We want to process the capabilities on per port granularity.
2805 	 * So, we are specifically restricting ourselves to whom != 0
2806 	 * to exclude the controller wide handling.
2807 	 */
2808 	if (cap == NULL || whom == 0)
2809 		return (-1);
2810 
2811 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2812 		/* Invalid address */
2813 		return (-1);
2814 	}
2815 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2816 	    sata_device.satadev_addr.cport)));
2817 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2818 	    NULL) {
2819 		/* invalid address */
2820 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2821 		    sata_device.satadev_addr.cport)));
2822 		return (-1);
2823 	}
2824 
2825 	switch (scsi_hba_lookup_capstr(cap)) {
2826 	case SCSI_CAP_ARQ:
2827 		rval = 1;		/* ARQ supported, turned on */
2828 		break;
2829 
2830 	case SCSI_CAP_SECTOR_SIZE:
2831 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2832 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2833 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2834 			rval = SATA_ATAPI_SECTOR_SIZE;
2835 		else rval = -1;
2836 		break;
2837 
2838 	/*
2839 	 * untagged queuing cause a performance inversion because of
2840 	 * the way sd operates.  Because of this reason we do not
2841 	 * use it when available.
2842 	 */
2843 	case SCSI_CAP_UNTAGGED_QING:
2844 		if (sdinfo->satadrv_features_enabled &
2845 		    SATA_DEV_F_E_UNTAGGED_QING)
2846 			rval = 1;	/* Untagged queuing available */
2847 		else
2848 			rval = -1;	/* Untagged queuing not available */
2849 		break;
2850 
2851 	case SCSI_CAP_TAGGED_QING:
2852 		if ((sdinfo->satadrv_features_enabled &
2853 		    SATA_DEV_F_E_TAGGED_QING) &&
2854 		    (sdinfo->satadrv_max_queue_depth > 1))
2855 			rval = 1;	/* Tagged queuing available */
2856 		else
2857 			rval = -1;	/* Tagged queuing not available */
2858 		break;
2859 
2860 	case SCSI_CAP_DMA_MAX:
2861 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2862 		    &adj_dma_attr);
2863 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2864 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2865 		break;
2866 
2867 	case SCSI_CAP_INTERCONNECT_TYPE:
2868 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2869 		break;
2870 
2871 	case SCSI_CAP_CDB_LEN:
2872 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2873 			rval = sdinfo->satadrv_atapi_cdb_len;
2874 		else
2875 			rval = -1;
2876 		break;
2877 
2878 	default:
2879 		rval = -1;
2880 		break;
2881 	}
2882 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2883 	    sata_device.satadev_addr.cport)));
2884 	return (rval);
2885 }
2886 
2887 /*
2888  * Implementation of scsi tran_setcap
2889  *
2890  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2891  *
2892  */
2893 static int
2894 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2895 {
2896 	sata_hba_inst_t	*sata_hba_inst =
2897 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2898 	sata_device_t	sata_device;
2899 	sata_drive_info_t	*sdinfo;
2900 	int		rval;
2901 
2902 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2903 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2904 
2905 	/*
2906 	 * We want to process the capabilities on per port granularity.
2907 	 * So, we are specifically restricting ourselves to whom != 0
2908 	 * to exclude the controller wide handling.
2909 	 */
2910 	if (cap == NULL || whom == 0) {
2911 		return (-1);
2912 	}
2913 
2914 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2915 		/* Invalid address */
2916 		return (-1);
2917 	}
2918 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2919 	    sata_device.satadev_addr.cport)));
2920 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2921 	    &sata_device)) == NULL) {
2922 		/* invalid address */
2923 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2924 		    sata_device.satadev_addr.cport)));
2925 		return (-1);
2926 	}
2927 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2928 	    sata_device.satadev_addr.cport)));
2929 
2930 	switch (scsi_hba_lookup_capstr(cap)) {
2931 	case SCSI_CAP_ARQ:
2932 	case SCSI_CAP_SECTOR_SIZE:
2933 	case SCSI_CAP_DMA_MAX:
2934 	case SCSI_CAP_INTERCONNECT_TYPE:
2935 		rval = 0;
2936 		break;
2937 	case SCSI_CAP_UNTAGGED_QING:
2938 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2939 			rval = 1;
2940 			if (value == 1) {
2941 				sdinfo->satadrv_features_enabled |=
2942 				    SATA_DEV_F_E_UNTAGGED_QING;
2943 			} else if (value == 0) {
2944 				sdinfo->satadrv_features_enabled &=
2945 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2946 			} else {
2947 				rval = -1;
2948 			}
2949 		} else {
2950 			rval = 0;
2951 		}
2952 		break;
2953 	case SCSI_CAP_TAGGED_QING:
2954 		/* This can TCQ or NCQ */
2955 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2956 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2957 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2958 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2959 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2960 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2961 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2962 			rval = 1;
2963 			if (value == 1) {
2964 				sdinfo->satadrv_features_enabled |=
2965 				    SATA_DEV_F_E_TAGGED_QING;
2966 			} else if (value == 0) {
2967 				sdinfo->satadrv_features_enabled &=
2968 				    ~SATA_DEV_F_E_TAGGED_QING;
2969 			} else {
2970 				rval = -1;
2971 			}
2972 		} else {
2973 			rval = 0;
2974 		}
2975 		break;
2976 	default:
2977 		rval = -1;
2978 		break;
2979 	}
2980 	return (rval);
2981 }
2982 
2983 /*
2984  * Implementations of scsi tran_destroy_pkt.
2985  * Free resources allocated by sata_scsi_init_pkt()
2986  */
2987 static void
2988 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2989 {
2990 	sata_pkt_txlate_t *spx;
2991 
2992 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2993 
2994 	sata_common_free_dma_rsrcs(spx);
2995 
2996 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2997 	sata_pkt_free(spx);
2998 
2999 	scsi_hba_pkt_free(ap, pkt);
3000 }
3001 
3002 /*
3003  * Implementation of scsi tran_dmafree.
3004  * Free DMA resources allocated by sata_scsi_init_pkt()
3005  */
3006 
3007 static void
3008 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3009 {
3010 #ifndef __lock_lint
3011 	_NOTE(ARGUNUSED(ap))
3012 #endif
3013 	sata_pkt_txlate_t *spx;
3014 
3015 	ASSERT(pkt != NULL);
3016 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3017 
3018 	sata_common_free_dma_rsrcs(spx);
3019 }
3020 
3021 /*
3022  * Implementation of scsi tran_sync_pkt.
3023  *
3024  * The assumption below is that pkt is unique - there is no need to check ap
3025  *
3026  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3027  * into/from the real buffer.
3028  */
3029 static void
3030 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3031 {
3032 #ifndef __lock_lint
3033 	_NOTE(ARGUNUSED(ap))
3034 #endif
3035 	int rval;
3036 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3037 	struct buf *bp;
3038 	int direction;
3039 
3040 	ASSERT(spx != NULL);
3041 	if (spx->txlt_buf_dma_handle != NULL) {
3042 		direction = spx->txlt_sata_pkt->
3043 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3044 		if (spx->txlt_sata_pkt != NULL &&
3045 		    direction != SATA_DIR_NODATA_XFER) {
3046 			if (spx->txlt_tmp_buf != NULL) {
3047 				/* Intermediate DMA buffer used */
3048 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3049 
3050 				if (direction & SATA_DIR_WRITE) {
3051 					bcopy(bp->b_un.b_addr,
3052 					    spx->txlt_tmp_buf, bp->b_bcount);
3053 				}
3054 			}
3055 			/* Sync the buffer for device or for CPU */
3056 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3057 			    (direction & SATA_DIR_WRITE) ?
3058 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3059 			ASSERT(rval == DDI_SUCCESS);
3060 			if (spx->txlt_tmp_buf != NULL &&
3061 			    !(direction & SATA_DIR_WRITE)) {
3062 				/* Intermediate DMA buffer used for read */
3063 				bcopy(spx->txlt_tmp_buf,
3064 				    bp->b_un.b_addr, bp->b_bcount);
3065 			}
3066 
3067 		}
3068 	}
3069 }
3070 
3071 
3072 
3073 /* *******************  SATA - SCSI Translation functions **************** */
3074 /*
3075  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3076  * translation.
3077  */
3078 
3079 /*
3080  * Checks if a device exists and can be access and translates common
3081  * scsi_pkt data to sata_pkt data.
3082  *
3083  * Flag argument indicates that a non-read/write ATA command may be sent
3084  * to HBA in arbitrary SYNC mode to execute this packet.
3085  *
3086  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3087  * sata_pkt was set-up.
3088  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3089  * exist and pkt_comp callback was scheduled.
3090  * Returns other TRAN_XXXXX values when error occured and command should be
3091  * rejected with the returned TRAN_XXXXX value.
3092  *
3093  * This function should be called with port mutex held.
3094  */
3095 static int
3096 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3097 {
3098 	sata_drive_info_t *sdinfo;
3099 	sata_device_t sata_device;
3100 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3101 		SATA_DIR_NODATA_XFER,
3102 		/* all other values to 0/FALSE */
3103 	};
3104 	/*
3105 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3106 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3107 	 * indicates that the scsi packet was not accepted (the reason will not
3108 	 * be checked by the scsi target driver).
3109 	 * To make debugging easier, we set pkt_reason to know value here.
3110 	 * It may be changed later when different completion reason is
3111 	 * determined.
3112 	 */
3113 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3114 	*reason = CMD_TRAN_ERR;
3115 
3116 	/* Validate address */
3117 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3118 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3119 
3120 	case -1:
3121 		/* Invalid address or invalid device type */
3122 		return (TRAN_BADPKT);
3123 	case 2:
3124 		/*
3125 		 * Valid address but device type is unknown - Chack if it is
3126 		 * in the reset state and therefore in an indeterminate state.
3127 		 */
3128 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3129 		    &spx->txlt_sata_pkt->satapkt_device);
3130 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3131 		    (SATA_EVNT_DEVICE_RESET |
3132 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3133 			if (!ddi_in_panic()) {
3134 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3135 				*reason = CMD_INCOMPLETE;
3136 				SATADBG1(SATA_DBG_SCSI_IF,
3137 				    spx->txlt_sata_hba_inst,
3138 				    "sata_scsi_start: rejecting command "
3139 				    "because of device reset state\n", NULL);
3140 				return (TRAN_BUSY);
3141 			}
3142 		}
3143 		/* FALLTHROUGH */
3144 	case 1:
3145 		/* valid address but no valid device - it has disappeared */
3146 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3147 		*reason = CMD_DEV_GONE;
3148 		/*
3149 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3150 		 * only in callback function (for normal requests) and
3151 		 * in the dump code path.
3152 		 * So, if the callback is available, we need to do
3153 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3154 		 */
3155 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3156 			/* scsi callback required */
3157 			if (servicing_interrupt()) {
3158 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3159 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3160 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3161 				    NULL) {
3162 					return (TRAN_BUSY);
3163 				}
3164 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3165 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3166 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3167 				/* Scheduling the callback failed */
3168 				return (TRAN_BUSY);
3169 			}
3170 
3171 			return (TRAN_ACCEPT);
3172 		}
3173 		return (TRAN_FATAL_ERROR);
3174 	default:
3175 		/* all OK; pkt reason will be overwritten later */
3176 		break;
3177 	}
3178 	/*
3179 	 * If pkt is to be executed in polling mode and a command will not be
3180 	 * emulated in SATA module (requires sending a non-read/write ATA
3181 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3182 	 * interrupt context and not in the panic dump, then reject the packet
3183 	 * to avoid a possible interrupt stack overrun or hang caused by
3184 	 * a potentially blocked interrupt.
3185 	 */
3186 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3187 	    servicing_interrupt() && !ddi_in_panic()) {
3188 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3189 		    "sata_scsi_start: rejecting synchronous command because "
3190 		    "of interrupt context\n", NULL);
3191 		return (TRAN_BUSY);
3192 	}
3193 
3194 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3195 	    &spx->txlt_sata_pkt->satapkt_device);
3196 
3197 	/*
3198 	 * If device is in reset condition, reject the packet with
3199 	 * TRAN_BUSY, unless:
3200 	 * 1. system is panicking (dumping)
3201 	 * In such case only one thread is running and there is no way to
3202 	 * process reset.
3203 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3204 	 * Some cfgadm operations involve drive commands, so reset condition
3205 	 * needs to be ignored for IOCTL operations.
3206 	 */
3207 	if ((sdinfo->satadrv_event_flags &
3208 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3209 
3210 		if (!ddi_in_panic() &&
3211 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3212 		    sata_device.satadev_addr.cport) &
3213 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3214 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3215 			*reason = CMD_INCOMPLETE;
3216 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3217 			    "sata_scsi_start: rejecting command because "
3218 			    "of device reset state\n", NULL);
3219 			return (TRAN_BUSY);
3220 		}
3221 	}
3222 
3223 	/*
3224 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3225 	 * sata_scsi_pkt_init() because pkt init had to work also with
3226 	 * non-existing devices.
3227 	 * Now we know that the packet was set-up for a real device, so its
3228 	 * type is known.
3229 	 */
3230 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3231 
3232 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3233 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3234 	    sata_device.satadev_addr.cport)->cport_event_flags &
3235 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3236 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3237 		    sata_ignore_dev_reset = B_TRUE;
3238 	}
3239 	/*
3240 	 * At this point the generic translation routine determined that the
3241 	 * scsi packet should be accepted. Packet completion reason may be
3242 	 * changed later when a different completion reason is determined.
3243 	 */
3244 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3245 	*reason = CMD_CMPLT;
3246 
3247 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3248 		/* Synchronous execution */
3249 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3250 		    SATA_OPMODE_POLLING;
3251 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3252 		    sata_ignore_dev_reset = ddi_in_panic();
3253 	} else {
3254 		/* Asynchronous execution */
3255 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3256 		    SATA_OPMODE_INTERRUPTS;
3257 	}
3258 	/* Convert queuing information */
3259 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3260 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3261 		    B_TRUE;
3262 	else if (spx->txlt_scsi_pkt->pkt_flags &
3263 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3264 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3265 		    B_TRUE;
3266 
3267 	/* Always limit pkt time */
3268 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3269 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3270 	else
3271 		/* Pass on scsi_pkt time */
3272 		spx->txlt_sata_pkt->satapkt_time =
3273 		    spx->txlt_scsi_pkt->pkt_time;
3274 
3275 	return (TRAN_ACCEPT);
3276 }
3277 
3278 
3279 /*
3280  * Translate ATA Identify Device data to SCSI Inquiry data.
3281  * This function may be called only for ATA devices.
3282  * This function should not be called for ATAPI devices - they
3283  * respond directly to SCSI Inquiry command.
3284  *
3285  * SATA Identify Device data has to be valid in sata_drive_info.
3286  * Buffer has to accomodate the inquiry length (36 bytes).
3287  *
3288  * This function should be called with a port mutex held.
3289  */
3290 static	void
3291 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3292     sata_drive_info_t *sdinfo, uint8_t *buf)
3293 {
3294 
3295 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3296 	struct sata_id *sid = &sdinfo->satadrv_id;
3297 
3298 	/* Start with a nice clean slate */
3299 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3300 
3301 	/*
3302 	 * Rely on the dev_type for setting paripheral qualifier.
3303 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3304 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3305 	 * ATAPI Inquiry may provide more data to the target driver.
3306 	 */
3307 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3308 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3309 
3310 	/* CFA type device is not a removable media device */
3311 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3312 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3313 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3314 	inq->inq_iso = 0;	/* ISO version */
3315 	inq->inq_ecma = 0;	/* ECMA version */
3316 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3317 	inq->inq_aenc = 0;	/* Async event notification cap. */
3318 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3319 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3320 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3321 	inq->inq_len = 31;	/* Additional length */
3322 	inq->inq_dualp = 0;	/* dual port device - NO */
3323 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3324 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3325 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3326 				/*
3327 				 * Queuing support - controller has to
3328 				 * support some sort of command queuing.
3329 				 */
3330 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3331 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3332 	else
3333 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3334 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3335 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3336 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3337 
3338 #ifdef	_LITTLE_ENDIAN
3339 	/* Swap text fields to match SCSI format */
3340 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3341 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3342 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3343 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3344 	else
3345 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3346 #else	/* _LITTLE_ENDIAN */
3347 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3348 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3349 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3350 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3351 	else
3352 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3353 #endif	/* _LITTLE_ENDIAN */
3354 }
3355 
3356 
3357 /*
3358  * Scsi response set up for invalid command (command not supported)
3359  *
3360  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3361  */
3362 static int
3363 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3364 {
3365 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3366 	struct scsi_extended_sense *sense;
3367 
3368 	scsipkt->pkt_reason = CMD_CMPLT;
3369 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3370 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3371 
3372 	*scsipkt->pkt_scbp = STATUS_CHECK;
3373 
3374 	sense = sata_arq_sense(spx);
3375 	sense->es_key = KEY_ILLEGAL_REQUEST;
3376 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3377 
3378 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3379 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3380 
3381 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3382 	    scsipkt->pkt_comp != NULL) {
3383 		/* scsi callback required */
3384 		if (servicing_interrupt()) {
3385 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3386 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3387 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3388 				return (TRAN_BUSY);
3389 			}
3390 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3391 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3392 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3393 			/* Scheduling the callback failed */
3394 			return (TRAN_BUSY);
3395 		}
3396 	}
3397 	return (TRAN_ACCEPT);
3398 }
3399 
3400 /*
3401  * Scsi response set up for check condition with special sense key
3402  * and additional sense code.
3403  *
3404  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3405  */
3406 static int
3407 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3408 {
3409 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3410 	int cport = SATA_TXLT_CPORT(spx);
3411 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3412 	struct scsi_extended_sense *sense;
3413 
3414 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3415 	scsipkt->pkt_reason = CMD_CMPLT;
3416 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3417 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3418 
3419 	*scsipkt->pkt_scbp = STATUS_CHECK;
3420 
3421 	sense = sata_arq_sense(spx);
3422 	sense->es_key = key;
3423 	sense->es_add_code = code;
3424 
3425 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3426 
3427 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3428 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3429 
3430 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3431 	    scsipkt->pkt_comp != NULL) {
3432 		/* scsi callback required */
3433 		if (servicing_interrupt()) {
3434 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3435 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3436 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3437 				return (TRAN_BUSY);
3438 			}
3439 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3440 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3441 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3442 			/* Scheduling the callback failed */
3443 			return (TRAN_BUSY);
3444 		}
3445 	}
3446 	return (TRAN_ACCEPT);
3447 }
3448 
3449 /*
3450  * Scsi response setup for
3451  * emulated non-data command that requires no action/return data
3452  *
3453  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3454  */
3455 static	int
3456 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3457 {
3458 	int rval;
3459 	int reason;
3460 
3461 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3462 
3463 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3464 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3465 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3466 		return (rval);
3467 	}
3468 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3469 
3470 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3471 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3472 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3473 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3474 
3475 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3476 	    "Scsi_pkt completion reason %x\n",
3477 	    spx->txlt_scsi_pkt->pkt_reason);
3478 
3479 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3480 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3481 		/* scsi callback required */
3482 		if (servicing_interrupt()) {
3483 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3484 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3485 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3486 				return (TRAN_BUSY);
3487 			}
3488 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3489 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3490 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3491 			/* Scheduling the callback failed */
3492 			return (TRAN_BUSY);
3493 		}
3494 	}
3495 	return (TRAN_ACCEPT);
3496 }
3497 
3498 
3499 /*
3500  * SATA translate command: Inquiry / Identify Device
3501  * Use cached Identify Device data for now, rather than issuing actual
3502  * Device Identify cmd request. If device is detached and re-attached,
3503  * asynchronous event processing should fetch and refresh Identify Device
3504  * data.
3505  * Two VPD pages are supported now:
3506  * Vital Product Data page
3507  * Unit Serial Number page
3508  *
3509  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3510  */
3511 
3512 #define	EVPD			1	/* Extended Vital Product Data flag */
3513 #define	CMDDT			2	/* Command Support Data - Obsolete */
3514 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3515 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3516 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3517 
3518 static int
3519 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3520 {
3521 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3522 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3523 	sata_drive_info_t *sdinfo;
3524 	struct scsi_extended_sense *sense;
3525 	int count;
3526 	uint8_t *p;
3527 	int i, j;
3528 	uint8_t page_buf[0xff]; /* Max length */
3529 	int rval, reason;
3530 
3531 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3532 
3533 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3534 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3535 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3536 		return (rval);
3537 	}
3538 
3539 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3540 	    &spx->txlt_sata_pkt->satapkt_device);
3541 
3542 	ASSERT(sdinfo != NULL);
3543 
3544 	scsipkt->pkt_reason = CMD_CMPLT;
3545 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3546 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3547 
3548 	/* Reject not supported request */
3549 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3550 		*scsipkt->pkt_scbp = STATUS_CHECK;
3551 		sense = sata_arq_sense(spx);
3552 		sense->es_key = KEY_ILLEGAL_REQUEST;
3553 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3554 		goto done;
3555 	}
3556 
3557 	/* Valid Inquiry request */
3558 	*scsipkt->pkt_scbp = STATUS_GOOD;
3559 
3560 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3561 
3562 		/*
3563 		 * Because it is fully emulated command storing data
3564 		 * programatically in the specified buffer, release
3565 		 * preallocated DMA resources before storing data in the buffer,
3566 		 * so no unwanted DMA sync would take place.
3567 		 */
3568 		sata_scsi_dmafree(NULL, scsipkt);
3569 
3570 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3571 			/* Standard Inquiry Data request */
3572 			struct scsi_inquiry inq;
3573 			unsigned int bufsize;
3574 
3575 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3576 			    sdinfo, (uint8_t *)&inq);
3577 			/* Copy no more than requested */
3578 			count = MIN(bp->b_bcount,
3579 			    sizeof (struct scsi_inquiry));
3580 			bufsize = scsipkt->pkt_cdbp[4];
3581 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3582 			count = MIN(count, bufsize);
3583 			bcopy(&inq, bp->b_un.b_addr, count);
3584 
3585 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3586 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3587 			    bufsize - count : 0;
3588 		} else {
3589 			/*
3590 			 * peripheral_qualifier = 0;
3591 			 *
3592 			 * We are dealing only with HD and will be
3593 			 * dealing with CD/DVD devices soon
3594 			 */
3595 			uint8_t peripheral_device_type =
3596 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3597 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3598 
3599 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3600 			case INQUIRY_SUP_VPD_PAGE:
3601 				/*
3602 				 * Request for suported Vital Product Data
3603 				 * pages - assuming only 2 page codes
3604 				 * supported.
3605 				 */
3606 				page_buf[0] = peripheral_device_type;
3607 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3608 				page_buf[2] = 0;
3609 				page_buf[3] = 2; /* page length */
3610 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3611 				page_buf[5] = INQUIRY_USN_PAGE;
3612 				/* Copy no more than requested */
3613 				count = MIN(bp->b_bcount, 6);
3614 				bcopy(page_buf, bp->b_un.b_addr, count);
3615 				break;
3616 
3617 			case INQUIRY_USN_PAGE:
3618 				/*
3619 				 * Request for Unit Serial Number page.
3620 				 * Set-up the page.
3621 				 */
3622 				page_buf[0] = peripheral_device_type;
3623 				page_buf[1] = INQUIRY_USN_PAGE;
3624 				page_buf[2] = 0;
3625 				/* remaining page length */
3626 				page_buf[3] = SATA_ID_SERIAL_LEN;
3627 
3628 				/*
3629 				 * Copy serial number from Identify Device data
3630 				 * words into the inquiry page and swap bytes
3631 				 * when necessary.
3632 				 */
3633 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3634 #ifdef	_LITTLE_ENDIAN
3635 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3636 #else
3637 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3638 #endif
3639 				/*
3640 				 * Least significant character of the serial
3641 				 * number shall appear as the last byte,
3642 				 * according to SBC-3 spec.
3643 				 * Count trailing spaces to determine the
3644 				 * necessary shift length.
3645 				 */
3646 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3647 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3648 					if (*(p - j) != '\0' &&
3649 					    *(p - j) != '\040')
3650 						break;
3651 				}
3652 
3653 				/*
3654 				 * Shift SN string right, so that the last
3655 				 * non-blank character would appear in last
3656 				 * byte of SN field in the page.
3657 				 * 'j' is the shift length.
3658 				 */
3659 				for (i = 0;
3660 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3661 				    i++, p--)
3662 					*p = *(p - j);
3663 
3664 				/*
3665 				 * Add leading spaces - same number as the
3666 				 * shift size
3667 				 */
3668 				for (; j > 0; j--)
3669 					page_buf[4 + j - 1] = '\040';
3670 
3671 				count = MIN(bp->b_bcount,
3672 				    SATA_ID_SERIAL_LEN + 4);
3673 				bcopy(page_buf, bp->b_un.b_addr, count);
3674 				break;
3675 
3676 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3677 				/*
3678 				 * We may want to implement this page, when
3679 				 * identifiers are common for SATA devices
3680 				 * But not now.
3681 				 */
3682 				/*FALLTHROUGH*/
3683 
3684 			default:
3685 				/* Request for unsupported VPD page */
3686 				*scsipkt->pkt_scbp = STATUS_CHECK;
3687 				sense = sata_arq_sense(spx);
3688 				sense->es_key = KEY_ILLEGAL_REQUEST;
3689 				sense->es_add_code =
3690 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3691 				goto done;
3692 			}
3693 		}
3694 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3695 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3696 		    scsipkt->pkt_cdbp[4] - count : 0;
3697 	}
3698 done:
3699 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3700 
3701 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3702 	    "Scsi_pkt completion reason %x\n",
3703 	    scsipkt->pkt_reason);
3704 
3705 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3706 	    scsipkt->pkt_comp != NULL) {
3707 		/* scsi callback required */
3708 		if (servicing_interrupt()) {
3709 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3710 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3711 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3712 				return (TRAN_BUSY);
3713 			}
3714 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3715 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3716 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3717 			/* Scheduling the callback failed */
3718 			return (TRAN_BUSY);
3719 		}
3720 	}
3721 	return (TRAN_ACCEPT);
3722 }
3723 
3724 /*
3725  * SATA translate command: Request Sense.
3726  *
3727  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3728  * At the moment this is an emulated command (ATA version for SATA hard disks).
3729  * May be translated into Check Power Mode command in the future.
3730  *
3731  * Note: There is a mismatch between already implemented Informational
3732  * Exception Mode Select page 0x1C and this function.
3733  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3734  * NO SENSE and set additional sense code to the exception code - this is not
3735  * implemented here.
3736  */
3737 static int
3738 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3739 {
3740 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3741 	struct scsi_extended_sense sense;
3742 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3743 	sata_drive_info_t *sdinfo;
3744 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3745 	int rval, reason, power_state = 0;
3746 
3747 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3748 
3749 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3750 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3751 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3752 		return (rval);
3753 	}
3754 
3755 	scsipkt->pkt_reason = CMD_CMPLT;
3756 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3757 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3758 	*scsipkt->pkt_scbp = STATUS_GOOD;
3759 
3760 	/*
3761 	 * when CONTROL field's NACA bit == 1
3762 	 * return ILLEGAL_REQUEST
3763 	 */
3764 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3765 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3766 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3767 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3768 	}
3769 
3770 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3771 	    &spx->txlt_sata_pkt->satapkt_device);
3772 	ASSERT(sdinfo != NULL);
3773 
3774 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3775 
3776 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3777 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3778 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3779 	if (sata_hba_start(spx, &rval) != 0) {
3780 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3781 		return (rval);
3782 	} else {
3783 		if (scmd->satacmd_error_reg != 0) {
3784 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3785 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3786 			    SD_SCSI_ASC_NO_ADD_SENSE));
3787 		}
3788 	}
3789 
3790 	switch (scmd->satacmd_sec_count_lsb) {
3791 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3792 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3793 			power_state = SATA_POWER_STOPPED;
3794 		else {
3795 			power_state = SATA_POWER_STANDBY;
3796 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3797 		}
3798 		break;
3799 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3800 		power_state = SATA_POWER_IDLE;
3801 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3802 		break;
3803 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3804 	default:		  /* 0x40, 0x41 active mode */
3805 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3806 			power_state = SATA_POWER_IDLE;
3807 		else {
3808 			power_state = SATA_POWER_ACTIVE;
3809 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3810 		}
3811 		break;
3812 	}
3813 
3814 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3815 
3816 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3817 		/*
3818 		 * Because it is fully emulated command storing data
3819 		 * programatically in the specified buffer, release
3820 		 * preallocated DMA resources before storing data in the buffer,
3821 		 * so no unwanted DMA sync would take place.
3822 		 */
3823 		int count = MIN(bp->b_bcount,
3824 		    sizeof (struct scsi_extended_sense));
3825 		sata_scsi_dmafree(NULL, scsipkt);
3826 		bzero(&sense, sizeof (struct scsi_extended_sense));
3827 		sense.es_valid = 0;	/* Valid LBA */
3828 		sense.es_class = 7;	/* Response code 0x70 - current err */
3829 		sense.es_key = KEY_NO_SENSE;
3830 		sense.es_add_len = 6;	/* Additional length */
3831 		/* Copy no more than requested */
3832 		bcopy(&sense, bp->b_un.b_addr, count);
3833 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3834 		scsipkt->pkt_resid = 0;
3835 		switch (power_state) {
3836 		case SATA_POWER_IDLE:
3837 		case SATA_POWER_STANDBY:
3838 			sense.es_add_code =
3839 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3840 			break;
3841 		case SATA_POWER_STOPPED:
3842 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3843 			break;
3844 		case SATA_POWER_ACTIVE:
3845 		default:
3846 			break;
3847 		}
3848 	}
3849 
3850 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3851 	    "Scsi_pkt completion reason %x\n",
3852 	    scsipkt->pkt_reason);
3853 
3854 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3855 	    scsipkt->pkt_comp != NULL) {
3856 		/* scsi callback required */
3857 		if (servicing_interrupt()) {
3858 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3859 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3860 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3861 				return (TRAN_BUSY);
3862 			}
3863 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3864 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3865 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3866 			/* Scheduling the callback failed */
3867 			return (TRAN_BUSY);
3868 		}
3869 	}
3870 	return (TRAN_ACCEPT);
3871 }
3872 
3873 /*
3874  * SATA translate command: Test Unit Ready
3875  * (ATA version for SATA hard disks).
3876  * It is translated into the Check Power Mode command.
3877  *
3878  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3879  */
3880 static int
3881 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3882 {
3883 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3884 	struct scsi_extended_sense *sense;
3885 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3886 	sata_drive_info_t *sdinfo;
3887 	int power_state;
3888 	int rval, reason;
3889 
3890 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3891 
3892 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3893 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3894 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3895 		return (rval);
3896 	}
3897 
3898 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3899 	    &spx->txlt_sata_pkt->satapkt_device);
3900 	ASSERT(sdinfo != NULL);
3901 
3902 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3903 
3904 	/* send CHECK POWER MODE command */
3905 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3906 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3907 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3908 	if (sata_hba_start(spx, &rval) != 0) {
3909 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3910 		return (rval);
3911 	} else {
3912 		if (scmd->satacmd_error_reg != 0) {
3913 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3914 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3915 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3916 		}
3917 	}
3918 
3919 	power_state = scmd->satacmd_sec_count_lsb;
3920 
3921 	/*
3922 	 * return NOT READY when device in STOPPED mode
3923 	 */
3924 	if (power_state == SATA_PWRMODE_STANDBY &&
3925 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3926 		*scsipkt->pkt_scbp = STATUS_CHECK;
3927 		sense = sata_arq_sense(spx);
3928 		sense->es_key = KEY_NOT_READY;
3929 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3930 	} else {
3931 		/*
3932 		 * For other power mode, return GOOD status
3933 		 */
3934 		*scsipkt->pkt_scbp = STATUS_GOOD;
3935 	}
3936 
3937 	scsipkt->pkt_reason = CMD_CMPLT;
3938 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3939 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3940 
3941 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3942 
3943 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3944 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3945 
3946 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3947 	    scsipkt->pkt_comp != NULL) {
3948 		/* scsi callback required */
3949 		if (servicing_interrupt()) {
3950 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3951 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3952 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3953 				return (TRAN_BUSY);
3954 			}
3955 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3956 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3957 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3958 			/* Scheduling the callback failed */
3959 			return (TRAN_BUSY);
3960 		}
3961 	}
3962 
3963 	return (TRAN_ACCEPT);
3964 }
3965 
3966 /*
3967  * SATA translate command: Start Stop Unit
3968  * Translation depends on a command:
3969  *
3970  * Power condition bits will be supported
3971  * and the power level should be maintained by SATL,
3972  * When SATL received a command, it will check the
3973  * power level firstly, and return the status according
3974  * to SAT2 v2.6 and SAT-2 Standby Modifications
3975  *
3976  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3977  * -----------------------------------------------------------------------
3978  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3979  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3980  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3981  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3982  *
3983  *	Unload Media / NOT SUPPORTED YET
3984  *	Load Media / NOT SUPPROTED YET
3985  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3986  *
3987  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3988  * appropriate values in scsi_pkt fields.
3989  */
3990 static int
3991 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3992 {
3993 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3994 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3995 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3996 	int cport = SATA_TXLT_CPORT(spx);
3997 	int rval, reason;
3998 	sata_drive_info_t *sdinfo;
3999 	sata_id_t *sata_id;
4000 
4001 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4002 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4003 
4004 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
4005 
4006 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4007 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4008 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4009 		return (rval);
4010 	}
4011 
4012 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4013 		/* IMMED bit - not supported */
4014 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4015 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4016 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4017 	}
4018 
4019 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4020 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4021 
4022 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4023 	    &spx->txlt_sata_pkt->satapkt_device);
4024 	ASSERT(sdinfo != NULL);
4025 	sata_id = &sdinfo->satadrv_id;
4026 
4027 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4028 	case 0:
4029 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4030 			/* Load/Unload Media - invalid request */
4031 			goto err_out;
4032 		}
4033 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4034 			/* Start Unit */
4035 			sata_build_read_verify_cmd(scmd, 1, 5);
4036 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4037 			/* Transfer command to HBA */
4038 			if (sata_hba_start(spx, &rval) != 0) {
4039 				/* Pkt not accepted for execution */
4040 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4041 				return (rval);
4042 			} else {
4043 				if (scmd->satacmd_error_reg != 0) {
4044 					goto err_out;
4045 				}
4046 			}
4047 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4048 		} else {
4049 			/* Stop Unit */
4050 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4051 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4052 			if (sata_hba_start(spx, &rval) != 0) {
4053 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4054 				return (rval);
4055 			} else {
4056 				if (scmd->satacmd_error_reg != 0) {
4057 					goto err_out;
4058 				}
4059 			}
4060 			/* ata standby immediate command */
4061 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4062 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4063 			if (sata_hba_start(spx, &rval) != 0) {
4064 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4065 				return (rval);
4066 			} else {
4067 				if (scmd->satacmd_error_reg != 0) {
4068 					goto err_out;
4069 				}
4070 			}
4071 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4072 		}
4073 		break;
4074 	case 0x1:
4075 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4076 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4077 		if (sata_hba_start(spx, &rval) != 0) {
4078 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4079 			return (rval);
4080 		} else {
4081 			if (scmd->satacmd_error_reg != 0) {
4082 				goto err_out;
4083 			}
4084 		}
4085 		sata_build_read_verify_cmd(scmd, 1, 5);
4086 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4087 		/* Transfer command to HBA */
4088 		if (sata_hba_start(spx, &rval) != 0) {
4089 			/* Pkt not accepted for execution */
4090 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4091 			return (rval);
4092 		} else {
4093 			if (scmd->satacmd_error_reg != 0) {
4094 				goto err_out;
4095 			}
4096 		}
4097 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4098 		break;
4099 	case 0x2:
4100 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4101 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4102 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4103 			if (sata_hba_start(spx, &rval) != 0) {
4104 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4105 				return (rval);
4106 			} else {
4107 				if (scmd->satacmd_error_reg != 0) {
4108 					goto err_out;
4109 				}
4110 			}
4111 		}
4112 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4113 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4114 		if (sata_hba_start(spx, &rval) != 0) {
4115 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4116 			return (rval);
4117 		} else {
4118 			if (scmd->satacmd_error_reg != 0) {
4119 				goto err_out;
4120 			}
4121 		}
4122 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4123 			/*
4124 			 *  POWER CONDITION MODIFIER bit set
4125 			 *  to 0x1 or larger it will be handled
4126 			 *  on the same way as bit = 0x1
4127 			 */
4128 			if (!(sata_id->ai_cmdset84 &
4129 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4130 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4131 				break;
4132 			}
4133 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4134 			scmd->satacmd_features_reg = 0x44;
4135 			scmd->satacmd_lba_low_lsb = 0x4c;
4136 			scmd->satacmd_lba_mid_lsb = 0x4e;
4137 			scmd->satacmd_lba_high_lsb = 0x55;
4138 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4139 			if (sata_hba_start(spx, &rval) != 0) {
4140 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4141 				return (rval);
4142 			} else {
4143 				if (scmd->satacmd_error_reg != 0) {
4144 					goto err_out;
4145 				}
4146 			}
4147 		}
4148 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4149 		break;
4150 	case 0x3:
4151 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4152 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4153 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
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 		}
4163 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4164 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4165 		if (sata_hba_start(spx, &rval) != 0) {
4166 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4167 			return (rval);
4168 		} else {
4169 			if (scmd->satacmd_error_reg != 0) {
4170 				goto err_out;
4171 			}
4172 		}
4173 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4174 		break;
4175 	case 0x7:
4176 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4177 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4178 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4179 		if (sata_hba_start(spx, &rval) != 0) {
4180 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4181 			return (rval);
4182 		} else {
4183 			if (scmd->satacmd_error_reg != 0) {
4184 				goto err_out;
4185 			}
4186 		}
4187 		switch (scmd->satacmd_sec_count_lsb) {
4188 		case SATA_PWRMODE_STANDBY:
4189 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4190 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4191 			    sdinfo->satadrv_standby_timer);
4192 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4193 			if (sata_hba_start(spx, &rval) != 0) {
4194 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4195 				return (rval);
4196 			} else {
4197 				if (scmd->satacmd_error_reg != 0) {
4198 					goto err_out;
4199 				}
4200 			}
4201 			break;
4202 		case SATA_PWRMODE_IDLE:
4203 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4204 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4205 			    sdinfo->satadrv_standby_timer);
4206 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4207 			if (sata_hba_start(spx, &rval) != 0) {
4208 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4209 				return (rval);
4210 			} else {
4211 				if (scmd->satacmd_error_reg != 0) {
4212 					goto err_out;
4213 				}
4214 			}
4215 			break;
4216 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4217 		case SATA_PWRMODE_ACTIVE_SPINUP:
4218 		case SATA_PWRMODE_ACTIVE:
4219 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4220 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4221 			    sdinfo->satadrv_standby_timer);
4222 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4223 			if (sata_hba_start(spx, &rval) != 0) {
4224 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4225 				return (rval);
4226 			} else {
4227 				if (scmd->satacmd_error_reg != 0) {
4228 					goto err_out;
4229 				}
4230 			}
4231 			sata_build_read_verify_cmd(scmd, 1, 5);
4232 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4233 			if (sata_hba_start(spx, &rval) != 0) {
4234 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4235 				return (rval);
4236 			} else {
4237 				if (scmd->satacmd_error_reg != 0) {
4238 					goto err_out;
4239 				}
4240 			}
4241 			break;
4242 		default:
4243 			goto err_out;
4244 		}
4245 		break;
4246 	case 0xb:
4247 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4248 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4249 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4250 			return (sata_txlt_check_condition(spx,
4251 			    KEY_ILLEGAL_REQUEST,
4252 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4253 		}
4254 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4255 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4256 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4257 			if (sata_hba_start(spx, &rval) != 0) {
4258 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4259 				return (rval);
4260 			} else {
4261 				if (scmd->satacmd_error_reg != 0) {
4262 					goto err_out;
4263 				}
4264 			}
4265 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4266 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4267 			if (sata_hba_start(spx, &rval) != 0) {
4268 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4269 				return (rval);
4270 			} else {
4271 				if (scmd->satacmd_error_reg != 0) {
4272 					goto err_out;
4273 				}
4274 			}
4275 		}
4276 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4277 		break;
4278 	default:
4279 err_out:
4280 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4281 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4282 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4283 	}
4284 
4285 	/*
4286 	 * Since it was a synchronous command,
4287 	 * a callback function will be called directly.
4288 	 */
4289 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4290 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4291 	    "synchronous execution status %x\n",
4292 	    spx->txlt_sata_pkt->satapkt_reason);
4293 
4294 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4295 	    scsipkt->pkt_comp != NULL) {
4296 		sata_set_arq_data(spx->txlt_sata_pkt);
4297 		if (servicing_interrupt()) {
4298 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4299 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4300 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4301 				return (TRAN_BUSY);
4302 			}
4303 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4304 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4305 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4306 			/* Scheduling the callback failed */
4307 			return (TRAN_BUSY);
4308 		}
4309 	}
4310 	else
4311 
4312 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4313 
4314 	return (TRAN_ACCEPT);
4315 
4316 }
4317 
4318 /*
4319  * SATA translate command:  Read Capacity.
4320  * Emulated command for SATA disks.
4321  * Capacity is retrieved from cached Idenifty Device data.
4322  * Identify Device data shows effective disk capacity, not the native
4323  * capacity, which may be limitted by Set Max Address command.
4324  * This is ATA version for SATA hard disks.
4325  *
4326  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4327  */
4328 static int
4329 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4330 {
4331 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4332 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4333 	sata_drive_info_t *sdinfo;
4334 	uint64_t val;
4335 	uchar_t *rbuf;
4336 	int rval, reason;
4337 
4338 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4339 	    "sata_txlt_read_capacity: ", NULL);
4340 
4341 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4342 
4343 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4344 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4345 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4346 		return (rval);
4347 	}
4348 
4349 	scsipkt->pkt_reason = CMD_CMPLT;
4350 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4351 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4352 	*scsipkt->pkt_scbp = STATUS_GOOD;
4353 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4354 		/*
4355 		 * Because it is fully emulated command storing data
4356 		 * programatically in the specified buffer, release
4357 		 * preallocated DMA resources before storing data in the buffer,
4358 		 * so no unwanted DMA sync would take place.
4359 		 */
4360 		sata_scsi_dmafree(NULL, scsipkt);
4361 
4362 		sdinfo = sata_get_device_info(
4363 		    spx->txlt_sata_hba_inst,
4364 		    &spx->txlt_sata_pkt->satapkt_device);
4365 		/* Last logical block address */
4366 		val = sdinfo->satadrv_capacity - 1;
4367 		rbuf = (uchar_t *)bp->b_un.b_addr;
4368 		/* Need to swap endians to match scsi format */
4369 		rbuf[0] = (val >> 24) & 0xff;
4370 		rbuf[1] = (val >> 16) & 0xff;
4371 		rbuf[2] = (val >> 8) & 0xff;
4372 		rbuf[3] = val & 0xff;
4373 		/* block size - always 512 bytes, for now */
4374 		rbuf[4] = 0;
4375 		rbuf[5] = 0;
4376 		rbuf[6] = 0x02;
4377 		rbuf[7] = 0;
4378 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4379 		scsipkt->pkt_resid = 0;
4380 
4381 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4382 		    sdinfo->satadrv_capacity -1);
4383 	}
4384 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4385 	/*
4386 	 * If a callback was requested, do it now.
4387 	 */
4388 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4389 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4390 
4391 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4392 	    scsipkt->pkt_comp != NULL) {
4393 		/* scsi callback required */
4394 		if (servicing_interrupt()) {
4395 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4396 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4397 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4398 				return (TRAN_BUSY);
4399 			}
4400 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4401 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4402 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4403 			/* Scheduling the callback failed */
4404 			return (TRAN_BUSY);
4405 		}
4406 	}
4407 
4408 	return (TRAN_ACCEPT);
4409 }
4410 
4411 /*
4412  * SATA translate command: Mode Sense.
4413  * Translated into appropriate SATA command or emulated.
4414  * Saved Values Page Control (03) are not supported.
4415  *
4416  * NOTE: only caching mode sense page is currently implemented.
4417  *
4418  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4419  */
4420 
4421 #define	LLBAA	0x10	/* Long LBA Accepted */
4422 
4423 static int
4424 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4425 {
4426 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4427 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4428 	sata_drive_info_t *sdinfo;
4429 	sata_id_t *sata_id;
4430 	struct scsi_extended_sense *sense;
4431 	int 		len, bdlen, count, alc_len;
4432 	int		pc;	/* Page Control code */
4433 	uint8_t		*buf;	/* mode sense buffer */
4434 	int		rval, reason;
4435 
4436 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4437 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4438 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4439 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4440 
4441 	if (servicing_interrupt()) {
4442 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4443 		if (buf == NULL) {
4444 			return (TRAN_BUSY);
4445 		}
4446 	} else {
4447 		buf = kmem_zalloc(1024, KM_SLEEP);
4448 	}
4449 
4450 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4451 
4452 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4453 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4454 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4455 		kmem_free(buf, 1024);
4456 		return (rval);
4457 	}
4458 
4459 	scsipkt->pkt_reason = CMD_CMPLT;
4460 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4461 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4462 
4463 	pc = scsipkt->pkt_cdbp[2] >> 6;
4464 
4465 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4466 		/*
4467 		 * Because it is fully emulated command storing data
4468 		 * programatically in the specified buffer, release
4469 		 * preallocated DMA resources before storing data in the buffer,
4470 		 * so no unwanted DMA sync would take place.
4471 		 */
4472 		sata_scsi_dmafree(NULL, scsipkt);
4473 
4474 		len = 0;
4475 		bdlen = 0;
4476 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4477 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4478 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4479 				bdlen = 16;
4480 			else
4481 				bdlen = 8;
4482 		}
4483 		/* Build mode parameter header */
4484 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4485 			/* 4-byte mode parameter header */
4486 			buf[len++] = 0;		/* mode data length */
4487 			buf[len++] = 0;		/* medium type */
4488 			buf[len++] = 0;		/* dev-specific param */
4489 			buf[len++] = bdlen;	/* Block Descriptor length */
4490 		} else {
4491 			/* 8-byte mode parameter header */
4492 			buf[len++] = 0;		/* mode data length */
4493 			buf[len++] = 0;
4494 			buf[len++] = 0;		/* medium type */
4495 			buf[len++] = 0;		/* dev-specific param */
4496 			if (bdlen == 16)
4497 				buf[len++] = 1;	/* long lba descriptor */
4498 			else
4499 				buf[len++] = 0;
4500 			buf[len++] = 0;
4501 			buf[len++] = 0;		/* Block Descriptor length */
4502 			buf[len++] = bdlen;
4503 		}
4504 
4505 		sdinfo = sata_get_device_info(
4506 		    spx->txlt_sata_hba_inst,
4507 		    &spx->txlt_sata_pkt->satapkt_device);
4508 
4509 		/* Build block descriptor only if not disabled (DBD) */
4510 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4511 			/* Block descriptor - direct-access device format */
4512 			if (bdlen == 8) {
4513 				/* build regular block descriptor */
4514 				buf[len++] =
4515 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4516 				buf[len++] =
4517 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4518 				buf[len++] =
4519 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4520 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4521 				buf[len++] = 0; /* density code */
4522 				buf[len++] = 0;
4523 				if (sdinfo->satadrv_type ==
4524 				    SATA_DTYPE_ATADISK)
4525 					buf[len++] = 2;
4526 				else
4527 					/* ATAPI */
4528 					buf[len++] = 8;
4529 				buf[len++] = 0;
4530 			} else if (bdlen == 16) {
4531 				/* Long LBA Accepted */
4532 				/* build long lba block descriptor */
4533 #ifndef __lock_lint
4534 				buf[len++] =
4535 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4536 				buf[len++] =
4537 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4538 				buf[len++] =
4539 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4540 				buf[len++] =
4541 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4542 #endif
4543 				buf[len++] =
4544 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4545 				buf[len++] =
4546 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4547 				buf[len++] =
4548 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4549 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4550 				buf[len++] = 0;
4551 				buf[len++] = 0; /* density code */
4552 				buf[len++] = 0;
4553 				buf[len++] = 0;
4554 				if (sdinfo->satadrv_type ==
4555 				    SATA_DTYPE_ATADISK)
4556 					buf[len++] = 2;
4557 				else
4558 					/* ATAPI */
4559 					buf[len++] = 8;
4560 				buf[len++] = 0;
4561 			}
4562 		}
4563 
4564 		sata_id = &sdinfo->satadrv_id;
4565 
4566 		/*
4567 		 * Add requested pages.
4568 		 * Page 3 and 4 are obsolete and we are not supporting them.
4569 		 * We deal now with:
4570 		 * caching (read/write cache control).
4571 		 * We should eventually deal with following mode pages:
4572 		 * error recovery  (0x01),
4573 		 * power condition (0x1a),
4574 		 * exception control page (enables SMART) (0x1c),
4575 		 * enclosure management (ses),
4576 		 * protocol-specific port mode (port control).
4577 		 */
4578 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4579 		case MODEPAGE_RW_ERRRECOV:
4580 			/* DAD_MODE_ERR_RECOV */
4581 			/* R/W recovery */
4582 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4583 			break;
4584 		case MODEPAGE_CACHING:
4585 			/* DAD_MODE_CACHE */
4586 			/* Reject not supported request for saved parameters */
4587 			if (pc == 3) {
4588 				*scsipkt->pkt_scbp = STATUS_CHECK;
4589 				sense = sata_arq_sense(spx);
4590 				sense->es_key = KEY_ILLEGAL_REQUEST;
4591 				sense->es_add_code =
4592 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4593 				goto done;
4594 			}
4595 
4596 			/* caching */
4597 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4598 			break;
4599 		case MODEPAGE_INFO_EXCPT:
4600 			/* exception cntrl */
4601 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4602 				len += sata_build_msense_page_1c(sdinfo, pc,
4603 				    buf+len);
4604 			}
4605 			else
4606 				goto err;
4607 			break;
4608 		case MODEPAGE_POWER_COND:
4609 			/* DAD_MODE_POWER_COND */
4610 			/* power condition */
4611 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4612 			break;
4613 
4614 		case MODEPAGE_ACOUSTIC_MANAG:
4615 			/* acoustic management */
4616 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4617 			break;
4618 		case MODEPAGE_ALLPAGES:
4619 			/* all pages */
4620 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4621 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4622 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4623 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4624 				len += sata_build_msense_page_1c(sdinfo, pc,
4625 				    buf+len);
4626 			}
4627 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4628 			break;
4629 		default:
4630 		err:
4631 			/* Invalid request */
4632 			*scsipkt->pkt_scbp = STATUS_CHECK;
4633 			sense = sata_arq_sense(spx);
4634 			sense->es_key = KEY_ILLEGAL_REQUEST;
4635 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4636 			goto done;
4637 		}
4638 
4639 		/* fix total mode data length */
4640 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4641 			/* 4-byte mode parameter header */
4642 			buf[0] = len - 1;	/* mode data length */
4643 		} else {
4644 			buf[0] = (len -2) >> 8;
4645 			buf[1] = (len -2) & 0xff;
4646 		}
4647 
4648 
4649 		/* Check allocation length */
4650 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4651 			alc_len = scsipkt->pkt_cdbp[4];
4652 		} else {
4653 			alc_len = scsipkt->pkt_cdbp[7];
4654 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4655 		}
4656 		/*
4657 		 * We do not check for possible parameters truncation
4658 		 * (alc_len < len) assuming that the target driver works
4659 		 * correctly. Just avoiding overrun.
4660 		 * Copy no more than requested and possible, buffer-wise.
4661 		 */
4662 		count = MIN(alc_len, len);
4663 		count = MIN(bp->b_bcount, count);
4664 		bcopy(buf, bp->b_un.b_addr, count);
4665 
4666 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4667 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4668 	}
4669 	*scsipkt->pkt_scbp = STATUS_GOOD;
4670 done:
4671 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4672 	(void) kmem_free(buf, 1024);
4673 
4674 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4675 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4676 
4677 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4678 	    scsipkt->pkt_comp != NULL) {
4679 		/* scsi callback required */
4680 		if (servicing_interrupt()) {
4681 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4682 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4683 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4684 				return (TRAN_BUSY);
4685 			}
4686 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4687 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4688 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4689 			/* Scheduling the callback failed */
4690 			return (TRAN_BUSY);
4691 		}
4692 	}
4693 
4694 	return (TRAN_ACCEPT);
4695 }
4696 
4697 
4698 /*
4699  * SATA translate command: Mode Select.
4700  * Translated into appropriate SATA command or emulated.
4701  * Saving parameters is not supported.
4702  * Changing device capacity is not supported (although theoretically
4703  * possible by executing SET FEATURES/SET MAX ADDRESS)
4704  *
4705  * Assumption is that the target driver is working correctly.
4706  *
4707  * More than one SATA command may be executed to perform operations specified
4708  * by mode select pages. The first error terminates further execution.
4709  * Operations performed successully are not backed-up in such case.
4710  *
4711  * NOTE: Implemented pages:
4712  * - caching page
4713  * - informational exception page
4714  * - acoustic management page
4715  * - power condition page
4716  * Caching setup is remembered so it could be re-stored in case of
4717  * an unexpected device reset.
4718  *
4719  * Returns TRAN_XXXX.
4720  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4721  */
4722 
4723 static int
4724 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4725 {
4726 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4727 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4728 	struct scsi_extended_sense *sense;
4729 	int len, pagelen, count, pllen;
4730 	uint8_t *buf;	/* mode select buffer */
4731 	int rval, stat, reason;
4732 	uint_t nointr_flag;
4733 	int dmod = 0;
4734 
4735 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4736 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4737 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4738 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4739 
4740 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4741 
4742 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4743 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4744 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4745 		return (rval);
4746 	}
4747 
4748 	rval = TRAN_ACCEPT;
4749 
4750 	scsipkt->pkt_reason = CMD_CMPLT;
4751 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4752 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4753 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4754 
4755 	/* Reject not supported request */
4756 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4757 		*scsipkt->pkt_scbp = STATUS_CHECK;
4758 		sense = sata_arq_sense(spx);
4759 		sense->es_key = KEY_ILLEGAL_REQUEST;
4760 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4761 		goto done;
4762 	}
4763 
4764 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4765 		pllen = scsipkt->pkt_cdbp[4];
4766 	} else {
4767 		pllen = scsipkt->pkt_cdbp[7];
4768 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4769 	}
4770 
4771 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4772 
4773 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4774 		buf = (uint8_t *)bp->b_un.b_addr;
4775 		count = MIN(bp->b_bcount, pllen);
4776 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4777 		scsipkt->pkt_resid = 0;
4778 		pllen = count;
4779 
4780 		/*
4781 		 * Check the header to skip the block descriptor(s) - we
4782 		 * do not support setting device capacity.
4783 		 * Existing macros do not recognize long LBA dscriptor,
4784 		 * hence manual calculation.
4785 		 */
4786 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4787 			/* 6-bytes CMD, 4 bytes header */
4788 			if (count <= 4)
4789 				goto done;		/* header only */
4790 			len = buf[3] + 4;
4791 		} else {
4792 			/* 10-bytes CMD, 8 bytes header */
4793 			if (count <= 8)
4794 				goto done;		/* header only */
4795 			len = buf[6];
4796 			len = (len << 8) + buf[7] + 8;
4797 		}
4798 		if (len >= count)
4799 			goto done;	/* header + descriptor(s) only */
4800 
4801 		pllen -= len;		/* remaining data length */
4802 
4803 		/*
4804 		 * We may be executing SATA command and want to execute it
4805 		 * in SYNCH mode, regardless of scsi_pkt setting.
4806 		 * Save scsi_pkt setting and indicate SYNCH mode
4807 		 */
4808 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4809 		    scsipkt->pkt_comp != NULL) {
4810 			scsipkt->pkt_flags |= FLAG_NOINTR;
4811 		}
4812 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4813 
4814 		/*
4815 		 * len is now the offset to a first mode select page
4816 		 * Process all pages
4817 		 */
4818 		while (pllen > 0) {
4819 			switch ((int)buf[len]) {
4820 			case MODEPAGE_CACHING:
4821 				/* No support for SP (saving) */
4822 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4823 					*scsipkt->pkt_scbp = STATUS_CHECK;
4824 					sense = sata_arq_sense(spx);
4825 					sense->es_key = KEY_ILLEGAL_REQUEST;
4826 					sense->es_add_code =
4827 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4828 					goto done;
4829 				}
4830 				stat = sata_mode_select_page_8(spx,
4831 				    (struct mode_cache_scsi3 *)&buf[len],
4832 				    pllen, &pagelen, &rval, &dmod);
4833 				/*
4834 				 * The pagelen value indicates the number of
4835 				 * parameter bytes already processed.
4836 				 * The rval is the return value from
4837 				 * sata_tran_start().
4838 				 * The stat indicates the overall status of
4839 				 * the operation(s).
4840 				 */
4841 				if (stat != SATA_SUCCESS)
4842 					/*
4843 					 * Page processing did not succeed -
4844 					 * all error info is already set-up,
4845 					 * just return
4846 					 */
4847 					pllen = 0; /* this breaks the loop */
4848 				else {
4849 					len += pagelen;
4850 					pllen -= pagelen;
4851 				}
4852 				break;
4853 
4854 			case MODEPAGE_INFO_EXCPT:
4855 				stat = sata_mode_select_page_1c(spx,
4856 				    (struct mode_info_excpt_page *)&buf[len],
4857 				    pllen, &pagelen, &rval, &dmod);
4858 				/*
4859 				 * The pagelen value indicates the number of
4860 				 * parameter bytes already processed.
4861 				 * The rval is the return value from
4862 				 * sata_tran_start().
4863 				 * The stat indicates the overall status of
4864 				 * the operation(s).
4865 				 */
4866 				if (stat != SATA_SUCCESS)
4867 					/*
4868 					 * Page processing did not succeed -
4869 					 * all error info is already set-up,
4870 					 * just return
4871 					 */
4872 					pllen = 0; /* this breaks the loop */
4873 				else {
4874 					len += pagelen;
4875 					pllen -= pagelen;
4876 				}
4877 				break;
4878 
4879 			case MODEPAGE_ACOUSTIC_MANAG:
4880 				stat = sata_mode_select_page_30(spx,
4881 				    (struct mode_acoustic_management *)
4882 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4883 				/*
4884 				 * The pagelen value indicates the number of
4885 				 * parameter bytes already processed.
4886 				 * The rval is the return value from
4887 				 * sata_tran_start().
4888 				 * The stat indicates the overall status of
4889 				 * the operation(s).
4890 				 */
4891 				if (stat != SATA_SUCCESS)
4892 					/*
4893 					 * Page processing did not succeed -
4894 					 * all error info is already set-up,
4895 					 * just return
4896 					 */
4897 					pllen = 0; /* this breaks the loop */
4898 				else {
4899 					len += pagelen;
4900 					pllen -= pagelen;
4901 				}
4902 
4903 				break;
4904 			case MODEPAGE_POWER_COND:
4905 				stat = sata_mode_select_page_1a(spx,
4906 				    (struct mode_info_power_cond *)&buf[len],
4907 				    pllen, &pagelen, &rval, &dmod);
4908 				/*
4909 				 * The pagelen value indicates the number of
4910 				 * parameter bytes already processed.
4911 				 * The rval is the return value from
4912 				 * sata_tran_start().
4913 				 * The stat indicates the overall status of
4914 				 * the operation(s).
4915 				 */
4916 				if (stat != SATA_SUCCESS)
4917 					/*
4918 					 * Page processing did not succeed -
4919 					 * all error info is already set-up,
4920 					 * just return
4921 					 */
4922 					pllen = 0; /* this breaks the loop */
4923 				else {
4924 					len += pagelen;
4925 					pllen -= pagelen;
4926 				}
4927 				break;
4928 			default:
4929 				*scsipkt->pkt_scbp = STATUS_CHECK;
4930 				sense = sata_arq_sense(spx);
4931 				sense->es_key = KEY_ILLEGAL_REQUEST;
4932 				sense->es_add_code =
4933 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4934 				goto done;
4935 			}
4936 		}
4937 	}
4938 done:
4939 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4940 	/*
4941 	 * If device parameters were modified, fetch and store the new
4942 	 * Identify Device data. Since port mutex could have been released
4943 	 * for accessing HBA driver, we need to re-check device existence.
4944 	 */
4945 	if (dmod != 0) {
4946 		sata_drive_info_t new_sdinfo, *sdinfo;
4947 		int rv = 0;
4948 
4949 		/*
4950 		 * Following statement has to be changed if this function is
4951 		 * used for devices other than SATA hard disks.
4952 		 */
4953 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4954 
4955 		new_sdinfo.satadrv_addr =
4956 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4957 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4958 		    &new_sdinfo);
4959 
4960 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4961 		/*
4962 		 * Since port mutex could have been released when
4963 		 * accessing HBA driver, we need to re-check that the
4964 		 * framework still holds the device info structure.
4965 		 */
4966 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4967 		    &spx->txlt_sata_pkt->satapkt_device);
4968 		if (sdinfo != NULL) {
4969 			/*
4970 			 * Device still has info structure in the
4971 			 * sata framework. Copy newly fetched info
4972 			 */
4973 			if (rv == 0) {
4974 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4975 				sata_save_drive_settings(sdinfo);
4976 			} else {
4977 				/*
4978 				 * Could not fetch new data - invalidate
4979 				 * sata_drive_info. That makes device
4980 				 * unusable.
4981 				 */
4982 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4983 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4984 			}
4985 		}
4986 		if (rv != 0 || sdinfo == NULL) {
4987 			/*
4988 			 * This changes the overall mode select completion
4989 			 * reason to a failed one !!!!!
4990 			 */
4991 			*scsipkt->pkt_scbp = STATUS_CHECK;
4992 			sense = sata_arq_sense(spx);
4993 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4994 			rval = TRAN_ACCEPT;
4995 		}
4996 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4997 	}
4998 	/* Restore the scsi pkt flags */
4999 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5000 	scsipkt->pkt_flags |= nointr_flag;
5001 
5002 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5003 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5004 
5005 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5006 	    scsipkt->pkt_comp != NULL) {
5007 		/* scsi callback required */
5008 		if (servicing_interrupt()) {
5009 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5010 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5011 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5012 				return (TRAN_BUSY);
5013 			}
5014 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5015 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5016 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5017 			/* Scheduling the callback failed */
5018 			return (TRAN_BUSY);
5019 		}
5020 	}
5021 
5022 	return (rval);
5023 }
5024 
5025 /*
5026  * Translate command: ATA Pass Through
5027  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5028  * PIO Data-Out protocols.  Also supports CK_COND bit.
5029  *
5030  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5031  * described in Table 111 of SAT-2 (Draft 9).
5032  */
5033 static  int
5034 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5035 {
5036 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5037 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5038 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5039 	int extend;
5040 	uint64_t lba;
5041 	uint16_t feature, sec_count;
5042 	int t_len, synch;
5043 	int rval, reason;
5044 
5045 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5046 
5047 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5048 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5049 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5050 		return (rval);
5051 	}
5052 
5053 	/* T_DIR bit */
5054 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5055 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5056 	else
5057 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5058 
5059 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5060 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5061 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5062 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5063 	}
5064 
5065 	/* OFFLINE field. If non-zero, invalid command (for now). */
5066 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5067 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5068 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5069 	}
5070 
5071 	/* PROTOCOL field */
5072 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5073 	case SATL_APT_P_HW_RESET:
5074 	case SATL_APT_P_SRST:
5075 	case SATL_APT_P_DMA:
5076 	case SATL_APT_P_DMA_QUEUED:
5077 	case SATL_APT_P_DEV_DIAG:
5078 	case SATL_APT_P_DEV_RESET:
5079 	case SATL_APT_P_UDMA_IN:
5080 	case SATL_APT_P_UDMA_OUT:
5081 	case SATL_APT_P_FPDMA:
5082 	case SATL_APT_P_RET_RESP:
5083 		/* Not yet implemented */
5084 	default:
5085 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5086 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5087 
5088 	case SATL_APT_P_NON_DATA:
5089 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5090 		break;
5091 
5092 	case SATL_APT_P_PIO_DATA_IN:
5093 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5094 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5095 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5096 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5097 		}
5098 
5099 		/* if there is a buffer, release its DMA resources */
5100 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5101 			sata_scsi_dmafree(NULL, scsipkt);
5102 		} else {
5103 			/* if there is no buffer, how do you PIO in? */
5104 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5105 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5106 		}
5107 
5108 		break;
5109 
5110 	case SATL_APT_P_PIO_DATA_OUT:
5111 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5112 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5113 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5114 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5115 		}
5116 
5117 		/* if there is a buffer, release its DMA resources */
5118 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5119 			sata_scsi_dmafree(NULL, scsipkt);
5120 		} else {
5121 			/* if there is no buffer, how do you PIO out? */
5122 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5123 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5124 		}
5125 
5126 		break;
5127 	}
5128 
5129 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5130 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5131 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5132 		feature = scsipkt->pkt_cdbp[3];
5133 
5134 		sec_count = scsipkt->pkt_cdbp[4];
5135 
5136 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5137 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5138 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5139 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5140 
5141 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5142 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5143 
5144 		break;
5145 
5146 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5147 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5148 			extend = 1;
5149 
5150 			feature = scsipkt->pkt_cdbp[3];
5151 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5152 
5153 			sec_count = scsipkt->pkt_cdbp[5];
5154 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5155 
5156 			lba = scsipkt->pkt_cdbp[11];
5157 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5158 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5159 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5160 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5161 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5162 
5163 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5164 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5165 		} else {
5166 			feature = scsipkt->pkt_cdbp[3];
5167 
5168 			sec_count = scsipkt->pkt_cdbp[5];
5169 
5170 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5171 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5172 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5173 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5174 
5175 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5176 			    0xf0;
5177 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5178 		}
5179 
5180 		break;
5181 	}
5182 
5183 	/* CK_COND bit */
5184 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5185 		if (extend) {
5186 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5187 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5188 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5189 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5190 		}
5191 
5192 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5193 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5194 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5195 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5196 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5197 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5198 	}
5199 
5200 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5201 	if (extend) {
5202 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5203 
5204 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5205 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5206 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5207 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5208 		scmd->satacmd_lba_high_msb = lba >> 40;
5209 	} else {
5210 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5211 
5212 		scmd->satacmd_features_reg_ext = 0;
5213 		scmd->satacmd_sec_count_msb = 0;
5214 		scmd->satacmd_lba_low_msb = 0;
5215 		scmd->satacmd_lba_mid_msb = 0;
5216 		scmd->satacmd_lba_high_msb = 0;
5217 	}
5218 
5219 	scmd->satacmd_features_reg = feature & 0xff;
5220 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5221 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5222 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5223 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5224 
5225 	/* Determine transfer length */
5226 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5227 	case 1:
5228 		t_len = feature;
5229 		break;
5230 	case 2:
5231 		t_len = sec_count;
5232 		break;
5233 	default:
5234 		t_len = 0;
5235 		break;
5236 	}
5237 
5238 	/* Adjust transfer length for the Byte Block bit */
5239 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5240 		t_len *= SATA_DISK_SECTOR_SIZE;
5241 
5242 	/* Start processing command */
5243 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5244 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5245 		synch = FALSE;
5246 	} else {
5247 		synch = TRUE;
5248 	}
5249 
5250 	if (sata_hba_start(spx, &rval) != 0) {
5251 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5252 		return (rval);
5253 	}
5254 
5255 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5256 
5257 	if (synch) {
5258 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5259 	}
5260 
5261 	return (TRAN_ACCEPT);
5262 }
5263 
5264 /*
5265  * Translate command: Log Sense
5266  */
5267 static 	int
5268 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5269 {
5270 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5271 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5272 	sata_drive_info_t *sdinfo;
5273 	struct scsi_extended_sense *sense;
5274 	int 		len, count, alc_len;
5275 	int		pc;	/* Page Control code */
5276 	int		page_code;	/* Page code */
5277 	uint8_t		*buf;	/* log sense buffer */
5278 	int		rval, reason;
5279 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5280 
5281 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5282 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5283 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5284 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5285 
5286 	if (servicing_interrupt()) {
5287 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5288 		if (buf == NULL) {
5289 			return (TRAN_BUSY);
5290 		}
5291 	} else {
5292 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5293 	}
5294 
5295 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5296 
5297 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5298 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5299 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5300 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5301 		return (rval);
5302 	}
5303 
5304 	scsipkt->pkt_reason = CMD_CMPLT;
5305 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5306 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5307 
5308 	pc = scsipkt->pkt_cdbp[2] >> 6;
5309 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5310 
5311 	/* Reject not supported request for all but cumulative values */
5312 	switch (pc) {
5313 	case PC_CUMULATIVE_VALUES:
5314 		break;
5315 	default:
5316 		*scsipkt->pkt_scbp = STATUS_CHECK;
5317 		sense = sata_arq_sense(spx);
5318 		sense->es_key = KEY_ILLEGAL_REQUEST;
5319 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5320 		goto done;
5321 	}
5322 
5323 	switch (page_code) {
5324 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5325 	case PAGE_CODE_SELF_TEST_RESULTS:
5326 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5327 	case PAGE_CODE_SMART_READ_DATA:
5328 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5329 		break;
5330 	default:
5331 		*scsipkt->pkt_scbp = STATUS_CHECK;
5332 		sense = sata_arq_sense(spx);
5333 		sense->es_key = KEY_ILLEGAL_REQUEST;
5334 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5335 		goto done;
5336 	}
5337 
5338 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5339 		/*
5340 		 * Because log sense uses local buffers for data retrieval from
5341 		 * the devices and sets the data programatically in the
5342 		 * original specified buffer, release preallocated DMA
5343 		 * resources before storing data in the original buffer,
5344 		 * so no unwanted DMA sync would take place.
5345 		 */
5346 		sata_id_t *sata_id;
5347 
5348 		sata_scsi_dmafree(NULL, scsipkt);
5349 
5350 		len = 0;
5351 
5352 		/* Build log parameter header */
5353 		buf[len++] = page_code;	/* page code as in the CDB */
5354 		buf[len++] = 0;		/* reserved */
5355 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5356 		buf[len++] = 0;		/* (LSB) */
5357 
5358 		sdinfo = sata_get_device_info(
5359 		    spx->txlt_sata_hba_inst,
5360 		    &spx->txlt_sata_pkt->satapkt_device);
5361 
5362 		/*
5363 		 * Add requested pages.
5364 		 */
5365 		switch (page_code) {
5366 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5367 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5368 			break;
5369 		case PAGE_CODE_SELF_TEST_RESULTS:
5370 			sata_id = &sdinfo->satadrv_id;
5371 			if ((! (sata_id->ai_cmdset84 &
5372 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5373 			    (! (sata_id->ai_features87 &
5374 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5375 				*scsipkt->pkt_scbp = STATUS_CHECK;
5376 				sense = sata_arq_sense(spx);
5377 				sense->es_key = KEY_ILLEGAL_REQUEST;
5378 				sense->es_add_code =
5379 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5380 
5381 				goto done;
5382 			}
5383 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5384 			    spx->txlt_sata_hba_inst);
5385 			break;
5386 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5387 			sata_id = &sdinfo->satadrv_id;
5388 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5389 				*scsipkt->pkt_scbp = STATUS_CHECK;
5390 				sense = sata_arq_sense(spx);
5391 				sense->es_key = KEY_ILLEGAL_REQUEST;
5392 				sense->es_add_code =
5393 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5394 
5395 				goto done;
5396 			}
5397 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5398 				*scsipkt->pkt_scbp = STATUS_CHECK;
5399 				sense = sata_arq_sense(spx);
5400 				sense->es_key = KEY_ABORTED_COMMAND;
5401 				sense->es_add_code =
5402 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5403 				sense->es_qual_code =
5404 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5405 
5406 				goto done;
5407 			}
5408 
5409 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5410 			    spx->txlt_sata_hba_inst);
5411 			break;
5412 		case PAGE_CODE_SMART_READ_DATA:
5413 			sata_id = &sdinfo->satadrv_id;
5414 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5415 				*scsipkt->pkt_scbp = STATUS_CHECK;
5416 				sense = sata_arq_sense(spx);
5417 				sense->es_key = KEY_ILLEGAL_REQUEST;
5418 				sense->es_add_code =
5419 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5420 
5421 				goto done;
5422 			}
5423 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5424 				*scsipkt->pkt_scbp = STATUS_CHECK;
5425 				sense = sata_arq_sense(spx);
5426 				sense->es_key = KEY_ABORTED_COMMAND;
5427 				sense->es_add_code =
5428 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5429 				sense->es_qual_code =
5430 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5431 
5432 				goto done;
5433 			}
5434 
5435 			/* This page doesn't include a page header */
5436 			len = sata_build_lsense_page_30(sdinfo, buf,
5437 			    spx->txlt_sata_hba_inst);
5438 			goto no_header;
5439 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5440 			sata_id = &sdinfo->satadrv_id;
5441 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5442 				*scsipkt->pkt_scbp = STATUS_CHECK;
5443 				sense = sata_arq_sense(spx);
5444 				sense->es_key = KEY_ILLEGAL_REQUEST;
5445 				sense->es_add_code =
5446 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5447 
5448 				goto done;
5449 			}
5450 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5451 				*scsipkt->pkt_scbp = STATUS_CHECK;
5452 				sense = sata_arq_sense(spx);
5453 				sense->es_key = KEY_ABORTED_COMMAND;
5454 				sense->es_add_code =
5455 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5456 				sense->es_qual_code =
5457 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5458 
5459 				goto done;
5460 			}
5461 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5462 			goto no_header;
5463 		default:
5464 			/* Invalid request */
5465 			*scsipkt->pkt_scbp = STATUS_CHECK;
5466 			sense = sata_arq_sense(spx);
5467 			sense->es_key = KEY_ILLEGAL_REQUEST;
5468 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5469 			goto done;
5470 		}
5471 
5472 		/* set parameter log sense data length */
5473 		buf[2] = len >> 8;	/* log sense length (MSB) */
5474 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5475 
5476 		len += SCSI_LOG_PAGE_HDR_LEN;
5477 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5478 
5479 no_header:
5480 		/* Check allocation length */
5481 		alc_len = scsipkt->pkt_cdbp[7];
5482 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5483 
5484 		/*
5485 		 * We do not check for possible parameters truncation
5486 		 * (alc_len < len) assuming that the target driver works
5487 		 * correctly. Just avoiding overrun.
5488 		 * Copy no more than requested and possible, buffer-wise.
5489 		 */
5490 		count = MIN(alc_len, len);
5491 		count = MIN(bp->b_bcount, count);
5492 		bcopy(buf, bp->b_un.b_addr, count);
5493 
5494 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5495 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5496 	}
5497 	*scsipkt->pkt_scbp = STATUS_GOOD;
5498 done:
5499 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5500 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5501 
5502 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5503 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5504 
5505 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5506 	    scsipkt->pkt_comp != NULL) {
5507 		/* scsi callback required */
5508 		if (servicing_interrupt()) {
5509 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5510 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5511 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5512 				return (TRAN_BUSY);
5513 			}
5514 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5515 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5516 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5517 			/* Scheduling the callback failed */
5518 			return (TRAN_BUSY);
5519 		}
5520 	}
5521 
5522 	return (TRAN_ACCEPT);
5523 }
5524 
5525 /*
5526  * Translate command: Log Select
5527  * Not implemented at this time - returns invalid command response.
5528  */
5529 static	int
5530 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5531 {
5532 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5533 	    "sata_txlt_log_select\n", NULL);
5534 
5535 	return (sata_txlt_invalid_command(spx));
5536 }
5537 
5538 
5539 /*
5540  * Translate command: Read (various types).
5541  * Translated into appropriate type of ATA READ command
5542  * for SATA hard disks.
5543  * Both the device capabilities and requested operation mode are
5544  * considered.
5545  *
5546  * Following scsi cdb fields are ignored:
5547  * rdprotect, dpo, fua, fua_nv, group_number.
5548  *
5549  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5550  * enable variable sata_func_enable), the capability of the controller and
5551  * capability of a device are checked and if both support queueing, read
5552  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5553  * command rather than plain READ_XXX command.
5554  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5555  * both the controller and device suport such functionality, the read
5556  * request will be translated to READ_FPDMA_QUEUED command.
5557  * In both cases the maximum queue depth is derived as minimum of:
5558  * HBA capability,device capability and sata_max_queue_depth variable setting.
5559  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5560  * used to pass max queue depth value, and the maximum possible queue depth
5561  * is 32.
5562  *
5563  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5564  * appropriate values in scsi_pkt fields.
5565  */
5566 static int
5567 sata_txlt_read(sata_pkt_txlate_t *spx)
5568 {
5569 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5570 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5571 	sata_drive_info_t *sdinfo;
5572 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5573 	int cport = SATA_TXLT_CPORT(spx);
5574 	uint16_t sec_count;
5575 	uint64_t lba;
5576 	int rval, reason;
5577 	int synch;
5578 
5579 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5580 
5581 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5582 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5583 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5584 		return (rval);
5585 	}
5586 
5587 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5588 	    &spx->txlt_sata_pkt->satapkt_device);
5589 
5590 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5591 	/*
5592 	 * Extract LBA and sector count from scsi CDB.
5593 	 */
5594 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5595 	case SCMD_READ:
5596 		/* 6-byte scsi read cmd : 0x08 */
5597 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5598 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5599 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5600 		sec_count = scsipkt->pkt_cdbp[4];
5601 		/* sec_count 0 will be interpreted as 256 by a device */
5602 		break;
5603 	case SCMD_READ_G1:
5604 		/* 10-bytes scsi read command : 0x28 */
5605 		lba = scsipkt->pkt_cdbp[2];
5606 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5607 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5608 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5609 		sec_count = scsipkt->pkt_cdbp[7];
5610 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5611 		break;
5612 	case SCMD_READ_G5:
5613 		/* 12-bytes scsi read command : 0xA8 */
5614 		lba = scsipkt->pkt_cdbp[2];
5615 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5616 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5617 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5618 		sec_count = scsipkt->pkt_cdbp[6];
5619 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5620 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5621 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5622 		break;
5623 	case SCMD_READ_G4:
5624 		/* 16-bytes scsi read command : 0x88 */
5625 		lba = scsipkt->pkt_cdbp[2];
5626 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5627 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5628 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5629 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5630 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5631 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5632 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5633 		sec_count = scsipkt->pkt_cdbp[10];
5634 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5635 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5636 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5637 		break;
5638 	default:
5639 		/* Unsupported command */
5640 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5641 		return (sata_txlt_invalid_command(spx));
5642 	}
5643 
5644 	/*
5645 	 * Check if specified address exceeds device capacity
5646 	 */
5647 	if ((lba >= sdinfo->satadrv_capacity) ||
5648 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5649 		/* LBA out of range */
5650 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5651 		return (sata_txlt_lba_out_of_range(spx));
5652 	}
5653 
5654 	/*
5655 	 * For zero-length transfer, emulate good completion of the command
5656 	 * (reasons for rejecting the command were already checked).
5657 	 * No DMA resources were allocated.
5658 	 */
5659 	if (spx->txlt_dma_cookie_list == NULL) {
5660 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5661 		return (sata_emul_rw_completion(spx));
5662 	}
5663 
5664 	/*
5665 	 * Build cmd block depending on the device capability and
5666 	 * requested operation mode.
5667 	 * Do not bother with non-dma mode - we are working only with
5668 	 * devices supporting DMA.
5669 	 */
5670 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5671 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5672 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5673 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5674 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5675 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5676 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5677 #ifndef __lock_lint
5678 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5679 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5680 		scmd->satacmd_lba_high_msb = lba >> 40;
5681 #endif
5682 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5683 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5684 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5685 	}
5686 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5687 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5688 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5689 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5690 	scmd->satacmd_features_reg = 0;
5691 	scmd->satacmd_status_reg = 0;
5692 	scmd->satacmd_error_reg = 0;
5693 
5694 	/*
5695 	 * Check if queueing commands should be used and switch
5696 	 * to appropriate command if possible
5697 	 */
5698 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5699 		boolean_t using_queuing;
5700 
5701 		/* Queuing supported by controller and device? */
5702 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5703 		    (sdinfo->satadrv_features_support &
5704 		    SATA_DEV_F_NCQ) &&
5705 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5706 		    SATA_CTLF_NCQ)) {
5707 			using_queuing = B_TRUE;
5708 
5709 			/* NCQ supported - use FPDMA READ */
5710 			scmd->satacmd_cmd_reg =
5711 			    SATAC_READ_FPDMA_QUEUED;
5712 			scmd->satacmd_features_reg_ext =
5713 			    scmd->satacmd_sec_count_msb;
5714 			scmd->satacmd_sec_count_msb = 0;
5715 		} else if ((sdinfo->satadrv_features_support &
5716 		    SATA_DEV_F_TCQ) &&
5717 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5718 		    SATA_CTLF_QCMD)) {
5719 			using_queuing = B_TRUE;
5720 
5721 			/* Legacy queueing */
5722 			if (sdinfo->satadrv_features_support &
5723 			    SATA_DEV_F_LBA48) {
5724 				scmd->satacmd_cmd_reg =
5725 				    SATAC_READ_DMA_QUEUED_EXT;
5726 				scmd->satacmd_features_reg_ext =
5727 				    scmd->satacmd_sec_count_msb;
5728 				scmd->satacmd_sec_count_msb = 0;
5729 			} else {
5730 				scmd->satacmd_cmd_reg =
5731 				    SATAC_READ_DMA_QUEUED;
5732 			}
5733 		} else	/* NCQ nor legacy queuing not supported */
5734 			using_queuing = B_FALSE;
5735 
5736 		/*
5737 		 * If queuing, the sector count goes in the features register
5738 		 * and the secount count will contain the tag.
5739 		 */
5740 		if (using_queuing) {
5741 			scmd->satacmd_features_reg =
5742 			    scmd->satacmd_sec_count_lsb;
5743 			scmd->satacmd_sec_count_lsb = 0;
5744 			scmd->satacmd_flags.sata_queued = B_TRUE;
5745 
5746 			/* Set-up maximum queue depth */
5747 			scmd->satacmd_flags.sata_max_queue_depth =
5748 			    sdinfo->satadrv_max_queue_depth - 1;
5749 		} else if (sdinfo->satadrv_features_enabled &
5750 		    SATA_DEV_F_E_UNTAGGED_QING) {
5751 			/*
5752 			 * Although NCQ/TCQ is not enabled, untagged queuing
5753 			 * may be still used.
5754 			 * Set-up the maximum untagged queue depth.
5755 			 * Use controller's queue depth from sata_hba_tran.
5756 			 * SATA HBA drivers may ignore this value and rely on
5757 			 * the internal limits.For drivers that do not
5758 			 * ignore untaged queue depth, limit the value to
5759 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5760 			 * largest value that can be passed via
5761 			 * satacmd_flags.sata_max_queue_depth.
5762 			 */
5763 			scmd->satacmd_flags.sata_max_queue_depth =
5764 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5765 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5766 
5767 		} else {
5768 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5769 		}
5770 	} else
5771 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5772 
5773 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5774 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5775 	    scmd->satacmd_cmd_reg, lba, sec_count);
5776 
5777 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5778 		/* Need callback function */
5779 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5780 		synch = FALSE;
5781 	} else
5782 		synch = TRUE;
5783 
5784 	/* Transfer command to HBA */
5785 	if (sata_hba_start(spx, &rval) != 0) {
5786 		/* Pkt not accepted for execution */
5787 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5788 		return (rval);
5789 	}
5790 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5791 	/*
5792 	 * If execution is non-synchronous,
5793 	 * a callback function will handle potential errors, translate
5794 	 * the response and will do a callback to a target driver.
5795 	 * If it was synchronous, check execution status using the same
5796 	 * framework callback.
5797 	 */
5798 	if (synch) {
5799 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5800 		    "synchronous execution status %x\n",
5801 		    spx->txlt_sata_pkt->satapkt_reason);
5802 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5803 	}
5804 	return (TRAN_ACCEPT);
5805 }
5806 
5807 
5808 /*
5809  * SATA translate command: Write (various types)
5810  * Translated into appropriate type of ATA WRITE command
5811  * for SATA hard disks.
5812  * Both the device capabilities and requested operation mode are
5813  * considered.
5814  *
5815  * Following scsi cdb fields are ignored:
5816  * rwprotect, dpo, fua, fua_nv, group_number.
5817  *
5818  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5819  * enable variable sata_func_enable), the capability of the controller and
5820  * capability of a device are checked and if both support queueing, write
5821  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5822  * command rather than plain WRITE_XXX command.
5823  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5824  * both the controller and device suport such functionality, the write
5825  * request will be translated to WRITE_FPDMA_QUEUED command.
5826  * In both cases the maximum queue depth is derived as minimum of:
5827  * HBA capability,device capability and sata_max_queue_depth variable setting.
5828  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5829  * used to pass max queue depth value, and the maximum possible queue depth
5830  * is 32.
5831  *
5832  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5833  * appropriate values in scsi_pkt fields.
5834  */
5835 static int
5836 sata_txlt_write(sata_pkt_txlate_t *spx)
5837 {
5838 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5839 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5840 	sata_drive_info_t *sdinfo;
5841 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5842 	int cport = SATA_TXLT_CPORT(spx);
5843 	uint16_t sec_count;
5844 	uint64_t lba;
5845 	int rval, reason;
5846 	int synch;
5847 
5848 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5849 
5850 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5851 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5852 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5853 		return (rval);
5854 	}
5855 
5856 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5857 	    &spx->txlt_sata_pkt->satapkt_device);
5858 
5859 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5860 	/*
5861 	 * Extract LBA and sector count from scsi CDB
5862 	 */
5863 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5864 	case SCMD_WRITE:
5865 		/* 6-byte scsi read cmd : 0x0A */
5866 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5867 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5868 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5869 		sec_count = scsipkt->pkt_cdbp[4];
5870 		/* sec_count 0 will be interpreted as 256 by a device */
5871 		break;
5872 	case SCMD_WRITE_G1:
5873 		/* 10-bytes scsi write command : 0x2A */
5874 		lba = scsipkt->pkt_cdbp[2];
5875 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5876 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5877 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5878 		sec_count = scsipkt->pkt_cdbp[7];
5879 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5880 		break;
5881 	case SCMD_WRITE_G5:
5882 		/* 12-bytes scsi read command : 0xAA */
5883 		lba = scsipkt->pkt_cdbp[2];
5884 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5885 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5886 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5887 		sec_count = scsipkt->pkt_cdbp[6];
5888 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5889 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5890 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5891 		break;
5892 	case SCMD_WRITE_G4:
5893 		/* 16-bytes scsi write command : 0x8A */
5894 		lba = scsipkt->pkt_cdbp[2];
5895 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5896 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5897 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5898 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5899 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5900 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5901 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5902 		sec_count = scsipkt->pkt_cdbp[10];
5903 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5904 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5905 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5906 		break;
5907 	default:
5908 		/* Unsupported command */
5909 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5910 		return (sata_txlt_invalid_command(spx));
5911 	}
5912 
5913 	/*
5914 	 * Check if specified address and length exceeds device capacity
5915 	 */
5916 	if ((lba >= sdinfo->satadrv_capacity) ||
5917 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5918 		/* LBA out of range */
5919 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5920 		return (sata_txlt_lba_out_of_range(spx));
5921 	}
5922 
5923 	/*
5924 	 * For zero-length transfer, emulate good completion of the command
5925 	 * (reasons for rejecting the command were already checked).
5926 	 * No DMA resources were allocated.
5927 	 */
5928 	if (spx->txlt_dma_cookie_list == NULL) {
5929 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5930 		return (sata_emul_rw_completion(spx));
5931 	}
5932 
5933 	/*
5934 	 * Build cmd block depending on the device capability and
5935 	 * requested operation mode.
5936 	 * Do not bother with non-dma mode- we are working only with
5937 	 * devices supporting DMA.
5938 	 */
5939 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5940 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5941 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5942 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5943 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5944 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5945 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5946 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5947 #ifndef __lock_lint
5948 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5949 		scmd->satacmd_lba_high_msb = lba >> 40;
5950 #endif
5951 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5952 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5953 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5954 	}
5955 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5956 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5957 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5958 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5959 	scmd->satacmd_features_reg = 0;
5960 	scmd->satacmd_status_reg = 0;
5961 	scmd->satacmd_error_reg = 0;
5962 
5963 	/*
5964 	 * Check if queueing commands should be used and switch
5965 	 * to appropriate command if possible
5966 	 */
5967 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5968 		boolean_t using_queuing;
5969 
5970 		/* Queuing supported by controller and device? */
5971 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5972 		    (sdinfo->satadrv_features_support &
5973 		    SATA_DEV_F_NCQ) &&
5974 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5975 		    SATA_CTLF_NCQ)) {
5976 			using_queuing = B_TRUE;
5977 
5978 			/* NCQ supported - use FPDMA WRITE */
5979 			scmd->satacmd_cmd_reg =
5980 			    SATAC_WRITE_FPDMA_QUEUED;
5981 			scmd->satacmd_features_reg_ext =
5982 			    scmd->satacmd_sec_count_msb;
5983 			scmd->satacmd_sec_count_msb = 0;
5984 		} else if ((sdinfo->satadrv_features_support &
5985 		    SATA_DEV_F_TCQ) &&
5986 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5987 		    SATA_CTLF_QCMD)) {
5988 			using_queuing = B_TRUE;
5989 
5990 			/* Legacy queueing */
5991 			if (sdinfo->satadrv_features_support &
5992 			    SATA_DEV_F_LBA48) {
5993 				scmd->satacmd_cmd_reg =
5994 				    SATAC_WRITE_DMA_QUEUED_EXT;
5995 				scmd->satacmd_features_reg_ext =
5996 				    scmd->satacmd_sec_count_msb;
5997 				scmd->satacmd_sec_count_msb = 0;
5998 			} else {
5999 				scmd->satacmd_cmd_reg =
6000 				    SATAC_WRITE_DMA_QUEUED;
6001 			}
6002 		} else	/*  NCQ nor legacy queuing not supported */
6003 			using_queuing = B_FALSE;
6004 
6005 		if (using_queuing) {
6006 			scmd->satacmd_features_reg =
6007 			    scmd->satacmd_sec_count_lsb;
6008 			scmd->satacmd_sec_count_lsb = 0;
6009 			scmd->satacmd_flags.sata_queued = B_TRUE;
6010 			/* Set-up maximum queue depth */
6011 			scmd->satacmd_flags.sata_max_queue_depth =
6012 			    sdinfo->satadrv_max_queue_depth - 1;
6013 		} else if (sdinfo->satadrv_features_enabled &
6014 		    SATA_DEV_F_E_UNTAGGED_QING) {
6015 			/*
6016 			 * Although NCQ/TCQ is not enabled, untagged queuing
6017 			 * may be still used.
6018 			 * Set-up the maximum untagged queue depth.
6019 			 * Use controller's queue depth from sata_hba_tran.
6020 			 * SATA HBA drivers may ignore this value and rely on
6021 			 * the internal limits. For drivera that do not
6022 			 * ignore untaged queue depth, limit the value to
6023 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6024 			 * largest value that can be passed via
6025 			 * satacmd_flags.sata_max_queue_depth.
6026 			 */
6027 			scmd->satacmd_flags.sata_max_queue_depth =
6028 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6029 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6030 
6031 		} else {
6032 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6033 		}
6034 	} else
6035 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6036 
6037 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6038 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6039 	    scmd->satacmd_cmd_reg, lba, sec_count);
6040 
6041 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6042 		/* Need callback function */
6043 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6044 		synch = FALSE;
6045 	} else
6046 		synch = TRUE;
6047 
6048 	/* Transfer command to HBA */
6049 	if (sata_hba_start(spx, &rval) != 0) {
6050 		/* Pkt not accepted for execution */
6051 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6052 		return (rval);
6053 	}
6054 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6055 
6056 	/*
6057 	 * If execution is non-synchronous,
6058 	 * a callback function will handle potential errors, translate
6059 	 * the response and will do a callback to a target driver.
6060 	 * If it was synchronous, check execution status using the same
6061 	 * framework callback.
6062 	 */
6063 	if (synch) {
6064 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6065 		    "synchronous execution status %x\n",
6066 		    spx->txlt_sata_pkt->satapkt_reason);
6067 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6068 	}
6069 	return (TRAN_ACCEPT);
6070 }
6071 
6072 
6073 /*
6074  * Implements SCSI SBC WRITE BUFFER command download microcode option
6075  */
6076 static int
6077 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6078 {
6079 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6080 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6081 
6082 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
6083 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6084 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6085 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6086 
6087 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6088 	struct scsi_extended_sense *sense;
6089 	int rval, mode, sector_count, reason;
6090 	int cport = SATA_TXLT_CPORT(spx);
6091 
6092 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6093 
6094 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6095 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6096 
6097 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6098 
6099 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6100 	    TRAN_ACCEPT) {
6101 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6102 		return (rval);
6103 	}
6104 
6105 	/* Use synchronous mode */
6106 	spx->txlt_sata_pkt->satapkt_op_mode
6107 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6108 
6109 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6110 
6111 	scsipkt->pkt_reason = CMD_CMPLT;
6112 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6113 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6114 
6115 	/*
6116 	 * The SCSI to ATA translation specification only calls
6117 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6118 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6119 	 * ATA 8 (draft) got rid of download microcode for temp
6120 	 * and it is even optional for ATA 7, so it may be aborted.
6121 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6122 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6123 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6124 	 * sectors.  Thus the offset really doesn't buy us anything.
6125 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6126 	 * is revised, this can be revisisted.
6127 	 */
6128 	/* Reject not supported request */
6129 	switch (mode) {
6130 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6131 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6132 		break;
6133 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6134 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6135 		break;
6136 	default:
6137 		goto bad_param;
6138 	}
6139 
6140 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6141 
6142 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6143 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6144 		goto bad_param;
6145 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6146 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6147 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6148 	scmd->satacmd_lba_mid_lsb = 0;
6149 	scmd->satacmd_lba_high_lsb = 0;
6150 	scmd->satacmd_device_reg = 0;
6151 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6152 	scmd->satacmd_addr_type = 0;
6153 
6154 	/* Transfer command to HBA */
6155 	if (sata_hba_start(spx, &rval) != 0) {
6156 		/* Pkt not accepted for execution */
6157 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6158 		return (rval);
6159 	}
6160 
6161 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6162 
6163 	/* Then we need synchronous check the status of the disk */
6164 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6165 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6166 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6167 		scsipkt->pkt_reason = CMD_CMPLT;
6168 
6169 		/* Download commmand succeed, so probe and identify device */
6170 		sata_reidentify_device(spx);
6171 	} else {
6172 		/* Something went wrong, microcode download command failed */
6173 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6174 		*scsipkt->pkt_scbp = STATUS_CHECK;
6175 		sense = sata_arq_sense(spx);
6176 		switch (sata_pkt->satapkt_reason) {
6177 		case SATA_PKT_PORT_ERROR:
6178 			/*
6179 			 * We have no device data. Assume no data transfered.
6180 			 */
6181 			sense->es_key = KEY_HARDWARE_ERROR;
6182 			break;
6183 
6184 		case SATA_PKT_DEV_ERROR:
6185 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6186 			    SATA_STATUS_ERR) {
6187 				/*
6188 				 * determine dev error reason from error
6189 				 * reg content
6190 				 */
6191 				sata_decode_device_error(spx, sense);
6192 				break;
6193 			}
6194 			/* No extended sense key - no info available */
6195 			break;
6196 
6197 		case SATA_PKT_TIMEOUT:
6198 			scsipkt->pkt_reason = CMD_TIMEOUT;
6199 			scsipkt->pkt_statistics |=
6200 			    STAT_TIMEOUT | STAT_DEV_RESET;
6201 			/* No extended sense key ? */
6202 			break;
6203 
6204 		case SATA_PKT_ABORTED:
6205 			scsipkt->pkt_reason = CMD_ABORTED;
6206 			scsipkt->pkt_statistics |= STAT_ABORTED;
6207 			/* No extended sense key ? */
6208 			break;
6209 
6210 		case SATA_PKT_RESET:
6211 			/* pkt aborted by an explicit reset from a host */
6212 			scsipkt->pkt_reason = CMD_RESET;
6213 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6214 			break;
6215 
6216 		default:
6217 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6218 			    "sata_txlt_nodata_cmd_completion: "
6219 			    "invalid packet completion reason %d",
6220 			    sata_pkt->satapkt_reason));
6221 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6222 			break;
6223 		}
6224 
6225 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6226 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6227 
6228 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6229 			/* scsi callback required */
6230 			scsi_hba_pkt_comp(scsipkt);
6231 	}
6232 	return (TRAN_ACCEPT);
6233 
6234 bad_param:
6235 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6236 	*scsipkt->pkt_scbp = STATUS_CHECK;
6237 	sense = sata_arq_sense(spx);
6238 	sense->es_key = KEY_ILLEGAL_REQUEST;
6239 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6240 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6241 	    scsipkt->pkt_comp != NULL) {
6242 		/* scsi callback required */
6243 		if (servicing_interrupt()) {
6244 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6245 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6246 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6247 				return (TRAN_BUSY);
6248 			}
6249 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6250 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6251 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6252 			/* Scheduling the callback failed */
6253 			return (TRAN_BUSY);
6254 		}
6255 	}
6256 	return (rval);
6257 }
6258 
6259 /*
6260  * Re-identify device after doing a firmware download.
6261  */
6262 static void
6263 sata_reidentify_device(sata_pkt_txlate_t *spx)
6264 {
6265 #define	DOWNLOAD_WAIT_TIME_SECS	60
6266 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6267 	int rval;
6268 	int retry_cnt;
6269 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6270 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6271 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6272 	sata_drive_info_t *sdinfo;
6273 
6274 	/*
6275 	 * Before returning good status, probe device.
6276 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6277 	 * The assumption is that the new microcode is applied by the
6278 	 * device. It is a caller responsibility to verify this.
6279 	 */
6280 	for (retry_cnt = 0;
6281 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6282 	    retry_cnt++) {
6283 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6284 
6285 		if (rval == SATA_SUCCESS) { /* Set default features */
6286 			sdinfo = sata_get_device_info(sata_hba_inst,
6287 			    &sata_device);
6288 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6289 			    SATA_SUCCESS) {
6290 				/* retry */
6291 				rval = sata_initialize_device(sata_hba_inst,
6292 				    sdinfo);
6293 				if (rval == SATA_RETRY)
6294 					sata_log(sata_hba_inst, CE_WARN,
6295 					    "SATA device at port %d pmport %d -"
6296 					    " default device features could not"
6297 					    " be set. Device may not operate "
6298 					    "as expected.",
6299 					    sata_device.satadev_addr.cport,
6300 					    sata_device.satadev_addr.pmport);
6301 			}
6302 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6303 				scsi_hba_pkt_comp(scsipkt);
6304 			return;
6305 		} else if (rval == SATA_RETRY) {
6306 			delay(drv_usectohz(1000000 *
6307 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6308 			continue;
6309 		} else	/* failed - no reason to retry */
6310 			break;
6311 	}
6312 
6313 	/*
6314 	 * Something went wrong, device probing failed.
6315 	 */
6316 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6317 	    "Cannot probe device after downloading microcode\n"));
6318 
6319 	/* Reset device to force retrying the probe. */
6320 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6321 	    (SATA_DIP(sata_hba_inst), &sata_device);
6322 
6323 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6324 		scsi_hba_pkt_comp(scsipkt);
6325 }
6326 
6327 
6328 /*
6329  * Translate command: Synchronize Cache.
6330  * Translates into Flush Cache command for SATA hard disks.
6331  *
6332  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6333  * appropriate values in scsi_pkt fields.
6334  */
6335 static 	int
6336 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6337 {
6338 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6339 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6340 	int cport = SATA_TXLT_CPORT(spx);
6341 	int rval, reason;
6342 	int synch;
6343 
6344 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6345 
6346 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6347 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6348 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6349 		return (rval);
6350 	}
6351 
6352 	scmd->satacmd_addr_type = 0;
6353 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6354 	scmd->satacmd_device_reg = 0;
6355 	scmd->satacmd_sec_count_lsb = 0;
6356 	scmd->satacmd_lba_low_lsb = 0;
6357 	scmd->satacmd_lba_mid_lsb = 0;
6358 	scmd->satacmd_lba_high_lsb = 0;
6359 	scmd->satacmd_features_reg = 0;
6360 	scmd->satacmd_status_reg = 0;
6361 	scmd->satacmd_error_reg = 0;
6362 
6363 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6364 	    "sata_txlt_synchronize_cache\n", NULL);
6365 
6366 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6367 		/* Need to set-up a callback function */
6368 		spx->txlt_sata_pkt->satapkt_comp =
6369 		    sata_txlt_nodata_cmd_completion;
6370 		synch = FALSE;
6371 	} else
6372 		synch = TRUE;
6373 
6374 	/* Transfer command to HBA */
6375 	if (sata_hba_start(spx, &rval) != 0) {
6376 		/* Pkt not accepted for execution */
6377 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6378 		return (rval);
6379 	}
6380 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6381 
6382 	/*
6383 	 * If execution non-synchronous, it had to be completed
6384 	 * a callback function will handle potential errors, translate
6385 	 * the response and will do a callback to a target driver.
6386 	 * If it was synchronous, check status, using the same
6387 	 * framework callback.
6388 	 */
6389 	if (synch) {
6390 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6391 		    "synchronous execution status %x\n",
6392 		    spx->txlt_sata_pkt->satapkt_reason);
6393 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6394 	}
6395 	return (TRAN_ACCEPT);
6396 }
6397 
6398 
6399 /*
6400  * Send pkt to SATA HBA driver
6401  *
6402  * This function may be called only if the operation is requested by scsi_pkt,
6403  * i.e. scsi_pkt is not NULL.
6404  *
6405  * This function has to be called with cport mutex held. It does release
6406  * the mutex when it calls HBA driver sata_tran_start function and
6407  * re-acquires it afterwards.
6408  *
6409  * If return value is 0, pkt was accepted, -1 otherwise
6410  * rval is set to appropriate sata_scsi_start return value.
6411  *
6412  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6413  * have called the sata_pkt callback function for this packet.
6414  *
6415  * The scsi callback has to be performed by the caller of this routine.
6416  */
6417 static int
6418 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6419 {
6420 	int stat;
6421 	uint8_t cport = SATA_TXLT_CPORT(spx);
6422 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6423 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6424 	sata_drive_info_t *sdinfo;
6425 	sata_pmult_info_t *pminfo;
6426 	sata_pmport_info_t *pmportinfo = NULL;
6427 	sata_device_t *sata_device = NULL;
6428 	uint8_t cmd;
6429 	struct sata_cmd_flags cmd_flags;
6430 
6431 	ASSERT(spx->txlt_sata_pkt != NULL);
6432 
6433 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6434 
6435 	sdinfo = sata_get_device_info(sata_hba_inst,
6436 	    &spx->txlt_sata_pkt->satapkt_device);
6437 	ASSERT(sdinfo != NULL);
6438 
6439 	/* Clear device reset state? */
6440 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6441 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6442 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6443 
6444 		/*
6445 		 * Get the pmult_info of the its parent port multiplier, all
6446 		 * sub-devices share a common device reset flags on in
6447 		 * pmult_info.
6448 		 */
6449 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6450 		pmportinfo = pminfo->pmult_dev_port[pmport];
6451 		ASSERT(pminfo != NULL);
6452 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6453 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6454 			    sata_clear_dev_reset = B_TRUE;
6455 			pminfo->pmult_event_flags &=
6456 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6457 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6458 			    "sata_hba_start: clearing device reset state"
6459 			    "on pmult.\n", NULL);
6460 		}
6461 	} else {
6462 		if (sdinfo->satadrv_event_flags &
6463 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6464 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6465 			    sata_clear_dev_reset = B_TRUE;
6466 			sdinfo->satadrv_event_flags &=
6467 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6468 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6469 			    "sata_hba_start: clearing device reset state\n",
6470 			    NULL);
6471 		}
6472 	}
6473 
6474 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6475 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6476 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6477 
6478 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6479 
6480 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6481 	    "Sata cmd 0x%2x\n", cmd);
6482 
6483 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6484 	    spx->txlt_sata_pkt);
6485 
6486 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6487 	/*
6488 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6489 	 * with the sata callback, the sata_pkt could be already destroyed
6490 	 * by the time we check ther return status from the hba_start()
6491 	 * function, because sata_scsi_destroy_pkt() could have been already
6492 	 * called (perhaps in the interrupt context). So, in such case, there
6493 	 * should be no references to it. In other cases, sata_pkt still
6494 	 * exists.
6495 	 */
6496 	if (stat == SATA_TRAN_ACCEPTED) {
6497 		/*
6498 		 * pkt accepted for execution.
6499 		 * If it was executed synchronously, it is already completed
6500 		 * and pkt completion_reason indicates completion status.
6501 		 */
6502 		*rval = TRAN_ACCEPT;
6503 		return (0);
6504 	}
6505 
6506 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6507 	switch (stat) {
6508 	case SATA_TRAN_QUEUE_FULL:
6509 		/*
6510 		 * Controller detected queue full condition.
6511 		 */
6512 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6513 		    "sata_hba_start: queue full\n", NULL);
6514 
6515 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6516 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6517 
6518 		*rval = TRAN_BUSY;
6519 		break;
6520 
6521 	case SATA_TRAN_PORT_ERROR:
6522 		/*
6523 		 * Communication/link with device or general port error
6524 		 * detected before pkt execution begun.
6525 		 */
6526 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6527 		    SATA_ADDR_CPORT ||
6528 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6529 		    SATA_ADDR_DCPORT)
6530 			sata_log(sata_hba_inst, CE_CONT,
6531 			    "SATA port %d error",
6532 			    sata_device->satadev_addr.cport);
6533 		else
6534 			sata_log(sata_hba_inst, CE_CONT,
6535 			    "SATA port %d:%d error\n",
6536 			    sata_device->satadev_addr.cport,
6537 			    sata_device->satadev_addr.pmport);
6538 
6539 		/*
6540 		 * Update the port/device structure.
6541 		 * sata_pkt should be still valid. Since port error is
6542 		 * returned, sata_device content should reflect port
6543 		 * state - it means, that sata address have been changed,
6544 		 * because original packet's sata address refered to a device
6545 		 * attached to some port.
6546 		 */
6547 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6548 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6549 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6550 			mutex_enter(&pmportinfo->pmport_mutex);
6551 			sata_update_pmport_info(sata_hba_inst, sata_device);
6552 			mutex_exit(&pmportinfo->pmport_mutex);
6553 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6554 		} else {
6555 			sata_update_port_info(sata_hba_inst, sata_device);
6556 		}
6557 
6558 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6559 		*rval = TRAN_FATAL_ERROR;
6560 		break;
6561 
6562 	case SATA_TRAN_CMD_UNSUPPORTED:
6563 		/*
6564 		 * Command rejected by HBA as unsupported. It was HBA driver
6565 		 * that rejected the command, command was not sent to
6566 		 * an attached device.
6567 		 */
6568 		if ((sdinfo != NULL) &&
6569 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6570 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6571 			    "sat_hba_start: cmd 0x%2x rejected "
6572 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6573 
6574 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6575 		(void) sata_txlt_invalid_command(spx);
6576 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6577 
6578 		*rval = TRAN_ACCEPT;
6579 		break;
6580 
6581 	case SATA_TRAN_BUSY:
6582 		/*
6583 		 * Command rejected by HBA because other operation prevents
6584 		 * accepting the packet, or device is in RESET condition.
6585 		 */
6586 		if (sdinfo != NULL) {
6587 			sdinfo->satadrv_state =
6588 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6589 
6590 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6591 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6592 				    "sata_hba_start: cmd 0x%2x rejected "
6593 				    "because of device reset condition\n",
6594 				    cmd);
6595 			} else {
6596 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6597 				    "sata_hba_start: cmd 0x%2x rejected "
6598 				    "with SATA_TRAN_BUSY status\n",
6599 				    cmd);
6600 			}
6601 		}
6602 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6603 		*rval = TRAN_BUSY;
6604 		break;
6605 
6606 	default:
6607 		/* Unrecognized HBA response */
6608 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6609 		    "sata_hba_start: unrecognized HBA response "
6610 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6611 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6612 		*rval = TRAN_FATAL_ERROR;
6613 		break;
6614 	}
6615 
6616 	/*
6617 	 * If we got here, the packet was rejected.
6618 	 * Check if we need to remember reset state clearing request
6619 	 */
6620 	if (cmd_flags.sata_clear_dev_reset) {
6621 		/*
6622 		 * Check if device is still configured - it may have
6623 		 * disapeared from the configuration
6624 		 */
6625 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6626 		if (sdinfo != NULL) {
6627 			/*
6628 			 * Restore the flag that requests clearing of
6629 			 * the device reset state,
6630 			 * so the next sata packet may carry it to HBA.
6631 			 */
6632 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6633 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6634 				pminfo->pmult_event_flags |=
6635 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6636 			} else {
6637 				sdinfo->satadrv_event_flags |=
6638 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6639 			}
6640 		}
6641 	}
6642 	return (-1);
6643 }
6644 
6645 /*
6646  * Scsi response setup for invalid LBA
6647  *
6648  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6649  */
6650 static int
6651 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6652 {
6653 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6654 	struct scsi_extended_sense *sense;
6655 
6656 	scsipkt->pkt_reason = CMD_CMPLT;
6657 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6658 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6659 	*scsipkt->pkt_scbp = STATUS_CHECK;
6660 
6661 	*scsipkt->pkt_scbp = STATUS_CHECK;
6662 	sense = sata_arq_sense(spx);
6663 	sense->es_key = KEY_ILLEGAL_REQUEST;
6664 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6665 
6666 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6667 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6668 
6669 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6670 	    scsipkt->pkt_comp != NULL) {
6671 		/* scsi callback required */
6672 		if (servicing_interrupt()) {
6673 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6674 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6675 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6676 				return (TRAN_BUSY);
6677 			}
6678 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6679 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6680 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6681 			/* Scheduling the callback failed */
6682 			return (TRAN_BUSY);
6683 		}
6684 	}
6685 	return (TRAN_ACCEPT);
6686 }
6687 
6688 
6689 /*
6690  * Analyze device status and error registers and translate them into
6691  * appropriate scsi sense codes.
6692  * NOTE: non-packet commands only for now
6693  */
6694 static void
6695 sata_decode_device_error(sata_pkt_txlate_t *spx,
6696     struct scsi_extended_sense *sense)
6697 {
6698 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6699 
6700 	ASSERT(sense != NULL);
6701 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6702 	    SATA_STATUS_ERR);
6703 
6704 
6705 	if (err_reg & SATA_ERROR_ICRC) {
6706 		sense->es_key = KEY_ABORTED_COMMAND;
6707 		sense->es_add_code = 0x08; /* Communication failure */
6708 		return;
6709 	}
6710 
6711 	if (err_reg & SATA_ERROR_UNC) {
6712 		sense->es_key = KEY_MEDIUM_ERROR;
6713 		/* Information bytes (LBA) need to be set by a caller */
6714 		return;
6715 	}
6716 
6717 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6718 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6719 		sense->es_key = KEY_UNIT_ATTENTION;
6720 		sense->es_add_code = 0x3a; /* No media present */
6721 		return;
6722 	}
6723 
6724 	if (err_reg & SATA_ERROR_IDNF) {
6725 		if (err_reg & SATA_ERROR_ABORT) {
6726 			sense->es_key = KEY_ABORTED_COMMAND;
6727 		} else {
6728 			sense->es_key = KEY_ILLEGAL_REQUEST;
6729 			sense->es_add_code = 0x21; /* LBA out of range */
6730 		}
6731 		return;
6732 	}
6733 
6734 	if (err_reg & SATA_ERROR_ABORT) {
6735 		ASSERT(spx->txlt_sata_pkt != NULL);
6736 		sense->es_key = KEY_ABORTED_COMMAND;
6737 		return;
6738 	}
6739 }
6740 
6741 /*
6742  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6743  */
6744 static void
6745 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6746 {
6747 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6748 
6749 	*lba = 0;
6750 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6751 		*lba = sata_cmd->satacmd_lba_high_msb;
6752 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6753 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6754 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6755 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6756 	}
6757 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6758 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6759 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6760 }
6761 
6762 /*
6763  * This is fixed sense format - if LBA exceeds the info field size,
6764  * no valid info will be returned (valid bit in extended sense will
6765  * be set to 0).
6766  */
6767 static struct scsi_extended_sense *
6768 sata_arq_sense(sata_pkt_txlate_t *spx)
6769 {
6770 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6771 	struct scsi_arq_status *arqs;
6772 	struct scsi_extended_sense *sense;
6773 
6774 	/* Fill ARQ sense data */
6775 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6776 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6777 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6778 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6779 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6780 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6781 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6782 	arqs->sts_rqpkt_resid = 0;
6783 	sense = &arqs->sts_sensedata;
6784 	bzero(sense, sizeof (struct scsi_extended_sense));
6785 	sata_fixed_sense_data_preset(sense);
6786 	return (sense);
6787 }
6788 
6789 /*
6790  * ATA Pass Through support
6791  * Sets flags indicating that an invalid value was found in some
6792  * field in the command.  It could be something illegal according to
6793  * the SAT-2 spec or it could be a feature that is not (yet?)
6794  * supported.
6795  */
6796 static int
6797 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6798 {
6799 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6800 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6801 
6802 	scsipkt->pkt_reason = CMD_CMPLT;
6803 	*scsipkt->pkt_scbp = STATUS_CHECK;
6804 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6805 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6806 
6807 	sense = sata_arq_sense(spx);
6808 	sense->es_key = KEY_ILLEGAL_REQUEST;
6809 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6810 
6811 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6812 	    scsipkt->pkt_comp != NULL) {
6813 		/* scsi callback required */
6814 		if (servicing_interrupt()) {
6815 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6816 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6817 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6818 				return (TRAN_BUSY);
6819 			}
6820 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6821 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6822 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6823 			/* Scheduling the callback failed */
6824 			return (TRAN_BUSY);
6825 		}
6826 	}
6827 
6828 	return (TRAN_ACCEPT);
6829 }
6830 
6831 /*
6832  * Emulated SATA Read/Write command completion for zero-length requests.
6833  * This request always succedes, so in synchronous mode it always returns
6834  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6835  * callback cannot be scheduled.
6836  */
6837 static int
6838 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6839 {
6840 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6841 
6842 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6843 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6844 	scsipkt->pkt_reason = CMD_CMPLT;
6845 	*scsipkt->pkt_scbp = STATUS_GOOD;
6846 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6847 		/* scsi callback required - have to schedule it */
6848 		if (servicing_interrupt()) {
6849 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6850 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6851 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6852 				return (TRAN_BUSY);
6853 			}
6854 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6855 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6856 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6857 			/* Scheduling the callback failed */
6858 			return (TRAN_BUSY);
6859 		}
6860 	}
6861 	return (TRAN_ACCEPT);
6862 }
6863 
6864 
6865 /*
6866  * Translate completion status of SATA read/write commands into scsi response.
6867  * pkt completion_reason is checked to determine the completion status.
6868  * Do scsi callback if necessary.
6869  *
6870  * Note: this function may be called also for synchronously executed
6871  * commands.
6872  * This function may be used only if scsi_pkt is non-NULL.
6873  */
6874 static void
6875 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6876 {
6877 	sata_pkt_txlate_t *spx =
6878 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6879 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6880 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6881 	struct scsi_extended_sense *sense;
6882 	uint64_t lba;
6883 	struct buf *bp;
6884 	int rval;
6885 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6886 		/* Normal completion */
6887 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6888 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6889 		scsipkt->pkt_reason = CMD_CMPLT;
6890 		*scsipkt->pkt_scbp = STATUS_GOOD;
6891 		if (spx->txlt_tmp_buf != NULL) {
6892 			/* Temporary buffer was used */
6893 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6894 			if (bp->b_flags & B_READ) {
6895 				rval = ddi_dma_sync(
6896 				    spx->txlt_buf_dma_handle, 0, 0,
6897 				    DDI_DMA_SYNC_FORCPU);
6898 				ASSERT(rval == DDI_SUCCESS);
6899 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6900 				    bp->b_bcount);
6901 			}
6902 		}
6903 	} else {
6904 		/*
6905 		 * Something went wrong - analyze return
6906 		 */
6907 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6908 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6909 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6910 		*scsipkt->pkt_scbp = STATUS_CHECK;
6911 		sense = sata_arq_sense(spx);
6912 		ASSERT(sense != NULL);
6913 
6914 		/*
6915 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6916 		 * extract from device registers the failing LBA.
6917 		 */
6918 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6919 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6920 			    (scmd->satacmd_lba_mid_msb != 0 ||
6921 			    scmd->satacmd_lba_high_msb != 0)) {
6922 				/*
6923 				 * We have problem reporting this cmd LBA
6924 				 * in fixed sense data format, because of
6925 				 * the size of the scsi LBA fields.
6926 				 */
6927 				sense->es_valid = 0;
6928 			} else {
6929 				sata_extract_error_lba(spx, &lba);
6930 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6931 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6932 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6933 				sense->es_info_4 = lba & 0xFF;
6934 			}
6935 		} else {
6936 			/* Invalid extended sense info */
6937 			sense->es_valid = 0;
6938 		}
6939 
6940 		switch (sata_pkt->satapkt_reason) {
6941 		case SATA_PKT_PORT_ERROR:
6942 			/* We may want to handle DEV GONE state as well */
6943 			/*
6944 			 * We have no device data. Assume no data transfered.
6945 			 */
6946 			sense->es_key = KEY_HARDWARE_ERROR;
6947 			break;
6948 
6949 		case SATA_PKT_DEV_ERROR:
6950 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6951 			    SATA_STATUS_ERR) {
6952 				/*
6953 				 * determine dev error reason from error
6954 				 * reg content
6955 				 */
6956 				sata_decode_device_error(spx, sense);
6957 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6958 					switch (scmd->satacmd_cmd_reg) {
6959 					case SATAC_READ_DMA:
6960 					case SATAC_READ_DMA_EXT:
6961 					case SATAC_READ_DMA_QUEUED:
6962 					case SATAC_READ_DMA_QUEUED_EXT:
6963 					case SATAC_READ_FPDMA_QUEUED:
6964 						/* Unrecovered read error */
6965 						sense->es_add_code =
6966 						    SD_SCSI_ASC_UNREC_READ_ERR;
6967 						break;
6968 					case SATAC_WRITE_DMA:
6969 					case SATAC_WRITE_DMA_EXT:
6970 					case SATAC_WRITE_DMA_QUEUED:
6971 					case SATAC_WRITE_DMA_QUEUED_EXT:
6972 					case SATAC_WRITE_FPDMA_QUEUED:
6973 						/* Write error */
6974 						sense->es_add_code =
6975 						    SD_SCSI_ASC_WRITE_ERR;
6976 						break;
6977 					default:
6978 						/* Internal error */
6979 						SATA_LOG_D((
6980 						    spx->txlt_sata_hba_inst,
6981 						    CE_WARN,
6982 						    "sata_txlt_rw_completion :"
6983 						    "internal error - invalid "
6984 						    "command 0x%2x",
6985 						    scmd->satacmd_cmd_reg));
6986 						break;
6987 					}
6988 				}
6989 				break;
6990 			}
6991 			/* No extended sense key - no info available */
6992 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6993 			break;
6994 
6995 		case SATA_PKT_TIMEOUT:
6996 			scsipkt->pkt_reason = CMD_TIMEOUT;
6997 			scsipkt->pkt_statistics |=
6998 			    STAT_TIMEOUT | STAT_DEV_RESET;
6999 			sense->es_key = KEY_ABORTED_COMMAND;
7000 			break;
7001 
7002 		case SATA_PKT_ABORTED:
7003 			scsipkt->pkt_reason = CMD_ABORTED;
7004 			scsipkt->pkt_statistics |= STAT_ABORTED;
7005 			sense->es_key = KEY_ABORTED_COMMAND;
7006 			break;
7007 
7008 		case SATA_PKT_RESET:
7009 			scsipkt->pkt_reason = CMD_RESET;
7010 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7011 			sense->es_key = KEY_ABORTED_COMMAND;
7012 			break;
7013 
7014 		default:
7015 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7016 			    "sata_txlt_rw_completion: "
7017 			    "invalid packet completion reason"));
7018 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7019 			break;
7020 		}
7021 	}
7022 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7023 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7024 
7025 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7026 		/* scsi callback required */
7027 		scsi_hba_pkt_comp(scsipkt);
7028 }
7029 
7030 
7031 /*
7032  * Translate completion status of non-data commands (i.e. commands returning
7033  * no data).
7034  * pkt completion_reason is checked to determine the completion status.
7035  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7036  *
7037  * Note: this function may be called also for synchronously executed
7038  * commands.
7039  * This function may be used only if scsi_pkt is non-NULL.
7040  */
7041 
7042 static	void
7043 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7044 {
7045 	sata_pkt_txlate_t *spx =
7046 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7047 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7048 
7049 	sata_set_arq_data(sata_pkt);
7050 
7051 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7052 		/* scsi callback required */
7053 		scsi_hba_pkt_comp(scsipkt);
7054 }
7055 
7056 /*
7057  * Completion handler for ATA Pass Through command
7058  */
7059 static void
7060 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7061 {
7062 	sata_pkt_txlate_t *spx =
7063 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7064 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7065 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7066 	struct buf *bp;
7067 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7068 
7069 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7070 		/* Normal completion */
7071 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7072 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7073 		scsipkt->pkt_reason = CMD_CMPLT;
7074 		*scsipkt->pkt_scbp = STATUS_GOOD;
7075 
7076 		/*
7077 		 * If the command has CK_COND set
7078 		 */
7079 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7080 			*scsipkt->pkt_scbp = STATUS_CHECK;
7081 			sata_fill_ata_return_desc(sata_pkt,
7082 			    KEY_RECOVERABLE_ERROR,
7083 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
7084 		}
7085 
7086 		if (spx->txlt_tmp_buf != NULL) {
7087 			/* Temporary buffer was used */
7088 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7089 			if (bp->b_flags & B_READ) {
7090 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7091 				    bp->b_bcount);
7092 			}
7093 		}
7094 	} else {
7095 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7096 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7097 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7098 		*scsipkt->pkt_scbp = STATUS_CHECK;
7099 
7100 		/*
7101 		 * If DF or ERR was set, the HBA should have copied out the
7102 		 * status and error registers to the satacmd structure.
7103 		 */
7104 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7105 			sense_key = KEY_HARDWARE_ERROR;
7106 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7107 			addl_sense_qual = 0;
7108 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7109 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7110 				sense_key = KEY_NOT_READY;
7111 				addl_sense_code =
7112 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7113 				addl_sense_qual = 0;
7114 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7115 				sense_key = KEY_MEDIUM_ERROR;
7116 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7117 				addl_sense_qual = 0;
7118 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7119 				sense_key = KEY_DATA_PROTECT;
7120 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7121 				addl_sense_qual = 0;
7122 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7123 				sense_key = KEY_ILLEGAL_REQUEST;
7124 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7125 				addl_sense_qual = 0;
7126 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7127 				sense_key = KEY_ABORTED_COMMAND;
7128 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7129 				addl_sense_qual = 0;
7130 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7131 				sense_key = KEY_UNIT_ATTENTION;
7132 				addl_sense_code =
7133 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7134 				addl_sense_qual = 0;
7135 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7136 				sense_key = KEY_UNIT_ATTENTION;
7137 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7138 				addl_sense_qual = 0;
7139 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7140 				sense_key = KEY_ABORTED_COMMAND;
7141 				addl_sense_code =
7142 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7143 				addl_sense_qual = 0;
7144 			}
7145 		}
7146 
7147 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7148 		    addl_sense_qual);
7149 	}
7150 
7151 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7152 		/* scsi callback required */
7153 		scsi_hba_pkt_comp(scsipkt);
7154 }
7155 
7156 /*
7157  * j
7158  */
7159 static void
7160 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7161     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7162 {
7163 	sata_pkt_txlate_t *spx =
7164 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7165 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7166 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7167 	struct sata_apt_sense_data *apt_sd =
7168 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7169 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7170 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7171 	    &(apt_sd->apt_sd_sense);
7172 	int extend = 0;
7173 
7174 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7175 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7176 		extend = 1;
7177 
7178 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7179 
7180 	/* update the residual count */
7181 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7182 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7183 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7184 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7185 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7186 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7187 	    sizeof (struct sata_apt_sense_data);
7188 
7189 	/*
7190 	 * Fill in the Descriptor sense header
7191 	 */
7192 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7193 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7194 	sds->ds_class = CLASS_EXTENDED_SENSE;
7195 	sds->ds_key = sense_key & 0xf;
7196 	sds->ds_add_code = addl_sense_code;
7197 	sds->ds_qual_code = addl_sense_qual;
7198 	sds->ds_addl_sense_length =
7199 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7200 
7201 	/*
7202 	 * Fill in the ATA Return descriptor sense data
7203 	 */
7204 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7205 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7206 	ata_ret_desc->ars_addl_length = 0xc;
7207 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7208 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7209 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7210 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7211 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7212 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7213 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7214 
7215 	if (extend == 1) {
7216 		ata_ret_desc->ars_extend = 1;
7217 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7218 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7219 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7220 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7221 	} else {
7222 		ata_ret_desc->ars_extend = 0;
7223 		ata_ret_desc->ars_sec_count_msb = 0;
7224 		ata_ret_desc->ars_lba_low_msb = 0;
7225 		ata_ret_desc->ars_lba_mid_msb = 0;
7226 		ata_ret_desc->ars_lba_high_msb = 0;
7227 	}
7228 }
7229 
7230 static	void
7231 sata_set_arq_data(sata_pkt_t *sata_pkt)
7232 {
7233 	sata_pkt_txlate_t *spx =
7234 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7235 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7236 	struct scsi_extended_sense *sense;
7237 
7238 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7239 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7240 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7241 		/* Normal completion */
7242 		scsipkt->pkt_reason = CMD_CMPLT;
7243 		*scsipkt->pkt_scbp = STATUS_GOOD;
7244 	} else {
7245 		/* Something went wrong */
7246 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7247 		*scsipkt->pkt_scbp = STATUS_CHECK;
7248 		sense = sata_arq_sense(spx);
7249 		switch (sata_pkt->satapkt_reason) {
7250 		case SATA_PKT_PORT_ERROR:
7251 			/*
7252 			 * We have no device data. Assume no data transfered.
7253 			 */
7254 			sense->es_key = KEY_HARDWARE_ERROR;
7255 			break;
7256 
7257 		case SATA_PKT_DEV_ERROR:
7258 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7259 			    SATA_STATUS_ERR) {
7260 				/*
7261 				 * determine dev error reason from error
7262 				 * reg content
7263 				 */
7264 				sata_decode_device_error(spx, sense);
7265 				break;
7266 			}
7267 			/* No extended sense key - no info available */
7268 			break;
7269 
7270 		case SATA_PKT_TIMEOUT:
7271 			scsipkt->pkt_reason = CMD_TIMEOUT;
7272 			scsipkt->pkt_statistics |=
7273 			    STAT_TIMEOUT | STAT_DEV_RESET;
7274 			/* No extended sense key ? */
7275 			break;
7276 
7277 		case SATA_PKT_ABORTED:
7278 			scsipkt->pkt_reason = CMD_ABORTED;
7279 			scsipkt->pkt_statistics |= STAT_ABORTED;
7280 			/* No extended sense key ? */
7281 			break;
7282 
7283 		case SATA_PKT_RESET:
7284 			/* pkt aborted by an explicit reset from a host */
7285 			scsipkt->pkt_reason = CMD_RESET;
7286 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7287 			break;
7288 
7289 		default:
7290 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7291 			    "sata_txlt_nodata_cmd_completion: "
7292 			    "invalid packet completion reason %d",
7293 			    sata_pkt->satapkt_reason));
7294 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7295 			break;
7296 		}
7297 
7298 	}
7299 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7300 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7301 }
7302 
7303 
7304 /*
7305  * Build Mode sense R/W recovery page
7306  * NOT IMPLEMENTED
7307  */
7308 
7309 static int
7310 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7311 {
7312 #ifndef __lock_lint
7313 	_NOTE(ARGUNUSED(sdinfo))
7314 	_NOTE(ARGUNUSED(pcntrl))
7315 	_NOTE(ARGUNUSED(buf))
7316 #endif
7317 	return (0);
7318 }
7319 
7320 /*
7321  * Build Mode sense caching page  -  scsi-3 implementation.
7322  * Page length distinguishes previous format from scsi-3 format.
7323  * buf must have space for 0x12 bytes.
7324  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7325  *
7326  */
7327 static int
7328 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7329 {
7330 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7331 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7332 
7333 	/*
7334 	 * Most of the fields are set to 0, being not supported and/or disabled
7335 	 */
7336 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7337 
7338 	/* Saved paramters not supported */
7339 	if (pcntrl == 3)
7340 		return (0);
7341 	if (pcntrl == 0 || pcntrl == 2) {
7342 		/*
7343 		 * For now treat current and default parameters as same
7344 		 * That may have to change, if target driver will complain
7345 		 */
7346 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7347 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7348 
7349 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7350 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7351 			page->dra = 1;		/* Read Ahead disabled */
7352 			page->rcd = 1;		/* Read Cache disabled */
7353 		}
7354 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7355 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7356 			page->wce = 1;		/* Write Cache enabled */
7357 	} else {
7358 		/* Changeable parameters */
7359 		page->mode_page.code = MODEPAGE_CACHING;
7360 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7361 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7362 			page->dra = 1;
7363 			page->rcd = 1;
7364 		}
7365 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7366 			page->wce = 1;
7367 	}
7368 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7369 	    sizeof (struct mode_page));
7370 }
7371 
7372 /*
7373  * Build Mode sense exception cntrl page
7374  */
7375 static int
7376 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7377 {
7378 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7379 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7380 
7381 	/*
7382 	 * Most of the fields are set to 0, being not supported and/or disabled
7383 	 */
7384 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7385 
7386 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7387 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7388 
7389 	/* Indicate that this is page is saveable */
7390 	page->mode_page.ps = 1;
7391 
7392 	/*
7393 	 * We will return the same data for default, current and saved page.
7394 	 * The only changeable bit is dexcpt and that bit is required
7395 	 * by the ATA specification to be preserved across power cycles.
7396 	 */
7397 	if (pcntrl != 1) {
7398 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7399 		page->mrie = MRIE_ONLY_ON_REQUEST;
7400 	}
7401 	else
7402 		page->dexcpt = 1;	/* Only changeable parameter */
7403 
7404 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7405 }
7406 
7407 
7408 static int
7409 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7410 {
7411 	struct mode_acoustic_management *page =
7412 	    (struct mode_acoustic_management *)buf;
7413 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7414 
7415 	/*
7416 	 * Most of the fields are set to 0, being not supported and/or disabled
7417 	 */
7418 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7419 
7420 	switch (pcntrl) {
7421 	case P_CNTRL_DEFAULT:
7422 		/*  default paramters not supported */
7423 		return (0);
7424 
7425 	case P_CNTRL_CURRENT:
7426 	case P_CNTRL_SAVED:
7427 		/* Saved and current are supported and are identical */
7428 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7429 		page->mode_page.length =
7430 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7431 		page->mode_page.ps = 1;
7432 
7433 		/* Word 83 indicates if feature is supported */
7434 		/* If feature is not supported */
7435 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7436 			page->acoustic_manag_enable =
7437 			    ACOUSTIC_DISABLED;
7438 		} else {
7439 			page->acoustic_manag_enable =
7440 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7441 			    != 0);
7442 			/* Word 94 inidicates the value */
7443 #ifdef	_LITTLE_ENDIAN
7444 			page->acoustic_manag_level =
7445 			    (uchar_t)sata_id->ai_acoustic;
7446 			page->vendor_recommended_value =
7447 			    sata_id->ai_acoustic >> 8;
7448 #else
7449 			page->acoustic_manag_level =
7450 			    sata_id->ai_acoustic >> 8;
7451 			page->vendor_recommended_value =
7452 			    (uchar_t)sata_id->ai_acoustic;
7453 #endif
7454 		}
7455 		break;
7456 
7457 	case P_CNTRL_CHANGEABLE:
7458 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7459 		page->mode_page.length =
7460 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7461 		page->mode_page.ps = 1;
7462 
7463 		/* Word 83 indicates if the feature is supported */
7464 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7465 			page->acoustic_manag_enable =
7466 			    ACOUSTIC_ENABLED;
7467 			page->acoustic_manag_level = 0xff;
7468 		}
7469 		break;
7470 	}
7471 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7472 	    sizeof (struct mode_page));
7473 }
7474 
7475 
7476 /*
7477  * Build Mode sense power condition page.
7478  */
7479 static int
7480 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7481 {
7482 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7483 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7484 
7485 	/*
7486 	 * Most of the fields are set to 0, being not supported and/or disabled
7487 	 * power condition page length was 0x0a
7488 	 */
7489 	bzero(buf, sizeof (struct mode_info_power_cond));
7490 
7491 	if (pcntrl == P_CNTRL_DEFAULT) {
7492 		/*  default paramters not supported */
7493 		return (0);
7494 	}
7495 
7496 	page->mode_page.code = MODEPAGE_POWER_COND;
7497 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7498 
7499 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7500 		page->standby = 1;
7501 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7502 		    sizeof (uchar_t) * 4);
7503 	}
7504 
7505 	return (sizeof (struct mode_info_power_cond));
7506 }
7507 
7508 /*
7509  * Process mode select caching page 8 (scsi3 format only).
7510  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7511  * if these features are supported by the device. If these features are not
7512  * supported, the command will be terminated with STATUS_CHECK.
7513  * This function fails only if the SET FEATURE command sent to
7514  * the device fails. The page format is not varified, assuming that the
7515  * target driver operates correctly - if parameters length is too short,
7516  * we just drop the page.
7517  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7518  * setting have to be changed.
7519  * SET FEATURE command is executed synchronously, i.e. we wait here until
7520  * it is completed, regardless of the scsi pkt directives.
7521  *
7522  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7523  * changing DRA will change RCD.
7524  *
7525  * More than one SATA command may be executed to perform operations specified
7526  * by mode select pages. The first error terminates further execution.
7527  * Operations performed successully are not backed-up in such case.
7528  *
7529  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7530  * If operation resulted in changing device setup, dmod flag should be set to
7531  * one (1). If parameters were not changed, dmod flag should be set to 0.
7532  * Upon return, if operation required sending command to the device, the rval
7533  * should be set to the value returned by sata_hba_start. If operation
7534  * did not require device access, rval should be set to TRAN_ACCEPT.
7535  * The pagelen should be set to the length of the page.
7536  *
7537  * This function has to be called with a port mutex held.
7538  *
7539  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7540  */
7541 int
7542 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7543     int parmlen, int *pagelen, int *rval, int *dmod)
7544 {
7545 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7546 	sata_drive_info_t *sdinfo;
7547 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7548 	sata_id_t *sata_id;
7549 	struct scsi_extended_sense *sense;
7550 	int wce, dra;	/* Current settings */
7551 
7552 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7553 	    &spx->txlt_sata_pkt->satapkt_device);
7554 	sata_id = &sdinfo->satadrv_id;
7555 	*dmod = 0;
7556 
7557 	/* Verify parameters length. If too short, drop it */
7558 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7559 	    sizeof (struct mode_page)) > parmlen) {
7560 		*scsipkt->pkt_scbp = STATUS_CHECK;
7561 		sense = sata_arq_sense(spx);
7562 		sense->es_key = KEY_ILLEGAL_REQUEST;
7563 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7564 		*pagelen = parmlen;
7565 		*rval = TRAN_ACCEPT;
7566 		return (SATA_FAILURE);
7567 	}
7568 
7569 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7570 
7571 	/* Current setting of Read Ahead (and Read Cache) */
7572 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7573 		dra = 0;	/* 0 == not disabled */
7574 	else
7575 		dra = 1;
7576 	/* Current setting of Write Cache */
7577 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7578 		wce = 1;
7579 	else
7580 		wce = 0;
7581 
7582 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7583 		/* nothing to do */
7584 		*rval = TRAN_ACCEPT;
7585 		return (SATA_SUCCESS);
7586 	}
7587 
7588 	/*
7589 	 * Need to flip some setting
7590 	 * Set-up Internal SET FEATURES command(s)
7591 	 */
7592 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7593 	scmd->satacmd_addr_type = 0;
7594 	scmd->satacmd_device_reg = 0;
7595 	scmd->satacmd_status_reg = 0;
7596 	scmd->satacmd_error_reg = 0;
7597 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7598 	if (page->dra != dra || page->rcd != dra) {
7599 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7600 			/* Need to flip read ahead setting */
7601 			if (dra == 0)
7602 				/* Disable read ahead / read cache */
7603 				scmd->satacmd_features_reg =
7604 				    SATAC_SF_DISABLE_READ_AHEAD;
7605 			else
7606 				/* Enable read ahead  / read cache */
7607 				scmd->satacmd_features_reg =
7608 				    SATAC_SF_ENABLE_READ_AHEAD;
7609 
7610 			/* Transfer command to HBA */
7611 			if (sata_hba_start(spx, rval) != 0)
7612 				/*
7613 				 * Pkt not accepted for execution.
7614 				 */
7615 				return (SATA_FAILURE);
7616 
7617 			*dmod = 1;
7618 
7619 			/* Now process return */
7620 			if (spx->txlt_sata_pkt->satapkt_reason !=
7621 			    SATA_PKT_COMPLETED) {
7622 				goto failure;	/* Terminate */
7623 			}
7624 		} else {
7625 			*scsipkt->pkt_scbp = STATUS_CHECK;
7626 			sense = sata_arq_sense(spx);
7627 			sense->es_key = KEY_ILLEGAL_REQUEST;
7628 			sense->es_add_code =
7629 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7630 			*pagelen = parmlen;
7631 			*rval = TRAN_ACCEPT;
7632 			return (SATA_FAILURE);
7633 		}
7634 	}
7635 
7636 	/* Note that the packet is not removed, so it could be re-used */
7637 	if (page->wce != wce) {
7638 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7639 			/* Need to flip Write Cache setting */
7640 			if (page->wce == 1)
7641 				/* Enable write cache */
7642 				scmd->satacmd_features_reg =
7643 				    SATAC_SF_ENABLE_WRITE_CACHE;
7644 			else
7645 				/* Disable write cache */
7646 				scmd->satacmd_features_reg =
7647 				    SATAC_SF_DISABLE_WRITE_CACHE;
7648 
7649 			/* Transfer command to HBA */
7650 			if (sata_hba_start(spx, rval) != 0)
7651 				/*
7652 				 * Pkt not accepted for execution.
7653 				 */
7654 				return (SATA_FAILURE);
7655 
7656 			*dmod = 1;
7657 
7658 			/* Now process return */
7659 			if (spx->txlt_sata_pkt->satapkt_reason !=
7660 			    SATA_PKT_COMPLETED) {
7661 				goto failure;
7662 			}
7663 		} else {
7664 			*scsipkt->pkt_scbp = STATUS_CHECK;
7665 			sense = sata_arq_sense(spx);
7666 			sense->es_key = KEY_ILLEGAL_REQUEST;
7667 			sense->es_add_code =
7668 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7669 			*pagelen = parmlen;
7670 			*rval = TRAN_ACCEPT;
7671 			return (SATA_FAILURE);
7672 		}
7673 	}
7674 	return (SATA_SUCCESS);
7675 
7676 failure:
7677 	sata_xlate_errors(spx);
7678 
7679 	return (SATA_FAILURE);
7680 }
7681 
7682 /*
7683  * Process mode select informational exceptions control page 0x1c
7684  *
7685  * The only changeable bit is dexcpt (disable exceptions).
7686  * MRIE (method of reporting informational exceptions) must be
7687  * "only on request".
7688  * This page applies to informational exceptions that report
7689  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7690  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7691  * Informational exception conditions occur as the result of background scan
7692  * errors, background self-test errors, or vendor specific events within a
7693  * logical unit. An informational exception condition may occur asynchronous
7694  * to any commands.
7695  *
7696  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7697  * If operation resulted in changing device setup, dmod flag should be set to
7698  * one (1). If parameters were not changed, dmod flag should be set to 0.
7699  * Upon return, if operation required sending command to the device, the rval
7700  * should be set to the value returned by sata_hba_start. If operation
7701  * did not require device access, rval should be set to TRAN_ACCEPT.
7702  * The pagelen should be set to the length of the page.
7703  *
7704  * This function has to be called with a port mutex held.
7705  *
7706  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7707  *
7708  * Cannot be called in the interrupt context.
7709  */
7710 static	int
7711 sata_mode_select_page_1c(
7712 	sata_pkt_txlate_t *spx,
7713 	struct mode_info_excpt_page *page,
7714 	int parmlen,
7715 	int *pagelen,
7716 	int *rval,
7717 	int *dmod)
7718 {
7719 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7720 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7721 	sata_drive_info_t *sdinfo;
7722 	sata_id_t *sata_id;
7723 	struct scsi_extended_sense *sense;
7724 
7725 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7726 	    &spx->txlt_sata_pkt->satapkt_device);
7727 	sata_id = &sdinfo->satadrv_id;
7728 
7729 	*dmod = 0;
7730 
7731 	/* Verify parameters length. If too short, drop it */
7732 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7733 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7734 		*scsipkt->pkt_scbp = STATUS_CHECK;
7735 		sense = sata_arq_sense(spx);
7736 		sense->es_key = KEY_ILLEGAL_REQUEST;
7737 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7738 		*pagelen = parmlen;
7739 		*rval = TRAN_ACCEPT;
7740 		return (SATA_FAILURE);
7741 	}
7742 
7743 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7744 
7745 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7746 		*scsipkt->pkt_scbp = STATUS_CHECK;
7747 		sense = sata_arq_sense(spx);
7748 		sense->es_key = KEY_ILLEGAL_REQUEST;
7749 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7750 		*pagelen = parmlen;
7751 		*rval = TRAN_ACCEPT;
7752 		return (SATA_FAILURE);
7753 	}
7754 
7755 	/* If already in the state requested, we are done */
7756 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7757 		/* nothing to do */
7758 		*rval = TRAN_ACCEPT;
7759 		return (SATA_SUCCESS);
7760 	}
7761 
7762 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7763 
7764 	/* Build SMART_ENABLE or SMART_DISABLE command */
7765 	scmd->satacmd_addr_type = 0;		/* N/A */
7766 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7767 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7768 	scmd->satacmd_features_reg = page->dexcpt ?
7769 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7770 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7771 	scmd->satacmd_cmd_reg = SATAC_SMART;
7772 
7773 	/* Transfer command to HBA */
7774 	if (sata_hba_start(spx, rval) != 0)
7775 		/*
7776 		 * Pkt not accepted for execution.
7777 		 */
7778 		return (SATA_FAILURE);
7779 
7780 	*dmod = 1;	/* At least may have been modified */
7781 
7782 	/* Now process return */
7783 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7784 		return (SATA_SUCCESS);
7785 
7786 	/* Packet did not complete successfully */
7787 	sata_xlate_errors(spx);
7788 
7789 	return (SATA_FAILURE);
7790 }
7791 
7792 /*
7793  * Process mode select acoustic management control page 0x30
7794  *
7795  *
7796  * This function has to be called with a port mutex held.
7797  *
7798  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7799  *
7800  * Cannot be called in the interrupt context.
7801  */
7802 int
7803 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7804     mode_acoustic_management *page, int parmlen, int *pagelen,
7805     int *rval, int *dmod)
7806 {
7807 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7808 	sata_drive_info_t *sdinfo;
7809 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7810 	sata_id_t *sata_id;
7811 	struct scsi_extended_sense *sense;
7812 
7813 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7814 	    &spx->txlt_sata_pkt->satapkt_device);
7815 	sata_id = &sdinfo->satadrv_id;
7816 	*dmod = 0;
7817 
7818 	/* If parmlen is too short or the feature is not supported, drop it */
7819 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7820 	    sizeof (struct mode_page)) > parmlen) ||
7821 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7822 		*scsipkt->pkt_scbp = STATUS_CHECK;
7823 		sense = sata_arq_sense(spx);
7824 		sense->es_key = KEY_ILLEGAL_REQUEST;
7825 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7826 		*pagelen = parmlen;
7827 		*rval = TRAN_ACCEPT;
7828 		return (SATA_FAILURE);
7829 	}
7830 
7831 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7832 	    sizeof (struct mode_page);
7833 
7834 	/*
7835 	 * We can enable and disable acoustice management and
7836 	 * set the acoustic management level.
7837 	 */
7838 
7839 	/*
7840 	 * Set-up Internal SET FEATURES command(s)
7841 	 */
7842 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7843 	scmd->satacmd_addr_type = 0;
7844 	scmd->satacmd_device_reg = 0;
7845 	scmd->satacmd_status_reg = 0;
7846 	scmd->satacmd_error_reg = 0;
7847 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7848 	if (page->acoustic_manag_enable) {
7849 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7850 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7851 	} else {	/* disabling acoustic management */
7852 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7853 	}
7854 
7855 	/* Transfer command to HBA */
7856 	if (sata_hba_start(spx, rval) != 0)
7857 		/*
7858 		 * Pkt not accepted for execution.
7859 		 */
7860 		return (SATA_FAILURE);
7861 
7862 	/* Now process return */
7863 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7864 		sata_xlate_errors(spx);
7865 		return (SATA_FAILURE);
7866 	}
7867 
7868 	*dmod = 1;
7869 
7870 	return (SATA_SUCCESS);
7871 }
7872 
7873 /*
7874  * Process mode select power condition page 0x1a
7875  *
7876  * This function has to be called with a port mutex held.
7877  *
7878  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7879  *
7880  * Cannot be called in the interrupt context.
7881  */
7882 int
7883 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7884     mode_info_power_cond *page, int parmlen, int *pagelen,
7885     int *rval, int *dmod)
7886 {
7887 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7888 	sata_drive_info_t *sdinfo;
7889 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7890 	sata_id_t *sata_id;
7891 	struct scsi_extended_sense *sense;
7892 	uint8_t ata_count;
7893 	int i, len;
7894 
7895 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7896 	    &spx->txlt_sata_pkt->satapkt_device);
7897 	sata_id = &sdinfo->satadrv_id;
7898 	*dmod = 0;
7899 
7900 	len = sizeof (struct mode_info_power_cond);
7901 	len += sizeof (struct mode_page);
7902 
7903 	/* If parmlen is too short or the feature is not supported, drop it */
7904 	if ((len < parmlen) || (page->idle == 1) ||
7905 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7906 		*scsipkt->pkt_scbp = STATUS_CHECK;
7907 		sense = sata_arq_sense(spx);
7908 		sense->es_key = KEY_ILLEGAL_REQUEST;
7909 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7910 		*pagelen = parmlen;
7911 		*rval = TRAN_ACCEPT;
7912 		return (SATA_FAILURE);
7913 	}
7914 
7915 	*pagelen = len;
7916 
7917 	/*
7918 	 * Set-up Internal STANDBY command(s)
7919 	 */
7920 	if (page->standby == 0)
7921 		goto out;
7922 
7923 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7924 
7925 	scmd->satacmd_addr_type = 0;
7926 	scmd->satacmd_sec_count_lsb = ata_count;
7927 	scmd->satacmd_lba_low_lsb = 0;
7928 	scmd->satacmd_lba_mid_lsb = 0;
7929 	scmd->satacmd_lba_high_lsb = 0;
7930 	scmd->satacmd_features_reg = 0;
7931 	scmd->satacmd_device_reg = 0;
7932 	scmd->satacmd_status_reg = 0;
7933 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7934 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7935 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7936 
7937 	/* Transfer command to HBA */
7938 	if (sata_hba_start(spx, rval) != 0) {
7939 		return (SATA_FAILURE);
7940 	} else {
7941 		if ((scmd->satacmd_error_reg != 0) ||
7942 		    (spx->txlt_sata_pkt->satapkt_reason !=
7943 		    SATA_PKT_COMPLETED)) {
7944 			sata_xlate_errors(spx);
7945 			return (SATA_FAILURE);
7946 		}
7947 	}
7948 
7949 	for (i = 0; i < 4; i++) {
7950 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7951 	}
7952 out:
7953 	*dmod = 1;
7954 	return (SATA_SUCCESS);
7955 }
7956 
7957 /*
7958  * sata_build_lsense_page0() is used to create the
7959  * SCSI LOG SENSE page 0 (supported log pages)
7960  *
7961  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7962  * (supported log pages, self-test results, informational exceptions
7963  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7964  *
7965  * Takes a sata_drive_info t * and the address of a buffer
7966  * in which to create the page information.
7967  *
7968  * Returns the number of bytes valid in the buffer.
7969  */
7970 static	int
7971 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7972 {
7973 	struct log_parameter *lpp = (struct log_parameter *)buf;
7974 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7975 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7976 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7977 
7978 	lpp->param_code[0] = 0;
7979 	lpp->param_code[1] = 0;
7980 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7981 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7982 
7983 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7984 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7985 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7986 			++num_pages_supported;
7987 		}
7988 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7989 		++num_pages_supported;
7990 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7991 		++num_pages_supported;
7992 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7993 		++num_pages_supported;
7994 	}
7995 
7996 	lpp->param_len = num_pages_supported;
7997 
7998 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7999 	    num_pages_supported);
8000 }
8001 
8002 /*
8003  * sata_build_lsense_page_10() is used to create the
8004  * SCSI LOG SENSE page 0x10 (self-test results)
8005  *
8006  * Takes a sata_drive_info t * and the address of a buffer
8007  * in which to create the page information as well as a sata_hba_inst_t *.
8008  *
8009  * Returns the number of bytes valid in the buffer.
8010  *
8011  * Note: Self test and SMART data is accessible in device log pages.
8012  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8013  * of data can be transferred by a single command), or by the General Purpose
8014  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8015  * - approximately 33MB - can be transferred by a single command.
8016  * The SCT Command response (either error or command) is the same for both
8017  * the SMART and GPL methods of issuing commands.
8018  * This function uses READ LOG EXT command when drive supports LBA48, and
8019  * SMART READ command otherwise.
8020  *
8021  * Since above commands are executed in a synchronous mode, this function
8022  * should not be called in an interrupt context.
8023  */
8024 static	int
8025 sata_build_lsense_page_10(
8026 	sata_drive_info_t *sdinfo,
8027 	uint8_t *buf,
8028 	sata_hba_inst_t *sata_hba_inst)
8029 {
8030 	struct log_parameter *lpp = (struct log_parameter *)buf;
8031 	int rval;
8032 
8033 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8034 		struct smart_ext_selftest_log *ext_selftest_log;
8035 
8036 		ext_selftest_log = kmem_zalloc(
8037 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8038 
8039 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8040 		    ext_selftest_log, 0);
8041 		if (rval == 0) {
8042 			int index, start_index;
8043 			struct smart_ext_selftest_log_entry *entry;
8044 			static const struct smart_ext_selftest_log_entry empty =
8045 			    {0};
8046 			uint16_t block_num;
8047 			int count;
8048 			boolean_t only_one_block = B_FALSE;
8049 
8050 			index = ext_selftest_log->
8051 			    smart_ext_selftest_log_index[0];
8052 			index |= ext_selftest_log->
8053 			    smart_ext_selftest_log_index[1] << 8;
8054 			if (index == 0)
8055 				goto out;
8056 
8057 			--index;	/* Correct for 0 origin */
8058 			start_index = index;	/* remember where we started */
8059 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8060 			if (block_num != 0) {
8061 				rval = sata_ext_smart_selftest_read_log(
8062 				    sata_hba_inst, sdinfo, ext_selftest_log,
8063 				    block_num);
8064 				if (rval != 0)
8065 					goto out;
8066 			}
8067 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8068 			entry =
8069 			    &ext_selftest_log->
8070 			    smart_ext_selftest_log_entries[index];
8071 
8072 			for (count = 1;
8073 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8074 			    ++count) {
8075 				uint8_t status;
8076 				uint8_t code;
8077 				uint8_t sense_key;
8078 				uint8_t add_sense_code;
8079 				uint8_t add_sense_code_qual;
8080 
8081 				/* If this is an unused entry, we are done */
8082 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8083 					/* Broken firmware on some disks */
8084 					if (index + 1 ==
8085 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8086 						--entry;
8087 						--index;
8088 						if (bcmp(entry, &empty,
8089 						    sizeof (empty)) == 0)
8090 							goto out;
8091 					} else
8092 						goto out;
8093 				}
8094 
8095 				if (only_one_block &&
8096 				    start_index == index)
8097 					goto out;
8098 
8099 				lpp->param_code[0] = 0;
8100 				lpp->param_code[1] = count;
8101 				lpp->param_ctrl_flags =
8102 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8103 				lpp->param_len =
8104 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8105 
8106 				status = entry->smart_ext_selftest_log_status;
8107 				status >>= 4;
8108 				switch (status) {
8109 				case 0:
8110 				default:
8111 					sense_key = KEY_NO_SENSE;
8112 					add_sense_code =
8113 					    SD_SCSI_ASC_NO_ADD_SENSE;
8114 					add_sense_code_qual = 0;
8115 					break;
8116 				case 1:
8117 					sense_key = KEY_ABORTED_COMMAND;
8118 					add_sense_code =
8119 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8120 					add_sense_code_qual = SCSI_COMPONENT_81;
8121 					break;
8122 				case 2:
8123 					sense_key = KEY_ABORTED_COMMAND;
8124 					add_sense_code =
8125 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8126 					add_sense_code_qual = SCSI_COMPONENT_82;
8127 					break;
8128 				case 3:
8129 					sense_key = KEY_ABORTED_COMMAND;
8130 					add_sense_code =
8131 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8132 					add_sense_code_qual = SCSI_COMPONENT_83;
8133 					break;
8134 				case 4:
8135 					sense_key = KEY_HARDWARE_ERROR;
8136 					add_sense_code =
8137 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8138 					add_sense_code_qual = SCSI_COMPONENT_84;
8139 					break;
8140 				case 5:
8141 					sense_key = KEY_HARDWARE_ERROR;
8142 					add_sense_code =
8143 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8144 					add_sense_code_qual = SCSI_COMPONENT_85;
8145 					break;
8146 				case 6:
8147 					sense_key = KEY_HARDWARE_ERROR;
8148 					add_sense_code =
8149 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8150 					add_sense_code_qual = SCSI_COMPONENT_86;
8151 					break;
8152 				case 7:
8153 					sense_key = KEY_MEDIUM_ERROR;
8154 					add_sense_code =
8155 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8156 					add_sense_code_qual = SCSI_COMPONENT_87;
8157 					break;
8158 				case 8:
8159 					sense_key = KEY_HARDWARE_ERROR;
8160 					add_sense_code =
8161 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8162 					add_sense_code_qual = SCSI_COMPONENT_88;
8163 					break;
8164 				}
8165 				code = 0;	/* unspecified */
8166 				status |= (code << 4);
8167 				lpp->param_values[0] = status;
8168 				lpp->param_values[1] = 0; /* unspecified */
8169 				lpp->param_values[2] = entry->
8170 				    smart_ext_selftest_log_timestamp[1];
8171 				lpp->param_values[3] = entry->
8172 				    smart_ext_selftest_log_timestamp[0];
8173 				if (status != 0) {
8174 					lpp->param_values[4] = 0;
8175 					lpp->param_values[5] = 0;
8176 					lpp->param_values[6] = entry->
8177 					    smart_ext_selftest_log_failing_lba
8178 					    [5];
8179 					lpp->param_values[7] = entry->
8180 					    smart_ext_selftest_log_failing_lba
8181 					    [4];
8182 					lpp->param_values[8] = entry->
8183 					    smart_ext_selftest_log_failing_lba
8184 					    [3];
8185 					lpp->param_values[9] = entry->
8186 					    smart_ext_selftest_log_failing_lba
8187 					    [2];
8188 					lpp->param_values[10] = entry->
8189 					    smart_ext_selftest_log_failing_lba
8190 					    [1];
8191 					lpp->param_values[11] = entry->
8192 					    smart_ext_selftest_log_failing_lba
8193 					    [0];
8194 				} else {	/* No bad block address */
8195 					lpp->param_values[4] = 0xff;
8196 					lpp->param_values[5] = 0xff;
8197 					lpp->param_values[6] = 0xff;
8198 					lpp->param_values[7] = 0xff;
8199 					lpp->param_values[8] = 0xff;
8200 					lpp->param_values[9] = 0xff;
8201 					lpp->param_values[10] = 0xff;
8202 					lpp->param_values[11] = 0xff;
8203 				}
8204 
8205 				lpp->param_values[12] = sense_key;
8206 				lpp->param_values[13] = add_sense_code;
8207 				lpp->param_values[14] = add_sense_code_qual;
8208 				lpp->param_values[15] = 0; /* undefined */
8209 
8210 				lpp = (struct log_parameter *)
8211 				    (((uint8_t *)lpp) +
8212 				    SCSI_LOG_PARAM_HDR_LEN +
8213 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8214 
8215 				--index;	/* Back up to previous entry */
8216 				if (index < 0) {
8217 					if (block_num > 0) {
8218 						--block_num;
8219 					} else {
8220 						struct read_log_ext_directory
8221 						    logdir;
8222 
8223 						rval =
8224 						    sata_read_log_ext_directory(
8225 						    sata_hba_inst, sdinfo,
8226 						    &logdir);
8227 						if (rval == -1)
8228 							goto out;
8229 						if ((logdir.read_log_ext_vers
8230 						    [0] == 0) &&
8231 						    (logdir.read_log_ext_vers
8232 						    [1] == 0))
8233 							goto out;
8234 						block_num =
8235 						    logdir.read_log_ext_nblks
8236 						    [EXT_SMART_SELFTEST_LOG_PAGE
8237 						    - 1][0];
8238 						block_num |= logdir.
8239 						    read_log_ext_nblks
8240 						    [EXT_SMART_SELFTEST_LOG_PAGE
8241 						    - 1][1] << 8;
8242 						--block_num;
8243 						only_one_block =
8244 						    (block_num == 0);
8245 					}
8246 					rval = sata_ext_smart_selftest_read_log(
8247 					    sata_hba_inst, sdinfo,
8248 					    ext_selftest_log, block_num);
8249 					if (rval != 0)
8250 						goto out;
8251 
8252 					index =
8253 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8254 					    1;
8255 				}
8256 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8257 				entry = &ext_selftest_log->
8258 				    smart_ext_selftest_log_entries[index];
8259 			}
8260 		}
8261 out:
8262 		kmem_free(ext_selftest_log,
8263 		    sizeof (struct smart_ext_selftest_log));
8264 	} else {
8265 		struct smart_selftest_log *selftest_log;
8266 
8267 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8268 		    KM_SLEEP);
8269 
8270 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8271 		    selftest_log);
8272 
8273 		if (rval == 0) {
8274 			int index;
8275 			int count;
8276 			struct smart_selftest_log_entry *entry;
8277 			static const struct smart_selftest_log_entry empty =
8278 			    { 0 };
8279 
8280 			index = selftest_log->smart_selftest_log_index;
8281 			if (index == 0)
8282 				goto done;
8283 			--index;	/* Correct for 0 origin */
8284 			entry = &selftest_log->
8285 			    smart_selftest_log_entries[index];
8286 			for (count = 1;
8287 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8288 			    ++count) {
8289 				uint8_t status;
8290 				uint8_t code;
8291 				uint8_t sense_key;
8292 				uint8_t add_sense_code;
8293 				uint8_t add_sense_code_qual;
8294 
8295 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8296 					goto done;
8297 
8298 				lpp->param_code[0] = 0;
8299 				lpp->param_code[1] = count;
8300 				lpp->param_ctrl_flags =
8301 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8302 				lpp->param_len =
8303 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8304 
8305 				status = entry->smart_selftest_log_status;
8306 				status >>= 4;
8307 				switch (status) {
8308 				case 0:
8309 				default:
8310 					sense_key = KEY_NO_SENSE;
8311 					add_sense_code =
8312 					    SD_SCSI_ASC_NO_ADD_SENSE;
8313 					break;
8314 				case 1:
8315 					sense_key = KEY_ABORTED_COMMAND;
8316 					add_sense_code =
8317 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8318 					add_sense_code_qual = SCSI_COMPONENT_81;
8319 					break;
8320 				case 2:
8321 					sense_key = KEY_ABORTED_COMMAND;
8322 					add_sense_code =
8323 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8324 					add_sense_code_qual = SCSI_COMPONENT_82;
8325 					break;
8326 				case 3:
8327 					sense_key = KEY_ABORTED_COMMAND;
8328 					add_sense_code =
8329 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8330 					add_sense_code_qual = SCSI_COMPONENT_83;
8331 					break;
8332 				case 4:
8333 					sense_key = KEY_HARDWARE_ERROR;
8334 					add_sense_code =
8335 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8336 					add_sense_code_qual = SCSI_COMPONENT_84;
8337 					break;
8338 				case 5:
8339 					sense_key = KEY_HARDWARE_ERROR;
8340 					add_sense_code =
8341 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8342 					add_sense_code_qual = SCSI_COMPONENT_85;
8343 					break;
8344 				case 6:
8345 					sense_key = KEY_HARDWARE_ERROR;
8346 					add_sense_code =
8347 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8348 					add_sense_code_qual = SCSI_COMPONENT_86;
8349 					break;
8350 				case 7:
8351 					sense_key = KEY_MEDIUM_ERROR;
8352 					add_sense_code =
8353 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8354 					add_sense_code_qual = SCSI_COMPONENT_87;
8355 					break;
8356 				case 8:
8357 					sense_key = KEY_HARDWARE_ERROR;
8358 					add_sense_code =
8359 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8360 					add_sense_code_qual = SCSI_COMPONENT_88;
8361 					break;
8362 				}
8363 				code = 0;	/* unspecified */
8364 				status |= (code << 4);
8365 				lpp->param_values[0] = status;
8366 				lpp->param_values[1] = 0; /* unspecified */
8367 				lpp->param_values[2] = entry->
8368 				    smart_selftest_log_timestamp[1];
8369 				lpp->param_values[3] = entry->
8370 				    smart_selftest_log_timestamp[0];
8371 				if (status != 0) {
8372 					lpp->param_values[4] = 0;
8373 					lpp->param_values[5] = 0;
8374 					lpp->param_values[6] = 0;
8375 					lpp->param_values[7] = 0;
8376 					lpp->param_values[8] = entry->
8377 					    smart_selftest_log_failing_lba[3];
8378 					lpp->param_values[9] = entry->
8379 					    smart_selftest_log_failing_lba[2];
8380 					lpp->param_values[10] = entry->
8381 					    smart_selftest_log_failing_lba[1];
8382 					lpp->param_values[11] = entry->
8383 					    smart_selftest_log_failing_lba[0];
8384 				} else {	/* No block address */
8385 					lpp->param_values[4] = 0xff;
8386 					lpp->param_values[5] = 0xff;
8387 					lpp->param_values[6] = 0xff;
8388 					lpp->param_values[7] = 0xff;
8389 					lpp->param_values[8] = 0xff;
8390 					lpp->param_values[9] = 0xff;
8391 					lpp->param_values[10] = 0xff;
8392 					lpp->param_values[11] = 0xff;
8393 				}
8394 				lpp->param_values[12] = sense_key;
8395 				lpp->param_values[13] = add_sense_code;
8396 				lpp->param_values[14] = add_sense_code_qual;
8397 				lpp->param_values[15] = 0; /* undefined */
8398 
8399 				lpp = (struct log_parameter *)
8400 				    (((uint8_t *)lpp) +
8401 				    SCSI_LOG_PARAM_HDR_LEN +
8402 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8403 				--index;	/* back up to previous entry */
8404 				if (index < 0) {
8405 					index =
8406 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8407 				}
8408 				entry = &selftest_log->
8409 				    smart_selftest_log_entries[index];
8410 			}
8411 		}
8412 done:
8413 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8414 	}
8415 
8416 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8417 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8418 }
8419 
8420 /*
8421  * sata_build_lsense_page_2f() is used to create the
8422  * SCSI LOG SENSE page 0x2f (informational exceptions)
8423  *
8424  * Takes a sata_drive_info t * and the address of a buffer
8425  * in which to create the page information as well as a sata_hba_inst_t *.
8426  *
8427  * Returns the number of bytes valid in the buffer.
8428  *
8429  * Because it invokes function(s) that send synchronously executed command
8430  * to the HBA, it cannot be called in the interrupt context.
8431  */
8432 static	int
8433 sata_build_lsense_page_2f(
8434 	sata_drive_info_t *sdinfo,
8435 	uint8_t *buf,
8436 	sata_hba_inst_t *sata_hba_inst)
8437 {
8438 	struct log_parameter *lpp = (struct log_parameter *)buf;
8439 	int rval;
8440 	uint8_t *smart_data;
8441 	uint8_t temp;
8442 	sata_id_t *sata_id;
8443 #define	SMART_NO_TEMP	0xff
8444 
8445 	lpp->param_code[0] = 0;
8446 	lpp->param_code[1] = 0;
8447 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8448 
8449 	/* Now get the SMART status w.r.t. threshold exceeded */
8450 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8451 	switch (rval) {
8452 	case 1:
8453 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8454 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8455 		break;
8456 	case 0:
8457 	case -1:	/* failed to get data */
8458 		lpp->param_values[0] = 0;	/* No failure predicted */
8459 		lpp->param_values[1] = 0;
8460 		break;
8461 #if defined(SATA_DEBUG)
8462 	default:
8463 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8464 		/* NOTREACHED */
8465 #endif
8466 	}
8467 
8468 	sata_id = &sdinfo->satadrv_id;
8469 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8470 		temp = SMART_NO_TEMP;
8471 	else {
8472 		/* Now get the temperature */
8473 		smart_data = kmem_zalloc(512, KM_SLEEP);
8474 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8475 		    SCT_STATUS_LOG_PAGE, 1);
8476 		if (rval == -1)
8477 			temp = SMART_NO_TEMP;
8478 		else {
8479 			temp = smart_data[200];
8480 			if (temp & 0x80) {
8481 				if (temp & 0x7f)
8482 					temp = 0;
8483 				else
8484 					temp = SMART_NO_TEMP;
8485 			}
8486 		}
8487 		kmem_free(smart_data, 512);
8488 	}
8489 
8490 	lpp->param_values[2] = temp;	/* most recent temperature */
8491 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8492 
8493 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8494 
8495 
8496 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8497 }
8498 
8499 /*
8500  * sata_build_lsense_page_30() is used to create the
8501  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8502  *
8503  * Takes a sata_drive_info t * and the address of a buffer
8504  * in which to create the page information as well as a sata_hba_inst_t *.
8505  *
8506  * Returns the number of bytes valid in the buffer.
8507  */
8508 static int
8509 sata_build_lsense_page_30(
8510 	sata_drive_info_t *sdinfo,
8511 	uint8_t *buf,
8512 	sata_hba_inst_t *sata_hba_inst)
8513 {
8514 	struct smart_data *smart_data = (struct smart_data *)buf;
8515 	int rval;
8516 
8517 	/* Now do the SMART READ DATA */
8518 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8519 	if (rval == -1)
8520 		return (0);
8521 
8522 	return (sizeof (struct smart_data));
8523 }
8524 
8525 /*
8526  * sata_build_lsense_page_0e() is used to create the
8527  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8528  *
8529  * Date of Manufacture (0x0001)
8530  *	YEAR = "0000"
8531  *	WEEK = "00"
8532  * Accounting Date (0x0002)
8533  *	6 ASCII space character(20h)
8534  * Specified cycle count over device lifetime
8535  *	VALUE - THRESH - the delta between max and min;
8536  * Accumulated start-stop cycles
8537  *	VALUE - WORST - the accumulated cycles;
8538  *
8539  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8540  *
8541  * Takes a sata_drive_info t * and the address of a buffer
8542  * in which to create the page information as well as a sata_hba_inst_t *.
8543  *
8544  * Returns the number of bytes valid in the buffer.
8545  */
8546 static	int
8547 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8548 	sata_pkt_txlate_t *spx)
8549 {
8550 	struct start_stop_cycle_counter_log *log_page;
8551 	int i, rval, index;
8552 	uint8_t smart_data[512], id, value, worst, thresh;
8553 	uint32_t max_count, cycles;
8554 
8555 	/* Now do the SMART READ DATA */
8556 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8557 	    (struct smart_data *)smart_data);
8558 	if (rval == -1)
8559 		return (0);
8560 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8561 		index = (i * 12) + 2;
8562 		id = smart_data[index];
8563 		if (id != SMART_START_STOP_COUNT_ID)
8564 			continue;
8565 		else {
8566 			thresh = smart_data[index + 2];
8567 			value = smart_data[index + 3];
8568 			worst = smart_data[index + 4];
8569 			break;
8570 		}
8571 	}
8572 	if (id != SMART_START_STOP_COUNT_ID)
8573 		return (0);
8574 	max_count = value - thresh;
8575 	cycles = value - worst;
8576 
8577 	log_page = (struct start_stop_cycle_counter_log *)buf;
8578 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8579 	log_page->code = 0x0e;
8580 	log_page->page_len_low = 0x24;
8581 
8582 	log_page->manufactor_date_low = 0x1;
8583 	log_page->param_1.fmt_link = 0x1; /* 01b */
8584 	log_page->param_len_1 = 0x06;
8585 	for (i = 0; i < 4; i++) {
8586 		log_page->year_manu[i] = 0x30;
8587 		if (i < 2)
8588 			log_page->week_manu[i] = 0x30;
8589 	}
8590 
8591 	log_page->account_date_low = 0x02;
8592 	log_page->param_2.fmt_link = 0x01; /* 01b */
8593 	log_page->param_len_2 = 0x06;
8594 	for (i = 0; i < 4; i++) {
8595 		log_page->year_account[i] = 0x20;
8596 		if (i < 2)
8597 			log_page->week_account[i] = 0x20;
8598 	}
8599 
8600 	log_page->lifetime_code_low = 0x03;
8601 	log_page->param_3.fmt_link = 0x03; /* 11b */
8602 	log_page->param_len_3 = 0x04;
8603 	/* VALUE - THRESH - the delta between max and min */
8604 	log_page->cycle_code_low = 0x04;
8605 	log_page->param_4.fmt_link = 0x03; /* 11b */
8606 	log_page->param_len_4 = 0x04;
8607 	/* WORST - THRESH - the distance from 'now' to min */
8608 
8609 	for (i = 0; i < 4; i++) {
8610 		log_page->cycle_lifetime[i] =
8611 		    (max_count >> (8 * (3 - i))) & 0xff;
8612 		log_page->cycle_accumulated[i] =
8613 		    (cycles >> (8 * (3 - i))) & 0xff;
8614 	}
8615 
8616 	return (sizeof (struct start_stop_cycle_counter_log));
8617 }
8618 
8619 /*
8620  * This function was used for build a ATA read verify sector command
8621  */
8622 static void
8623 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8624 {
8625 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8626 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8627 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8628 
8629 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8630 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8631 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8632 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8633 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8634 	scmd->satacmd_features_reg = 0;
8635 	scmd->satacmd_status_reg = 0;
8636 	scmd->satacmd_error_reg = 0;
8637 }
8638 
8639 /*
8640  * This function was used for building an ATA
8641  * command, and only command register need to
8642  * be defined, other register will be zero or na.
8643  */
8644 static void
8645 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8646 {
8647 	scmd->satacmd_addr_type = 0;
8648 	scmd->satacmd_cmd_reg = cmd;
8649 	scmd->satacmd_device_reg = 0;
8650 	scmd->satacmd_sec_count_lsb = 0;
8651 	scmd->satacmd_lba_low_lsb = 0;
8652 	scmd->satacmd_lba_mid_lsb = 0;
8653 	scmd->satacmd_lba_high_lsb = 0;
8654 	scmd->satacmd_features_reg = 0;
8655 	scmd->satacmd_status_reg = 0;
8656 	scmd->satacmd_error_reg = 0;
8657 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8658 }
8659 
8660 /*
8661  * This function was used for changing the standby
8662  * timer format from SCSI to ATA.
8663  */
8664 static uint8_t
8665 sata_get_standby_timer(uint8_t *timer)
8666 {
8667 	uint32_t i = 0, count = 0;
8668 	uint8_t ata_count;
8669 
8670 	for (i = 0; i < 4; i++) {
8671 		count = count << 8 | timer[i];
8672 	}
8673 
8674 	if (count == 0)
8675 		return (0);
8676 
8677 	if (count >= 1 && count <= 12000)
8678 		ata_count = (count -1) / 50 + 1;
8679 	else if (count > 12000 && count <= 12600)
8680 		ata_count = 0xfc;
8681 	else if (count > 12601 && count <= 12750)
8682 		ata_count = 0xff;
8683 	else if (count > 12750 && count <= 17999)
8684 		ata_count = 0xf1;
8685 	else if (count > 18000 && count <= 198000)
8686 		ata_count = count / 18000 + 240;
8687 	else
8688 		ata_count = 0xfd;
8689 	return (ata_count);
8690 }
8691 
8692 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8693 
8694 /*
8695  * Start command for ATAPI device.
8696  * This function processes scsi_pkt requests.
8697  * Now CD/DVD, tape and ATAPI disk devices are supported.
8698  * Most commands are packet without any translation into Packet Command.
8699  * Some may be trapped and executed as SATA commands (not clear which one).
8700  *
8701  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8702  * execution).
8703  * Returns other TRAN_XXXX codes if command is not accepted or completed
8704  * (see return values for sata_hba_start()).
8705  *
8706  * Note:
8707  * Inquiry cdb format differs between transport version 2 and 3.
8708  * However, the transport version 3 devices that were checked did not adhere
8709  * to the specification (ignored MSB of the allocation length). Therefore,
8710  * the transport version is not checked, but Inquiry allocation length is
8711  * truncated to 255 bytes if the original allocation length set-up by the
8712  * target driver is greater than 255 bytes.
8713  */
8714 static int
8715 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8716 {
8717 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8718 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8719 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8720 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8721 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8722 	    &spx->txlt_sata_pkt->satapkt_device);
8723 	int cport = SATA_TXLT_CPORT(spx);
8724 	int cdblen;
8725 	int rval, reason;
8726 	int synch;
8727 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8728 
8729 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8730 
8731 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8732 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8733 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8734 		return (rval);
8735 	}
8736 
8737 	/*
8738 	 * ATAPI device executes some ATA commands in addition to those
8739 	 * commands sent via PACKET command. These ATA commands may be
8740 	 * executed by the regular SATA translation functions. None needs
8741 	 * to be captured now.
8742 	 *
8743 	 * Commands sent via PACKET command include:
8744 	 *	MMC command set for ATAPI CD/DVD device
8745 	 *	SSC command set for ATAPI TAPE device
8746 	 *	SBC command set for ATAPI disk device
8747 	 *
8748 	 */
8749 
8750 	/* Check the size of cdb */
8751 
8752 	switch (GETGROUP(cdbp)) {
8753 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
8754 		/*
8755 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
8756 		 * therefore require special handling.  Return failure, for now.
8757 		 */
8758 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8759 		return (TRAN_BADPKT);
8760 
8761 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
8762 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
8763 		/* obtain length from the scsi_pkt */
8764 		cdblen = scsipkt->pkt_cdblen;
8765 		break;
8766 
8767 	default:
8768 		/* CDB's length is statically known, per SPC-4 */
8769 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8770 		break;
8771 	}
8772 
8773 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
8774 		sata_log(NULL, CE_WARN,
8775 		    "sata: invalid ATAPI cdb length %d",
8776 		    cdblen);
8777 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8778 		return (TRAN_BADPKT);
8779 	}
8780 
8781 	SATAATAPITRACE(spx, cdblen);
8782 
8783 	/*
8784 	 * For non-read/write commands we need to
8785 	 * map buffer
8786 	 */
8787 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8788 	case SCMD_READ:
8789 	case SCMD_READ_G1:
8790 	case SCMD_READ_G5:
8791 	case SCMD_READ_G4:
8792 	case SCMD_WRITE:
8793 	case SCMD_WRITE_G1:
8794 	case SCMD_WRITE_G5:
8795 	case SCMD_WRITE_G4:
8796 		break;
8797 	default:
8798 		if (bp != NULL) {
8799 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8800 				bp_mapin(bp);
8801 		}
8802 		break;
8803 	}
8804 	/*
8805 	 * scmd->satacmd_flags.sata_data_direction default -
8806 	 * SATA_DIR_NODATA_XFER - is set by
8807 	 * sata_txlt_generic_pkt_info().
8808 	 */
8809 	if (scmd->satacmd_bp) {
8810 		if (scmd->satacmd_bp->b_flags & B_READ) {
8811 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8812 		} else {
8813 			scmd->satacmd_flags.sata_data_direction =
8814 			    SATA_DIR_WRITE;
8815 		}
8816 	}
8817 
8818 	/*
8819 	 * Set up ATAPI packet command.
8820 	 */
8821 
8822 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8823 
8824 	/* Copy cdb into sata_cmd */
8825 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8826 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8827 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8828 
8829 	/* See note in the command header */
8830 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8831 		if (scmd->satacmd_acdb[3] != 0)
8832 			scmd->satacmd_acdb[4] = 255;
8833 	}
8834 
8835 #ifdef SATA_DEBUG
8836 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8837 		uint8_t *p = scmd->satacmd_acdb;
8838 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8839 
8840 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8841 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8842 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8843 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8844 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8845 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8846 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8847 	}
8848 #endif
8849 
8850 	/*
8851 	 * Preset request sense data to NO SENSE.
8852 	 * If there is no way to get error information via Request Sense,
8853 	 * the packet request sense data would not have to be modified by HBA,
8854 	 * but it could be returned as is.
8855 	 */
8856 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8857 	sata_fixed_sense_data_preset(
8858 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8859 
8860 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8861 		/* Need callback function */
8862 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8863 		synch = FALSE;
8864 	} else
8865 		synch = TRUE;
8866 
8867 	/* Transfer command to HBA */
8868 	if (sata_hba_start(spx, &rval) != 0) {
8869 		/* Pkt not accepted for execution */
8870 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8871 		return (rval);
8872 	}
8873 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8874 	/*
8875 	 * If execution is non-synchronous,
8876 	 * a callback function will handle potential errors, translate
8877 	 * the response and will do a callback to a target driver.
8878 	 * If it was synchronous, use the same framework callback to check
8879 	 * an execution status.
8880 	 */
8881 	if (synch) {
8882 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8883 		    "synchronous execution status %x\n",
8884 		    spx->txlt_sata_pkt->satapkt_reason);
8885 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8886 	}
8887 	return (TRAN_ACCEPT);
8888 }
8889 
8890 
8891 /*
8892  * ATAPI Packet command completion.
8893  *
8894  * Failure of the command passed via Packet command are considered device
8895  * error. SATA HBA driver would have to retrieve error data (via Request
8896  * Sense command delivered via error retrieval sata packet) and copy it
8897  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8898  */
8899 static void
8900 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8901 {
8902 	sata_pkt_txlate_t *spx =
8903 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8904 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8905 	struct scsi_extended_sense *sense;
8906 	struct buf *bp;
8907 	int rval;
8908 
8909 #ifdef SATA_DEBUG
8910 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8911 #endif
8912 
8913 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8914 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8915 
8916 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8917 		/* Normal completion */
8918 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8919 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8920 		scsipkt->pkt_reason = CMD_CMPLT;
8921 		*scsipkt->pkt_scbp = STATUS_GOOD;
8922 		if (spx->txlt_tmp_buf != NULL) {
8923 			/* Temporary buffer was used */
8924 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8925 			if (bp->b_flags & B_READ) {
8926 				rval = ddi_dma_sync(
8927 				    spx->txlt_buf_dma_handle, 0, 0,
8928 				    DDI_DMA_SYNC_FORCPU);
8929 				ASSERT(rval == DDI_SUCCESS);
8930 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8931 				    bp->b_bcount);
8932 			}
8933 		}
8934 	} else {
8935 		/*
8936 		 * Something went wrong - analyze return
8937 		 */
8938 		*scsipkt->pkt_scbp = STATUS_CHECK;
8939 		sense = sata_arq_sense(spx);
8940 
8941 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8942 			/*
8943 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8944 			 * Under this condition ERR bit is set for ATA command,
8945 			 * and CHK bit set for ATAPI command.
8946 			 *
8947 			 * Please check st_intr & sdintr about how pkt_reason
8948 			 * is used.
8949 			 */
8950 			scsipkt->pkt_reason = CMD_CMPLT;
8951 
8952 			/*
8953 			 * We may not have ARQ data if there was a double
8954 			 * error. But sense data in sata packet was pre-set
8955 			 * with NO SENSE so it is valid even if HBA could
8956 			 * not retrieve a real sense data.
8957 			 * Just copy this sense data into scsi pkt sense area.
8958 			 */
8959 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8960 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8961 #ifdef SATA_DEBUG
8962 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8963 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8964 				    "sata_txlt_atapi_completion: %02x\n"
8965 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8966 				    "          %02x %02x %02x %02x %02x %02x "
8967 				    "          %02x %02x %02x %02x %02x %02x\n",
8968 				    scsipkt->pkt_reason,
8969 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8970 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8971 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8972 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8973 				    rqsp[16], rqsp[17]);
8974 			}
8975 #endif
8976 		} else {
8977 			switch (sata_pkt->satapkt_reason) {
8978 			case SATA_PKT_PORT_ERROR:
8979 				/*
8980 				 * We have no device data.
8981 				 */
8982 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8983 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8984 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8985 				    STATE_GOT_STATUS);
8986 				sense->es_key = KEY_HARDWARE_ERROR;
8987 				break;
8988 
8989 			case SATA_PKT_TIMEOUT:
8990 				scsipkt->pkt_reason = CMD_TIMEOUT;
8991 				scsipkt->pkt_statistics |=
8992 				    STAT_TIMEOUT | STAT_DEV_RESET;
8993 				/*
8994 				 * Need to check if HARDWARE_ERROR/
8995 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8996 				 * appropriate.
8997 				 */
8998 				break;
8999 
9000 			case SATA_PKT_ABORTED:
9001 				scsipkt->pkt_reason = CMD_ABORTED;
9002 				scsipkt->pkt_statistics |= STAT_ABORTED;
9003 				/* Should we set key COMMAND_ABPRTED? */
9004 				break;
9005 
9006 			case SATA_PKT_RESET:
9007 				scsipkt->pkt_reason = CMD_RESET;
9008 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9009 				/*
9010 				 * May be we should set Unit Attention /
9011 				 * Reset. Perhaps the same should be
9012 				 * returned for disks....
9013 				 */
9014 				sense->es_key = KEY_UNIT_ATTENTION;
9015 				sense->es_add_code = SD_SCSI_ASC_RESET;
9016 				break;
9017 
9018 			default:
9019 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9020 				    "sata_txlt_atapi_completion: "
9021 				    "invalid packet completion reason"));
9022 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9023 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9024 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9025 				    STATE_GOT_STATUS);
9026 				break;
9027 			}
9028 		}
9029 	}
9030 
9031 	SATAATAPITRACE(spx, 0);
9032 
9033 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9034 	    scsipkt->pkt_comp != NULL) {
9035 		/* scsi callback required */
9036 		(*scsipkt->pkt_comp)(scsipkt);
9037 	}
9038 }
9039 
9040 /*
9041  * Set up error retrieval sata command for ATAPI Packet Command error data
9042  * recovery.
9043  *
9044  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9045  * returns SATA_FAILURE otherwise.
9046  */
9047 
9048 static int
9049 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9050 {
9051 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9052 	sata_cmd_t *scmd;
9053 	struct buf *bp;
9054 
9055 	/*
9056 	 * Allocate dma-able buffer error data.
9057 	 * Buffer allocation will take care of buffer alignment and other DMA
9058 	 * attributes.
9059 	 */
9060 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9061 	if (bp == NULL) {
9062 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9063 		    "sata_get_err_retrieval_pkt: "
9064 		    "cannot allocate buffer for error data", NULL);
9065 		return (SATA_FAILURE);
9066 	}
9067 	bp_mapin(bp); /* make data buffer accessible */
9068 
9069 	/* Operation modes are up to the caller */
9070 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9071 
9072 	/* Synchronous mode, no callback - may be changed by the caller */
9073 	spkt->satapkt_comp = NULL;
9074 	spkt->satapkt_time = sata_default_pkt_time;
9075 
9076 	scmd = &spkt->satapkt_cmd;
9077 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9078 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9079 
9080 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9081 
9082 	/*
9083 	 * Set-up acdb. Request Sense CDB (packet command content) is
9084 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9085 	 * it is transfered into packet FIS).
9086 	 */
9087 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9088 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9089 	/* Following zeroing of pad bytes may not be necessary */
9090 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9091 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9092 
9093 	/*
9094 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9095 	 * before accessing it. Handle is in usual place in translate struct.
9096 	 */
9097 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9098 
9099 	/*
9100 	 * Preset request sense data to NO SENSE.
9101 	 * Here it is redundant, only for a symetry with scsi-originated
9102 	 * packets. It should not be used for anything but debugging.
9103 	 */
9104 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9105 	sata_fixed_sense_data_preset(
9106 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9107 
9108 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9109 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9110 
9111 	return (SATA_SUCCESS);
9112 }
9113 
9114 /*
9115  * Set-up ATAPI packet command.
9116  * Data transfer direction has to be set-up in sata_cmd structure prior to
9117  * calling this function.
9118  *
9119  * Returns void
9120  */
9121 
9122 static void
9123 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9124 {
9125 	scmd->satacmd_addr_type = 0;		/* N/A */
9126 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9127 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9128 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9129 	scmd->satacmd_lba_high_lsb =
9130 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9131 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9132 
9133 	/*
9134 	 * We want all data to be transfered via DMA.
9135 	 * But specify it only if drive supports DMA and DMA mode is
9136 	 * selected - some drives are sensitive about it.
9137 	 * Hopefully it wil work for all drives....
9138 	 */
9139 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9140 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9141 
9142 	/*
9143 	 * Features register requires special care for devices that use
9144 	 * Serial ATA bridge - they need an explicit specification of
9145 	 * the data transfer direction for Packet DMA commands.
9146 	 * Setting this bit is harmless if DMA is not used.
9147 	 *
9148 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9149 	 * spec they follow.
9150 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9151 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9152 	 * ATA/ATAPI-7 support is explicitly indicated.
9153 	 */
9154 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9155 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9156 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9157 		/*
9158 		 * Specification of major version is valid and version 7
9159 		 * is supported. It does automatically imply that all
9160 		 * spec features are supported. For now, we assume that
9161 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9162 		 */
9163 		if ((sdinfo->satadrv_id.ai_dirdma &
9164 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9165 			if (scmd->satacmd_flags.sata_data_direction ==
9166 			    SATA_DIR_READ)
9167 			scmd->satacmd_features_reg |=
9168 			    SATA_ATAPI_F_DATA_DIR_READ;
9169 		}
9170 	}
9171 }
9172 
9173 
9174 #ifdef SATA_DEBUG
9175 
9176 /* Display 18 bytes of Inquiry data */
9177 static void
9178 sata_show_inqry_data(uint8_t *buf)
9179 {
9180 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9181 	uint8_t *p;
9182 
9183 	cmn_err(CE_NOTE, "Inquiry data:");
9184 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9185 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9186 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9187 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9188 	    SATA_ATAPI_TRANS_VERSION(inq));
9189 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9190 	    inq->inq_rdf, inq->inq_aenc);
9191 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9192 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9193 	p = (uint8_t *)inq->inq_vid;
9194 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9195 	    "%02x %02x %02x %02x",
9196 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9197 	p = (uint8_t *)inq->inq_vid;
9198 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9199 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9200 
9201 	p = (uint8_t *)inq->inq_pid;
9202 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9203 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9204 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9205 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9206 	p = (uint8_t *)inq->inq_pid;
9207 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9208 	    "%c %c %c %c %c %c %c %c",
9209 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9210 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9211 
9212 	p = (uint8_t *)inq->inq_revision;
9213 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9214 	    p[0], p[1], p[2], p[3]);
9215 	p = (uint8_t *)inq->inq_revision;
9216 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9217 	    p[0], p[1], p[2], p[3]);
9218 
9219 }
9220 
9221 
9222 static void
9223 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9224 {
9225 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9226 
9227 	if (scsi_pkt == NULL)
9228 		return;
9229 	if (count != 0) {
9230 		/* saving cdb */
9231 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9232 		    SATA_ATAPI_MAX_CDB_LEN);
9233 		bcopy(scsi_pkt->pkt_cdbp,
9234 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9235 	} else {
9236 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9237 		    sts_sensedata,
9238 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9239 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9240 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9241 		    scsi_pkt->pkt_reason;
9242 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9243 		    spx->txlt_sata_pkt->satapkt_reason;
9244 
9245 		if (++sata_atapi_trace_index >= 64)
9246 			sata_atapi_trace_index = 0;
9247 	}
9248 }
9249 
9250 #endif
9251 
9252 /*
9253  * Fetch inquiry data from ATAPI device
9254  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9255  *
9256  * Note:
9257  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9258  * where the caller expects to see the inquiry data.
9259  *
9260  */
9261 
9262 static int
9263 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9264     sata_address_t *saddr, struct scsi_inquiry *inq)
9265 {
9266 	sata_pkt_txlate_t *spx;
9267 	sata_pkt_t *spkt;
9268 	struct buf *bp;
9269 	sata_drive_info_t *sdinfo;
9270 	sata_cmd_t *scmd;
9271 	int rval;
9272 	uint8_t *rqsp;
9273 #ifdef SATA_DEBUG
9274 	char msg_buf[MAXPATHLEN];
9275 #endif
9276 
9277 	ASSERT(sata_hba != NULL);
9278 
9279 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9280 	spx->txlt_sata_hba_inst = sata_hba;
9281 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9282 	spkt = sata_pkt_alloc(spx, NULL);
9283 	if (spkt == NULL) {
9284 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9285 		return (SATA_FAILURE);
9286 	}
9287 	/* address is needed now */
9288 	spkt->satapkt_device.satadev_addr = *saddr;
9289 
9290 	/* scsi_inquiry size buffer */
9291 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9292 	if (bp == NULL) {
9293 		sata_pkt_free(spx);
9294 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9295 		SATA_LOG_D((sata_hba, CE_WARN,
9296 		    "sata_get_atapi_inquiry_data: "
9297 		    "cannot allocate data buffer"));
9298 		return (SATA_FAILURE);
9299 	}
9300 	bp_mapin(bp); /* make data buffer accessible */
9301 
9302 	scmd = &spkt->satapkt_cmd;
9303 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9304 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9305 
9306 	/* Use synchronous mode */
9307 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9308 	spkt->satapkt_comp = NULL;
9309 	spkt->satapkt_time = sata_default_pkt_time;
9310 
9311 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9312 
9313 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9314 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9315 
9316 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9317 	sdinfo = sata_get_device_info(sata_hba,
9318 	    &spx->txlt_sata_pkt->satapkt_device);
9319 	if (sdinfo == NULL) {
9320 		/* we have to be carefull about the disapearing device */
9321 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9322 		rval = SATA_FAILURE;
9323 		goto cleanup;
9324 	}
9325 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9326 
9327 	/*
9328 	 * Set-up acdb. This works for atapi transport version 2 and later.
9329 	 */
9330 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9331 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9332 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9333 	scmd->satacmd_acdb[1] = 0x00;
9334 	scmd->satacmd_acdb[2] = 0x00;
9335 	scmd->satacmd_acdb[3] = 0x00;
9336 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9337 	scmd->satacmd_acdb[5] = 0x00;
9338 
9339 	sata_fixed_sense_data_preset(
9340 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9341 
9342 	/* Transfer command to HBA */
9343 	if (sata_hba_start(spx, &rval) != 0) {
9344 		/* Pkt not accepted for execution */
9345 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9346 		    "sata_get_atapi_inquiry_data: "
9347 		    "Packet not accepted for execution - ret: %02x", rval);
9348 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9349 		rval = SATA_FAILURE;
9350 		goto cleanup;
9351 	}
9352 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9353 
9354 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9355 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9356 		    "sata_get_atapi_inquiry_data: "
9357 		    "Packet completed successfully - ret: %02x", rval);
9358 		if (spx->txlt_buf_dma_handle != NULL) {
9359 			/*
9360 			 * Sync buffer. Handle is in usual place in translate
9361 			 * struct.
9362 			 */
9363 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9364 			    DDI_DMA_SYNC_FORCPU);
9365 			ASSERT(rval == DDI_SUCCESS);
9366 		}
9367 		/*
9368 		 * Normal completion - copy data into caller's buffer
9369 		 */
9370 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9371 		    sizeof (struct scsi_inquiry));
9372 #ifdef SATA_DEBUG
9373 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9374 			sata_show_inqry_data((uint8_t *)inq);
9375 		}
9376 #endif
9377 		rval = SATA_SUCCESS;
9378 	} else {
9379 		/*
9380 		 * Something went wrong - analyze return - check rqsense data
9381 		 */
9382 		rval = SATA_FAILURE;
9383 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9384 			/*
9385 			 * ARQ data hopefull show something other than NO SENSE
9386 			 */
9387 			rqsp = scmd->satacmd_rqsense;
9388 #ifdef SATA_DEBUG
9389 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9390 				msg_buf[0] = '\0';
9391 				(void) snprintf(msg_buf, MAXPATHLEN,
9392 				    "ATAPI packet completion reason: %02x\n"
9393 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9394 				    "          %02x %02x %02x %02x %02x %02x\n"
9395 				    "          %02x %02x %02x %02x %02x %02x",
9396 				    spkt->satapkt_reason,
9397 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9398 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9399 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9400 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9401 				    rqsp[16], rqsp[17]);
9402 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9403 				    "%s", msg_buf);
9404 			}
9405 #endif
9406 		} else {
9407 			switch (spkt->satapkt_reason) {
9408 			case SATA_PKT_PORT_ERROR:
9409 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9410 				    "sata_get_atapi_inquiry_data: "
9411 				    "packet reason: port error", NULL);
9412 				break;
9413 
9414 			case SATA_PKT_TIMEOUT:
9415 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9416 				    "sata_get_atapi_inquiry_data: "
9417 				    "packet reason: timeout", NULL);
9418 				break;
9419 
9420 			case SATA_PKT_ABORTED:
9421 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9422 				    "sata_get_atapi_inquiry_data: "
9423 				    "packet reason: aborted", NULL);
9424 				break;
9425 
9426 			case SATA_PKT_RESET:
9427 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9428 				    "sata_get_atapi_inquiry_data: "
9429 				    "packet reason: reset\n", NULL);
9430 				break;
9431 			default:
9432 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9433 				    "sata_get_atapi_inquiry_data: "
9434 				    "invalid packet reason: %02x\n",
9435 				    spkt->satapkt_reason);
9436 				break;
9437 			}
9438 		}
9439 	}
9440 cleanup:
9441 	sata_free_local_buffer(spx);
9442 	sata_pkt_free(spx);
9443 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9444 	return (rval);
9445 }
9446 
9447 
9448 
9449 
9450 
9451 #if 0
9452 #ifdef SATA_DEBUG
9453 
9454 /*
9455  * Test ATAPI packet command.
9456  * Single threaded test: send packet command in synch mode, process completion
9457  *
9458  */
9459 static void
9460 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9461 {
9462 	sata_pkt_txlate_t *spx;
9463 	sata_pkt_t *spkt;
9464 	struct buf *bp;
9465 	sata_device_t sata_device;
9466 	sata_drive_info_t *sdinfo;
9467 	sata_cmd_t *scmd;
9468 	int rval;
9469 	uint8_t *rqsp;
9470 
9471 	ASSERT(sata_hba_inst != NULL);
9472 	sata_device.satadev_addr.cport = cport;
9473 	sata_device.satadev_addr.pmport = 0;
9474 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9475 	sata_device.satadev_rev = SATA_DEVICE_REV;
9476 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9477 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9478 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9479 	if (sdinfo == NULL) {
9480 		sata_log(sata_hba_inst, CE_WARN,
9481 		    "sata_test_atapi_packet_command: "
9482 		    "no device info for cport %d",
9483 		    sata_device.satadev_addr.cport);
9484 		return;
9485 	}
9486 
9487 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9488 	spx->txlt_sata_hba_inst = sata_hba_inst;
9489 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9490 	spkt = sata_pkt_alloc(spx, NULL);
9491 	if (spkt == NULL) {
9492 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9493 		return;
9494 	}
9495 	/* address is needed now */
9496 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9497 
9498 	/* 1024k buffer */
9499 	bp = sata_alloc_local_buffer(spx, 1024);
9500 	if (bp == NULL) {
9501 		sata_pkt_free(spx);
9502 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9503 		sata_log(sata_hba_inst, CE_WARN,
9504 		    "sata_test_atapi_packet_command: "
9505 		    "cannot allocate data buffer");
9506 		return;
9507 	}
9508 	bp_mapin(bp); /* make data buffer accessible */
9509 
9510 	scmd = &spkt->satapkt_cmd;
9511 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9512 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9513 
9514 	/* Use synchronous mode */
9515 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9516 
9517 	/* Synchronous mode, no callback - may be changed by the caller */
9518 	spkt->satapkt_comp = NULL;
9519 	spkt->satapkt_time = sata_default_pkt_time;
9520 
9521 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9522 
9523 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9524 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9525 
9526 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9527 
9528 	/* Set-up acdb. */
9529 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9530 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9531 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9532 	scmd->satacmd_acdb[1] = 0x00;
9533 	scmd->satacmd_acdb[2] = 0x00;
9534 	scmd->satacmd_acdb[3] = 0x00;
9535 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9536 	scmd->satacmd_acdb[5] = 0x00;
9537 
9538 	sata_fixed_sense_data_preset(
9539 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9540 
9541 	/* Transfer command to HBA */
9542 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9543 	if (sata_hba_start(spx, &rval) != 0) {
9544 		/* Pkt not accepted for execution */
9545 		sata_log(sata_hba_inst, CE_WARN,
9546 		    "sata_test_atapi_packet_command: "
9547 		    "Packet not accepted for execution - ret: %02x", rval);
9548 		mutex_exit(
9549 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9550 		goto cleanup;
9551 	}
9552 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9553 
9554 	if (spx->txlt_buf_dma_handle != NULL) {
9555 		/*
9556 		 * Sync buffer. Handle is in usual place in translate struct.
9557 		 */
9558 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9559 		    DDI_DMA_SYNC_FORCPU);
9560 		ASSERT(rval == DDI_SUCCESS);
9561 	}
9562 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9563 		sata_log(sata_hba_inst, CE_WARN,
9564 		    "sata_test_atapi_packet_command: "
9565 		    "Packet completed successfully");
9566 		/*
9567 		 * Normal completion - show inquiry data
9568 		 */
9569 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9570 	} else {
9571 		/*
9572 		 * Something went wrong - analyze return - check rqsense data
9573 		 */
9574 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9575 			/*
9576 			 * ARQ data hopefull show something other than NO SENSE
9577 			 */
9578 			rqsp = scmd->satacmd_rqsense;
9579 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9580 			    "ATAPI packet completion reason: %02x\n"
9581 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9582 			    "          %02x %02x %02x %02x %02x %02x "
9583 			    "          %02x %02x %02x %02x %02x %02x\n",
9584 			    spkt->satapkt_reason,
9585 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9586 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9587 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9588 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9589 			    rqsp[16], rqsp[17]);
9590 		} else {
9591 			switch (spkt->satapkt_reason) {
9592 			case SATA_PKT_PORT_ERROR:
9593 				sata_log(sata_hba_inst, CE_WARN,
9594 				    "sata_test_atapi_packet_command: "
9595 				    "packet reason: port error\n");
9596 				break;
9597 
9598 			case SATA_PKT_TIMEOUT:
9599 				sata_log(sata_hba_inst, CE_WARN,
9600 				    "sata_test_atapi_packet_command: "
9601 				    "packet reason: timeout\n");
9602 				break;
9603 
9604 			case SATA_PKT_ABORTED:
9605 				sata_log(sata_hba_inst, CE_WARN,
9606 				    "sata_test_atapi_packet_command: "
9607 				    "packet reason: aborted\n");
9608 				break;
9609 
9610 			case SATA_PKT_RESET:
9611 				sata_log(sata_hba_inst, CE_WARN,
9612 				    "sata_test_atapi_packet_command: "
9613 				    "packet reason: reset\n");
9614 				break;
9615 			default:
9616 				sata_log(sata_hba_inst, CE_WARN,
9617 				    "sata_test_atapi_packet_command: "
9618 				    "invalid packet reason: %02x\n",
9619 				    spkt->satapkt_reason);
9620 				break;
9621 			}
9622 		}
9623 	}
9624 cleanup:
9625 	sata_free_local_buffer(spx);
9626 	sata_pkt_free(spx);
9627 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9628 }
9629 
9630 #endif /* SATA_DEBUG */
9631 #endif /* 1 */
9632 
9633 
9634 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9635 
9636 /*
9637  * Validate sata_tran info
9638  * SATA_FAILURE returns if structure is inconsistent or structure revision
9639  * does not match one used by the framework.
9640  *
9641  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9642  * required function pointers.
9643  * Returns SATA_FAILURE otherwise.
9644  */
9645 static int
9646 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9647 {
9648 	/*
9649 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9650 	 * of the SATA interface.
9651 	 */
9652 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9653 		sata_log(NULL, CE_WARN,
9654 		    "sata: invalid sata_hba_tran version %d for driver %s",
9655 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9656 		return (SATA_FAILURE);
9657 	}
9658 
9659 	if (dip != sata_tran->sata_tran_hba_dip) {
9660 		SATA_LOG_D((NULL, CE_WARN,
9661 		    "sata: inconsistent sata_tran_hba_dip "
9662 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9663 		return (SATA_FAILURE);
9664 	}
9665 
9666 	if (sata_tran->sata_tran_probe_port == NULL ||
9667 	    sata_tran->sata_tran_start == NULL ||
9668 	    sata_tran->sata_tran_abort == NULL ||
9669 	    sata_tran->sata_tran_reset_dport == NULL ||
9670 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9671 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9672 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9673 	    NULL) {
9674 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9675 		    "required functions"));
9676 	}
9677 	return (SATA_SUCCESS);
9678 }
9679 
9680 /*
9681  * Remove HBA instance from sata_hba_list.
9682  */
9683 static void
9684 sata_remove_hba_instance(dev_info_t *dip)
9685 {
9686 	sata_hba_inst_t	*sata_hba_inst;
9687 
9688 	mutex_enter(&sata_mutex);
9689 	for (sata_hba_inst = sata_hba_list;
9690 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9691 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9692 		if (sata_hba_inst->satahba_dip == dip)
9693 			break;
9694 	}
9695 
9696 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9697 #ifdef SATA_DEBUG
9698 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9699 		    "unknown HBA instance\n");
9700 #endif
9701 		ASSERT(FALSE);
9702 	}
9703 	if (sata_hba_inst == sata_hba_list) {
9704 		sata_hba_list = sata_hba_inst->satahba_next;
9705 		if (sata_hba_list) {
9706 			sata_hba_list->satahba_prev =
9707 			    (struct sata_hba_inst *)NULL;
9708 		}
9709 		if (sata_hba_inst == sata_hba_list_tail) {
9710 			sata_hba_list_tail = NULL;
9711 		}
9712 	} else if (sata_hba_inst == sata_hba_list_tail) {
9713 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9714 		if (sata_hba_list_tail) {
9715 			sata_hba_list_tail->satahba_next =
9716 			    (struct sata_hba_inst *)NULL;
9717 		}
9718 	} else {
9719 		sata_hba_inst->satahba_prev->satahba_next =
9720 		    sata_hba_inst->satahba_next;
9721 		sata_hba_inst->satahba_next->satahba_prev =
9722 		    sata_hba_inst->satahba_prev;
9723 	}
9724 	mutex_exit(&sata_mutex);
9725 }
9726 
9727 /*
9728  * Probe all SATA ports of the specified HBA instance.
9729  * The assumption is that there are no target and attachment point minor nodes
9730  * created by the boot subsystems, so we do not need to prune device tree.
9731  *
9732  * This function is called only from sata_hba_attach(). It does not have to
9733  * be protected by controller mutex, because the hba_attached flag is not set
9734  * yet and no one would be touching this HBA instance other than this thread.
9735  * Determines if port is active and what type of the device is attached
9736  * (if any). Allocates necessary structures for each port.
9737  *
9738  * An AP (Attachement Point) node is created for each SATA device port even
9739  * when there is no device attached.
9740  */
9741 
9742 static 	void
9743 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9744 {
9745 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9746 	int			ncport;
9747 	sata_cport_info_t 	*cportinfo;
9748 	sata_drive_info_t	*drive;
9749 	sata_device_t		sata_device;
9750 	int			rval;
9751 	dev_t			minor_number;
9752 	char			name[16];
9753 	clock_t			start_time, cur_time;
9754 
9755 	/*
9756 	 * Probe controller ports first, to find port status and
9757 	 * any port multiplier attached.
9758 	 */
9759 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9760 		/* allocate cport structure */
9761 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9762 		ASSERT(cportinfo != NULL);
9763 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9764 
9765 		mutex_enter(&cportinfo->cport_mutex);
9766 
9767 		cportinfo->cport_addr.cport = ncport;
9768 		cportinfo->cport_addr.pmport = 0;
9769 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9770 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9771 		cportinfo->cport_state |= SATA_STATE_PROBING;
9772 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9773 
9774 		/*
9775 		 * Regardless if a port is usable or not, create
9776 		 * an attachment point
9777 		 */
9778 		mutex_exit(&cportinfo->cport_mutex);
9779 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9780 		    ncport, 0, SATA_ADDR_CPORT);
9781 		(void) sprintf(name, "%d", ncport);
9782 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9783 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9784 		    DDI_SUCCESS) {
9785 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9786 			    "cannot create SATA attachment point for port %d",
9787 			    ncport);
9788 		}
9789 
9790 		/* Probe port */
9791 		start_time = ddi_get_lbolt();
9792 	reprobe_cport:
9793 		sata_device.satadev_addr.cport = ncport;
9794 		sata_device.satadev_addr.pmport = 0;
9795 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9796 		sata_device.satadev_rev = SATA_DEVICE_REV;
9797 
9798 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9799 		    (dip, &sata_device);
9800 
9801 		mutex_enter(&cportinfo->cport_mutex);
9802 		cportinfo->cport_scr = sata_device.satadev_scr;
9803 		if (rval != SATA_SUCCESS) {
9804 			/* Something went wrong? Fail the port */
9805 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9806 			mutex_exit(&cportinfo->cport_mutex);
9807 			continue;
9808 		}
9809 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9810 		cportinfo->cport_state |= SATA_STATE_PROBED;
9811 		cportinfo->cport_dev_type = sata_device.satadev_type;
9812 
9813 		cportinfo->cport_state |= SATA_STATE_READY;
9814 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9815 			mutex_exit(&cportinfo->cport_mutex);
9816 			continue;
9817 		}
9818 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9819 			/*
9820 			 * There is some device attached.
9821 			 * Allocate device info structure
9822 			 */
9823 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9824 				mutex_exit(&cportinfo->cport_mutex);
9825 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9826 				    kmem_zalloc(sizeof (sata_drive_info_t),
9827 				    KM_SLEEP);
9828 				mutex_enter(&cportinfo->cport_mutex);
9829 			}
9830 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9831 			drive->satadrv_addr = cportinfo->cport_addr;
9832 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9833 			drive->satadrv_type = cportinfo->cport_dev_type;
9834 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9835 
9836 			mutex_exit(&cportinfo->cport_mutex);
9837 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9838 			    SATA_SUCCESS) {
9839 				/*
9840 				 * Plugged device was not correctly identified.
9841 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9842 				 */
9843 				cur_time = ddi_get_lbolt();
9844 				if ((cur_time - start_time) <
9845 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9846 					/* sleep for a while */
9847 					delay(drv_usectohz(
9848 					    SATA_DEV_RETRY_DLY));
9849 					goto reprobe_cport;
9850 				}
9851 			}
9852 		} else { /* SATA_DTYPE_PMULT */
9853 			mutex_exit(&cportinfo->cport_mutex);
9854 
9855 			/* Allocate sata_pmult_info and sata_pmport_info */
9856 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9857 			    SATA_SUCCESS)
9858 				continue;
9859 
9860 			/* Log the information of the port multiplier */
9861 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9862 
9863 			/* Probe its pmports */
9864 			sata_probe_pmports(sata_hba_inst, ncport);
9865 		}
9866 	}
9867 }
9868 
9869 /*
9870  * Probe all device ports behind a port multiplier.
9871  *
9872  * PMult-related structure should be allocated before by sata_alloc_pmult().
9873  *
9874  * NOTE1: Only called from sata_probe_ports()
9875  * NOTE2: No mutex should be hold.
9876  */
9877 static void
9878 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9879 {
9880 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9881 	sata_pmult_info_t	*pmultinfo = NULL;
9882 	sata_pmport_info_t 	*pmportinfo = NULL;
9883 	sata_drive_info_t	*drive = NULL;
9884 	sata_device_t		sata_device;
9885 
9886 	clock_t			start_time, cur_time;
9887 	int			npmport;
9888 	int			rval;
9889 
9890 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9891 
9892 	/* Probe Port Multiplier ports */
9893 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9894 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9895 		start_time = ddi_get_lbolt();
9896 reprobe_pmport:
9897 		sata_device.satadev_addr.cport = ncport;
9898 		sata_device.satadev_addr.pmport = npmport;
9899 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9900 		sata_device.satadev_rev = SATA_DEVICE_REV;
9901 
9902 		/* Let HBA driver probe it. */
9903 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9904 		    (dip, &sata_device);
9905 		mutex_enter(&pmportinfo->pmport_mutex);
9906 
9907 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9908 
9909 		if (rval != SATA_SUCCESS) {
9910 			pmportinfo->pmport_state =
9911 			    SATA_PSTATE_FAILED;
9912 			mutex_exit(&pmportinfo->pmport_mutex);
9913 			continue;
9914 		}
9915 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9916 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9917 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9918 
9919 		pmportinfo->pmport_state |= SATA_STATE_READY;
9920 		if (pmportinfo->pmport_dev_type ==
9921 		    SATA_DTYPE_NONE) {
9922 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9923 			    "no device found at port %d:%d", ncport, npmport);
9924 			mutex_exit(&pmportinfo->pmport_mutex);
9925 			continue;
9926 		}
9927 		/* Port multipliers cannot be chained */
9928 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9929 		/*
9930 		 * There is something attached to Port
9931 		 * Multiplier device port
9932 		 * Allocate device info structure
9933 		 */
9934 		if (pmportinfo->pmport_sata_drive == NULL) {
9935 			mutex_exit(&pmportinfo->pmport_mutex);
9936 			pmportinfo->pmport_sata_drive =
9937 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9938 			mutex_enter(&pmportinfo->pmport_mutex);
9939 		}
9940 		drive = pmportinfo->pmport_sata_drive;
9941 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9942 		drive->satadrv_addr.pmport = npmport;
9943 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9944 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9945 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9946 
9947 		mutex_exit(&pmportinfo->pmport_mutex);
9948 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9949 
9950 		if (rval != SATA_SUCCESS) {
9951 			/*
9952 			 * Plugged device was not correctly identified.
9953 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9954 			 */
9955 			cur_time = ddi_get_lbolt();
9956 			if ((cur_time - start_time) < drv_usectohz(
9957 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9958 				/* sleep for a while */
9959 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9960 				goto reprobe_pmport;
9961 			}
9962 		}
9963 	}
9964 }
9965 
9966 /*
9967  * Add SATA device for specified HBA instance & port (SCSI target
9968  * device nodes).
9969  * This function is called (indirectly) only from sata_hba_attach().
9970  * A target node is created when there is a supported type device attached,
9971  * but may be removed if it cannot be put online.
9972  *
9973  * This function cannot be called from an interrupt context.
9974  *
9975  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9976  *
9977  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9978  * device identification failed - adding a device could be retried.
9979  *
9980  */
9981 static 	int
9982 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9983     sata_device_t *sata_device)
9984 {
9985 	sata_cport_info_t 	*cportinfo;
9986 	sata_pmult_info_t	*pminfo;
9987 	sata_pmport_info_t	*pmportinfo;
9988 	dev_info_t		*cdip;		/* child dip */
9989 	sata_address_t		*saddr = &sata_device->satadev_addr;
9990 	uint8_t			cport, pmport;
9991 	int			rval;
9992 
9993 	cport = saddr->cport;
9994 	pmport = saddr->pmport;
9995 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9996 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9997 
9998 	/*
9999 	 * Some device is attached to a controller port.
10000 	 * We rely on controllers distinquishing between no-device,
10001 	 * attached port multiplier and other kind of attached device.
10002 	 * We need to get Identify Device data and determine
10003 	 * positively the dev type before trying to attach
10004 	 * the target driver.
10005 	 */
10006 	sata_device->satadev_rev = SATA_DEVICE_REV;
10007 	switch (saddr->qual) {
10008 	case SATA_ADDR_CPORT:
10009 		/*
10010 		 * Add a non-port-multiplier device at controller port.
10011 		 */
10012 		saddr->qual = SATA_ADDR_DCPORT;
10013 
10014 		rval = sata_probe_device(sata_hba_inst, sata_device);
10015 		if (rval != SATA_SUCCESS ||
10016 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10017 			return (SATA_FAILURE);
10018 
10019 		mutex_enter(&cportinfo->cport_mutex);
10020 		sata_show_drive_info(sata_hba_inst,
10021 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10022 
10023 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10024 			/*
10025 			 * Could not determine device type or
10026 			 * a device is not supported.
10027 			 * Degrade this device to unknown.
10028 			 */
10029 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10030 			mutex_exit(&cportinfo->cport_mutex);
10031 			return (SATA_SUCCESS);
10032 		}
10033 		cportinfo->cport_dev_type = sata_device->satadev_type;
10034 		cportinfo->cport_tgtnode_clean = B_TRUE;
10035 		mutex_exit(&cportinfo->cport_mutex);
10036 
10037 		/*
10038 		 * Initialize device to the desired state. Even if it
10039 		 * fails, the device will still attach but syslog
10040 		 * will show the warning.
10041 		 */
10042 		if (sata_initialize_device(sata_hba_inst,
10043 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10044 			/* Retry */
10045 			rval = sata_initialize_device(sata_hba_inst,
10046 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10047 
10048 			if (rval == SATA_RETRY)
10049 				sata_log(sata_hba_inst, CE_WARN,
10050 				    "SATA device at port %d - "
10051 				    "default device features could not be set."
10052 				    " Device may not operate as expected.",
10053 				    cport);
10054 		}
10055 
10056 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10057 		if (cdip == NULL) {
10058 			/*
10059 			 * Attaching target node failed.
10060 			 * We retain sata_drive_info structure...
10061 			 */
10062 			return (SATA_SUCCESS);
10063 		}
10064 
10065 		mutex_enter(&cportinfo->cport_mutex);
10066 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10067 		    satadrv_state = SATA_STATE_READY;
10068 		mutex_exit(&cportinfo->cport_mutex);
10069 
10070 		break;
10071 
10072 	case SATA_ADDR_PMPORT:
10073 		saddr->qual = SATA_ADDR_DPMPORT;
10074 
10075 		mutex_enter(&cportinfo->cport_mutex);
10076 		/* It must be a Port Multiplier at the controller port */
10077 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10078 
10079 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10080 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10081 		mutex_exit(&cportinfo->cport_mutex);
10082 
10083 		rval = sata_probe_device(sata_hba_inst, sata_device);
10084 		if (rval != SATA_SUCCESS ||
10085 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10086 			return (SATA_FAILURE);
10087 		}
10088 
10089 		mutex_enter(&pmportinfo->pmport_mutex);
10090 		sata_show_drive_info(sata_hba_inst,
10091 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10092 
10093 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10094 			/*
10095 			 * Could not determine device type.
10096 			 * Degrade this device to unknown.
10097 			 */
10098 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10099 			mutex_exit(&pmportinfo->pmport_mutex);
10100 			return (SATA_SUCCESS);
10101 		}
10102 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10103 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10104 		mutex_exit(&pmportinfo->pmport_mutex);
10105 
10106 		/*
10107 		 * Initialize device to the desired state.
10108 		 * Even if it fails, the device will still
10109 		 * attach but syslog will show the warning.
10110 		 */
10111 		if (sata_initialize_device(sata_hba_inst,
10112 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10113 			/* Retry */
10114 			rval = sata_initialize_device(sata_hba_inst,
10115 			    pmportinfo->pmport_sata_drive);
10116 
10117 			if (rval == SATA_RETRY)
10118 				sata_log(sata_hba_inst, CE_WARN,
10119 				    "SATA device at port %d:%d - "
10120 				    "default device features could not be set."
10121 				    " Device may not operate as expected.",
10122 				    cport, pmport);
10123 		}
10124 
10125 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10126 		if (cdip == NULL) {
10127 			/*
10128 			 * Attaching target node failed.
10129 			 * We retain sata_drive_info structure...
10130 			 */
10131 			return (SATA_SUCCESS);
10132 		}
10133 		mutex_enter(&pmportinfo->pmport_mutex);
10134 		pmportinfo->pmport_sata_drive->satadrv_state |=
10135 		    SATA_STATE_READY;
10136 		mutex_exit(&pmportinfo->pmport_mutex);
10137 
10138 		break;
10139 
10140 	default:
10141 		return (SATA_FAILURE);
10142 	}
10143 
10144 	return (SATA_SUCCESS);
10145 }
10146 
10147 /*
10148  * Clean up target node at specific address.
10149  *
10150  * NOTE: No Mutex should be hold.
10151  */
10152 static int
10153 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10154     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10155 {
10156 	uint8_t cport, pmport, qual;
10157 	dev_info_t *tdip;
10158 
10159 	cport = sata_device->satadev_addr.cport;
10160 	pmport = sata_device->satadev_addr.pmport;
10161 	qual = sata_device->satadev_addr.qual;
10162 
10163 	if (qual == SATA_ADDR_DCPORT) {
10164 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10165 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10166 	} else {
10167 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10168 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10169 		    cport, pmport));
10170 	}
10171 
10172 	/* We are addressing attached device, not a port */
10173 	sata_device->satadev_addr.qual =
10174 	    sdinfo->satadrv_addr.qual;
10175 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10176 	    &sata_device->satadev_addr);
10177 	if (tdip != NULL && ndi_devi_offline(tdip,
10178 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10179 		/*
10180 		 * Problem :
10181 		 * The target node remained attached.
10182 		 * This happens when the device file was open
10183 		 * or a node was waiting for resources.
10184 		 * Cannot do anything about it.
10185 		 */
10186 		if (qual == SATA_ADDR_DCPORT) {
10187 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10188 			    "sata_hba_ioctl: disconnect: could "
10189 			    "not unconfigure device before "
10190 			    "disconnecting the SATA port %d",
10191 			    cport));
10192 		} else {
10193 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10194 			    "sata_hba_ioctl: disconnect: could "
10195 			    "not unconfigure device before "
10196 			    "disconnecting the SATA port %d:%d",
10197 			    cport, pmport));
10198 		}
10199 		/*
10200 		 * Set DEVICE REMOVED state in the target
10201 		 * node. It will prevent access to the device
10202 		 * even when a new device is attached, until
10203 		 * the old target node is released, removed and
10204 		 * recreated for a new  device.
10205 		 */
10206 		sata_set_device_removed(tdip);
10207 
10208 		/*
10209 		 * Instruct event daemon to try the target
10210 		 * node cleanup later.
10211 		 */
10212 		sata_set_target_node_cleanup(
10213 		    sata_hba_inst, &sata_device->satadev_addr);
10214 	}
10215 
10216 
10217 	return (SATA_SUCCESS);
10218 }
10219 
10220 
10221 /*
10222  * Create scsi target node for attached device, create node properties and
10223  * attach the node.
10224  * The node could be removed if the device onlining fails.
10225  *
10226  * A dev_info_t pointer is returned if operation is successful, NULL is
10227  * returned otherwise.
10228  */
10229 
10230 static dev_info_t *
10231 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10232 			sata_address_t *sata_addr)
10233 {
10234 	dev_info_t *cdip = NULL;
10235 	int rval;
10236 	char *nname = NULL;
10237 	char **compatible = NULL;
10238 	int ncompatible;
10239 	struct scsi_inquiry inq;
10240 	sata_device_t sata_device;
10241 	sata_drive_info_t *sdinfo;
10242 	int target;
10243 	int i;
10244 
10245 	sata_device.satadev_rev = SATA_DEVICE_REV;
10246 	sata_device.satadev_addr = *sata_addr;
10247 
10248 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10249 
10250 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10251 
10252 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10253 	    sata_addr->pmport, sata_addr->qual);
10254 
10255 	if (sdinfo == NULL) {
10256 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10257 		    sata_addr->cport)));
10258 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10259 		    "sata_create_target_node: no sdinfo for target %x",
10260 		    target));
10261 		return (NULL);
10262 	}
10263 
10264 	/*
10265 	 * create or get scsi inquiry data, expected by
10266 	 * scsi_hba_nodename_compatible_get()
10267 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10268 	 * ATAPI devices respond directly to Inquiry request.
10269 	 */
10270 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10271 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10272 		    (uint8_t *)&inq);
10273 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10274 		    sata_addr->cport)));
10275 	} else { /* Assume supported ATAPI device */
10276 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10277 		    sata_addr->cport)));
10278 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10279 		    &inq) == SATA_FAILURE)
10280 			return (NULL);
10281 		/*
10282 		 * Save supported ATAPI transport version
10283 		 */
10284 		sdinfo->satadrv_atapi_trans_ver =
10285 		    SATA_ATAPI_TRANS_VERSION(&inq);
10286 	}
10287 
10288 	/* determine the node name and compatible */
10289 	scsi_hba_nodename_compatible_get(&inq, NULL,
10290 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10291 
10292 #ifdef SATA_DEBUG
10293 	if (sata_debug_flags & SATA_DBG_NODES) {
10294 		if (nname == NULL) {
10295 			cmn_err(CE_NOTE, "sata_create_target_node: "
10296 			    "cannot determine nodename for target %d\n",
10297 			    target);
10298 		} else {
10299 			cmn_err(CE_WARN, "sata_create_target_node: "
10300 			    "target %d nodename: %s\n", target, nname);
10301 		}
10302 		if (compatible == NULL) {
10303 			cmn_err(CE_WARN,
10304 			    "sata_create_target_node: no compatible name\n");
10305 		} else {
10306 			for (i = 0; i < ncompatible; i++) {
10307 				cmn_err(CE_WARN, "sata_create_target_node: "
10308 				    "compatible name: %s\n", compatible[i]);
10309 			}
10310 		}
10311 	}
10312 #endif
10313 
10314 	/* if nodename can't be determined, log error and exit */
10315 	if (nname == NULL) {
10316 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10317 		    "sata_create_target_node: cannot determine nodename "
10318 		    "for target %d\n", target));
10319 		scsi_hba_nodename_compatible_free(nname, compatible);
10320 		return (NULL);
10321 	}
10322 	/*
10323 	 * Create scsi target node
10324 	 */
10325 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10326 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10327 	    "device-type", "scsi");
10328 
10329 	if (rval != DDI_PROP_SUCCESS) {
10330 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10331 		    "updating device_type prop failed %d", rval));
10332 		goto fail;
10333 	}
10334 
10335 	/*
10336 	 * Create target node properties: target & lun
10337 	 */
10338 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10339 	if (rval != DDI_PROP_SUCCESS) {
10340 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10341 		    "updating target prop failed %d", rval));
10342 		goto fail;
10343 	}
10344 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10345 	if (rval != DDI_PROP_SUCCESS) {
10346 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10347 		    "updating target prop failed %d", rval));
10348 		goto fail;
10349 	}
10350 
10351 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10352 		/*
10353 		 * Add "variant" property
10354 		 */
10355 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10356 		    "variant", "atapi");
10357 		if (rval != DDI_PROP_SUCCESS) {
10358 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10359 			    "sata_create_target_node: variant atapi "
10360 			    "property could not be created: %d", rval));
10361 			goto fail;
10362 		}
10363 	}
10364 	/* decorate the node with compatible */
10365 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10366 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10367 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10368 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10369 		    (void *)cdip));
10370 		goto fail;
10371 	}
10372 
10373 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10374 		/*
10375 		 * Add "sata-phy" property
10376 		 */
10377 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
10378 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
10379 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10380 			    "sata_create_target_node: failed to create "
10381 			    "\"sata-phy\" property: port %d",
10382 			    sata_addr->cport));
10383 		}
10384 	}
10385 
10386 
10387 	/*
10388 	 * Now, try to attach the driver. If probing of the device fails,
10389 	 * the target node may be removed
10390 	 */
10391 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10392 
10393 	scsi_hba_nodename_compatible_free(nname, compatible);
10394 
10395 	if (rval == NDI_SUCCESS)
10396 		return (cdip);
10397 
10398 	/* target node was removed - are we sure? */
10399 	return (NULL);
10400 
10401 fail:
10402 	scsi_hba_nodename_compatible_free(nname, compatible);
10403 	ddi_prop_remove_all(cdip);
10404 	rval = ndi_devi_free(cdip);
10405 	if (rval != NDI_SUCCESS) {
10406 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10407 		    "node removal failed %d", rval));
10408 	}
10409 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10410 	    "cannot create target node for SATA device at port %d",
10411 	    sata_addr->cport);
10412 	return (NULL);
10413 }
10414 
10415 /*
10416  * Remove a target node.
10417  */
10418 static void
10419 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10420 			sata_address_t *sata_addr)
10421 {
10422 	dev_info_t *tdip;
10423 	uint8_t cport = sata_addr->cport;
10424 	uint8_t pmport = sata_addr->pmport;
10425 	uint8_t qual = sata_addr->qual;
10426 
10427 	/* Note the sata daemon uses the address of the port/pmport */
10428 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10429 
10430 	/* Remove target node */
10431 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10432 	if (tdip != NULL) {
10433 		/*
10434 		 * Target node exists.  Unconfigure device
10435 		 * then remove the target node (one ndi
10436 		 * operation).
10437 		 */
10438 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10439 			/*
10440 			 * PROBLEM - no device, but target node remained. This
10441 			 * happens when the file was open or node was waiting
10442 			 * for resources.
10443 			 */
10444 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10445 			    "sata_remove_target_node: "
10446 			    "Failed to remove target node for "
10447 			    "detached SATA device."));
10448 			/*
10449 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10450 			 * re-check first that the node still exists.
10451 			 */
10452 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10453 			    cport, pmport);
10454 			if (tdip != NULL) {
10455 				sata_set_device_removed(tdip);
10456 				/*
10457 				 * Instruct event daemon to retry the cleanup
10458 				 * later.
10459 				 */
10460 				sata_set_target_node_cleanup(sata_hba_inst,
10461 				    sata_addr);
10462 			}
10463 		}
10464 
10465 		if (qual == SATA_ADDR_CPORT)
10466 			sata_log(sata_hba_inst, CE_WARN,
10467 			    "SATA device detached at port %d", cport);
10468 		else
10469 			sata_log(sata_hba_inst, CE_WARN,
10470 			    "SATA device detached at port %d:%d",
10471 			    cport, pmport);
10472 	}
10473 #ifdef SATA_DEBUG
10474 	else {
10475 		if (qual == SATA_ADDR_CPORT)
10476 			sata_log(sata_hba_inst, CE_WARN,
10477 			    "target node not found at port %d", cport);
10478 		else
10479 			sata_log(sata_hba_inst, CE_WARN,
10480 			    "target node not found at port %d:%d",
10481 			    cport, pmport);
10482 	}
10483 #endif
10484 }
10485 
10486 
10487 /*
10488  * Re-probe sata port, check for a device and attach info
10489  * structures when necessary. Identify Device data is fetched, if possible.
10490  * Assumption: sata address is already validated.
10491  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10492  * the presence of a device and its type.
10493  *
10494  * flag arg specifies that the function should try multiple times to identify
10495  * device type and to initialize it, or it should return immediately on failure.
10496  * SATA_DEV_IDENTIFY_RETRY - retry
10497  * SATA_DEV_IDENTIFY_NORETRY - no retry
10498  *
10499  * SATA_FAILURE is returned if one of the operations failed.
10500  *
10501  * This function cannot be called in interrupt context - it may sleep.
10502  *
10503  * Note: Port multiplier is supported.
10504  */
10505 static int
10506 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10507     int flag)
10508 {
10509 	sata_cport_info_t *cportinfo;
10510 	sata_pmult_info_t *pmultinfo;
10511 	sata_drive_info_t *sdinfo, *osdinfo;
10512 	boolean_t init_device = B_FALSE;
10513 	int prev_device_type = SATA_DTYPE_NONE;
10514 	int prev_device_settings = 0;
10515 	int prev_device_state = 0;
10516 	clock_t start_time;
10517 	int retry = B_FALSE;
10518 	uint8_t cport = sata_device->satadev_addr.cport;
10519 	int rval_probe, rval_init;
10520 
10521 	/*
10522 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10523 	 */
10524 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10525 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10526 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10527 
10528 	/* We only care about host sata cport for now */
10529 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10530 	    sata_device->satadev_addr.cport);
10531 
10532 	/*
10533 	 * If a port multiplier was previously attached (we have no idea it
10534 	 * still there or not), sata_reprobe_pmult() will handle it.
10535 	 */
10536 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10537 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10538 
10539 	/* Store sata_drive_info when a non-pmult device was attached. */
10540 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10541 	if (osdinfo != NULL) {
10542 		/*
10543 		 * We are re-probing port with a previously attached device.
10544 		 * Save previous device type and settings.
10545 		 */
10546 		prev_device_type = cportinfo->cport_dev_type;
10547 		prev_device_settings = osdinfo->satadrv_settings;
10548 		prev_device_state = osdinfo->satadrv_state;
10549 	}
10550 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10551 		start_time = ddi_get_lbolt();
10552 		retry = B_TRUE;
10553 	}
10554 retry_probe:
10555 
10556 	/* probe port */
10557 	mutex_enter(&cportinfo->cport_mutex);
10558 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10559 	cportinfo->cport_state |= SATA_STATE_PROBING;
10560 	mutex_exit(&cportinfo->cport_mutex);
10561 
10562 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10563 	    (SATA_DIP(sata_hba_inst), sata_device);
10564 
10565 	mutex_enter(&cportinfo->cport_mutex);
10566 	if (rval_probe != SATA_SUCCESS) {
10567 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10568 		mutex_exit(&cportinfo->cport_mutex);
10569 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10570 		    "SATA port %d probing failed",
10571 		    cportinfo->cport_addr.cport));
10572 		return (SATA_FAILURE);
10573 	}
10574 
10575 	/*
10576 	 * update sata port state and set device type
10577 	 */
10578 	sata_update_port_info(sata_hba_inst, sata_device);
10579 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10580 
10581 	/*
10582 	 * Sanity check - Port is active? Is the link active?
10583 	 * Is there any device attached?
10584 	 */
10585 	if ((cportinfo->cport_state &
10586 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10587 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10588 	    SATA_PORT_DEVLINK_UP) {
10589 		/*
10590 		 * Port in non-usable state or no link active/no device.
10591 		 * Free info structure if necessary (direct attached drive
10592 		 * only, for now!
10593 		 */
10594 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10595 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10596 		/* Add here differentiation for device attached or not */
10597 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10598 		mutex_exit(&cportinfo->cport_mutex);
10599 		if (sdinfo != NULL)
10600 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10601 		return (SATA_SUCCESS);
10602 	}
10603 
10604 	cportinfo->cport_state |= SATA_STATE_READY;
10605 	cportinfo->cport_state |= SATA_STATE_PROBED;
10606 
10607 	cportinfo->cport_dev_type = sata_device->satadev_type;
10608 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10609 
10610 	/*
10611 	 * If we are re-probing the port, there may be
10612 	 * sata_drive_info structure attached
10613 	 */
10614 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10615 
10616 		/*
10617 		 * There is no device, so remove device info structure,
10618 		 * if necessary.
10619 		 */
10620 		/* Device change: Drive -> None */
10621 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10622 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10623 		if (sdinfo != NULL) {
10624 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10625 			sata_log(sata_hba_inst, CE_WARN,
10626 			    "SATA device detached "
10627 			    "from port %d", cportinfo->cport_addr.cport);
10628 		}
10629 		mutex_exit(&cportinfo->cport_mutex);
10630 		return (SATA_SUCCESS);
10631 
10632 	}
10633 
10634 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10635 
10636 		/* Device (may) change: Drive -> Drive */
10637 		if (sdinfo == NULL) {
10638 			/*
10639 			 * There is some device attached, but there is
10640 			 * no sata_drive_info structure - allocate one
10641 			 */
10642 			mutex_exit(&cportinfo->cport_mutex);
10643 			sdinfo = kmem_zalloc(
10644 			    sizeof (sata_drive_info_t), KM_SLEEP);
10645 			mutex_enter(&cportinfo->cport_mutex);
10646 			/*
10647 			 * Recheck, that the port state did not change when we
10648 			 * released mutex.
10649 			 */
10650 			if (cportinfo->cport_state & SATA_STATE_READY) {
10651 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10652 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10653 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10654 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10655 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10656 			} else {
10657 				/*
10658 				 * Port is not in ready state, we
10659 				 * cannot attach a device.
10660 				 */
10661 				mutex_exit(&cportinfo->cport_mutex);
10662 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10663 				return (SATA_SUCCESS);
10664 			}
10665 			/*
10666 			 * Since we are adding device, presumably new one,
10667 			 * indicate that it  should be initalized,
10668 			 * as well as some internal framework states).
10669 			 */
10670 			init_device = B_TRUE;
10671 		}
10672 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10673 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10674 	} else {
10675 		/* Device change: Drive -> PMult */
10676 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10677 		if (sdinfo != NULL) {
10678 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10679 			sata_log(sata_hba_inst, CE_WARN,
10680 			    "SATA device detached "
10681 			    "from port %d", cportinfo->cport_addr.cport);
10682 		}
10683 
10684 		sata_log(sata_hba_inst, CE_WARN,
10685 		    "SATA port multiplier detected at port %d",
10686 		    cportinfo->cport_addr.cport);
10687 
10688 		mutex_exit(&cportinfo->cport_mutex);
10689 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10690 		    SATA_SUCCESS)
10691 			return (SATA_FAILURE);
10692 		sata_show_pmult_info(sata_hba_inst, sata_device);
10693 		mutex_enter(&cportinfo->cport_mutex);
10694 
10695 		/*
10696 		 * Mark all the port multiplier port behind the port
10697 		 * multiplier behind with link events, so that the sata daemon
10698 		 * will update their status.
10699 		 */
10700 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10701 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10702 		mutex_exit(&cportinfo->cport_mutex);
10703 		return (SATA_SUCCESS);
10704 	}
10705 	mutex_exit(&cportinfo->cport_mutex);
10706 
10707 	/*
10708 	 * Figure out what kind of device we are really
10709 	 * dealing with. Failure of identifying device does not fail this
10710 	 * function.
10711 	 */
10712 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10713 	rval_init = SATA_FAILURE;
10714 	mutex_enter(&cportinfo->cport_mutex);
10715 	if (rval_probe == SATA_SUCCESS) {
10716 		/*
10717 		 * If we are dealing with the same type of a device as before,
10718 		 * restore its settings flags.
10719 		 */
10720 		if (osdinfo != NULL &&
10721 		    sata_device->satadev_type == prev_device_type)
10722 			sdinfo->satadrv_settings = prev_device_settings;
10723 
10724 		mutex_exit(&cportinfo->cport_mutex);
10725 		rval_init = SATA_SUCCESS;
10726 		/* Set initial device features, if necessary */
10727 		if (init_device == B_TRUE) {
10728 			rval_init = sata_initialize_device(sata_hba_inst,
10729 			    sdinfo);
10730 		}
10731 		if (rval_init == SATA_SUCCESS)
10732 			return (rval_init);
10733 		/* else we will retry if retry was asked for */
10734 
10735 	} else {
10736 		/*
10737 		 * If there was some device info before we probe the device,
10738 		 * restore previous device setting, so we can retry from scratch
10739 		 * later. Providing, of course, that device has not disapear
10740 		 * during probing process.
10741 		 */
10742 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10743 			if (osdinfo != NULL) {
10744 				cportinfo->cport_dev_type = prev_device_type;
10745 				sdinfo->satadrv_type = prev_device_type;
10746 				sdinfo->satadrv_state = prev_device_state;
10747 			}
10748 		} else {
10749 			/* device is gone */
10750 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10751 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10752 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10753 			mutex_exit(&cportinfo->cport_mutex);
10754 			return (SATA_SUCCESS);
10755 		}
10756 		mutex_exit(&cportinfo->cport_mutex);
10757 	}
10758 
10759 	if (retry) {
10760 		clock_t cur_time = ddi_get_lbolt();
10761 		/*
10762 		 * A device was not successfully identified or initialized.
10763 		 * Track retry time for device identification.
10764 		 */
10765 		if ((cur_time - start_time) <
10766 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10767 			/* sleep for a while */
10768 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10769 			goto retry_probe;
10770 		}
10771 		/* else no more retries */
10772 		mutex_enter(&cportinfo->cport_mutex);
10773 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10774 			if (rval_init == SATA_RETRY) {
10775 				/*
10776 				 * Setting drive features have failed, but
10777 				 * because the drive is still accessible,
10778 				 * keep it and emit a warning message.
10779 				 */
10780 				sata_log(sata_hba_inst, CE_WARN,
10781 				    "SATA device at port %d - desired "
10782 				    "drive features could not be set. "
10783 				    "Device may not operate as expected.",
10784 				    cportinfo->cport_addr.cport);
10785 			} else {
10786 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10787 				    satadrv_state = SATA_DSTATE_FAILED;
10788 			}
10789 		}
10790 		mutex_exit(&cportinfo->cport_mutex);
10791 	}
10792 	return (SATA_SUCCESS);
10793 }
10794 
10795 /*
10796  * Reprobe a controller port that connected to a port multiplier.
10797  *
10798  * NOTE: No Mutex should be hold.
10799  */
10800 static int
10801 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10802     int flag)
10803 {
10804 	_NOTE(ARGUNUSED(flag))
10805 	sata_cport_info_t *cportinfo;
10806 	sata_pmult_info_t *pmultinfo;
10807 	uint8_t cport = sata_device->satadev_addr.cport;
10808 	int rval_probe;
10809 
10810 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10811 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10812 
10813 	/* probe port */
10814 	mutex_enter(&cportinfo->cport_mutex);
10815 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10816 	cportinfo->cport_state |= SATA_STATE_PROBING;
10817 	mutex_exit(&cportinfo->cport_mutex);
10818 
10819 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10820 	    (SATA_DIP(sata_hba_inst), sata_device);
10821 
10822 	mutex_enter(&cportinfo->cport_mutex);
10823 	if (rval_probe != SATA_SUCCESS) {
10824 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10825 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10826 		    "SATA port %d probing failed", cport));
10827 		sata_log(sata_hba_inst, CE_WARN,
10828 		    "SATA port multiplier detached at port %d", cport);
10829 		mutex_exit(&cportinfo->cport_mutex);
10830 		sata_free_pmult(sata_hba_inst, sata_device);
10831 		return (SATA_FAILURE);
10832 	}
10833 
10834 	/*
10835 	 * update sata port state and set device type
10836 	 */
10837 	sata_update_port_info(sata_hba_inst, sata_device);
10838 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10839 	cportinfo->cport_state |= SATA_STATE_PROBED;
10840 
10841 	/*
10842 	 * Sanity check - Port is active? Is the link active?
10843 	 * Is there any device attached?
10844 	 */
10845 	if ((cportinfo->cport_state &
10846 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10847 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10848 	    SATA_PORT_DEVLINK_UP ||
10849 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10850 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10851 		mutex_exit(&cportinfo->cport_mutex);
10852 		sata_free_pmult(sata_hba_inst, sata_device);
10853 		sata_log(sata_hba_inst, CE_WARN,
10854 		    "SATA port multiplier detached at port %d", cport);
10855 		return (SATA_SUCCESS);
10856 	}
10857 
10858 	/*
10859 	 * Device changed: PMult -> Non-PMult
10860 	 *
10861 	 * This situation is uncommon, most possibly being caused by errors
10862 	 * after which the port multiplier is not correct initialized and
10863 	 * recognized. In that case the new device will be marked as unknown
10864 	 * and will not be automatically probed in this routine. Instead
10865 	 * system administrator could manually restart it via cfgadm(1M).
10866 	 */
10867 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10868 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10869 		mutex_exit(&cportinfo->cport_mutex);
10870 		sata_free_pmult(sata_hba_inst, sata_device);
10871 		sata_log(sata_hba_inst, CE_WARN,
10872 		    "SATA port multiplier detached at port %d", cport);
10873 		return (SATA_FAILURE);
10874 	}
10875 
10876 	/*
10877 	 * Now we know it is a port multiplier. However, if this is not the
10878 	 * previously attached port multiplier - they may have different
10879 	 * pmport numbers - we need to re-allocate data structures for every
10880 	 * pmport and drive.
10881 	 *
10882 	 * Port multipliers of the same model have identical values in these
10883 	 * registers, so it is still necessary to update the information of
10884 	 * all drives attached to the previous port multiplier afterwards.
10885 	 */
10886 	/* Device changed: PMult -> another PMult */
10887 	mutex_exit(&cportinfo->cport_mutex);
10888 	sata_free_pmult(sata_hba_inst, sata_device);
10889 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10890 		return (SATA_FAILURE);
10891 	mutex_enter(&cportinfo->cport_mutex);
10892 
10893 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10894 	    "SATA port multiplier [changed] at port %d", cport);
10895 	sata_log(sata_hba_inst, CE_WARN,
10896 	    "SATA port multiplier detected at port %d", cport);
10897 
10898 	/*
10899 	 * Mark all the port multiplier port behind the port
10900 	 * multiplier behind with link events, so that the sata daemon
10901 	 * will update their status.
10902 	 */
10903 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10904 	mutex_exit(&cportinfo->cport_mutex);
10905 
10906 	return (SATA_SUCCESS);
10907 }
10908 
10909 /*
10910  * Re-probe a port multiplier port, check for a device and attach info
10911  * structures when necessary. Identify Device data is fetched, if possible.
10912  * Assumption: sata address is already validated as port multiplier port.
10913  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10914  * the presence of a device and its type.
10915  *
10916  * flag arg specifies that the function should try multiple times to identify
10917  * device type and to initialize it, or it should return immediately on failure.
10918  * SATA_DEV_IDENTIFY_RETRY - retry
10919  * SATA_DEV_IDENTIFY_NORETRY - no retry
10920  *
10921  * SATA_FAILURE is returned if one of the operations failed.
10922  *
10923  * This function cannot be called in interrupt context - it may sleep.
10924  *
10925  * NOTE: Should be only called by sata_probe_port() in case target port is a
10926  *       port multiplier port.
10927  * NOTE: No Mutex should be hold.
10928  */
10929 static int
10930 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10931     int flag)
10932 {
10933 	sata_cport_info_t *cportinfo = NULL;
10934 	sata_pmport_info_t *pmportinfo = NULL;
10935 	sata_drive_info_t *sdinfo, *osdinfo;
10936 	sata_device_t sdevice;
10937 	boolean_t init_device = B_FALSE;
10938 	int prev_device_type = SATA_DTYPE_NONE;
10939 	int prev_device_settings = 0;
10940 	int prev_device_state = 0;
10941 	clock_t start_time;
10942 	uint8_t cport = sata_device->satadev_addr.cport;
10943 	uint8_t pmport = sata_device->satadev_addr.pmport;
10944 	int rval;
10945 
10946 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10947 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10948 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10949 
10950 	if (osdinfo != NULL) {
10951 		/*
10952 		 * We are re-probing port with a previously attached device.
10953 		 * Save previous device type and settings.
10954 		 */
10955 		prev_device_type = pmportinfo->pmport_dev_type;
10956 		prev_device_settings = osdinfo->satadrv_settings;
10957 		prev_device_state = osdinfo->satadrv_state;
10958 	}
10959 
10960 	start_time = ddi_get_lbolt();
10961 
10962 	/* check parent status */
10963 	mutex_enter(&cportinfo->cport_mutex);
10964 	if ((cportinfo->cport_state &
10965 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10966 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10967 	    SATA_PORT_DEVLINK_UP) {
10968 		mutex_exit(&cportinfo->cport_mutex);
10969 		return (SATA_FAILURE);
10970 	}
10971 	mutex_exit(&cportinfo->cport_mutex);
10972 
10973 retry_probe_pmport:
10974 
10975 	/* probe port */
10976 	mutex_enter(&pmportinfo->pmport_mutex);
10977 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10978 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10979 	mutex_exit(&pmportinfo->pmport_mutex);
10980 
10981 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10982 	    (SATA_DIP(sata_hba_inst), sata_device);
10983 
10984 	/* might need retry because we cannot touch registers. */
10985 	if (rval == SATA_FAILURE) {
10986 		mutex_enter(&pmportinfo->pmport_mutex);
10987 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10988 		mutex_exit(&pmportinfo->pmport_mutex);
10989 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10990 		    "SATA port %d:%d probing failed",
10991 		    cport, pmport));
10992 		return (SATA_FAILURE);
10993 	} else if (rval == SATA_RETRY) {
10994 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10995 		    "SATA port %d:%d probing failed, retrying...",
10996 		    cport, pmport));
10997 		clock_t cur_time = ddi_get_lbolt();
10998 		/*
10999 		 * A device was not successfully identified or initialized.
11000 		 * Track retry time for device identification.
11001 		 */
11002 		if ((cur_time - start_time) <
11003 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11004 			/* sleep for a while */
11005 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11006 			goto retry_probe_pmport;
11007 		} else {
11008 			mutex_enter(&pmportinfo->pmport_mutex);
11009 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11010 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11011 				    satadrv_state = SATA_DSTATE_FAILED;
11012 			mutex_exit(&pmportinfo->pmport_mutex);
11013 			return (SATA_SUCCESS);
11014 		}
11015 	}
11016 
11017 	/*
11018 	 * Sanity check - Controller port is active? Is the link active?
11019 	 * Is it still a port multiplier?
11020 	 */
11021 	if ((cportinfo->cport_state &
11022 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11023 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11024 	    SATA_PORT_DEVLINK_UP ||
11025 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11026 		/*
11027 		 * Port in non-usable state or no link active/no
11028 		 * device. Free info structure.
11029 		 */
11030 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11031 
11032 		sdevice.satadev_addr.cport = cport;
11033 		sdevice.satadev_addr.pmport = pmport;
11034 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11035 		mutex_exit(&cportinfo->cport_mutex);
11036 
11037 		sata_free_pmult(sata_hba_inst, &sdevice);
11038 		return (SATA_FAILURE);
11039 	}
11040 
11041 	/* SATA_SUCCESS NOW */
11042 	/*
11043 	 * update sata port state and set device type
11044 	 */
11045 	mutex_enter(&pmportinfo->pmport_mutex);
11046 	sata_update_pmport_info(sata_hba_inst, sata_device);
11047 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11048 
11049 	/*
11050 	 * Sanity check - Port is active? Is the link active?
11051 	 * Is there any device attached?
11052 	 */
11053 	if ((pmportinfo->pmport_state &
11054 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11055 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11056 	    SATA_PORT_DEVLINK_UP) {
11057 		/*
11058 		 * Port in non-usable state or no link active/no device.
11059 		 * Free info structure if necessary (direct attached drive
11060 		 * only, for now!
11061 		 */
11062 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11063 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11064 		/* Add here differentiation for device attached or not */
11065 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11066 		mutex_exit(&pmportinfo->pmport_mutex);
11067 		if (sdinfo != NULL)
11068 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11069 		return (SATA_SUCCESS);
11070 	}
11071 
11072 	pmportinfo->pmport_state |= SATA_STATE_READY;
11073 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11074 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11075 
11076 	/*
11077 	 * If we are re-probing the port, there may be
11078 	 * sata_drive_info structure attached
11079 	 * (or sata_pm_info, if PMult is supported).
11080 	 */
11081 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11082 		/*
11083 		 * There is no device, so remove device info structure,
11084 		 * if necessary.
11085 		 */
11086 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11087 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11088 		if (sdinfo != NULL) {
11089 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11090 			sata_log(sata_hba_inst, CE_WARN,
11091 			    "SATA device detached from port %d:%d",
11092 			    cport, pmport);
11093 		}
11094 		mutex_exit(&pmportinfo->pmport_mutex);
11095 		return (SATA_SUCCESS);
11096 	}
11097 
11098 	/* this should not be a pmult */
11099 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11100 	if (sdinfo == NULL) {
11101 		/*
11102 		 * There is some device attached, but there is
11103 		 * no sata_drive_info structure - allocate one
11104 		 */
11105 		mutex_exit(&pmportinfo->pmport_mutex);
11106 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11107 		    KM_SLEEP);
11108 		mutex_enter(&pmportinfo->pmport_mutex);
11109 		/*
11110 		 * Recheck, that the port state did not change when we
11111 		 * released mutex.
11112 		 */
11113 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11114 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11115 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11116 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11117 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11118 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11119 		} else {
11120 			/*
11121 			 * Port is not in ready state, we
11122 			 * cannot attach a device.
11123 			 */
11124 			mutex_exit(&pmportinfo->pmport_mutex);
11125 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11126 			return (SATA_SUCCESS);
11127 		}
11128 		/*
11129 		 * Since we are adding device, presumably new one,
11130 		 * indicate that it  should be initalized,
11131 		 * as well as some internal framework states).
11132 		 */
11133 		init_device = B_TRUE;
11134 	}
11135 
11136 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11137 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11138 
11139 	mutex_exit(&pmportinfo->pmport_mutex);
11140 	/*
11141 	 * Figure out what kind of device we are really
11142 	 * dealing with.
11143 	 */
11144 	rval = sata_probe_device(sata_hba_inst, sata_device);
11145 
11146 	mutex_enter(&pmportinfo->pmport_mutex);
11147 	if (rval == SATA_SUCCESS) {
11148 		/*
11149 		 * If we are dealing with the same type of a device as before,
11150 		 * restore its settings flags.
11151 		 */
11152 		if (osdinfo != NULL &&
11153 		    sata_device->satadev_type == prev_device_type)
11154 			sdinfo->satadrv_settings = prev_device_settings;
11155 
11156 		mutex_exit(&pmportinfo->pmport_mutex);
11157 		/* Set initial device features, if necessary */
11158 		if (init_device == B_TRUE) {
11159 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11160 		}
11161 		if (rval == SATA_SUCCESS)
11162 			return (rval);
11163 	} else {
11164 		/*
11165 		 * If there was some device info before we probe the device,
11166 		 * restore previous device setting, so we can retry from scratch
11167 		 * later. Providing, of course, that device has not disappeared
11168 		 * during probing process.
11169 		 */
11170 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11171 			if (osdinfo != NULL) {
11172 				pmportinfo->pmport_dev_type = prev_device_type;
11173 				sdinfo->satadrv_type = prev_device_type;
11174 				sdinfo->satadrv_state = prev_device_state;
11175 			}
11176 		} else {
11177 			/* device is gone */
11178 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11179 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11180 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11181 			mutex_exit(&pmportinfo->pmport_mutex);
11182 			return (SATA_SUCCESS);
11183 		}
11184 		mutex_exit(&pmportinfo->pmport_mutex);
11185 	}
11186 
11187 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11188 		clock_t cur_time = ddi_get_lbolt();
11189 		/*
11190 		 * A device was not successfully identified or initialized.
11191 		 * Track retry time for device identification.
11192 		 */
11193 		if ((cur_time - start_time) <
11194 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11195 			/* sleep for a while */
11196 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11197 			goto retry_probe_pmport;
11198 		} else {
11199 			mutex_enter(&pmportinfo->pmport_mutex);
11200 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11201 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11202 				    satadrv_state = SATA_DSTATE_FAILED;
11203 			mutex_exit(&pmportinfo->pmport_mutex);
11204 		}
11205 	}
11206 	return (SATA_SUCCESS);
11207 }
11208 
11209 /*
11210  * Allocated related structure for a port multiplier and its device ports
11211  *
11212  * Port multiplier should be ready and probed, and related information like
11213  * the number of the device ports should be store in sata_device_t.
11214  *
11215  * NOTE: No Mutex should be hold.
11216  */
11217 static int
11218 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11219 {
11220 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11221 	sata_cport_info_t *cportinfo = NULL;
11222 	sata_pmult_info_t *pmultinfo = NULL;
11223 	sata_pmport_info_t *pmportinfo = NULL;
11224 	sata_device_t sd;
11225 	dev_t minor_number;
11226 	char name[16];
11227 	uint8_t cport = sata_device->satadev_addr.cport;
11228 	int rval;
11229 	int npmport;
11230 
11231 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11232 
11233 	/* This function might be called while a port-mult is hot-plugged. */
11234 	mutex_enter(&cportinfo->cport_mutex);
11235 
11236 	/* dev_type's not updated when get called from sata_reprobe_port() */
11237 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11238 		/* Create a pmult_info structure */
11239 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11240 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11241 	}
11242 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11243 
11244 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11245 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11246 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11247 
11248 	/*
11249 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11250 	 * The HBA driver should initialize and register the port multiplier,
11251 	 * sata_register_pmult() will fill following fields,
11252 	 *   + sata_pmult_info.pmult_gscr
11253 	 *   + sata_pmult_info.pmult_num_dev_ports
11254 	 */
11255 	sd.satadev_addr = sata_device->satadev_addr;
11256 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11257 	mutex_exit(&cportinfo->cport_mutex);
11258 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11259 	    (SATA_DIP(sata_hba_inst), &sd);
11260 	mutex_enter(&cportinfo->cport_mutex);
11261 
11262 	if (rval != SATA_SUCCESS ||
11263 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11264 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11265 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11266 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11267 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11268 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11269 		mutex_exit(&cportinfo->cport_mutex);
11270 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11271 		    "sata_alloc_pmult: failed to initialize pmult "
11272 		    "at port %d.", cport)
11273 		return (SATA_FAILURE);
11274 	}
11275 
11276 	/* Initialize pmport_info structure */
11277 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11278 	    npmport++) {
11279 
11280 		/* if everything is allocated, skip */
11281 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11282 			continue;
11283 
11284 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11285 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11286 		mutex_exit(&cportinfo->cport_mutex);
11287 
11288 		mutex_enter(&pmportinfo->pmport_mutex);
11289 		pmportinfo->pmport_addr.cport = cport;
11290 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11291 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11292 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11293 		mutex_exit(&pmportinfo->pmport_mutex);
11294 
11295 		mutex_enter(&cportinfo->cport_mutex);
11296 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11297 
11298 		/* Create an attachment point */
11299 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11300 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11301 		(void) sprintf(name, "%d.%d", cport, npmport);
11302 
11303 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11304 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11305 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11306 			    "cannot create SATA attachment point for "
11307 			    "port %d:%d", cport, npmport);
11308 		}
11309 	}
11310 
11311 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11312 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11313 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11314 
11315 	mutex_exit(&cportinfo->cport_mutex);
11316 	return (SATA_SUCCESS);
11317 }
11318 
11319 /*
11320  * Free data structures when a port multiplier is removed.
11321  *
11322  * NOTE: No Mutex should be hold.
11323  */
11324 static void
11325 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11326 {
11327 	sata_cport_info_t *cportinfo;
11328 	sata_pmult_info_t *pmultinfo;
11329 	sata_pmport_info_t *pmportinfo;
11330 	sata_device_t pmport_device;
11331 	sata_drive_info_t *sdinfo;
11332 	dev_info_t *tdip;
11333 	char name[16];
11334 	uint8_t cport = sata_device->satadev_addr.cport;
11335 	int npmport;
11336 
11337 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11338 
11339 	/* This function might be called while port-mult is hot plugged. */
11340 	mutex_enter(&cportinfo->cport_mutex);
11341 
11342 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11343 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11344 	ASSERT(pmultinfo != NULL);
11345 
11346 	/* Free pmport_info structure */
11347 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11348 	    npmport++) {
11349 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11350 		if (pmportinfo == NULL)
11351 			continue;
11352 		mutex_exit(&cportinfo->cport_mutex);
11353 
11354 		mutex_enter(&pmportinfo->pmport_mutex);
11355 		sdinfo = pmportinfo->pmport_sata_drive;
11356 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11357 		mutex_exit(&pmportinfo->pmport_mutex);
11358 
11359 		/* Remove attachment point. */
11360 		name[0] = '\0';
11361 		(void) sprintf(name, "%d.%d", cport, npmport);
11362 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11363 		sata_log(sata_hba_inst, CE_NOTE,
11364 		    "Remove attachment point of port %d:%d",
11365 		    cport, npmport);
11366 
11367 		/*
11368 		 * Rumove target node
11369 		 */
11370 		bzero(&pmport_device, sizeof (sata_device_t));
11371 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11372 		pmport_device.satadev_addr.cport = cport;
11373 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11374 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11375 
11376 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11377 		    &(pmport_device.satadev_addr));
11378 		if (tdip != NULL && ndi_devi_offline(tdip,
11379 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11380 			/*
11381 			 * Problem :
11382 			 * The target node remained attached.
11383 			 * This happens when the device file was open
11384 			 * or a node was waiting for resources.
11385 			 * Cannot do anything about it.
11386 			 */
11387 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11388 			    "sata_free_pmult: could not unconfigure device "
11389 			    "before disconnecting the SATA port %d:%d",
11390 			    cport, npmport));
11391 
11392 			/*
11393 			 * Set DEVICE REMOVED state in the target
11394 			 * node. It will prevent access to the device
11395 			 * even when a new device is attached, until
11396 			 * the old target node is released, removed and
11397 			 * recreated for a new  device.
11398 			 */
11399 			sata_set_device_removed(tdip);
11400 
11401 			/*
11402 			 * Instruct event daemon to try the target
11403 			 * node cleanup later.
11404 			 */
11405 			sata_set_target_node_cleanup(
11406 			    sata_hba_inst, &(pmport_device.satadev_addr));
11407 
11408 		}
11409 		mutex_enter(&cportinfo->cport_mutex);
11410 
11411 		/*
11412 		 * Add here differentiation for device attached or not
11413 		 */
11414 		if (sdinfo != NULL)  {
11415 			sata_log(sata_hba_inst, CE_WARN,
11416 			    "SATA device detached from port %d:%d",
11417 			    cport, npmport);
11418 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11419 		}
11420 
11421 		mutex_destroy(&pmportinfo->pmport_mutex);
11422 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11423 	}
11424 
11425 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11426 
11427 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11428 
11429 	sata_log(sata_hba_inst, CE_WARN,
11430 	    "SATA port multiplier detached at port %d", cport);
11431 
11432 	mutex_exit(&cportinfo->cport_mutex);
11433 }
11434 
11435 /*
11436  * Initialize device
11437  * Specified device is initialized to a default state.
11438  *
11439  * Returns SATA_SUCCESS if all device features are set successfully,
11440  * SATA_RETRY if device is accessible but device features were not set
11441  * successfully, and SATA_FAILURE otherwise.
11442  */
11443 static int
11444 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11445     sata_drive_info_t *sdinfo)
11446 {
11447 	int rval;
11448 
11449 	sata_save_drive_settings(sdinfo);
11450 
11451 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11452 
11453 	sata_init_write_cache_mode(sdinfo);
11454 
11455 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11456 
11457 	/* Determine current data transfer mode */
11458 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11459 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11460 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11461 	    SATA_VALIDINFO_88) != 0 &&
11462 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11463 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11464 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11465 	    SATA_MDMA_SEL_MASK) != 0) {
11466 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11467 	} else
11468 		/* DMA supported, not no DMA transfer mode is selected !? */
11469 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11470 
11471 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11472 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11473 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11474 	else
11475 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11476 
11477 	return (rval);
11478 }
11479 
11480 
11481 /*
11482  * Initialize write cache mode.
11483  *
11484  * The default write cache setting for SATA HDD is provided by sata_write_cache
11485  * static variable. ATAPI CD/DVDs devices have write cache default is
11486  * determined by sata_atapicdvd_write_cache static variable.
11487  * ATAPI tape devices have write cache default is determined by
11488  * sata_atapitape_write_cache static variable.
11489  * ATAPI disk devices have write cache default is determined by
11490  * sata_atapidisk_write_cache static variable.
11491  * 1 - enable
11492  * 0 - disable
11493  * any other value - current drive setting
11494  *
11495  * Although there is not reason to disable write cache on CD/DVD devices,
11496  * tape devices and ATAPI disk devices, the default setting control is provided
11497  * for the maximun flexibility.
11498  *
11499  * In the future, it may be overridden by the
11500  * disk-write-cache-enable property setting, if it is defined.
11501  * Returns SATA_SUCCESS if all device features are set successfully,
11502  * SATA_FAILURE otherwise.
11503  */
11504 static void
11505 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11506 {
11507 	switch (sdinfo->satadrv_type) {
11508 	case SATA_DTYPE_ATADISK:
11509 		if (sata_write_cache == 1)
11510 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11511 		else if (sata_write_cache == 0)
11512 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11513 		/*
11514 		 * When sata_write_cache value is not 0 or 1,
11515 		 * a current setting of the drive's write cache is used.
11516 		 */
11517 		break;
11518 	case SATA_DTYPE_ATAPICD:
11519 		if (sata_atapicdvd_write_cache == 1)
11520 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11521 		else if (sata_atapicdvd_write_cache == 0)
11522 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11523 		/*
11524 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11525 		 * a current setting of the drive's write cache is used.
11526 		 */
11527 		break;
11528 	case SATA_DTYPE_ATAPITAPE:
11529 		if (sata_atapitape_write_cache == 1)
11530 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11531 		else if (sata_atapitape_write_cache == 0)
11532 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11533 		/*
11534 		 * When sata_atapitape_write_cache value is not 0 or 1,
11535 		 * a current setting of the drive's write cache is used.
11536 		 */
11537 		break;
11538 	case SATA_DTYPE_ATAPIDISK:
11539 		if (sata_atapidisk_write_cache == 1)
11540 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11541 		else if (sata_atapidisk_write_cache == 0)
11542 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11543 		/*
11544 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11545 		 * a current setting of the drive's write cache is used.
11546 		 */
11547 		break;
11548 	}
11549 }
11550 
11551 
11552 /*
11553  * Validate sata address.
11554  * Specified cport, pmport and qualifier has to match
11555  * passed sata_scsi configuration info.
11556  * The presence of an attached device is not verified.
11557  *
11558  * Returns 0 when address is valid, -1 otherwise.
11559  */
11560 static int
11561 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11562 	int pmport, int qual)
11563 {
11564 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11565 		goto invalid_address;
11566 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11567 		goto invalid_address;
11568 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11569 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11570 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11571 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11572 		goto invalid_address;
11573 
11574 	return (0);
11575 
11576 invalid_address:
11577 	return (-1);
11578 
11579 }
11580 
11581 /*
11582  * Validate scsi address
11583  * SCSI target address is translated into SATA cport/pmport and compared
11584  * with a controller port/device configuration. LUN has to be 0.
11585  * Returns 0 if a scsi target refers to an attached device,
11586  * returns 1 if address is valid but no valid device is attached,
11587  * returns 2 if address is valid but device type is unknown (not valid device),
11588  * returns -1 if bad address or device is of an unsupported type.
11589  * Upon return sata_device argument is set.
11590  *
11591  * Port multiplier is supported now.
11592  */
11593 static int
11594 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11595 	struct scsi_address *ap, sata_device_t *sata_device)
11596 {
11597 	int cport, pmport, qual, rval;
11598 
11599 	rval = -1;	/* Invalid address */
11600 	if (ap->a_lun != 0)
11601 		goto out;
11602 
11603 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11604 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11605 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11606 
11607 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11608 		goto out;
11609 
11610 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11611 	    0) {
11612 
11613 		sata_cport_info_t *cportinfo;
11614 		sata_pmult_info_t *pmultinfo;
11615 		sata_drive_info_t *sdinfo = NULL;
11616 
11617 		sata_device->satadev_addr.qual = qual;
11618 		sata_device->satadev_addr.cport = cport;
11619 		sata_device->satadev_addr.pmport = pmport;
11620 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11621 
11622 		rval = 1;	/* Valid sata address */
11623 
11624 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11625 		if (qual == SATA_ADDR_DCPORT) {
11626 			if (cportinfo == NULL ||
11627 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11628 				goto out;
11629 
11630 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11631 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11632 			    sdinfo != NULL) {
11633 				rval = 2;
11634 				goto out;
11635 			}
11636 
11637 			if ((cportinfo->cport_dev_type &
11638 			    SATA_VALID_DEV_TYPE) == 0) {
11639 				rval = -1;
11640 				goto out;
11641 			}
11642 
11643 		} else if (qual == SATA_ADDR_DPMPORT) {
11644 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11645 			if (pmultinfo == NULL) {
11646 				rval = -1;
11647 				goto out;
11648 			}
11649 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11650 			    NULL ||
11651 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11652 			    pmport) == SATA_DTYPE_NONE)
11653 				goto out;
11654 
11655 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11656 			    pmport);
11657 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11658 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11659 				rval = 2;
11660 				goto out;
11661 			}
11662 
11663 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11664 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11665 				rval = -1;
11666 				goto out;
11667 			}
11668 
11669 		} else {
11670 			rval = -1;
11671 			goto out;
11672 		}
11673 		if ((sdinfo == NULL) ||
11674 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11675 			goto out;
11676 
11677 		sata_device->satadev_type = sdinfo->satadrv_type;
11678 
11679 		return (0);
11680 	}
11681 out:
11682 	if (rval > 0) {
11683 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11684 		    "sata_validate_scsi_address: no valid target %x lun %x",
11685 		    ap->a_target, ap->a_lun);
11686 	}
11687 	return (rval);
11688 }
11689 
11690 /*
11691  * Find dip corresponding to passed device number
11692  *
11693  * Returns NULL if invalid device number is passed or device cannot be found,
11694  * Returns dip is device is found.
11695  */
11696 static dev_info_t *
11697 sata_devt_to_devinfo(dev_t dev)
11698 {
11699 	dev_info_t *dip;
11700 #ifndef __lock_lint
11701 	struct devnames *dnp;
11702 	major_t major = getmajor(dev);
11703 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11704 
11705 	if (major >= devcnt)
11706 		return (NULL);
11707 
11708 	dnp = &devnamesp[major];
11709 	LOCK_DEV_OPS(&(dnp->dn_lock));
11710 	dip = dnp->dn_head;
11711 	while (dip && (ddi_get_instance(dip) != instance)) {
11712 		dip = ddi_get_next(dip);
11713 	}
11714 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11715 #endif
11716 
11717 	return (dip);
11718 }
11719 
11720 
11721 /*
11722  * Probe device.
11723  * This function issues Identify Device command and initializes local
11724  * sata_drive_info structure if the device can be identified.
11725  * The device type is determined by examining Identify Device
11726  * command response.
11727  * If the sata_hba_inst has linked drive info structure for this
11728  * device address, the Identify Device data is stored into sata_drive_info
11729  * structure linked to the port info structure.
11730  *
11731  * sata_device has to refer to the valid sata port(s) for HBA described
11732  * by sata_hba_inst structure.
11733  *
11734  * Returns:
11735  *	SATA_SUCCESS if device type was successfully probed and port-linked
11736  *		drive info structure was updated;
11737  * 	SATA_FAILURE if there is no device, or device was not probed
11738  *		successully;
11739  *	SATA_RETRY if device probe can be retried later.
11740  * If a device cannot be identified, sata_device's dev_state and dev_type
11741  * fields are set to unknown.
11742  * There are no retries in this function. Any retries should be managed by
11743  * the caller.
11744  */
11745 
11746 
11747 static int
11748 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11749 {
11750 	sata_pmport_info_t *pmportinfo;
11751 	sata_drive_info_t *sdinfo;
11752 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11753 	int rval;
11754 
11755 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11756 	    sata_device->satadev_addr.cport) &
11757 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11758 
11759 	sata_device->satadev_type = SATA_DTYPE_NONE;
11760 
11761 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11762 	    sata_device->satadev_addr.cport)));
11763 
11764 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11765 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11766 		    sata_device->satadev_addr.cport,
11767 		    sata_device->satadev_addr.pmport);
11768 		ASSERT(pmportinfo != NULL);
11769 	}
11770 
11771 	/* Get pointer to port-linked sata device info structure */
11772 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11773 	if (sdinfo != NULL) {
11774 		sdinfo->satadrv_state &=
11775 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11776 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11777 	} else {
11778 		/* No device to probe */
11779 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11780 		    sata_device->satadev_addr.cport)));
11781 		sata_device->satadev_type = SATA_DTYPE_NONE;
11782 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11783 		return (SATA_FAILURE);
11784 	}
11785 	/*
11786 	 * Need to issue both types of identify device command and
11787 	 * determine device type by examining retreived data/status.
11788 	 * First, ATA Identify Device.
11789 	 */
11790 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11791 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11792 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11793 	    sata_device->satadev_addr.cport)));
11794 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11795 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11796 	if (rval == SATA_RETRY) {
11797 		/* We may try to check for ATAPI device */
11798 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11799 			/*
11800 			 * HBA supports ATAPI - try to issue Identify Packet
11801 			 * Device command.
11802 			 */
11803 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11804 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11805 		}
11806 	}
11807 	if (rval == SATA_SUCCESS) {
11808 		/*
11809 		 * Got something responding positively to ATA Identify Device
11810 		 * or to Identify Packet Device cmd.
11811 		 * Save last used device type.
11812 		 */
11813 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11814 
11815 		/* save device info, if possible */
11816 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11817 		    sata_device->satadev_addr.cport)));
11818 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11819 		if (sdinfo == NULL) {
11820 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11821 			    sata_device->satadev_addr.cport)));
11822 			return (SATA_FAILURE);
11823 		}
11824 		/*
11825 		 * Copy drive info into the port-linked drive info structure.
11826 		 */
11827 		*sdinfo = new_sdinfo;
11828 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11829 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11830 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11831 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11832 			    sata_device->satadev_addr.cport) =
11833 			    sdinfo->satadrv_type;
11834 		else { /* SATA_ADDR_DPMPORT */
11835 			mutex_enter(&pmportinfo->pmport_mutex);
11836 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11837 			    sata_device->satadev_addr.cport,
11838 			    sata_device->satadev_addr.pmport) =
11839 			    sdinfo->satadrv_type;
11840 			mutex_exit(&pmportinfo->pmport_mutex);
11841 		}
11842 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11843 		    sata_device->satadev_addr.cport)));
11844 		return (SATA_SUCCESS);
11845 	}
11846 
11847 	/*
11848 	 * It may be SATA_RETRY or SATA_FAILURE return.
11849 	 * Looks like we cannot determine the device type at this time.
11850 	 */
11851 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11852 	    sata_device->satadev_addr.cport)));
11853 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11854 	if (sdinfo != NULL) {
11855 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11856 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11857 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11858 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11859 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11860 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11861 			    sata_device->satadev_addr.cport) =
11862 			    SATA_DTYPE_UNKNOWN;
11863 		else {
11864 			/* SATA_ADDR_DPMPORT */
11865 			mutex_enter(&pmportinfo->pmport_mutex);
11866 			if ((SATA_PMULT_INFO(sata_hba_inst,
11867 			    sata_device->satadev_addr.cport) != NULL) &&
11868 			    (SATA_PMPORT_INFO(sata_hba_inst,
11869 			    sata_device->satadev_addr.cport,
11870 			    sata_device->satadev_addr.pmport) != NULL))
11871 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11872 				    sata_device->satadev_addr.cport,
11873 				    sata_device->satadev_addr.pmport) =
11874 				    SATA_DTYPE_UNKNOWN;
11875 			mutex_exit(&pmportinfo->pmport_mutex);
11876 		}
11877 	}
11878 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11879 	    sata_device->satadev_addr.cport)));
11880 	return (rval);
11881 }
11882 
11883 
11884 /*
11885  * Get pointer to sata_drive_info structure.
11886  *
11887  * The sata_device has to contain address (cport, pmport and qualifier) for
11888  * specified sata_scsi structure.
11889  *
11890  * Returns NULL if device address is not valid for this HBA configuration.
11891  * Otherwise, returns a pointer to sata_drive_info structure.
11892  *
11893  * This function should be called with a port mutex held.
11894  */
11895 static sata_drive_info_t *
11896 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11897     sata_device_t *sata_device)
11898 {
11899 	uint8_t cport = sata_device->satadev_addr.cport;
11900 	uint8_t pmport = sata_device->satadev_addr.pmport;
11901 	uint8_t qual = sata_device->satadev_addr.qual;
11902 
11903 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11904 		return (NULL);
11905 
11906 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11907 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11908 		/* Port not probed yet */
11909 		return (NULL);
11910 
11911 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11912 		return (NULL);
11913 
11914 	if (qual == SATA_ADDR_DCPORT) {
11915 		/* Request for a device on a controller port */
11916 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11917 		    SATA_DTYPE_PMULT)
11918 			/* Port multiplier attached */
11919 			return (NULL);
11920 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11921 	}
11922 	if (qual == SATA_ADDR_DPMPORT) {
11923 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11924 		    SATA_DTYPE_PMULT)
11925 			return (NULL);
11926 
11927 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11928 			return (NULL);
11929 
11930 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11931 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11932 			/* Port multiplier port not probed yet */
11933 			return (NULL);
11934 
11935 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11936 	}
11937 
11938 	/* we should not get here */
11939 	return (NULL);
11940 }
11941 
11942 
11943 /*
11944  * sata_identify_device.
11945  * Send Identify Device command to SATA HBA driver.
11946  * If command executes successfully, update sata_drive_info structure pointed
11947  * to by sdinfo argument, including Identify Device data.
11948  * If command fails, invalidate data in sata_drive_info.
11949  *
11950  * Cannot be called from interrupt level.
11951  *
11952  * Returns:
11953  * SATA_SUCCESS if the device was identified as a supported device,
11954  * SATA_RETRY if the device was not identified but could be retried,
11955  * SATA_FAILURE if the device was not identified and identify attempt
11956  *	should not be retried.
11957  */
11958 static int
11959 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11960     sata_drive_info_t *sdinfo)
11961 {
11962 	uint16_t cfg_word;
11963 	int rval;
11964 
11965 	/* fetch device identify data */
11966 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11967 	    sdinfo)) != SATA_SUCCESS)
11968 		goto fail_unknown;
11969 
11970 	cfg_word = sdinfo->satadrv_id.ai_config;
11971 
11972 	/* Set the correct device type */
11973 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11974 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11975 	} else if (cfg_word == SATA_CFA_TYPE) {
11976 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11977 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11978 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11979 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11980 		case SATA_ATAPI_CDROM_DEV:
11981 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11982 			break;
11983 		case SATA_ATAPI_SQACC_DEV:
11984 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11985 			break;
11986 		case SATA_ATAPI_DIRACC_DEV:
11987 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11988 			break;
11989 		default:
11990 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11991 		}
11992 	} else {
11993 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11994 	}
11995 
11996 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11997 		if (sdinfo->satadrv_capacity == 0) {
11998 			/* Non-LBA disk. Too bad... */
11999 			sata_log(sata_hba_inst, CE_WARN,
12000 			    "SATA disk device at port %d does not support LBA",
12001 			    sdinfo->satadrv_addr.cport);
12002 			rval = SATA_FAILURE;
12003 			goto fail_unknown;
12004 		}
12005 	}
12006 #if 0
12007 	/* Left for historical reason */
12008 	/*
12009 	 * Some initial version of SATA spec indicated that at least
12010 	 * UDMA mode 4 has to be supported. It is not metioned in
12011 	 * SerialATA 2.6, so this restriction is removed.
12012 	 */
12013 	/* Check for Ultra DMA modes 6 through 0 being supported */
12014 	for (i = 6; i >= 0; --i) {
12015 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12016 			break;
12017 	}
12018 
12019 	/*
12020 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12021 	 * higher are not supported by the device, fail this
12022 	 * device.
12023 	 */
12024 	if (i < 4) {
12025 		/* No required Ultra DMA mode supported */
12026 		sata_log(sata_hba_inst, CE_WARN,
12027 		    "SATA disk device at port %d does not support UDMA "
12028 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12029 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12030 		    "mode 4 or higher required, %d supported", i));
12031 		rval = SATA_FAILURE;
12032 		goto fail_unknown;
12033 	}
12034 #endif
12035 
12036 	/*
12037 	 * For Disk devices, if it doesn't support UDMA mode, we would
12038 	 * like to return failure directly.
12039 	 */
12040 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12041 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12042 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12043 		sata_log(sata_hba_inst, CE_WARN,
12044 		    "SATA disk device at port %d does not support UDMA",
12045 		    sdinfo->satadrv_addr.cport);
12046 		rval = SATA_FAILURE;
12047 		goto fail_unknown;
12048 	}
12049 
12050 	return (SATA_SUCCESS);
12051 
12052 fail_unknown:
12053 	/* Invalidate sata_drive_info ? */
12054 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12055 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12056 	return (rval);
12057 }
12058 
12059 /*
12060  * Log/display device information
12061  */
12062 static void
12063 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12064     sata_drive_info_t *sdinfo)
12065 {
12066 	int valid_version;
12067 	char msg_buf[MAXPATHLEN];
12068 	int i;
12069 
12070 	/* Show HBA path */
12071 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12072 
12073 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12074 
12075 	switch (sdinfo->satadrv_type) {
12076 	case SATA_DTYPE_ATADISK:
12077 		(void) sprintf(msg_buf, "SATA disk device at");
12078 		break;
12079 
12080 	case SATA_DTYPE_ATAPICD:
12081 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12082 		break;
12083 
12084 	case SATA_DTYPE_ATAPITAPE:
12085 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12086 		break;
12087 
12088 	case SATA_DTYPE_ATAPIDISK:
12089 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12090 		break;
12091 
12092 	case SATA_DTYPE_UNKNOWN:
12093 		(void) sprintf(msg_buf,
12094 		    "Unsupported SATA device type (cfg 0x%x) at ",
12095 		    sdinfo->satadrv_id.ai_config);
12096 		break;
12097 	}
12098 
12099 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12100 		cmn_err(CE_CONT, "?\t%s port %d\n",
12101 		    msg_buf, sdinfo->satadrv_addr.cport);
12102 	else
12103 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12104 		    msg_buf, sdinfo->satadrv_addr.cport,
12105 		    sdinfo->satadrv_addr.pmport);
12106 
12107 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12108 	    sizeof (sdinfo->satadrv_id.ai_model));
12109 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12110 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12111 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12112 
12113 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12114 	    sizeof (sdinfo->satadrv_id.ai_fw));
12115 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12116 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12117 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12118 
12119 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12120 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12121 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12122 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12123 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12124 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12125 	} else {
12126 		/*
12127 		 * Some drives do not implement serial number and may
12128 		 * violate the spec by providing spaces rather than zeros
12129 		 * in serial number field. Scan the buffer to detect it.
12130 		 */
12131 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12132 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12133 				break;
12134 		}
12135 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12136 			cmn_err(CE_CONT, "?\tserial number - none\n");
12137 		} else {
12138 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12139 		}
12140 	}
12141 
12142 #ifdef SATA_DEBUG
12143 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12144 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12145 		int i;
12146 		for (i = 14; i >= 2; i--) {
12147 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12148 				valid_version = i;
12149 				break;
12150 			}
12151 		}
12152 		cmn_err(CE_CONT,
12153 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12154 		    valid_version,
12155 		    sdinfo->satadrv_id.ai_majorversion,
12156 		    sdinfo->satadrv_id.ai_minorversion);
12157 	}
12158 #endif
12159 	/* Log some info */
12160 	cmn_err(CE_CONT, "?\tsupported features:\n");
12161 	msg_buf[0] = '\0';
12162 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12163 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12164 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12165 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12166 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12167 	}
12168 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12169 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12170 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12171 		(void) strlcat(msg_buf, ", Native Command Queueing",
12172 		    MAXPATHLEN);
12173 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12174 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12175 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12176 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12177 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12178 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12179 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12180 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12181 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12182 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12183 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12184 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12185 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12186 	if (sdinfo->satadrv_features_support &
12187 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12188 		msg_buf[0] = '\0';
12189 		(void) snprintf(msg_buf, MAXPATHLEN,
12190 		    "Supported queue depth %d",
12191 		    sdinfo->satadrv_queue_depth);
12192 		if (!(sata_func_enable &
12193 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12194 			(void) strlcat(msg_buf,
12195 			    " - queueing disabled globally", MAXPATHLEN);
12196 		else if (sdinfo->satadrv_queue_depth >
12197 		    sdinfo->satadrv_max_queue_depth) {
12198 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12199 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12200 			    (int)sdinfo->satadrv_max_queue_depth);
12201 		}
12202 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12203 	}
12204 
12205 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12206 #ifdef __i386
12207 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12208 		    sdinfo->satadrv_capacity);
12209 #else
12210 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12211 		    sdinfo->satadrv_capacity);
12212 #endif
12213 		cmn_err(CE_CONT, "?%s", msg_buf);
12214 	}
12215 }
12216 
12217 /*
12218  * Log/display port multiplier information
12219  * No Mutex should be hold.
12220  */
12221 static void
12222 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12223     sata_device_t *sata_device)
12224 {
12225 	_NOTE(ARGUNUSED(sata_hba_inst))
12226 
12227 	int cport = sata_device->satadev_addr.cport;
12228 	sata_pmult_info_t *pmultinfo;
12229 	char msg_buf[MAXPATHLEN];
12230 	uint32_t gscr0, gscr1, gscr2, gscr64;
12231 
12232 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12233 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12234 	if (pmultinfo == NULL) {
12235 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12236 		return;
12237 	}
12238 
12239 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12240 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12241 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12242 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12243 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12244 
12245 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12246 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12247 
12248 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12249 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12250 	cmn_err(CE_CONT, "?%s", msg_buf);
12251 
12252 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12253 	if (gscr1 & (1 << 3))
12254 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12255 	else if (gscr1 & (1 << 2))
12256 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12257 	else if (gscr1 & (1 << 1))
12258 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12259 	else
12260 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12261 	cmn_err(CE_CONT, "?%s", msg_buf);
12262 
12263 	(void) strcpy(msg_buf, "\tSupport ");
12264 	if (gscr64 & (1 << 3))
12265 		(void) strlcat(msg_buf, "Asy-Notif, ",
12266 		    MAXPATHLEN);
12267 	if (gscr64 & (1 << 2))
12268 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12269 	if (gscr64 & (1 << 1))
12270 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12271 	if (gscr64 & (1 << 0))
12272 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12273 	if ((gscr64 & 0xf) == 0)
12274 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12275 	cmn_err(CE_CONT, "?%s", msg_buf);
12276 
12277 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12278 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12279 	cmn_err(CE_CONT, "?%s", msg_buf);
12280 }
12281 
12282 /*
12283  * sata_save_drive_settings extracts current setting of the device and stores
12284  * it for future reference, in case the device setup would need to be restored
12285  * after the device reset.
12286  *
12287  * For all devices read ahead and write cache settings are saved, if the
12288  * device supports these features at all.
12289  * For ATAPI devices the Removable Media Status Notification setting is saved.
12290  */
12291 static void
12292 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12293 {
12294 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12295 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12296 
12297 		/* Current setting of Read Ahead (and Read Cache) */
12298 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12299 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12300 		else
12301 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12302 
12303 		/* Current setting of Write Cache */
12304 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12305 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12306 		else
12307 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12308 	}
12309 
12310 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12311 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12312 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12313 		else
12314 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12315 	}
12316 }
12317 
12318 
12319 /*
12320  * sata_check_capacity function determines a disk capacity
12321  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12322  *
12323  * NOTE: CHS mode is not supported! If a device does not support LBA,
12324  * this function is not called.
12325  *
12326  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12327  */
12328 static uint64_t
12329 sata_check_capacity(sata_drive_info_t *sdinfo)
12330 {
12331 	uint64_t capacity = 0;
12332 	int i;
12333 
12334 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12335 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12336 		/* Capacity valid only for LBA-addressable disk devices */
12337 		return (0);
12338 
12339 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12340 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12341 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12342 		/* LBA48 mode supported and enabled */
12343 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12344 		    SATA_DEV_F_LBA28;
12345 		for (i = 3;  i >= 0;  --i) {
12346 			capacity <<= 16;
12347 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12348 		}
12349 	} else {
12350 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12351 		capacity <<= 16;
12352 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12353 		if (capacity >= 0x1000000)
12354 			/* LBA28 mode */
12355 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12356 	}
12357 	return (capacity);
12358 }
12359 
12360 
12361 /*
12362  * Allocate consistent buffer for DMA transfer
12363  *
12364  * Cannot be called from interrupt level or with mutex held - it may sleep.
12365  *
12366  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12367  */
12368 static struct buf *
12369 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12370 {
12371 	struct scsi_address ap;
12372 	struct buf *bp;
12373 	ddi_dma_attr_t	cur_dma_attr;
12374 
12375 	ASSERT(spx->txlt_sata_pkt != NULL);
12376 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12377 	ap.a_target = SATA_TO_SCSI_TARGET(
12378 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12379 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12380 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12381 	ap.a_lun = 0;
12382 
12383 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12384 	    B_READ, SLEEP_FUNC, NULL);
12385 
12386 	if (bp != NULL) {
12387 		/* Allocate DMA resources for this buffer */
12388 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12389 		/*
12390 		 * We use a local version of the dma_attr, to account
12391 		 * for a device addressing limitations.
12392 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12393 		 * will cause dma attributes to be adjusted to a lowest
12394 		 * acceptable level.
12395 		 */
12396 		sata_adjust_dma_attr(NULL,
12397 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12398 
12399 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12400 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12401 			scsi_free_consistent_buf(bp);
12402 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12403 			bp = NULL;
12404 		}
12405 	}
12406 	return (bp);
12407 }
12408 
12409 /*
12410  * Release local buffer (consistent buffer for DMA transfer) allocated
12411  * via sata_alloc_local_buffer().
12412  */
12413 static void
12414 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12415 {
12416 	ASSERT(spx->txlt_sata_pkt != NULL);
12417 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12418 
12419 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12420 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12421 
12422 	sata_common_free_dma_rsrcs(spx);
12423 
12424 	/* Free buffer */
12425 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12426 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12427 }
12428 
12429 /*
12430  * Allocate sata_pkt
12431  * Pkt structure version and embedded strcutures version are initialized.
12432  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12433  *
12434  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12435  * callback argument determines if it can sleep or not.
12436  * Hence, it should not be called from interrupt context.
12437  *
12438  * If successful, non-NULL pointer to a sata pkt is returned.
12439  * Upon failure, NULL pointer is returned.
12440  */
12441 static sata_pkt_t *
12442 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12443 {
12444 	sata_pkt_t *spkt;
12445 	int kmsflag;
12446 
12447 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12448 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12449 	if (spkt == NULL) {
12450 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12451 		    "sata_pkt_alloc: failed"));
12452 		return (NULL);
12453 	}
12454 	spkt->satapkt_rev = SATA_PKT_REV;
12455 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12456 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12457 	spkt->satapkt_framework_private = spx;
12458 	spx->txlt_sata_pkt = spkt;
12459 	return (spkt);
12460 }
12461 
12462 /*
12463  * Free sata pkt allocated via sata_pkt_alloc()
12464  */
12465 static void
12466 sata_pkt_free(sata_pkt_txlate_t *spx)
12467 {
12468 	ASSERT(spx->txlt_sata_pkt != NULL);
12469 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12470 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12471 	spx->txlt_sata_pkt = NULL;
12472 }
12473 
12474 
12475 /*
12476  * Adjust DMA attributes.
12477  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12478  * from 8 bits to 16 bits, depending on a command being used.
12479  * Limiting max block count arbitrarily to 256 for all read/write
12480  * commands may affects performance, so check both the device and
12481  * controller capability before adjusting dma attributes.
12482  */
12483 void
12484 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12485     ddi_dma_attr_t *adj_dma_attr)
12486 {
12487 	uint32_t count_max;
12488 
12489 	/* Copy original attributes */
12490 	*adj_dma_attr = *dma_attr;
12491 	/*
12492 	 * Things to consider: device addressing capability,
12493 	 * "excessive" controller DMA capabilities.
12494 	 * If a device is being probed/initialized, there are
12495 	 * no device info - use default limits then.
12496 	 */
12497 	if (sdinfo == NULL) {
12498 		count_max = dma_attr->dma_attr_granular * 0x100;
12499 		if (dma_attr->dma_attr_count_max > count_max)
12500 			adj_dma_attr->dma_attr_count_max = count_max;
12501 		if (dma_attr->dma_attr_maxxfer > count_max)
12502 			adj_dma_attr->dma_attr_maxxfer = count_max;
12503 		return;
12504 	}
12505 
12506 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12507 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12508 			/*
12509 			 * 16-bit sector count may be used - we rely on
12510 			 * the assumption that only read and write cmds
12511 			 * will request more than 256 sectors worth of data
12512 			 */
12513 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12514 		} else {
12515 			/*
12516 			 * 8-bit sector count will be used - default limits
12517 			 * for dma attributes
12518 			 */
12519 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12520 		}
12521 		/*
12522 		 * Adjust controler dma attributes, if necessary
12523 		 */
12524 		if (dma_attr->dma_attr_count_max > count_max)
12525 			adj_dma_attr->dma_attr_count_max = count_max;
12526 		if (dma_attr->dma_attr_maxxfer > count_max)
12527 			adj_dma_attr->dma_attr_maxxfer = count_max;
12528 	}
12529 }
12530 
12531 
12532 /*
12533  * Allocate DMA resources for the buffer
12534  * This function handles initial DMA resource allocation as well as
12535  * DMA window shift and may be called repeatedly for the same DMA window
12536  * until all DMA cookies in the DMA window are processed.
12537  * To guarantee that there is always a coherent set of cookies to process
12538  * by SATA HBA driver (observing alignment, device granularity, etc.),
12539  * the number of slots for DMA cookies is equal to lesser of  a number of
12540  * cookies in a DMA window and a max number of scatter/gather entries.
12541  *
12542  * Returns DDI_SUCCESS upon successful operation.
12543  * Return failure code of a failing command or DDI_FAILURE when
12544  * internal cleanup failed.
12545  */
12546 static int
12547 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12548     int (*callback)(caddr_t), caddr_t arg,
12549     ddi_dma_attr_t *cur_dma_attr)
12550 {
12551 	int	rval;
12552 	off_t	offset;
12553 	size_t	size;
12554 	int	max_sg_len, req_len, i;
12555 	uint_t	dma_flags;
12556 	struct buf	*bp;
12557 	uint64_t	cur_txfer_len;
12558 
12559 
12560 	ASSERT(spx->txlt_sata_pkt != NULL);
12561 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12562 	ASSERT(bp != NULL);
12563 
12564 
12565 	if (spx->txlt_buf_dma_handle == NULL) {
12566 		/*
12567 		 * No DMA resources allocated so far - this is a first call
12568 		 * for this sata pkt.
12569 		 */
12570 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12571 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12572 
12573 		if (rval != DDI_SUCCESS) {
12574 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12575 			    "sata_dma_buf_setup: no buf DMA resources %x",
12576 			    rval));
12577 			return (rval);
12578 		}
12579 
12580 		if (bp->b_flags & B_READ)
12581 			dma_flags = DDI_DMA_READ;
12582 		else
12583 			dma_flags = DDI_DMA_WRITE;
12584 
12585 		if (flags & PKT_CONSISTENT)
12586 			dma_flags |= DDI_DMA_CONSISTENT;
12587 
12588 		if (flags & PKT_DMA_PARTIAL)
12589 			dma_flags |= DDI_DMA_PARTIAL;
12590 
12591 		/*
12592 		 * Check buffer alignment and size against dma attributes
12593 		 * Consider dma_attr_align only. There may be requests
12594 		 * with the size lower than device granularity, but they
12595 		 * will not read/write from/to the device, so no adjustment
12596 		 * is necessary. The dma_attr_minxfer theoretically should
12597 		 * be considered, but no HBA driver is checking it.
12598 		 */
12599 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12600 		    cur_dma_attr->dma_attr_align)) {
12601 			rval = ddi_dma_buf_bind_handle(
12602 			    spx->txlt_buf_dma_handle,
12603 			    bp, dma_flags, callback, arg,
12604 			    &spx->txlt_dma_cookie,
12605 			    &spx->txlt_curwin_num_dma_cookies);
12606 		} else { /* Buffer is not aligned */
12607 
12608 			int	(*ddicallback)(caddr_t);
12609 			size_t	bufsz;
12610 
12611 			/* Check id sleeping is allowed */
12612 			ddicallback = (callback == NULL_FUNC) ?
12613 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12614 
12615 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12616 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12617 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12618 
12619 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12620 				/*
12621 				 * CPU will need to access data in the buffer
12622 				 * (for copying) so map it.
12623 				 */
12624 				bp_mapin(bp);
12625 
12626 			ASSERT(spx->txlt_tmp_buf == NULL);
12627 
12628 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12629 			rval = ddi_dma_mem_alloc(
12630 			    spx->txlt_buf_dma_handle,
12631 			    bp->b_bcount,
12632 			    &sata_acc_attr,
12633 			    DDI_DMA_STREAMING,
12634 			    ddicallback, NULL,
12635 			    &spx->txlt_tmp_buf,
12636 			    &bufsz,
12637 			    &spx->txlt_tmp_buf_handle);
12638 
12639 			if (rval != DDI_SUCCESS) {
12640 				/* DMA mapping failed */
12641 				(void) ddi_dma_free_handle(
12642 				    &spx->txlt_buf_dma_handle);
12643 				spx->txlt_buf_dma_handle = NULL;
12644 #ifdef SATA_DEBUG
12645 				mbuffail_count++;
12646 #endif
12647 				SATADBG1(SATA_DBG_DMA_SETUP,
12648 				    spx->txlt_sata_hba_inst,
12649 				    "sata_dma_buf_setup: "
12650 				    "buf dma mem alloc failed %x\n", rval);
12651 				return (rval);
12652 			}
12653 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12654 			    cur_dma_attr->dma_attr_align));
12655 
12656 #ifdef SATA_DEBUG
12657 			mbuf_count++;
12658 
12659 			if (bp->b_bcount != bufsz)
12660 				/*
12661 				 * This will require special handling, because
12662 				 * DMA cookies will be based on the temporary
12663 				 * buffer size, not the original buffer
12664 				 * b_bcount, so the residue may have to
12665 				 * be counted differently.
12666 				 */
12667 				SATADBG2(SATA_DBG_DMA_SETUP,
12668 				    spx->txlt_sata_hba_inst,
12669 				    "sata_dma_buf_setup: bp size %x != "
12670 				    "bufsz %x\n", bp->b_bcount, bufsz);
12671 #endif
12672 			if (dma_flags & DDI_DMA_WRITE) {
12673 				/*
12674 				 * Write operation - copy data into
12675 				 * an aligned temporary buffer. Buffer will be
12676 				 * synced for device by ddi_dma_addr_bind_handle
12677 				 */
12678 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12679 				    bp->b_bcount);
12680 			}
12681 
12682 			rval = ddi_dma_addr_bind_handle(
12683 			    spx->txlt_buf_dma_handle,
12684 			    NULL,
12685 			    spx->txlt_tmp_buf,
12686 			    bufsz, dma_flags, ddicallback, 0,
12687 			    &spx->txlt_dma_cookie,
12688 			    &spx->txlt_curwin_num_dma_cookies);
12689 		}
12690 
12691 		switch (rval) {
12692 		case DDI_DMA_PARTIAL_MAP:
12693 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12694 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12695 			/*
12696 			 * Partial DMA mapping.
12697 			 * Retrieve number of DMA windows for this request.
12698 			 */
12699 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12700 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12701 				if (spx->txlt_tmp_buf != NULL) {
12702 					ddi_dma_mem_free(
12703 					    &spx->txlt_tmp_buf_handle);
12704 					spx->txlt_tmp_buf = NULL;
12705 				}
12706 				(void) ddi_dma_unbind_handle(
12707 				    spx->txlt_buf_dma_handle);
12708 				(void) ddi_dma_free_handle(
12709 				    &spx->txlt_buf_dma_handle);
12710 				spx->txlt_buf_dma_handle = NULL;
12711 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12712 				    "sata_dma_buf_setup: numwin failed\n"));
12713 				return (DDI_FAILURE);
12714 			}
12715 			SATADBG2(SATA_DBG_DMA_SETUP,
12716 			    spx->txlt_sata_hba_inst,
12717 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12718 			    spx->txlt_num_dma_win,
12719 			    spx->txlt_curwin_num_dma_cookies);
12720 			spx->txlt_cur_dma_win = 0;
12721 			break;
12722 
12723 		case DDI_DMA_MAPPED:
12724 			/* DMA fully mapped */
12725 			spx->txlt_num_dma_win = 1;
12726 			spx->txlt_cur_dma_win = 0;
12727 			SATADBG1(SATA_DBG_DMA_SETUP,
12728 			    spx->txlt_sata_hba_inst,
12729 			    "sata_dma_buf_setup: windows: 1 "
12730 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12731 			break;
12732 
12733 		default:
12734 			/* DMA mapping failed */
12735 			if (spx->txlt_tmp_buf != NULL) {
12736 				ddi_dma_mem_free(
12737 				    &spx->txlt_tmp_buf_handle);
12738 				spx->txlt_tmp_buf = NULL;
12739 			}
12740 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12741 			spx->txlt_buf_dma_handle = NULL;
12742 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12743 			    "sata_dma_buf_setup: buf dma handle binding "
12744 			    "failed %x\n", rval));
12745 			return (rval);
12746 		}
12747 		spx->txlt_curwin_processed_dma_cookies = 0;
12748 		spx->txlt_dma_cookie_list = NULL;
12749 	} else {
12750 		/*
12751 		 * DMA setup is reused. Check if we need to process more
12752 		 * cookies in current window, or to get next window, if any.
12753 		 */
12754 
12755 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12756 		    spx->txlt_curwin_num_dma_cookies);
12757 
12758 		if (spx->txlt_curwin_processed_dma_cookies ==
12759 		    spx->txlt_curwin_num_dma_cookies) {
12760 			/*
12761 			 * All cookies from current DMA window were processed.
12762 			 * Get next DMA window.
12763 			 */
12764 			spx->txlt_cur_dma_win++;
12765 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12766 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12767 				    spx->txlt_cur_dma_win, &offset, &size,
12768 				    &spx->txlt_dma_cookie,
12769 				    &spx->txlt_curwin_num_dma_cookies);
12770 				spx->txlt_curwin_processed_dma_cookies = 0;
12771 			} else {
12772 				/* No more windows! End of request! */
12773 				/* What to do? - panic for now */
12774 				ASSERT(spx->txlt_cur_dma_win >=
12775 				    spx->txlt_num_dma_win);
12776 
12777 				spx->txlt_curwin_num_dma_cookies = 0;
12778 				spx->txlt_curwin_processed_dma_cookies = 0;
12779 				spx->txlt_sata_pkt->
12780 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12781 				return (DDI_SUCCESS);
12782 			}
12783 		}
12784 	}
12785 	/* There better be at least one DMA cookie outstanding */
12786 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12787 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12788 
12789 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12790 		/* The default cookie slot was used in previous run */
12791 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12792 		spx->txlt_dma_cookie_list = NULL;
12793 		spx->txlt_dma_cookie_list_len = 0;
12794 	}
12795 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12796 		/*
12797 		 * Processing a new DMA window - set-up dma cookies list.
12798 		 * We may reuse previously allocated cookie array if it is
12799 		 * possible.
12800 		 */
12801 		if (spx->txlt_dma_cookie_list != NULL &&
12802 		    spx->txlt_dma_cookie_list_len <
12803 		    spx->txlt_curwin_num_dma_cookies) {
12804 			/*
12805 			 * New DMA window contains more cookies than
12806 			 * the previous one. We need larger cookie list - free
12807 			 * the old one.
12808 			 */
12809 			(void) kmem_free(spx->txlt_dma_cookie_list,
12810 			    spx->txlt_dma_cookie_list_len *
12811 			    sizeof (ddi_dma_cookie_t));
12812 			spx->txlt_dma_cookie_list = NULL;
12813 			spx->txlt_dma_cookie_list_len = 0;
12814 		}
12815 		if (spx->txlt_dma_cookie_list == NULL) {
12816 			/*
12817 			 * Calculate lesser of number of cookies in this
12818 			 * DMA window and number of s/g entries.
12819 			 */
12820 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12821 			req_len = MIN(max_sg_len,
12822 			    spx->txlt_curwin_num_dma_cookies);
12823 
12824 			/* Allocate new dma cookie array if necessary */
12825 			if (req_len == 1) {
12826 				/* Only one cookie - no need for a list */
12827 				spx->txlt_dma_cookie_list =
12828 				    &spx->txlt_dma_cookie;
12829 				spx->txlt_dma_cookie_list_len = 1;
12830 			} else {
12831 				/*
12832 				 * More than one cookie - try to allocate space.
12833 				 */
12834 				spx->txlt_dma_cookie_list = kmem_zalloc(
12835 				    sizeof (ddi_dma_cookie_t) * req_len,
12836 				    callback == NULL_FUNC ? KM_NOSLEEP :
12837 				    KM_SLEEP);
12838 				if (spx->txlt_dma_cookie_list == NULL) {
12839 					SATADBG1(SATA_DBG_DMA_SETUP,
12840 					    spx->txlt_sata_hba_inst,
12841 					    "sata_dma_buf_setup: cookie list "
12842 					    "allocation failed\n", NULL);
12843 					/*
12844 					 * We could not allocate space for
12845 					 * neccessary number of dma cookies in
12846 					 * this window, so we fail this request.
12847 					 * Next invocation would try again to
12848 					 * allocate space for cookie list.
12849 					 * Note:Packet residue was not modified.
12850 					 */
12851 					return (DDI_DMA_NORESOURCES);
12852 				} else {
12853 					spx->txlt_dma_cookie_list_len = req_len;
12854 				}
12855 			}
12856 		}
12857 		/*
12858 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12859 		 * First cookie was already fetched.
12860 		 */
12861 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12862 		cur_txfer_len =
12863 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12864 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12865 		spx->txlt_curwin_processed_dma_cookies++;
12866 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12867 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12868 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12869 			    &spx->txlt_dma_cookie_list[i]);
12870 			cur_txfer_len +=
12871 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12872 			spx->txlt_curwin_processed_dma_cookies++;
12873 			spx->txlt_sata_pkt->
12874 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12875 		}
12876 	} else {
12877 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12878 		    "sata_dma_buf_setup: sliding within DMA window, "
12879 		    "cur cookie %d, total cookies %d\n",
12880 		    spx->txlt_curwin_processed_dma_cookies,
12881 		    spx->txlt_curwin_num_dma_cookies);
12882 
12883 		/*
12884 		 * Not all cookies from the current dma window were used because
12885 		 * of s/g limitation.
12886 		 * There is no need to re-size the list - it was set at
12887 		 * optimal size, or only default entry is used (s/g = 1).
12888 		 */
12889 		if (spx->txlt_dma_cookie_list == NULL) {
12890 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12891 			spx->txlt_dma_cookie_list_len = 1;
12892 		}
12893 		/*
12894 		 * Since we are processing remaining cookies in a DMA window,
12895 		 * there may be less of them than the number of entries in the
12896 		 * current dma cookie list.
12897 		 */
12898 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12899 		    (spx->txlt_curwin_num_dma_cookies -
12900 		    spx->txlt_curwin_processed_dma_cookies));
12901 
12902 		/* Fetch the next batch of cookies */
12903 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12904 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12905 			    &spx->txlt_dma_cookie_list[i]);
12906 			cur_txfer_len +=
12907 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12908 			spx->txlt_sata_pkt->
12909 			    satapkt_cmd.satacmd_num_dma_cookies++;
12910 			spx->txlt_curwin_processed_dma_cookies++;
12911 		}
12912 	}
12913 
12914 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12915 
12916 	/* Point sata_cmd to the cookie list */
12917 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12918 	    &spx->txlt_dma_cookie_list[0];
12919 
12920 	/* Remember number of DMA cookies passed in sata packet */
12921 	spx->txlt_num_dma_cookies =
12922 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12923 
12924 	ASSERT(cur_txfer_len != 0);
12925 	if (cur_txfer_len <= bp->b_bcount)
12926 		spx->txlt_total_residue -= cur_txfer_len;
12927 	else {
12928 		/*
12929 		 * Temporary DMA buffer has been padded by
12930 		 * ddi_dma_mem_alloc()!
12931 		 * This requires special handling, because DMA cookies are
12932 		 * based on the temporary buffer size, not the b_bcount,
12933 		 * and we have extra bytes to transfer - but the packet
12934 		 * residue has to stay correct because we will copy only
12935 		 * the requested number of bytes.
12936 		 */
12937 		spx->txlt_total_residue -= bp->b_bcount;
12938 	}
12939 
12940 	return (DDI_SUCCESS);
12941 }
12942 
12943 /*
12944  * Common routine for releasing DMA resources
12945  */
12946 static void
12947 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12948 {
12949 	if (spx->txlt_buf_dma_handle != NULL) {
12950 		if (spx->txlt_tmp_buf != NULL)  {
12951 			/*
12952 			 * Intermediate DMA buffer was allocated.
12953 			 * Free allocated buffer and associated access handle.
12954 			 */
12955 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12956 			spx->txlt_tmp_buf = NULL;
12957 		}
12958 		/*
12959 		 * Free DMA resources - cookies and handles
12960 		 */
12961 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12962 		if (spx->txlt_dma_cookie_list != NULL) {
12963 			if (spx->txlt_dma_cookie_list !=
12964 			    &spx->txlt_dma_cookie) {
12965 				(void) kmem_free(spx->txlt_dma_cookie_list,
12966 				    spx->txlt_dma_cookie_list_len *
12967 				    sizeof (ddi_dma_cookie_t));
12968 				spx->txlt_dma_cookie_list = NULL;
12969 			}
12970 		}
12971 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12972 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12973 		spx->txlt_buf_dma_handle = NULL;
12974 	}
12975 }
12976 
12977 /*
12978  * Free DMA resources
12979  * Used by the HBA driver to release DMA resources that it does not use.
12980  *
12981  * Returns Void
12982  */
12983 void
12984 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12985 {
12986 	sata_pkt_txlate_t *spx;
12987 
12988 	if (sata_pkt == NULL)
12989 		return;
12990 
12991 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12992 
12993 	sata_common_free_dma_rsrcs(spx);
12994 }
12995 
12996 /*
12997  * Fetch Device Identify data.
12998  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12999  * command to a device and get the device identify data.
13000  * The device_info structure has to be set to device type (for selecting proper
13001  * device identify command).
13002  *
13003  * Returns:
13004  * SATA_SUCCESS if cmd succeeded
13005  * SATA_RETRY if cmd was rejected and could be retried,
13006  * SATA_FAILURE if cmd failed and should not be retried (port error)
13007  *
13008  * Cannot be called in an interrupt context.
13009  */
13010 
13011 static int
13012 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13013     sata_drive_info_t *sdinfo)
13014 {
13015 	struct buf *bp;
13016 	sata_pkt_t *spkt;
13017 	sata_cmd_t *scmd;
13018 	sata_pkt_txlate_t *spx;
13019 	int rval;
13020 
13021 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13022 	spx->txlt_sata_hba_inst = sata_hba_inst;
13023 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13024 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13025 	if (spkt == NULL) {
13026 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13027 		return (SATA_RETRY); /* may retry later */
13028 	}
13029 	/* address is needed now */
13030 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13031 
13032 	/*
13033 	 * Allocate buffer for Identify Data return data
13034 	 */
13035 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13036 	if (bp == NULL) {
13037 		sata_pkt_free(spx);
13038 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13039 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13040 		    "sata_fetch_device_identify_data: "
13041 		    "cannot allocate buffer for ID"));
13042 		return (SATA_RETRY); /* may retry later */
13043 	}
13044 
13045 	/* Fill sata_pkt */
13046 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13047 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13048 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13049 	/* Synchronous mode, no callback */
13050 	spkt->satapkt_comp = NULL;
13051 	/* Timeout 30s */
13052 	spkt->satapkt_time = sata_default_pkt_time;
13053 
13054 	scmd = &spkt->satapkt_cmd;
13055 	scmd->satacmd_bp = bp;
13056 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13057 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13058 
13059 	/* Build Identify Device cmd in the sata_pkt */
13060 	scmd->satacmd_addr_type = 0;		/* N/A */
13061 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13062 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13063 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13064 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13065 	scmd->satacmd_features_reg = 0;		/* N/A */
13066 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13067 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13068 		/* Identify Packet Device cmd */
13069 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13070 	} else {
13071 		/* Identify Device cmd - mandatory for all other devices */
13072 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13073 	}
13074 
13075 	/* Send pkt to SATA HBA driver */
13076 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13077 
13078 #ifdef SATA_INJECT_FAULTS
13079 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13080 #endif
13081 
13082 	if (rval == SATA_TRAN_ACCEPTED &&
13083 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13084 		if (spx->txlt_buf_dma_handle != NULL) {
13085 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13086 			    DDI_DMA_SYNC_FORKERNEL);
13087 			ASSERT(rval == DDI_SUCCESS);
13088 		}
13089 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13090 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13091 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13092 			    "SATA disk device at port %d - "
13093 			    "partial Identify Data",
13094 			    sdinfo->satadrv_addr.cport));
13095 			rval = SATA_RETRY; /* may retry later */
13096 			goto fail;
13097 		}
13098 		/* Update sata_drive_info */
13099 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13100 		    sizeof (sata_id_t));
13101 
13102 		sdinfo->satadrv_features_support = 0;
13103 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13104 			/*
13105 			 * Retrieve capacity (disks only) and addressing mode
13106 			 */
13107 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13108 		} else {
13109 			/*
13110 			 * For ATAPI devices one would have to issue
13111 			 * Get Capacity cmd for media capacity. Not here.
13112 			 */
13113 			sdinfo->satadrv_capacity = 0;
13114 			/*
13115 			 * Check what cdb length is supported
13116 			 */
13117 			if ((sdinfo->satadrv_id.ai_config &
13118 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13119 				sdinfo->satadrv_atapi_cdb_len = 16;
13120 			else
13121 				sdinfo->satadrv_atapi_cdb_len = 12;
13122 		}
13123 		/* Setup supported features flags */
13124 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13125 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13126 
13127 		/* Check for SATA GEN and NCQ support */
13128 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13129 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13130 			/* SATA compliance */
13131 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13132 				sdinfo->satadrv_features_support |=
13133 				    SATA_DEV_F_NCQ;
13134 			if (sdinfo->satadrv_id.ai_satacap &
13135 			    (SATA_1_SPEED | SATA_2_SPEED)) {
13136 				if (sdinfo->satadrv_id.ai_satacap &
13137 				    SATA_2_SPEED)
13138 					sdinfo->satadrv_features_support |=
13139 					    SATA_DEV_F_SATA2;
13140 				if (sdinfo->satadrv_id.ai_satacap &
13141 				    SATA_1_SPEED)
13142 					sdinfo->satadrv_features_support |=
13143 					    SATA_DEV_F_SATA1;
13144 			} else {
13145 				sdinfo->satadrv_features_support |=
13146 				    SATA_DEV_F_SATA1;
13147 			}
13148 		}
13149 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13150 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13151 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13152 
13153 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13154 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13155 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13156 			++sdinfo->satadrv_queue_depth;
13157 			/* Adjust according to controller capabilities */
13158 			sdinfo->satadrv_max_queue_depth = MIN(
13159 			    sdinfo->satadrv_queue_depth,
13160 			    SATA_QDEPTH(sata_hba_inst));
13161 			/* Adjust according to global queue depth limit */
13162 			sdinfo->satadrv_max_queue_depth = MIN(
13163 			    sdinfo->satadrv_max_queue_depth,
13164 			    sata_current_max_qdepth);
13165 			if (sdinfo->satadrv_max_queue_depth == 0)
13166 				sdinfo->satadrv_max_queue_depth = 1;
13167 		} else
13168 			sdinfo->satadrv_max_queue_depth = 1;
13169 
13170 		rval = SATA_SUCCESS;
13171 	} else {
13172 		/*
13173 		 * Woops, no Identify Data.
13174 		 */
13175 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13176 			rval = SATA_RETRY; /* may retry later */
13177 		} else if (rval == SATA_TRAN_ACCEPTED) {
13178 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13179 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13180 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13181 			    spkt->satapkt_reason == SATA_PKT_RESET)
13182 				rval = SATA_RETRY; /* may retry later */
13183 			else
13184 				rval = SATA_FAILURE;
13185 		} else {
13186 			rval = SATA_FAILURE;
13187 		}
13188 	}
13189 fail:
13190 	/* Free allocated resources */
13191 	sata_free_local_buffer(spx);
13192 	sata_pkt_free(spx);
13193 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13194 
13195 	return (rval);
13196 }
13197 
13198 
13199 /*
13200  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13201  * UDMA mode is checked first, followed by MWDMA mode.
13202  * set correctly, so this function is setting it to the highest supported level.
13203  * Older SATA spec required that the device supports at least DMA 4 mode and
13204  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13205  * restriction has been removed.
13206  *
13207  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13208  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13209  *
13210  * NOTE: This function should be called only if DMA mode is supported.
13211  */
13212 static int
13213 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13214 {
13215 	sata_pkt_t *spkt;
13216 	sata_cmd_t *scmd;
13217 	sata_pkt_txlate_t *spx;
13218 	int i, mode;
13219 	uint8_t subcmd;
13220 	int rval = SATA_SUCCESS;
13221 
13222 	ASSERT(sdinfo != NULL);
13223 	ASSERT(sata_hba_inst != NULL);
13224 
13225 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13226 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13227 		/* Find highest Ultra DMA mode supported */
13228 		for (mode = 6; mode >= 0; --mode) {
13229 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13230 				break;
13231 		}
13232 #if 0
13233 		/* Left for historical reasons */
13234 		/*
13235 		 * Some initial version of SATA spec indicated that at least
13236 		 * UDMA mode 4 has to be supported. It is not mentioned in
13237 		 * SerialATA 2.6, so this restriction is removed.
13238 		 */
13239 		if (mode < 4)
13240 			return (SATA_FAILURE);
13241 #endif
13242 
13243 		/*
13244 		 * For disk, we're still going to set DMA mode whatever is
13245 		 * selected by default
13246 		 *
13247 		 * We saw an old maxtor sata drive will select Ultra DMA and
13248 		 * Multi-Word DMA simultaneouly by default, which is going
13249 		 * to cause DMA command timed out, so we need to select DMA
13250 		 * mode even when it's already done by default
13251 		 */
13252 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13253 
13254 			/* Find UDMA mode currently selected */
13255 			for (i = 6; i >= 0; --i) {
13256 				if (sdinfo->satadrv_id.ai_ultradma &
13257 				    (1 << (i + 8)))
13258 					break;
13259 			}
13260 			if (i >= mode)
13261 				/* Nothing to do */
13262 				return (SATA_SUCCESS);
13263 		}
13264 
13265 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13266 
13267 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13268 		/* Find highest MultiWord DMA mode supported */
13269 		for (mode = 2; mode >= 0; --mode) {
13270 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13271 				break;
13272 		}
13273 
13274 		/*
13275 		 * For disk, We're still going to set DMA mode whatever is
13276 		 * selected by default
13277 		 *
13278 		 * We saw an old maxtor sata drive will select Ultra DMA and
13279 		 * Multi-Word DMA simultaneouly by default, which is going
13280 		 * to cause DMA command timed out, so we need to select DMA
13281 		 * mode even when it's already done by default
13282 		 */
13283 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13284 
13285 			/* Find highest MultiWord DMA mode selected */
13286 			for (i = 2; i >= 0; --i) {
13287 				if (sdinfo->satadrv_id.ai_dworddma &
13288 				    (1 << (i + 8)))
13289 					break;
13290 			}
13291 			if (i >= mode)
13292 				/* Nothing to do */
13293 				return (SATA_SUCCESS);
13294 		}
13295 
13296 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13297 	} else
13298 		return (SATA_SUCCESS);
13299 
13300 	/*
13301 	 * Set DMA mode via SET FEATURES COMMAND.
13302 	 * Prepare packet for SET FEATURES COMMAND.
13303 	 */
13304 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13305 	spx->txlt_sata_hba_inst = sata_hba_inst;
13306 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13307 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13308 	if (spkt == NULL) {
13309 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13310 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
13311 		rval = SATA_FAILURE;
13312 		goto done;
13313 	}
13314 	/* Fill sata_pkt */
13315 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13316 	/* Timeout 30s */
13317 	spkt->satapkt_time = sata_default_pkt_time;
13318 	/* Synchronous mode, no callback, interrupts */
13319 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13320 	spkt->satapkt_comp = NULL;
13321 	scmd = &spkt->satapkt_cmd;
13322 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13323 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13324 	scmd->satacmd_addr_type = 0;
13325 	scmd->satacmd_device_reg = 0;
13326 	scmd->satacmd_status_reg = 0;
13327 	scmd->satacmd_error_reg = 0;
13328 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13329 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13330 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13331 
13332 	/* Transfer command to HBA */
13333 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13334 	    spkt) != SATA_TRAN_ACCEPTED ||
13335 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13336 		/* Pkt execution failed */
13337 		rval = SATA_FAILURE;
13338 	}
13339 done:
13340 
13341 	/* Free allocated resources */
13342 	if (spkt != NULL)
13343 		sata_pkt_free(spx);
13344 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13345 
13346 	return (rval);
13347 }
13348 
13349 
13350 /*
13351  * Set device caching mode.
13352  * One of the following operations should be specified:
13353  * SATAC_SF_ENABLE_READ_AHEAD
13354  * SATAC_SF_DISABLE_READ_AHEAD
13355  * SATAC_SF_ENABLE_WRITE_CACHE
13356  * SATAC_SF_DISABLE_WRITE_CACHE
13357  *
13358  * If operation fails, system log messgage is emitted.
13359  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13360  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13361  */
13362 
13363 static int
13364 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13365     int cache_op)
13366 {
13367 	sata_pkt_t *spkt;
13368 	sata_cmd_t *scmd;
13369 	sata_pkt_txlate_t *spx;
13370 	int rval = SATA_SUCCESS;
13371 	int hba_rval;
13372 	char *infop;
13373 
13374 	ASSERT(sdinfo != NULL);
13375 	ASSERT(sata_hba_inst != NULL);
13376 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13377 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13378 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13379 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13380 
13381 
13382 	/* Prepare packet for SET FEATURES COMMAND */
13383 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13384 	spx->txlt_sata_hba_inst = sata_hba_inst;
13385 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13386 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13387 	if (spkt == NULL) {
13388 		rval = SATA_FAILURE;
13389 		goto failure;
13390 	}
13391 	/* Fill sata_pkt */
13392 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13393 	/* Timeout 30s */
13394 	spkt->satapkt_time = sata_default_pkt_time;
13395 	/* Synchronous mode, no callback, interrupts */
13396 	spkt->satapkt_op_mode =
13397 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13398 	spkt->satapkt_comp = NULL;
13399 	scmd = &spkt->satapkt_cmd;
13400 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13401 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13402 	scmd->satacmd_addr_type = 0;
13403 	scmd->satacmd_device_reg = 0;
13404 	scmd->satacmd_status_reg = 0;
13405 	scmd->satacmd_error_reg = 0;
13406 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13407 	scmd->satacmd_features_reg = cache_op;
13408 
13409 	/* Transfer command to HBA */
13410 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13411 	    SATA_DIP(sata_hba_inst), spkt);
13412 
13413 #ifdef SATA_INJECT_FAULTS
13414 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13415 #endif
13416 
13417 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13418 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13419 		/* Pkt execution failed */
13420 		switch (cache_op) {
13421 		case SATAC_SF_ENABLE_READ_AHEAD:
13422 			infop = "enabling read ahead failed";
13423 			break;
13424 		case SATAC_SF_DISABLE_READ_AHEAD:
13425 			infop = "disabling read ahead failed";
13426 			break;
13427 		case SATAC_SF_ENABLE_WRITE_CACHE:
13428 			infop = "enabling write cache failed";
13429 			break;
13430 		case SATAC_SF_DISABLE_WRITE_CACHE:
13431 			infop = "disabling write cache failed";
13432 			break;
13433 		}
13434 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13435 		rval = SATA_RETRY;
13436 	}
13437 failure:
13438 	/* Free allocated resources */
13439 	if (spkt != NULL)
13440 		sata_pkt_free(spx);
13441 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13442 	return (rval);
13443 }
13444 
13445 /*
13446  * Set Removable Media Status Notification (enable/disable)
13447  * state == 0 , disable
13448  * state != 0 , enable
13449  *
13450  * If operation fails, system log messgage is emitted.
13451  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13452  */
13453 
13454 static int
13455 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13456     int state)
13457 {
13458 	sata_pkt_t *spkt;
13459 	sata_cmd_t *scmd;
13460 	sata_pkt_txlate_t *spx;
13461 	int rval = SATA_SUCCESS;
13462 	char *infop;
13463 
13464 	ASSERT(sdinfo != NULL);
13465 	ASSERT(sata_hba_inst != NULL);
13466 
13467 	/* Prepare packet for SET FEATURES COMMAND */
13468 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13469 	spx->txlt_sata_hba_inst = sata_hba_inst;
13470 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13471 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13472 	if (spkt == NULL) {
13473 		rval = SATA_FAILURE;
13474 		goto failure;
13475 	}
13476 	/* Fill sata_pkt */
13477 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13478 	/* Timeout 30s */
13479 	spkt->satapkt_time = sata_default_pkt_time;
13480 	/* Synchronous mode, no callback, interrupts */
13481 	spkt->satapkt_op_mode =
13482 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13483 	spkt->satapkt_comp = NULL;
13484 	scmd = &spkt->satapkt_cmd;
13485 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13486 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13487 	scmd->satacmd_addr_type = 0;
13488 	scmd->satacmd_device_reg = 0;
13489 	scmd->satacmd_status_reg = 0;
13490 	scmd->satacmd_error_reg = 0;
13491 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13492 	if (state == 0)
13493 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13494 	else
13495 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13496 
13497 	/* Transfer command to HBA */
13498 	if (((*SATA_START_FUNC(sata_hba_inst))(
13499 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13500 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13501 		/* Pkt execution failed */
13502 		if (state == 0)
13503 			infop = "disabling Removable Media Status "
13504 			    "Notification failed";
13505 		else
13506 			infop = "enabling Removable Media Status "
13507 			    "Notification failed";
13508 
13509 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13510 		rval = SATA_FAILURE;
13511 	}
13512 failure:
13513 	/* Free allocated resources */
13514 	if (spkt != NULL)
13515 		sata_pkt_free(spx);
13516 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13517 	return (rval);
13518 }
13519 
13520 
13521 /*
13522  * Update state and copy port ss* values from passed sata_device structure.
13523  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13524  * configuration struct.
13525  *
13526  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13527  * regardless of the state in device argument.
13528  *
13529  * Port mutex should be held while calling this function.
13530  */
13531 static void
13532 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13533     sata_device_t *sata_device)
13534 {
13535 	sata_cport_info_t *cportinfo;
13536 
13537 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13538 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13539 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13540 		    sata_device->satadev_addr.cport)
13541 			return;
13542 
13543 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13544 		    sata_device->satadev_addr.cport);
13545 
13546 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13547 		cportinfo->cport_scr = sata_device->satadev_scr;
13548 
13549 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13550 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13551 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13552 		cportinfo->cport_state |=
13553 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13554 	}
13555 }
13556 
13557 void
13558 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13559     sata_device_t *sata_device)
13560 {
13561 	sata_pmport_info_t *pmportinfo;
13562 
13563 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13564 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13565 	    SATA_NUM_PMPORTS(sata_hba_inst,
13566 	    sata_device->satadev_addr.cport) <
13567 	    sata_device->satadev_addr.pmport) {
13568 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13569 		    "sata_update_port_info: error address %p.",
13570 		    &sata_device->satadev_addr);
13571 		return;
13572 	}
13573 
13574 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13575 	    sata_device->satadev_addr.cport,
13576 	    sata_device->satadev_addr.pmport);
13577 
13578 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13579 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13580 
13581 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13582 	pmportinfo->pmport_state &=
13583 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13584 	pmportinfo->pmport_state |=
13585 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13586 }
13587 
13588 /*
13589  * Extract SATA port specification from an IOCTL argument.
13590  *
13591  * This function return the port the user land send us as is, unless it
13592  * cannot retrieve port spec, then -1 is returned.
13593  *
13594  * Support port multiplier.
13595  */
13596 static int32_t
13597 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13598 {
13599 	int32_t port;
13600 
13601 	/* Extract port number from nvpair in dca structure  */
13602 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13603 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13604 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13605 		    port));
13606 		port = -1;
13607 	}
13608 
13609 	return (port);
13610 }
13611 
13612 /*
13613  * Get dev_info_t pointer to the device node pointed to by port argument.
13614  * NOTE: target argument is a value used in ioctls to identify
13615  * the AP - it is not a sata_address.
13616  * It is a combination of cport, pmport and address qualifier, encodded same
13617  * way as a scsi target number.
13618  * At this moment it carries only cport number.
13619  *
13620  * PMult hotplug is supported now.
13621  *
13622  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13623  */
13624 
13625 static dev_info_t *
13626 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13627 {
13628 	dev_info_t	*cdip = NULL;
13629 	int		target, tgt;
13630 	int 		circ;
13631 	uint8_t		qual;
13632 
13633 	sata_hba_inst_t	*sata_hba_inst;
13634 	scsi_hba_tran_t *scsi_hba_tran;
13635 
13636 	/* Get target id */
13637 	scsi_hba_tran = ddi_get_driver_private(dip);
13638 	if (scsi_hba_tran == NULL)
13639 		return (NULL);
13640 
13641 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13642 
13643 	if (sata_hba_inst == NULL)
13644 		return (NULL);
13645 
13646 	/* Identify a port-mult by cport_info.cport_dev_type */
13647 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13648 		qual = SATA_ADDR_DPMPORT;
13649 	else
13650 		qual = SATA_ADDR_DCPORT;
13651 
13652 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13653 
13654 	/* Retrieve target dip */
13655 	ndi_devi_enter(dip, &circ);
13656 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13657 		dev_info_t *next = ddi_get_next_sibling(cdip);
13658 
13659 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13660 		    DDI_PROP_DONTPASS, "target", -1);
13661 		if (tgt == -1) {
13662 			/*
13663 			 * This is actually an error condition, but not
13664 			 * a fatal one. Just continue the search.
13665 			 */
13666 			cdip = next;
13667 			continue;
13668 		}
13669 
13670 		if (tgt == target)
13671 			break;
13672 
13673 		cdip = next;
13674 	}
13675 	ndi_devi_exit(dip, circ);
13676 
13677 	return (cdip);
13678 }
13679 
13680 /*
13681  * Get dev_info_t pointer to the device node pointed to by port argument.
13682  * NOTE: target argument is a value used in ioctls to identify
13683  * the AP - it is not a sata_address.
13684  * It is a combination of cport, pmport and address qualifier, encoded same
13685  * way as a scsi target number.
13686  *
13687  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13688  */
13689 
13690 static dev_info_t *
13691 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13692 {
13693 	dev_info_t	*cdip = NULL;
13694 	int		target, tgt;
13695 	int 		circ;
13696 
13697 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13698 
13699 	ndi_devi_enter(dip, &circ);
13700 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13701 		dev_info_t *next = ddi_get_next_sibling(cdip);
13702 
13703 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13704 		    DDI_PROP_DONTPASS, "target", -1);
13705 		if (tgt == -1) {
13706 			/*
13707 			 * This is actually an error condition, but not
13708 			 * a fatal one. Just continue the search.
13709 			 */
13710 			cdip = next;
13711 			continue;
13712 		}
13713 
13714 		if (tgt == target)
13715 			break;
13716 
13717 		cdip = next;
13718 	}
13719 	ndi_devi_exit(dip, circ);
13720 
13721 	return (cdip);
13722 }
13723 
13724 /*
13725  * Process sata port disconnect request.
13726  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13727  * before this request. Nevertheless, if a device is still configured,
13728  * we need to attempt to offline and unconfigure device.
13729  * Regardless of the unconfigure operation results the port is marked as
13730  * deactivated and no access to the attached device is possible.
13731  * If the target node remains because unconfigure operation failed, its state
13732  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13733  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13734  * the device and remove old target node.
13735  *
13736  * This function invokes sata_hba_inst->satahba_tran->
13737  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13738  * If successful, the device structure (if any) attached to the specified port
13739  * is removed and state of the port marked appropriately.
13740  * Failure of the port_deactivate may keep port in the physically active state,
13741  * or may fail the port.
13742  *
13743  * NOTE: Port multiplier is supported.
13744  */
13745 
13746 static int
13747 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13748     sata_device_t *sata_device)
13749 {
13750 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13751 	sata_cport_info_t *cportinfo = NULL;
13752 	sata_pmport_info_t *pmportinfo = NULL;
13753 	sata_pmult_info_t *pmultinfo = NULL;
13754 	sata_device_t subsdevice;
13755 	int cport, pmport, qual;
13756 	int rval = SATA_SUCCESS;
13757 	int npmport = 0;
13758 	int rv = 0;
13759 
13760 	cport = sata_device->satadev_addr.cport;
13761 	pmport = sata_device->satadev_addr.pmport;
13762 	qual = sata_device->satadev_addr.qual;
13763 
13764 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13765 	if (qual == SATA_ADDR_DCPORT)
13766 		qual = SATA_ADDR_CPORT;
13767 	else
13768 		qual = SATA_ADDR_PMPORT;
13769 
13770 	/*
13771 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13772 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13773 	 * Do the sanity check.
13774 	 */
13775 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13776 		/* No physical port deactivation supported. */
13777 		return (EINVAL);
13778 	}
13779 
13780 	/* Check the current state of the port */
13781 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13782 	    (SATA_DIP(sata_hba_inst), sata_device);
13783 
13784 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13785 
13786 	/*
13787 	 * Processing port mulitiplier
13788 	 */
13789 	if (qual == SATA_ADDR_CPORT &&
13790 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13791 		mutex_enter(&cportinfo->cport_mutex);
13792 
13793 		/* Check controller port status */
13794 		sata_update_port_info(sata_hba_inst, sata_device);
13795 		if (rval != SATA_SUCCESS ||
13796 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13797 			/*
13798 			 * Device port status is unknown or it is in failed
13799 			 * state
13800 			 */
13801 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13802 			    SATA_PSTATE_FAILED;
13803 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13804 			    "sata_hba_ioctl: connect: failed to deactivate "
13805 			    "SATA port %d", cport);
13806 			mutex_exit(&cportinfo->cport_mutex);
13807 			return (EIO);
13808 		}
13809 
13810 		/* Disconnect all sub-devices. */
13811 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13812 		if (pmultinfo != NULL) {
13813 
13814 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13815 			    sata_hba_inst, cport); npmport ++) {
13816 				subsdinfo = SATA_PMPORT_DRV_INFO(
13817 				    sata_hba_inst, cport, npmport);
13818 				if (subsdinfo == NULL)
13819 					continue;
13820 
13821 				subsdevice.satadev_addr = subsdinfo->
13822 				    satadrv_addr;
13823 
13824 				mutex_exit(&cportinfo->cport_mutex);
13825 				if (sata_ioctl_disconnect(sata_hba_inst,
13826 				    &subsdevice) == SATA_SUCCESS) {
13827 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13828 					"[Remove] device at port %d:%d "
13829 					"successfully.", cport, npmport);
13830 				}
13831 				mutex_enter(&cportinfo->cport_mutex);
13832 			}
13833 		}
13834 
13835 		/* Disconnect the port multiplier */
13836 		cportinfo->cport_state &= ~SATA_STATE_READY;
13837 		mutex_exit(&cportinfo->cport_mutex);
13838 
13839 		sata_device->satadev_addr.qual = qual;
13840 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13841 		    (SATA_DIP(sata_hba_inst), sata_device);
13842 
13843 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13844 		    SE_NO_HINT);
13845 
13846 		mutex_enter(&cportinfo->cport_mutex);
13847 		sata_update_port_info(sata_hba_inst, sata_device);
13848 		if (rval != SATA_SUCCESS &&
13849 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13850 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13851 			rv = EIO;
13852 		} else {
13853 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13854 		}
13855 		mutex_exit(&cportinfo->cport_mutex);
13856 
13857 		return (rv);
13858 	}
13859 
13860 	/*
13861 	 * Process non-port-multiplier device - it could be a drive connected
13862 	 * to a port multiplier port or a controller port.
13863 	 */
13864 	if (qual == SATA_ADDR_PMPORT) {
13865 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13866 		mutex_enter(&pmportinfo->pmport_mutex);
13867 		sata_update_pmport_info(sata_hba_inst, sata_device);
13868 		if (rval != SATA_SUCCESS ||
13869 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13870 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13871 			    SATA_PSTATE_FAILED;
13872 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13873 			    "sata_hba_ioctl: connect: failed to deactivate "
13874 			    "SATA port %d:%d", cport, pmport);
13875 			mutex_exit(&pmportinfo->pmport_mutex);
13876 			return (EIO);
13877 		}
13878 
13879 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13880 			sdinfo = pmportinfo->pmport_sata_drive;
13881 			ASSERT(sdinfo != NULL);
13882 		}
13883 
13884 		/*
13885 		 * Set port's dev_state to not ready - this will disable
13886 		 * an access to a potentially attached device.
13887 		 */
13888 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13889 
13890 		/* Remove and release sata_drive info structure. */
13891 		if (sdinfo != NULL) {
13892 			if ((sdinfo->satadrv_type &
13893 			    SATA_VALID_DEV_TYPE) != 0) {
13894 				/*
13895 				 * If a target node exists, try to offline
13896 				 * a device and remove target node.
13897 				 */
13898 				mutex_exit(&pmportinfo->pmport_mutex);
13899 				(void) sata_offline_device(sata_hba_inst,
13900 				    sata_device, sdinfo);
13901 				mutex_enter(&pmportinfo->pmport_mutex);
13902 			}
13903 
13904 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13905 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13906 			(void) kmem_free((void *)sdinfo,
13907 			    sizeof (sata_drive_info_t));
13908 		}
13909 		mutex_exit(&pmportinfo->pmport_mutex);
13910 
13911 	} else if (qual == SATA_ADDR_CPORT) {
13912 		mutex_enter(&cportinfo->cport_mutex);
13913 		sata_update_port_info(sata_hba_inst, sata_device);
13914 		if (rval != SATA_SUCCESS ||
13915 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13916 			/*
13917 			 * Device port status is unknown or it is in failed
13918 			 * state
13919 			 */
13920 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13921 			    SATA_PSTATE_FAILED;
13922 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13923 			    "sata_hba_ioctl: connect: failed to deactivate "
13924 			    "SATA port %d", cport);
13925 			mutex_exit(&cportinfo->cport_mutex);
13926 			return (EIO);
13927 		}
13928 
13929 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13930 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13931 			ASSERT(pmultinfo != NULL);
13932 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13933 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13934 			ASSERT(sdinfo != NULL);
13935 		}
13936 		cportinfo->cport_state &= ~SATA_STATE_READY;
13937 
13938 		if (sdinfo != NULL) {
13939 			if ((sdinfo->satadrv_type &
13940 			    SATA_VALID_DEV_TYPE) != 0) {
13941 				/*
13942 				 * If a target node exists, try to offline
13943 				 * a device and remove target node.
13944 				 */
13945 				mutex_exit(&cportinfo->cport_mutex);
13946 				(void) sata_offline_device(sata_hba_inst,
13947 				    sata_device, sdinfo);
13948 				mutex_enter(&cportinfo->cport_mutex);
13949 			}
13950 
13951 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13952 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13953 			(void) kmem_free((void *)sdinfo,
13954 			    sizeof (sata_drive_info_t));
13955 		}
13956 		mutex_exit(&cportinfo->cport_mutex);
13957 	}
13958 
13959 	/* Just ask HBA driver to deactivate port */
13960 	sata_device->satadev_addr.qual = qual;
13961 
13962 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13963 	    (SATA_DIP(sata_hba_inst), sata_device);
13964 
13965 	/*
13966 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13967 	 * without the hint (to force listener to investivate the state).
13968 	 */
13969 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13970 	    SE_NO_HINT);
13971 
13972 	if (qual == SATA_ADDR_PMPORT) {
13973 		mutex_enter(&pmportinfo->pmport_mutex);
13974 		sata_update_pmport_info(sata_hba_inst, sata_device);
13975 
13976 		if (rval != SATA_SUCCESS &&
13977 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13978 			/*
13979 			 * Port deactivation failure - do not change port
13980 			 * state unless the state returned by HBA indicates a
13981 			 * port failure.
13982 			 *
13983 			 * NOTE: device structures were released, so devices
13984 			 * now are invisible! Port reset is needed to
13985 			 * re-enumerate devices.
13986 			 */
13987 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13988 			rv = EIO;
13989 		} else {
13990 			/*
13991 			 * Deactivation succeded. From now on the sata framework
13992 			 * will not care what is happening to the device, until
13993 			 * the port is activated again.
13994 			 */
13995 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13996 		}
13997 		mutex_exit(&pmportinfo->pmport_mutex);
13998 	} else if (qual == SATA_ADDR_CPORT) {
13999 		mutex_enter(&cportinfo->cport_mutex);
14000 		sata_update_port_info(sata_hba_inst, sata_device);
14001 
14002 		if (rval != SATA_SUCCESS &&
14003 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14004 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14005 			rv = EIO;
14006 		} else {
14007 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14008 		}
14009 		mutex_exit(&cportinfo->cport_mutex);
14010 	}
14011 
14012 	return (rv);
14013 }
14014 
14015 
14016 
14017 /*
14018  * Process sata port connect request
14019  * The sata cfgadm pluging will invoke this operation only if port was found
14020  * in the disconnect state (failed state is also treated as the disconnected
14021  * state).
14022  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14023  * sata_tran_hotplug_ops->sata_tran_port_activate().
14024  * If successful and a device is found attached to the port,
14025  * the initialization sequence is executed to attach a device structure to
14026  * a port structure. The state of the port and a device would be set
14027  * appropriately.
14028  * The device is not set in configured state (system-wise) by this operation.
14029  *
14030  * Note, that activating the port may generate link events,
14031  * so it is important that following processing and the
14032  * event processing does not interfere with each other!
14033  *
14034  * This operation may remove port failed state and will
14035  * try to make port active and in good standing.
14036  *
14037  * NOTE: Port multiplier is supported.
14038  */
14039 
14040 static int
14041 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14042     sata_device_t *sata_device)
14043 {
14044 	sata_pmport_info_t	*pmportinfo = NULL;
14045 	uint8_t cport, pmport, qual;
14046 	int rv = 0;
14047 
14048 	cport = sata_device->satadev_addr.cport;
14049 	pmport = sata_device->satadev_addr.pmport;
14050 	qual = sata_device->satadev_addr.qual;
14051 
14052 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14053 	if (qual == SATA_ADDR_DCPORT)
14054 		qual = SATA_ADDR_CPORT;
14055 	else
14056 		qual = SATA_ADDR_PMPORT;
14057 
14058 	if (qual == SATA_ADDR_PMPORT)
14059 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14060 
14061 	/*
14062 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14063 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14064 	 * Perform sanity check now.
14065 	 */
14066 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14067 		/* No physical port activation supported. */
14068 		return (EINVAL);
14069 	}
14070 
14071 	/* Just ask HBA driver to activate port */
14072 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14073 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14074 		/*
14075 		 * Port activation failure.
14076 		 */
14077 		if (qual == SATA_ADDR_CPORT) {
14078 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14079 			    cport)->cport_mutex);
14080 			sata_update_port_info(sata_hba_inst, sata_device);
14081 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14082 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14083 				    SATA_PSTATE_FAILED;
14084 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14085 				    "sata_hba_ioctl: connect: failed to "
14086 				    "activate SATA port %d", cport);
14087 			}
14088 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14089 			    cport)->cport_mutex);
14090 		} else { /* port multiplier device port */
14091 			mutex_enter(&pmportinfo->pmport_mutex);
14092 			sata_update_pmport_info(sata_hba_inst, sata_device);
14093 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14094 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14095 				    pmport) = SATA_PSTATE_FAILED;
14096 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14097 				    "sata_hba_ioctl: connect: failed to "
14098 				    "activate SATA port %d:%d", cport, pmport);
14099 			}
14100 			mutex_exit(&pmportinfo->pmport_mutex);
14101 		}
14102 		return (EIO);
14103 	}
14104 
14105 	/* Virgin port state - will be updated by the port re-probe. */
14106 	if (qual == SATA_ADDR_CPORT) {
14107 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14108 		    cport)->cport_mutex);
14109 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14110 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14111 		    cport)->cport_mutex);
14112 	} else { /* port multiplier device port */
14113 		mutex_enter(&pmportinfo->pmport_mutex);
14114 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14115 		mutex_exit(&pmportinfo->pmport_mutex);
14116 	}
14117 
14118 	/*
14119 	 * Probe the port to find its state and attached device.
14120 	 */
14121 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14122 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14123 		rv = EIO;
14124 
14125 	/*
14126 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14127 	 * without the hint
14128 	 */
14129 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14130 	    SE_NO_HINT);
14131 
14132 	/*
14133 	 * If there is a device attached to the port, emit
14134 	 * a message.
14135 	 */
14136 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14137 
14138 		if (qual == SATA_ADDR_CPORT) {
14139 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14140 				sata_log(sata_hba_inst, CE_WARN,
14141 				    "SATA port multiplier detected "
14142 				    "at port %d", cport);
14143 			} else {
14144 				sata_log(sata_hba_inst, CE_WARN,
14145 				    "SATA device detected at port %d", cport);
14146 				if (sata_device->satadev_type ==
14147 				    SATA_DTYPE_UNKNOWN) {
14148 				/*
14149 				 * A device was not successfully identified
14150 				 */
14151 				sata_log(sata_hba_inst, CE_WARN,
14152 				    "Could not identify SATA "
14153 				    "device at port %d", cport);
14154 				}
14155 			}
14156 		} else { /* port multiplier device port */
14157 			sata_log(sata_hba_inst, CE_WARN,
14158 			    "SATA device detected at port %d:%d",
14159 			    cport, pmport);
14160 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14161 				/*
14162 				 * A device was not successfully identified
14163 				 */
14164 				sata_log(sata_hba_inst, CE_WARN,
14165 				    "Could not identify SATA "
14166 				    "device at port %d:%d", cport, pmport);
14167 			}
14168 		}
14169 	}
14170 
14171 	return (rv);
14172 }
14173 
14174 
14175 /*
14176  * Process sata device unconfigure request.
14177  * The unconfigure operation uses generic nexus operation to
14178  * offline a device. It leaves a target device node attached.
14179  * and obviously sata_drive_info attached as well, because
14180  * from the hardware point of view nothing has changed.
14181  */
14182 static int
14183 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14184     sata_device_t *sata_device)
14185 {
14186 	int rv = 0;
14187 	dev_info_t *tdip;
14188 
14189 	/* We are addressing attached device, not a port */
14190 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14191 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14192 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14193 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14194 
14195 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14196 	    &sata_device->satadev_addr)) != NULL) {
14197 
14198 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14199 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14200 			    "sata_hba_ioctl: unconfigure: "
14201 			    "failed to unconfigure device at SATA port %d:%d",
14202 			    sata_device->satadev_addr.cport,
14203 			    sata_device->satadev_addr.pmport));
14204 			rv = EIO;
14205 		}
14206 		/*
14207 		 * The target node devi_state should be marked with
14208 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14209 		 * This would be the indication for cfgadm that
14210 		 * the AP node occupant state is 'unconfigured'.
14211 		 */
14212 
14213 	} else {
14214 		/*
14215 		 * This would indicate a failure on the part of cfgadm
14216 		 * to detect correct state of the node prior to this
14217 		 * call - one cannot unconfigure non-existing device.
14218 		 */
14219 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14220 		    "sata_hba_ioctl: unconfigure: "
14221 		    "attempt to unconfigure non-existing device "
14222 		    "at SATA port %d:%d",
14223 		    sata_device->satadev_addr.cport,
14224 		    sata_device->satadev_addr.pmport));
14225 		rv = ENXIO;
14226 	}
14227 	return (rv);
14228 }
14229 
14230 /*
14231  * Process sata device configure request
14232  * If port is in a failed state, operation is aborted - one has to use
14233  * an explicit connect or port activate request to try to get a port into
14234  * non-failed mode. Port reset wil also work in such situation.
14235  * If the port is in disconnected (shutdown) state, the connect operation is
14236  * attempted prior to any other action.
14237  * When port is in the active state, there is a device attached and the target
14238  * node exists, a device was most likely offlined.
14239  * If target node does not exist, a new target node is created. In both cases
14240  * an attempt is made to online (configure) the device.
14241  *
14242  * NOTE: Port multiplier is supported.
14243  */
14244 static int
14245 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14246     sata_device_t *sata_device)
14247 {
14248 	int cport, pmport, qual;
14249 	int rval;
14250 	boolean_t target = TRUE;
14251 	sata_cport_info_t *cportinfo;
14252 	sata_pmport_info_t *pmportinfo = NULL;
14253 	dev_info_t *tdip;
14254 	sata_drive_info_t *sdinfo;
14255 
14256 	cport = sata_device->satadev_addr.cport;
14257 	pmport = sata_device->satadev_addr.pmport;
14258 	qual = sata_device->satadev_addr.qual;
14259 
14260 	/* Get current port state */
14261 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14262 	    (SATA_DIP(sata_hba_inst), sata_device);
14263 
14264 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14265 	if (qual == SATA_ADDR_DPMPORT) {
14266 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14267 		mutex_enter(&pmportinfo->pmport_mutex);
14268 		sata_update_pmport_info(sata_hba_inst, sata_device);
14269 		if (rval != SATA_SUCCESS ||
14270 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14271 			/*
14272 			 * Obviously, device on a failed port is not visible
14273 			 */
14274 			mutex_exit(&pmportinfo->pmport_mutex);
14275 			return (ENXIO);
14276 		}
14277 		mutex_exit(&pmportinfo->pmport_mutex);
14278 	} else {
14279 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14280 		    cport)->cport_mutex);
14281 		sata_update_port_info(sata_hba_inst, sata_device);
14282 		if (rval != SATA_SUCCESS ||
14283 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14284 			/*
14285 			 * Obviously, device on a failed port is not visible
14286 			 */
14287 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14288 			    cport)->cport_mutex);
14289 			return (ENXIO);
14290 		}
14291 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14292 		    cport)->cport_mutex);
14293 	}
14294 
14295 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14296 		/* need to activate port */
14297 		target = FALSE;
14298 
14299 		/* Sanity check */
14300 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14301 			return (ENXIO);
14302 
14303 		/* Just let HBA driver to activate port */
14304 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14305 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14306 			/*
14307 			 * Port activation failure - do not change port state
14308 			 * unless the state returned by HBA indicates a port
14309 			 * failure.
14310 			 */
14311 			if (qual == SATA_ADDR_DPMPORT) {
14312 				mutex_enter(&pmportinfo->pmport_mutex);
14313 				sata_update_pmport_info(sata_hba_inst,
14314 				    sata_device);
14315 				if (sata_device->satadev_state &
14316 				    SATA_PSTATE_FAILED)
14317 					pmportinfo->pmport_state =
14318 					    SATA_PSTATE_FAILED;
14319 				mutex_exit(&pmportinfo->pmport_mutex);
14320 			} else {
14321 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14322 				    cport)->cport_mutex);
14323 				sata_update_port_info(sata_hba_inst,
14324 				    sata_device);
14325 				if (sata_device->satadev_state &
14326 				    SATA_PSTATE_FAILED)
14327 					cportinfo->cport_state =
14328 					    SATA_PSTATE_FAILED;
14329 				mutex_exit(&SATA_CPORT_INFO(
14330 				    sata_hba_inst, cport)->cport_mutex);
14331 			}
14332 		}
14333 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14334 		    "sata_hba_ioctl: configure: "
14335 		    "failed to activate SATA port %d:%d",
14336 		    cport, pmport));
14337 		return (EIO);
14338 	}
14339 	/*
14340 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14341 	 * without the hint.
14342 	 */
14343 	sata_gen_sysevent(sata_hba_inst,
14344 	    &sata_device->satadev_addr, SE_NO_HINT);
14345 
14346 	/* Virgin port state */
14347 	if (qual == SATA_ADDR_DPMPORT) {
14348 		mutex_enter(&pmportinfo->pmport_mutex);
14349 		pmportinfo->pmport_state = 0;
14350 		mutex_exit(&pmportinfo->pmport_mutex);
14351 	} else {
14352 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14353 		    cport)-> cport_mutex);
14354 		cportinfo->cport_state = 0;
14355 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14356 		    cport)->cport_mutex);
14357 	}
14358 	/*
14359 	 * Always reprobe port, to get current device info.
14360 	 */
14361 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14362 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14363 		return (EIO);
14364 
14365 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14366 		if (qual == SATA_ADDR_DPMPORT) {
14367 			/*
14368 			 * That's the transition from "inactive" port
14369 			 * to active one with device attached.
14370 			 */
14371 			sata_log(sata_hba_inst, CE_WARN,
14372 			    "SATA device detected at port %d:%d",
14373 			    cport, pmport);
14374 		} else {
14375 			/*
14376 			 * When PM is attached to the cport and cport is
14377 			 * activated, every PM device port needs to be reprobed.
14378 			 * We need to emit message for all devices detected
14379 			 * at port multiplier's device ports.
14380 			 * Add such code here.
14381 			 * For now, just inform about device attached to
14382 			 * cport.
14383 			 */
14384 			sata_log(sata_hba_inst, CE_WARN,
14385 			    "SATA device detected at port %d", cport);
14386 		}
14387 	}
14388 
14389 	/*
14390 	 * This is where real configuration operation starts.
14391 	 *
14392 	 * When PM is attached to the cport and cport is activated,
14393 	 * devices attached PM device ports may have to be configured
14394 	 * explicitly. This may change when port multiplier is supported.
14395 	 * For now, configure only disks and other valid target devices.
14396 	 */
14397 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14398 		if (qual == SATA_ADDR_DCPORT) {
14399 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14400 				/*
14401 				 * A device was not successfully identified
14402 				 */
14403 				sata_log(sata_hba_inst, CE_WARN,
14404 				    "Could not identify SATA "
14405 				    "device at port %d", cport);
14406 			}
14407 		} else { /* port multiplier device port */
14408 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14409 				/*
14410 				 * A device was not successfully identified
14411 				 */
14412 				sata_log(sata_hba_inst, CE_WARN,
14413 				    "Could not identify SATA "
14414 				    "device at port %d:%d", cport, pmport);
14415 			}
14416 		}
14417 		return (ENXIO);		/* No device to configure */
14418 	}
14419 
14420 	/*
14421 	 * Here we may have a device in reset condition,
14422 	 * but because we are just configuring it, there is
14423 	 * no need to process the reset other than just
14424 	 * to clear device reset condition in the HBA driver.
14425 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14426 	 * cause a first command sent the HBA driver with the request
14427 	 * to clear device reset condition.
14428 	 */
14429 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14430 	if (qual == SATA_ADDR_DPMPORT)
14431 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14432 	else
14433 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14434 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14435 	if (sdinfo == NULL) {
14436 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14437 		return (ENXIO);
14438 	}
14439 	if (sdinfo->satadrv_event_flags &
14440 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14441 		sdinfo->satadrv_event_flags = 0;
14442 	}
14443 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14444 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14445 
14446 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14447 	    &sata_device->satadev_addr)) != NULL) {
14448 		/*
14449 		 * Target node exists. Verify, that it belongs
14450 		 * to existing, attached device and not to
14451 		 * a removed device.
14452 		 */
14453 		if (sata_check_device_removed(tdip) == B_TRUE) {
14454 			if (qual == SATA_ADDR_DPMPORT)
14455 				sata_log(sata_hba_inst, CE_WARN,
14456 				    "SATA device at port %d cannot be "
14457 				    "configured. "
14458 				    "Application(s) accessing "
14459 				    "previously attached device "
14460 				    "have to release it before newly "
14461 				    "inserted device can be made accessible.",
14462 				    cport);
14463 			else
14464 				sata_log(sata_hba_inst, CE_WARN,
14465 				    "SATA device at port %d:%d cannot be"
14466 				    "configured. "
14467 				    "Application(s) accessing "
14468 				    "previously attached device "
14469 				    "have to release it before newly "
14470 				    "inserted device can be made accessible.",
14471 				    cport, pmport);
14472 			return (EIO);
14473 		}
14474 		/*
14475 		 * Device was not removed and re-inserted.
14476 		 * Try to online it.
14477 		 */
14478 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14479 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14480 			    "sata_hba_ioctl: configure: "
14481 			    "onlining device at SATA port "
14482 			    "%d:%d failed", cport, pmport));
14483 			return (EIO);
14484 		}
14485 
14486 		if (qual == SATA_ADDR_DPMPORT) {
14487 			mutex_enter(&pmportinfo->pmport_mutex);
14488 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14489 			mutex_exit(&pmportinfo->pmport_mutex);
14490 		} else {
14491 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14492 			    cport)->cport_mutex);
14493 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14494 			mutex_exit(&SATA_CPORT_INFO(
14495 			    sata_hba_inst, cport)->cport_mutex);
14496 		}
14497 	} else {
14498 		/*
14499 		 * No target node - need to create a new target node.
14500 		 */
14501 		if (qual == SATA_ADDR_DPMPORT) {
14502 			mutex_enter(&pmportinfo->pmport_mutex);
14503 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14504 			mutex_exit(&pmportinfo->pmport_mutex);
14505 		} else {
14506 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14507 			    cport_mutex);
14508 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14509 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14510 			    cport_mutex);
14511 		}
14512 
14513 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14514 		    sata_hba_inst, &sata_device->satadev_addr);
14515 		if (tdip == NULL) {
14516 			/* Configure operation failed */
14517 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14518 			    "sata_hba_ioctl: configure: "
14519 			    "configuring SATA device at port %d:%d "
14520 			    "failed", cport, pmport));
14521 			return (EIO);
14522 		}
14523 	}
14524 	return (0);
14525 }
14526 
14527 
14528 /*
14529  * Process ioctl deactivate port request.
14530  * Arbitrarily unconfigure attached device, if any.
14531  * Even if the unconfigure fails, proceed with the
14532  * port deactivation.
14533  *
14534  * NOTE: Port Multiplier is supported now.
14535  */
14536 
14537 static int
14538 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14539     sata_device_t *sata_device)
14540 {
14541 	int cport, pmport, qual;
14542 	int rval, rv = 0;
14543 	int npmport;
14544 	sata_cport_info_t *cportinfo;
14545 	sata_pmport_info_t *pmportinfo;
14546 	sata_pmult_info_t *pmultinfo;
14547 	dev_info_t *tdip;
14548 	sata_drive_info_t *sdinfo = NULL;
14549 	sata_device_t subsdevice;
14550 
14551 	/* Sanity check */
14552 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14553 		return (ENOTSUP);
14554 
14555 	cport = sata_device->satadev_addr.cport;
14556 	pmport = sata_device->satadev_addr.pmport;
14557 	qual = sata_device->satadev_addr.qual;
14558 
14559 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14560 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14561 	if (qual == SATA_ADDR_DCPORT)
14562 		qual = SATA_ADDR_CPORT;
14563 	else
14564 		qual = SATA_ADDR_PMPORT;
14565 
14566 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14567 	if (qual == SATA_ADDR_PMPORT)
14568 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14569 
14570 	/*
14571 	 * Processing port multiplier
14572 	 */
14573 	if (qual == SATA_ADDR_CPORT &&
14574 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14575 		mutex_enter(&cportinfo->cport_mutex);
14576 
14577 		/* Deactivate all sub-deices */
14578 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14579 		if (pmultinfo != NULL) {
14580 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14581 			    sata_hba_inst, cport); npmport++) {
14582 
14583 				subsdevice.satadev_addr.cport = cport;
14584 				subsdevice.satadev_addr.pmport =
14585 				    (uint8_t)npmport;
14586 				subsdevice.satadev_addr.qual =
14587 				    SATA_ADDR_DPMPORT;
14588 
14589 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14590 				    "sata_hba_ioctl: deactivate: trying to "
14591 				    "deactivate SATA port %d:%d",
14592 				    cport, npmport);
14593 
14594 				mutex_exit(&cportinfo->cport_mutex);
14595 				if (sata_ioctl_deactivate(sata_hba_inst,
14596 				    &subsdevice) == SATA_SUCCESS) {
14597 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14598 					    "[Deactivate] device at port %d:%d "
14599 					    "successfully.", cport, npmport);
14600 				}
14601 				mutex_enter(&cportinfo->cport_mutex);
14602 			}
14603 		}
14604 
14605 		/* Deactivate the port multiplier now. */
14606 		cportinfo->cport_state &= ~SATA_STATE_READY;
14607 		mutex_exit(&cportinfo->cport_mutex);
14608 
14609 		sata_device->satadev_addr.qual = qual;
14610 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14611 		    (SATA_DIP(sata_hba_inst), sata_device);
14612 
14613 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14614 		    SE_NO_HINT);
14615 
14616 		mutex_enter(&cportinfo->cport_mutex);
14617 		sata_update_port_info(sata_hba_inst, sata_device);
14618 		if (rval != SATA_SUCCESS) {
14619 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14620 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14621 			}
14622 			rv = EIO;
14623 		} else {
14624 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14625 		}
14626 		mutex_exit(&cportinfo->cport_mutex);
14627 
14628 		return (rv);
14629 	}
14630 
14631 	/*
14632 	 * Process non-port-multiplier device - it could be a drive connected
14633 	 * to a port multiplier port or a controller port.
14634 	 */
14635 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14636 	if (qual == SATA_ADDR_CPORT) {
14637 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14638 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14639 			/* deal only with valid devices */
14640 			if ((cportinfo->cport_dev_type &
14641 			    SATA_VALID_DEV_TYPE) != 0)
14642 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14643 		}
14644 		cportinfo->cport_state &= ~SATA_STATE_READY;
14645 	} else {
14646 		/* Port multiplier device port */
14647 		mutex_enter(&pmportinfo->pmport_mutex);
14648 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14649 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14650 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14651 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14652 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14653 		mutex_exit(&pmportinfo->pmport_mutex);
14654 	}
14655 
14656 	if (sdinfo != NULL) {
14657 		/*
14658 		 * If a target node exists, try to offline a device and
14659 		 * to remove a target node.
14660 		 */
14661 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14662 		    cport_mutex);
14663 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14664 		    &sata_device->satadev_addr);
14665 		if (tdip != NULL) {
14666 			/* target node exist */
14667 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14668 			    "sata_hba_ioctl: port deactivate: "
14669 			    "target node exists.", NULL);
14670 
14671 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14672 			    NDI_SUCCESS) {
14673 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14674 				    "sata_hba_ioctl: port deactivate: "
14675 				    "failed to unconfigure device at port "
14676 				    "%d:%d before deactivating the port",
14677 				    cport, pmport));
14678 				/*
14679 				 * Set DEVICE REMOVED state in the target
14680 				 * node. It will prevent an access to
14681 				 * the device even when a new device is
14682 				 * attached, until the old target node is
14683 				 * released, removed and recreated for a new
14684 				 * device.
14685 				 */
14686 				sata_set_device_removed(tdip);
14687 
14688 				/*
14689 				 * Instruct the event daemon to try the
14690 				 * target node cleanup later.
14691 				 */
14692 				sata_set_target_node_cleanup(sata_hba_inst,
14693 				    &sata_device->satadev_addr);
14694 			}
14695 		}
14696 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14697 		    cport_mutex);
14698 		/*
14699 		 * In any case, remove and release sata_drive_info
14700 		 * structure.
14701 		 */
14702 		if (qual == SATA_ADDR_CPORT) {
14703 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14704 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14705 		} else { /* port multiplier device port */
14706 			mutex_enter(&pmportinfo->pmport_mutex);
14707 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14708 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14709 			mutex_exit(&pmportinfo->pmport_mutex);
14710 		}
14711 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14712 	}
14713 
14714 	if (qual == SATA_ADDR_CPORT) {
14715 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14716 		    SATA_STATE_PROBING);
14717 	} else if (qual == SATA_ADDR_PMPORT) {
14718 		mutex_enter(&pmportinfo->pmport_mutex);
14719 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14720 		    SATA_STATE_PROBING);
14721 		mutex_exit(&pmportinfo->pmport_mutex);
14722 	}
14723 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14724 
14725 	/* Just let HBA driver to deactivate port */
14726 	sata_device->satadev_addr.qual = qual;
14727 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14728 	    (SATA_DIP(sata_hba_inst), sata_device);
14729 
14730 	/*
14731 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14732 	 * without the hint
14733 	 */
14734 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14735 	    SE_NO_HINT);
14736 
14737 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14738 	sata_update_port_info(sata_hba_inst, sata_device);
14739 	if (qual == SATA_ADDR_CPORT) {
14740 		if (rval != SATA_SUCCESS) {
14741 			/*
14742 			 * Port deactivation failure - do not change port state
14743 			 * unless the state returned by HBA indicates a port
14744 			 * failure.
14745 			 */
14746 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14747 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14748 				    SATA_PSTATE_FAILED;
14749 			}
14750 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14751 			    "sata_hba_ioctl: port deactivate: "
14752 			    "cannot deactivate SATA port %d", cport));
14753 			rv = EIO;
14754 		} else {
14755 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14756 		}
14757 	} else {
14758 		mutex_enter(&pmportinfo->pmport_mutex);
14759 		if (rval != SATA_SUCCESS) {
14760 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14761 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14762 				    pmport) = SATA_PSTATE_FAILED;
14763 			}
14764 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14765 			    "sata_hba_ioctl: port deactivate: "
14766 			    "cannot deactivate SATA port %d:%d",
14767 			    cport, pmport));
14768 			rv = EIO;
14769 		} else {
14770 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14771 		}
14772 		mutex_exit(&pmportinfo->pmport_mutex);
14773 	}
14774 
14775 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14776 
14777 	return (rv);
14778 }
14779 
14780 /*
14781  * Process ioctl port activate request.
14782  *
14783  * NOTE: Port multiplier is supported now.
14784  */
14785 static int
14786 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14787     sata_device_t *sata_device)
14788 {
14789 	int cport, pmport, qual;
14790 	sata_cport_info_t *cportinfo;
14791 	sata_pmport_info_t *pmportinfo = NULL;
14792 	boolean_t dev_existed = TRUE;
14793 
14794 	/* Sanity check */
14795 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14796 		return (ENOTSUP);
14797 
14798 	cport = sata_device->satadev_addr.cport;
14799 	pmport = sata_device->satadev_addr.pmport;
14800 	qual = sata_device->satadev_addr.qual;
14801 
14802 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14803 
14804 	/*
14805 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14806 	 * is a device. But what we are dealing with is port/pmport.
14807 	 */
14808 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14809 	if (qual == SATA_ADDR_DCPORT)
14810 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14811 	else
14812 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14813 
14814 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14815 	if (qual == SATA_ADDR_PMPORT) {
14816 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14817 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14818 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14819 			dev_existed = FALSE;
14820 	} else { /* cport */
14821 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14822 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14823 			dev_existed = FALSE;
14824 	}
14825 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14826 
14827 	/* Just let HBA driver to activate port, if necessary */
14828 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14829 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14830 		/*
14831 		 * Port activation failure - do not change port state unless
14832 		 * the state returned by HBA indicates a port failure.
14833 		 */
14834 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14835 		    cport)->cport_mutex);
14836 		sata_update_port_info(sata_hba_inst, sata_device);
14837 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14838 			if (qual == SATA_ADDR_PMPORT) {
14839 				mutex_enter(&pmportinfo->pmport_mutex);
14840 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14841 				mutex_exit(&pmportinfo->pmport_mutex);
14842 			} else
14843 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14844 
14845 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14846 			    cport)->cport_mutex);
14847 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14848 			    "sata_hba_ioctl: port activate: cannot activate "
14849 			    "SATA port %d:%d", cport, pmport));
14850 			return (EIO);
14851 		}
14852 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14853 	}
14854 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14855 	if (qual == SATA_ADDR_PMPORT) {
14856 		mutex_enter(&pmportinfo->pmport_mutex);
14857 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14858 		mutex_exit(&pmportinfo->pmport_mutex);
14859 	} else
14860 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14861 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14862 
14863 	/*
14864 	 * Re-probe port to find its current state and possibly attached device.
14865 	 * Port re-probing may change the cportinfo device type if device is
14866 	 * found attached.
14867 	 * If port probing failed, the device type would be set to
14868 	 * SATA_DTYPE_NONE.
14869 	 */
14870 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14871 	    SATA_DEV_IDENTIFY_RETRY);
14872 
14873 	/*
14874 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14875 	 * without the hint.
14876 	 */
14877 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14878 	    SE_NO_HINT);
14879 
14880 	if (dev_existed == FALSE) {
14881 		if (qual == SATA_ADDR_PMPORT &&
14882 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14883 			/*
14884 			 * That's the transition from the "inactive" port state
14885 			 * or the active port without a device attached to the
14886 			 * active port state with a device attached.
14887 			 */
14888 			sata_log(sata_hba_inst, CE_WARN,
14889 			    "SATA device detected at port %d:%d",
14890 			    cport, pmport);
14891 		} else if (qual == SATA_ADDR_CPORT &&
14892 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14893 			/*
14894 			 * That's the transition from the "inactive" port state
14895 			 * or the active port without a device attached to the
14896 			 * active port state with a device attached.
14897 			 */
14898 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14899 				sata_log(sata_hba_inst, CE_WARN,
14900 				    "SATA device detected at port %d", cport);
14901 			} else {
14902 				sata_log(sata_hba_inst, CE_WARN,
14903 				    "SATA port multiplier detected at port %d",
14904 				    cport);
14905 			}
14906 		}
14907 	}
14908 	return (0);
14909 }
14910 
14911 
14912 
14913 /*
14914  * Process ioctl reset port request.
14915  *
14916  * NOTE: Port-Multiplier is supported.
14917  */
14918 static int
14919 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14920     sata_device_t *sata_device)
14921 {
14922 	int cport, pmport, qual;
14923 	int rv = 0;
14924 
14925 	cport = sata_device->satadev_addr.cport;
14926 	pmport = sata_device->satadev_addr.pmport;
14927 	qual = sata_device->satadev_addr.qual;
14928 
14929 	/*
14930 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14931 	 * is a device. But what we are dealing with is port/pmport.
14932 	 */
14933 	if (qual == SATA_ADDR_DCPORT)
14934 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14935 	else
14936 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14937 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14938 
14939 	/* Sanity check */
14940 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14941 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14942 		    "sata_hba_ioctl: sata_hba_tran missing required "
14943 		    "function sata_tran_reset_dport"));
14944 		return (ENOTSUP);
14945 	}
14946 
14947 	/* Ask HBA to reset port */
14948 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14949 	    sata_device) != SATA_SUCCESS) {
14950 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14951 		    "sata_hba_ioctl: reset port: failed %d:%d",
14952 		    cport, pmport));
14953 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14954 		    cport_mutex);
14955 		sata_update_port_info(sata_hba_inst, sata_device);
14956 		if (qual == SATA_ADDR_CPORT)
14957 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14958 			    SATA_PSTATE_FAILED;
14959 		else {
14960 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14961 			    pmport));
14962 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14963 			    SATA_PSTATE_FAILED;
14964 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14965 			    pmport));
14966 		}
14967 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14968 		    cport_mutex);
14969 		rv = EIO;
14970 	}
14971 	/*
14972 	 * Beacuse the port was reset, it should be probed and
14973 	 * attached device reinitialized. At this point the
14974 	 * port state is unknown - it's state is HBA-specific.
14975 	 * Re-probe port to get its state.
14976 	 */
14977 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14978 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14979 		rv = EIO;
14980 	}
14981 	return (rv);
14982 }
14983 
14984 /*
14985  * Process ioctl reset device request.
14986  *
14987  * NOTE: Port multiplier is supported.
14988  */
14989 static int
14990 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14991     sata_device_t *sata_device)
14992 {
14993 	sata_drive_info_t *sdinfo = NULL;
14994 	sata_pmult_info_t *pmultinfo = NULL;
14995 	int cport, pmport;
14996 	int rv = 0;
14997 
14998 	/* Sanity check */
14999 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15000 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15001 		    "sata_hba_ioctl: sata_hba_tran missing required "
15002 		    "function sata_tran_reset_dport"));
15003 		return (ENOTSUP);
15004 	}
15005 
15006 	cport = sata_device->satadev_addr.cport;
15007 	pmport = sata_device->satadev_addr.pmport;
15008 
15009 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15010 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15011 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15012 		    SATA_DTYPE_PMULT)
15013 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15014 			    cport_devp.cport_sata_pmult;
15015 		else
15016 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15017 			    sata_device->satadev_addr.cport);
15018 	} else { /* port multiplier */
15019 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15020 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15021 		    sata_device->satadev_addr.cport,
15022 		    sata_device->satadev_addr.pmport);
15023 	}
15024 	if (sdinfo == NULL && pmultinfo == NULL) {
15025 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15026 		return (EINVAL);
15027 	}
15028 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15029 
15030 	/* Ask HBA to reset device */
15031 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15032 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15033 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15034 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15035 		    cport, pmport));
15036 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15037 		    cport_mutex);
15038 		sata_update_port_info(sata_hba_inst, sata_device);
15039 		/*
15040 		 * Device info structure remains attached. Another device reset
15041 		 * or port disconnect/connect and re-probing is
15042 		 * needed to change it's state
15043 		 */
15044 		if (sdinfo != NULL) {
15045 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15046 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15047 		} else if (pmultinfo != NULL) {
15048 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15049 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15050 		}
15051 
15052 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15053 		rv = EIO;
15054 	}
15055 	/*
15056 	 * If attached device was a port multiplier, some extra processing
15057 	 * may be needed to bring it back. SATA specification requies a
15058 	 * mandatory software reset on host port to reliably enumerate a port
15059 	 * multiplier, the HBA driver should handle that after reset
15060 	 * operation.
15061 	 */
15062 	return (rv);
15063 }
15064 
15065 
15066 /*
15067  * Process ioctl reset all request.
15068  */
15069 static int
15070 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15071 {
15072 	sata_device_t sata_device;
15073 	int rv = 0;
15074 	int tcport;
15075 	int tpmport = 0;
15076 
15077 	sata_device.satadev_rev = SATA_DEVICE_REV;
15078 
15079 	/*
15080 	 * There is no protection here for configured devices.
15081 	 */
15082 	/* Sanity check */
15083 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15084 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15085 		    "sata_hba_ioctl: sata_hba_tran missing required "
15086 		    "function sata_tran_reset_dport"));
15087 		return (ENOTSUP);
15088 	}
15089 
15090 	/*
15091 	 * Need to lock all ports, not just one.
15092 	 * If any port is locked by event processing, fail the whole operation.
15093 	 * One port is already locked, but for simplicity lock it again.
15094 	 */
15095 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15096 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15097 		    cport_mutex);
15098 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15099 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15100 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15101 			    cport_mutex);
15102 			rv = EBUSY;
15103 			break;
15104 		} else {
15105 			/*
15106 			 * It is enough to lock cport in command-based
15107 			 * switching mode.
15108 			 */
15109 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15110 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15111 		}
15112 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15113 		    cport_mutex);
15114 	}
15115 
15116 	if (rv == 0) {
15117 		/*
15118 		 * All cports were successfully locked.
15119 		 * Reset main SATA controller.
15120 		 * Set the device address to port 0, to have a valid device
15121 		 * address.
15122 		 */
15123 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15124 		sata_device.satadev_addr.cport = 0;
15125 		sata_device.satadev_addr.pmport = 0;
15126 
15127 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15128 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15129 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15130 			    "sata_hba_ioctl: reset controller failed"));
15131 			return (EIO);
15132 		}
15133 		/*
15134 		 * Because ports were reset, port states are unknown.
15135 		 * They should be re-probed to get their state and
15136 		 * attached devices should be reinitialized.
15137 		 */
15138 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
15139 		    tcport++) {
15140 			sata_device.satadev_addr.cport = tcport;
15141 			sata_device.satadev_addr.pmport = tpmport;
15142 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
15143 
15144 			/*
15145 			 * The sata_reprobe_port() will mark a
15146 			 * SATA_EVNT_DEVICE_RESET event on the port
15147 			 * multiplier, all its sub-ports will be probed by
15148 			 * sata daemon afterwards.
15149 			 */
15150 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
15151 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15152 				rv = EIO;
15153 		}
15154 	}
15155 	/*
15156 	 * Unlock all ports
15157 	 */
15158 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15159 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15160 		    cport_mutex);
15161 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15162 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15163 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15164 		    cport_mutex);
15165 	}
15166 
15167 	/*
15168 	 * This operation returns EFAULT if either reset
15169 	 * controller failed or a re-probing of any port failed.
15170 	 */
15171 	return (rv);
15172 }
15173 
15174 
15175 /*
15176  * Process ioctl port self test request.
15177  *
15178  * NOTE: Port multiplier code is not completed nor tested.
15179  */
15180 static int
15181 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15182     sata_device_t *sata_device)
15183 {
15184 	int cport, pmport, qual;
15185 	int rv = 0;
15186 
15187 	/* Sanity check */
15188 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15189 		return (ENOTSUP);
15190 
15191 	cport = sata_device->satadev_addr.cport;
15192 	pmport = sata_device->satadev_addr.pmport;
15193 	qual = sata_device->satadev_addr.qual;
15194 
15195 	/*
15196 	 * There is no protection here for a configured
15197 	 * device attached to this port.
15198 	 */
15199 
15200 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15201 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15202 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15203 		    "sata_hba_ioctl: port selftest: "
15204 		    "failed port %d:%d", cport, pmport));
15205 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15206 		    cport_mutex);
15207 		sata_update_port_info(sata_hba_inst, sata_device);
15208 		if (qual == SATA_ADDR_CPORT)
15209 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15210 			    SATA_PSTATE_FAILED;
15211 		else { /* port multiplier device port */
15212 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15213 			    cport, pmport));
15214 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15215 			    SATA_PSTATE_FAILED;
15216 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15217 			    cport, pmport));
15218 		}
15219 
15220 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15221 		    cport_mutex);
15222 		return (EIO);
15223 	}
15224 	/*
15225 	 * Beacuse the port was reset in the course of testing, it should be
15226 	 * re-probed and attached device state should be restored. At this
15227 	 * point the port state is unknown - it's state is HBA-specific.
15228 	 * Force port re-probing to get it into a known state.
15229 	 */
15230 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15231 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15232 		rv = EIO;
15233 	return (rv);
15234 }
15235 
15236 
15237 /*
15238  * sata_cfgadm_state:
15239  * Use the sata port state and state of the target node to figure out
15240  * the cfgadm_state.
15241  *
15242  * The port argument is a value with encoded cport,
15243  * pmport and address qualifier, in the same manner as a scsi target number.
15244  * SCSI_TO_SATA_CPORT macro extracts cport number,
15245  * SCSI_TO_SATA_PMPORT extracts pmport number and
15246  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15247  *
15248  * Port multiplier is supported.
15249  */
15250 
15251 static void
15252 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15253     devctl_ap_state_t *ap_state)
15254 {
15255 	uint8_t		cport, pmport, qual;
15256 	uint32_t	port_state, pmult_state;
15257 	uint32_t	dev_type;
15258 	sata_drive_info_t *sdinfo;
15259 
15260 	cport = SCSI_TO_SATA_CPORT(port);
15261 	pmport = SCSI_TO_SATA_PMPORT(port);
15262 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15263 
15264 	/* Check cport state */
15265 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15266 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15267 	    port_state & SATA_PSTATE_FAILED) {
15268 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15269 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15270 		if (port_state & SATA_PSTATE_FAILED)
15271 			ap_state->ap_condition = AP_COND_FAILED;
15272 		else
15273 			ap_state->ap_condition = AP_COND_UNKNOWN;
15274 
15275 		return;
15276 	}
15277 
15278 	/* cport state is okay. Now check pmport state */
15279 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15280 		/* Sanity check */
15281 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15282 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15283 		    cport, pmport) == NULL)
15284 			return;
15285 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15286 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15287 		    port_state & SATA_PSTATE_FAILED) {
15288 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15289 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15290 			if (port_state & SATA_PSTATE_FAILED)
15291 				ap_state->ap_condition = AP_COND_FAILED;
15292 			else
15293 				ap_state->ap_condition = AP_COND_UNKNOWN;
15294 
15295 			return;
15296 		}
15297 	}
15298 
15299 	/* Port is enabled and ready */
15300 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15301 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15302 	else
15303 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15304 
15305 	switch (dev_type) {
15306 	case SATA_DTYPE_NONE:
15307 	{
15308 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15309 		ap_state->ap_condition = AP_COND_OK;
15310 		/* No device attached */
15311 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15312 		break;
15313 	}
15314 	case SATA_DTYPE_PMULT:
15315 	{
15316 		/* Need to check port multiplier state */
15317 		ASSERT(qual == SATA_ADDR_DCPORT);
15318 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15319 		    pmult_state;
15320 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15321 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15322 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15323 			if (pmult_state & SATA_PSTATE_FAILED)
15324 				ap_state->ap_condition = AP_COND_FAILED;
15325 			else
15326 				ap_state->ap_condition = AP_COND_UNKNOWN;
15327 
15328 			return;
15329 		}
15330 
15331 		/* Port multiplier is not configurable */
15332 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15333 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15334 		ap_state->ap_condition = AP_COND_OK;
15335 		break;
15336 	}
15337 
15338 	case SATA_DTYPE_ATADISK:
15339 	case SATA_DTYPE_ATAPICD:
15340 	case SATA_DTYPE_ATAPITAPE:
15341 	case SATA_DTYPE_ATAPIDISK:
15342 	{
15343 		dev_info_t *tdip = NULL;
15344 		dev_info_t *dip = NULL;
15345 		int circ;
15346 
15347 		dip = SATA_DIP(sata_hba_inst);
15348 		tdip = sata_get_target_dip(dip, cport, pmport);
15349 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15350 		if (tdip != NULL) {
15351 			ndi_devi_enter(dip, &circ);
15352 			mutex_enter(&(DEVI(tdip)->devi_lock));
15353 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15354 				/*
15355 				 * There could be the case where previously
15356 				 * configured and opened device was removed
15357 				 * and unknown device was plugged.
15358 				 * In such case we want to show a device, and
15359 				 * its configured or unconfigured state but
15360 				 * indicate unusable condition untill the
15361 				 * old target node is released and removed.
15362 				 */
15363 				ap_state->ap_condition = AP_COND_UNUSABLE;
15364 			} else {
15365 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15366 				    cport));
15367 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15368 				    cport);
15369 				if (sdinfo != NULL) {
15370 					if ((sdinfo->satadrv_state &
15371 					    SATA_DSTATE_FAILED) != 0)
15372 						ap_state->ap_condition =
15373 						    AP_COND_FAILED;
15374 					else
15375 						ap_state->ap_condition =
15376 						    AP_COND_OK;
15377 				} else {
15378 					ap_state->ap_condition =
15379 					    AP_COND_UNKNOWN;
15380 				}
15381 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15382 				    cport));
15383 			}
15384 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15385 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15386 				ap_state->ap_ostate =
15387 				    AP_OSTATE_UNCONFIGURED;
15388 			} else {
15389 				ap_state->ap_ostate =
15390 				    AP_OSTATE_CONFIGURED;
15391 			}
15392 			mutex_exit(&(DEVI(tdip)->devi_lock));
15393 			ndi_devi_exit(dip, circ);
15394 		} else {
15395 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15396 			ap_state->ap_condition = AP_COND_UNKNOWN;
15397 		}
15398 		break;
15399 	}
15400 	default:
15401 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15402 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15403 		ap_state->ap_condition = AP_COND_UNKNOWN;
15404 		/*
15405 		 * This is actually internal error condition (non fatal),
15406 		 * because we have already checked all defined device types.
15407 		 */
15408 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15409 		    "sata_cfgadm_state: Internal error: "
15410 		    "unknown device type"));
15411 		break;
15412 	}
15413 }
15414 
15415 
15416 /*
15417  * Process ioctl get device path request.
15418  *
15419  * NOTE: Port multiplier has no target dip. Devices connected to port
15420  * multiplier have target node attached to the HBA node. The only difference
15421  * between them and the directly-attached device node is a target address.
15422  */
15423 static int
15424 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15425     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15426 {
15427 	char path[MAXPATHLEN];
15428 	uint32_t size;
15429 	dev_info_t *tdip;
15430 
15431 	(void) strcpy(path, "/devices");
15432 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15433 	    &sata_device->satadev_addr)) == NULL) {
15434 		/*
15435 		 * No such device. If this is a request for a size, do not
15436 		 * return EINVAL for non-existing target, because cfgadm
15437 		 * will then indicate a meaningless ioctl failure.
15438 		 * If this is a request for a path, indicate invalid
15439 		 * argument.
15440 		 */
15441 		if (ioc->get_size == 0)
15442 			return (EINVAL);
15443 	} else {
15444 		(void) ddi_pathname(tdip, path + strlen(path));
15445 	}
15446 	size = strlen(path) + 1;
15447 
15448 	if (ioc->get_size != 0) {
15449 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15450 		    mode) != 0)
15451 			return (EFAULT);
15452 	} else {
15453 		if (ioc->bufsiz != size)
15454 			return (EINVAL);
15455 
15456 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15457 		    mode) != 0)
15458 			return (EFAULT);
15459 	}
15460 	return (0);
15461 }
15462 
15463 /*
15464  * Process ioctl get attachment point type request.
15465  *
15466  * NOTE: Port multiplier is supported.
15467  */
15468 static	int
15469 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15470     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15471 {
15472 	uint32_t	type_len;
15473 	const char	*ap_type;
15474 	int		dev_type;
15475 
15476 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15477 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15478 		    sata_device->satadev_addr.cport);
15479 	else /* pmport */
15480 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15481 		    sata_device->satadev_addr.cport,
15482 		    sata_device->satadev_addr.pmport);
15483 
15484 	switch (dev_type) {
15485 	case SATA_DTYPE_NONE:
15486 		ap_type = "port";
15487 		break;
15488 
15489 	case SATA_DTYPE_ATADISK:
15490 	case SATA_DTYPE_ATAPIDISK:
15491 		ap_type = "disk";
15492 		break;
15493 
15494 	case SATA_DTYPE_ATAPICD:
15495 		ap_type = "cd/dvd";
15496 		break;
15497 
15498 	case SATA_DTYPE_ATAPITAPE:
15499 		ap_type = "tape";
15500 		break;
15501 
15502 	case SATA_DTYPE_PMULT:
15503 		ap_type = "sata-pmult";
15504 		break;
15505 
15506 	case SATA_DTYPE_UNKNOWN:
15507 		ap_type = "unknown";
15508 		break;
15509 
15510 	default:
15511 		ap_type = "unsupported";
15512 		break;
15513 
15514 	} /* end of dev_type switch */
15515 
15516 	type_len = strlen(ap_type) + 1;
15517 
15518 	if (ioc->get_size) {
15519 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15520 		    mode) != 0)
15521 			return (EFAULT);
15522 	} else {
15523 		if (ioc->bufsiz != type_len)
15524 			return (EINVAL);
15525 
15526 		if (ddi_copyout((void *)ap_type, ioc->buf,
15527 		    ioc->bufsiz, mode) != 0)
15528 			return (EFAULT);
15529 	}
15530 	return (0);
15531 
15532 }
15533 
15534 /*
15535  * Process ioctl get device model info request.
15536  * This operation should return to cfgadm the device model
15537  * information string
15538  *
15539  * NOTE: Port multiplier is supported.
15540  */
15541 static	int
15542 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15543     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15544 {
15545 	sata_drive_info_t *sdinfo;
15546 	uint32_t info_len;
15547 	char ap_info[SATA_ID_MODEL_LEN + 1];
15548 
15549 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15550 	    sata_device->satadev_addr.cport)->cport_mutex);
15551 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15552 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15553 		    sata_device->satadev_addr.cport);
15554 	else /* port multiplier */
15555 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15556 		    sata_device->satadev_addr.cport,
15557 		    sata_device->satadev_addr.pmport);
15558 	if (sdinfo == NULL) {
15559 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15560 		    sata_device->satadev_addr.cport)->cport_mutex);
15561 		return (EINVAL);
15562 	}
15563 
15564 #ifdef	_LITTLE_ENDIAN
15565 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15566 #else	/* _LITTLE_ENDIAN */
15567 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15568 #endif	/* _LITTLE_ENDIAN */
15569 
15570 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15571 	    sata_device->satadev_addr.cport)->cport_mutex);
15572 
15573 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15574 
15575 	info_len = strlen(ap_info) + 1;
15576 
15577 	if (ioc->get_size) {
15578 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15579 		    mode) != 0)
15580 			return (EFAULT);
15581 	} else {
15582 		if (ioc->bufsiz < info_len)
15583 			return (EINVAL);
15584 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15585 		    mode) != 0)
15586 			return (EFAULT);
15587 	}
15588 	return (0);
15589 }
15590 
15591 
15592 /*
15593  * Process ioctl get device firmware revision info request.
15594  * This operation should return to cfgadm the device firmware revision
15595  * information string
15596  *
15597  * Port multiplier is supported.
15598  */
15599 static	int
15600 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15601     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15602 {
15603 	sata_drive_info_t *sdinfo;
15604 	uint32_t info_len;
15605 	char ap_info[SATA_ID_FW_LEN + 1];
15606 
15607 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15608 	    sata_device->satadev_addr.cport)->cport_mutex);
15609 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15610 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15611 		    sata_device->satadev_addr.cport);
15612 	else /* port multiplier */
15613 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15614 		    sata_device->satadev_addr.cport,
15615 		    sata_device->satadev_addr.pmport);
15616 	if (sdinfo == NULL) {
15617 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15618 		    sata_device->satadev_addr.cport)->cport_mutex);
15619 		return (EINVAL);
15620 	}
15621 
15622 #ifdef	_LITTLE_ENDIAN
15623 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15624 #else	/* _LITTLE_ENDIAN */
15625 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15626 #endif	/* _LITTLE_ENDIAN */
15627 
15628 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15629 	    sata_device->satadev_addr.cport)->cport_mutex);
15630 
15631 	ap_info[SATA_ID_FW_LEN] = '\0';
15632 
15633 	info_len = strlen(ap_info) + 1;
15634 
15635 	if (ioc->get_size) {
15636 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15637 		    mode) != 0)
15638 			return (EFAULT);
15639 	} else {
15640 		if (ioc->bufsiz < info_len)
15641 			return (EINVAL);
15642 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15643 		    mode) != 0)
15644 			return (EFAULT);
15645 	}
15646 	return (0);
15647 }
15648 
15649 
15650 /*
15651  * Process ioctl get device serial number info request.
15652  * This operation should return to cfgadm the device serial number string.
15653  *
15654  * NOTE: Port multiplier is supported.
15655  */
15656 static	int
15657 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15658     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15659 {
15660 	sata_drive_info_t *sdinfo;
15661 	uint32_t info_len;
15662 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15663 
15664 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15665 	    sata_device->satadev_addr.cport)->cport_mutex);
15666 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15667 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15668 		    sata_device->satadev_addr.cport);
15669 	else /* port multiplier */
15670 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15671 		    sata_device->satadev_addr.cport,
15672 		    sata_device->satadev_addr.pmport);
15673 	if (sdinfo == NULL) {
15674 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15675 		    sata_device->satadev_addr.cport)->cport_mutex);
15676 		return (EINVAL);
15677 	}
15678 
15679 #ifdef	_LITTLE_ENDIAN
15680 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15681 #else	/* _LITTLE_ENDIAN */
15682 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15683 #endif	/* _LITTLE_ENDIAN */
15684 
15685 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15686 	    sata_device->satadev_addr.cport)->cport_mutex);
15687 
15688 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15689 
15690 	info_len = strlen(ap_info) + 1;
15691 
15692 	if (ioc->get_size) {
15693 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15694 		    mode) != 0)
15695 			return (EFAULT);
15696 	} else {
15697 		if (ioc->bufsiz < info_len)
15698 			return (EINVAL);
15699 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15700 		    mode) != 0)
15701 			return (EFAULT);
15702 	}
15703 	return (0);
15704 }
15705 
15706 
15707 /*
15708  * Preset scsi extended sense data (to NO SENSE)
15709  * First 18 bytes of the sense data are preset to current valid sense
15710  * with a key NO SENSE data.
15711  *
15712  * Returns void
15713  */
15714 static void
15715 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15716 {
15717 	sense->es_valid = 1;		/* Valid sense */
15718 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15719 	sense->es_key = KEY_NO_SENSE;
15720 	sense->es_info_1 = 0;
15721 	sense->es_info_2 = 0;
15722 	sense->es_info_3 = 0;
15723 	sense->es_info_4 = 0;
15724 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15725 	sense->es_cmd_info[0] = 0;
15726 	sense->es_cmd_info[1] = 0;
15727 	sense->es_cmd_info[2] = 0;
15728 	sense->es_cmd_info[3] = 0;
15729 	sense->es_add_code = 0;
15730 	sense->es_qual_code = 0;
15731 }
15732 
15733 /*
15734  * Register a legacy cmdk-style devid for the target (disk) device.
15735  *
15736  * Note: This function is called only when the HBA devinfo node has the
15737  * property "use-cmdk-devid-format" set. This property indicates that
15738  * devid compatible with old cmdk (target) driver is to be generated
15739  * for any target device attached to this controller. This will take
15740  * precedence over the devid generated by sd (target) driver.
15741  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15742  */
15743 static void
15744 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15745 {
15746 	char	*hwid;
15747 	int	modlen;
15748 	int	serlen;
15749 	int	rval;
15750 	ddi_devid_t	devid;
15751 
15752 	/*
15753 	 * device ID is a concatanation of model number, "=", serial number.
15754 	 */
15755 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15756 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15757 	    sizeof (sdinfo->satadrv_id.ai_model));
15758 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15759 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15760 	if (modlen == 0)
15761 		goto err;
15762 	hwid[modlen++] = '=';
15763 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15764 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15765 	swab(&hwid[modlen], &hwid[modlen],
15766 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15767 	serlen = sata_check_modser(&hwid[modlen],
15768 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15769 	if (serlen == 0)
15770 		goto err;
15771 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15772 
15773 	/* initialize/register devid */
15774 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15775 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15776 		rval = ddi_devid_register(dip, devid);
15777 		/*
15778 		 * Free up the allocated devid buffer.
15779 		 * NOTE: This doesn't mean unregistering devid.
15780 		 */
15781 		ddi_devid_free(devid);
15782 	}
15783 
15784 	if (rval != DDI_SUCCESS)
15785 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15786 		    " on port %d", sdinfo->satadrv_addr.cport);
15787 err:
15788 	kmem_free(hwid, LEGACY_HWID_LEN);
15789 }
15790 
15791 /*
15792  * valid model/serial string must contain a non-zero non-space characters.
15793  * trim trailing spaces/NULLs.
15794  */
15795 static int
15796 sata_check_modser(char *buf, int buf_len)
15797 {
15798 	boolean_t ret;
15799 	char *s;
15800 	int i;
15801 	int tb;
15802 	char ch;
15803 
15804 	ret = B_FALSE;
15805 	s = buf;
15806 	for (i = 0; i < buf_len; i++) {
15807 		ch = *s++;
15808 		if (ch != ' ' && ch != '\0')
15809 			tb = i + 1;
15810 		if (ch != ' ' && ch != '\0' && ch != '0')
15811 			ret = B_TRUE;
15812 	}
15813 
15814 	if (ret == B_FALSE)
15815 		return (0); /* invalid string */
15816 
15817 	return (tb); /* return length */
15818 }
15819 
15820 /*
15821  * sata_set_drive_features function compares current device features setting
15822  * with the saved device features settings and, if there is a difference,
15823  * it restores device features setting to the previously saved state.
15824  * It also arbitrarily tries to select the highest supported DMA mode.
15825  * Device Identify or Identify Packet Device data has to be current.
15826  * At the moment read ahead and write cache are considered for all devices.
15827  * For atapi devices, Removable Media Status Notification is set in addition
15828  * to common features.
15829  *
15830  * This function cannot be called in the interrupt context (it may sleep).
15831  *
15832  * The input argument sdinfo should point to the drive info structure
15833  * to be updated after features are set. Note, that only
15834  * device (packet) identify data is updated, not the flags indicating the
15835  * supported features.
15836  *
15837  * Returns SATA_SUCCESS if successful or there was nothing to do.
15838  * Device Identify data in the drive info structure pointed to by the sdinfo
15839  * arguments is updated even when no features were set or changed.
15840  *
15841  * Returns SATA_FAILURE if device features could not be set or DMA mode
15842  * for a disk cannot be set and device identify data cannot be fetched.
15843  *
15844  * Returns SATA_RETRY if device features could not be set (other than disk
15845  * DMA mode) but the device identify data was fetched successfully.
15846  *
15847  * Note: This function may fail the port, making it inaccessible.
15848  * In such case the explicit port disconnect/connect or physical device
15849  * detach/attach is required to re-evaluate port state again.
15850  */
15851 
15852 static int
15853 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15854     sata_drive_info_t *sdinfo, int restore)
15855 {
15856 	int rval = SATA_SUCCESS;
15857 	int rval_set;
15858 	sata_drive_info_t new_sdinfo;
15859 	char *finfo = "sata_set_drive_features: cannot";
15860 	char *finfox;
15861 	int cache_op;
15862 
15863 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15864 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15865 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15866 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15867 		/*
15868 		 * Cannot get device identification - caller may retry later
15869 		 */
15870 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15871 		    "%s fetch device identify data\n", finfo);
15872 		return (SATA_FAILURE);
15873 	}
15874 	finfox = (restore != 0) ? " restore device features" :
15875 	    " initialize device features\n";
15876 
15877 	switch (sdinfo->satadrv_type) {
15878 	case SATA_DTYPE_ATADISK:
15879 		/* Arbitrarily set UDMA mode */
15880 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15881 		    SATA_SUCCESS) {
15882 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15883 			    "%s set UDMA mode\n", finfo));
15884 			return (SATA_FAILURE);
15885 		}
15886 		break;
15887 	case SATA_DTYPE_ATAPICD:
15888 	case SATA_DTYPE_ATAPITAPE:
15889 	case SATA_DTYPE_ATAPIDISK:
15890 		/*  Set Removable Media Status Notification, if necessary */
15891 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15892 		    restore != 0) {
15893 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15894 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15895 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15896 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15897 				/* Current setting does not match saved one */
15898 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15899 				    sdinfo->satadrv_settings &
15900 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15901 					rval = SATA_FAILURE;
15902 			}
15903 		}
15904 		/*
15905 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15906 		 * we want to use DMA transfer mode whenever possible.
15907 		 * Some devices require explicit setting of the DMA mode.
15908 		 */
15909 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15910 			/* Set highest supported DMA mode */
15911 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15912 			    SATA_SUCCESS) {
15913 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15914 				    "%s set UDMA mode\n", finfo));
15915 				rval = SATA_FAILURE;
15916 			}
15917 		}
15918 		break;
15919 	}
15920 
15921 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15922 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15923 		/*
15924 		 * neither READ AHEAD nor WRITE CACHE is supported
15925 		 * - do nothing
15926 		 */
15927 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15928 		    "settable features not supported\n", NULL);
15929 		goto update_sdinfo;
15930 	}
15931 
15932 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15933 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15934 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15935 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15936 		/*
15937 		 * both READ AHEAD and WRITE CACHE are enabled
15938 		 * - Nothing to do
15939 		 */
15940 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15941 		    "no device features to set\n", NULL);
15942 		goto update_sdinfo;
15943 	}
15944 
15945 	cache_op = 0;
15946 
15947 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15948 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15949 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15950 			/* Enable read ahead / read cache */
15951 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15952 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15953 			    "enabling read cache\n", NULL);
15954 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15955 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15956 			/* Disable read ahead  / read cache */
15957 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15958 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15959 			    "disabling read cache\n", NULL);
15960 		}
15961 
15962 		if (cache_op != 0) {
15963 			/* Try to set read cache mode */
15964 			rval_set = sata_set_cache_mode(sata_hba_inst,
15965 			    &new_sdinfo, cache_op);
15966 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15967 				rval = rval_set;
15968 		}
15969 	}
15970 
15971 	cache_op = 0;
15972 
15973 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15974 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15975 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15976 			/* Enable write cache */
15977 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15978 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15979 			    "enabling write cache\n", NULL);
15980 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15981 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15982 			/* Disable write cache */
15983 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15984 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15985 			    "disabling write cache\n", NULL);
15986 		}
15987 
15988 		if (cache_op != 0) {
15989 			/* Try to set write cache mode */
15990 			rval_set = sata_set_cache_mode(sata_hba_inst,
15991 			    &new_sdinfo, cache_op);
15992 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15993 				rval = rval_set;
15994 		}
15995 	}
15996 	if (rval != SATA_SUCCESS)
15997 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15998 		    "%s %s", finfo, finfox));
15999 
16000 update_sdinfo:
16001 	/*
16002 	 * We need to fetch Device Identify data again
16003 	 */
16004 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16005 		/*
16006 		 * Cannot get device identification - retry later
16007 		 */
16008 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16009 		    "%s re-fetch device identify data\n", finfo));
16010 		rval = SATA_FAILURE;
16011 	}
16012 	/* Copy device sata info. */
16013 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16014 
16015 	return (rval);
16016 }
16017 
16018 
16019 /*
16020  *
16021  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16022  * unable to determine.
16023  *
16024  * Cannot be called in an interrupt context.
16025  *
16026  * Called by sata_build_lsense_page_2f()
16027  */
16028 
16029 static int
16030 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16031     sata_drive_info_t *sdinfo)
16032 {
16033 	sata_pkt_t *spkt;
16034 	sata_cmd_t *scmd;
16035 	sata_pkt_txlate_t *spx;
16036 	int rval;
16037 
16038 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16039 	spx->txlt_sata_hba_inst = sata_hba_inst;
16040 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16041 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16042 	if (spkt == NULL) {
16043 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16044 		return (-1);
16045 	}
16046 	/* address is needed now */
16047 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16048 
16049 
16050 	/* Fill sata_pkt */
16051 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16052 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16053 	/* Synchronous mode, no callback */
16054 	spkt->satapkt_comp = NULL;
16055 	/* Timeout 30s */
16056 	spkt->satapkt_time = sata_default_pkt_time;
16057 
16058 	scmd = &spkt->satapkt_cmd;
16059 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16060 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16061 
16062 	/* Set up which registers need to be returned */
16063 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16064 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16065 
16066 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16067 	scmd->satacmd_addr_type = 0;		/* N/A */
16068 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16069 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16070 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16071 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16072 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16073 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16074 	scmd->satacmd_cmd_reg = SATAC_SMART;
16075 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16076 	    sdinfo->satadrv_addr.cport)));
16077 
16078 
16079 	/* Send pkt to SATA HBA driver */
16080 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16081 	    SATA_TRAN_ACCEPTED ||
16082 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16083 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16084 		    sdinfo->satadrv_addr.cport)));
16085 		/*
16086 		 * Whoops, no SMART RETURN STATUS
16087 		 */
16088 		rval = -1;
16089 	} else {
16090 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16091 		    sdinfo->satadrv_addr.cport)));
16092 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16093 			rval = -1;
16094 			goto fail;
16095 		}
16096 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16097 			rval = -1;
16098 			goto fail;
16099 		}
16100 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16101 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16102 			rval = 0;
16103 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16104 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16105 			rval = 1;
16106 		else {
16107 			rval = -1;
16108 			goto fail;
16109 		}
16110 	}
16111 fail:
16112 	/* Free allocated resources */
16113 	sata_pkt_free(spx);
16114 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16115 
16116 	return (rval);
16117 }
16118 
16119 /*
16120  *
16121  * Returns 0 if succeeded, -1 otherwise
16122  *
16123  * Cannot be called in an interrupt context.
16124  *
16125  */
16126 static int
16127 sata_fetch_smart_data(
16128 	sata_hba_inst_t *sata_hba_inst,
16129 	sata_drive_info_t *sdinfo,
16130 	struct smart_data *smart_data)
16131 {
16132 	sata_pkt_t *spkt;
16133 	sata_cmd_t *scmd;
16134 	sata_pkt_txlate_t *spx;
16135 	int rval;
16136 
16137 #if ! defined(lint)
16138 	ASSERT(sizeof (struct smart_data) == 512);
16139 #endif
16140 
16141 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16142 	spx->txlt_sata_hba_inst = sata_hba_inst;
16143 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16144 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16145 	if (spkt == NULL) {
16146 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16147 		return (-1);
16148 	}
16149 	/* address is needed now */
16150 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16151 
16152 
16153 	/* Fill sata_pkt */
16154 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16155 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16156 	/* Synchronous mode, no callback */
16157 	spkt->satapkt_comp = NULL;
16158 	/* Timeout 30s */
16159 	spkt->satapkt_time = sata_default_pkt_time;
16160 
16161 	scmd = &spkt->satapkt_cmd;
16162 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16163 
16164 	/*
16165 	 * Allocate buffer for SMART data
16166 	 */
16167 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16168 	    sizeof (struct smart_data));
16169 	if (scmd->satacmd_bp == NULL) {
16170 		sata_pkt_free(spx);
16171 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16172 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16173 		    "sata_fetch_smart_data: "
16174 		    "cannot allocate buffer"));
16175 		return (-1);
16176 	}
16177 
16178 
16179 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16180 	scmd->satacmd_addr_type = 0;		/* N/A */
16181 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16182 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16183 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16184 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16185 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16186 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16187 	scmd->satacmd_cmd_reg = SATAC_SMART;
16188 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16189 	    sdinfo->satadrv_addr.cport)));
16190 
16191 	/* Send pkt to SATA HBA driver */
16192 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16193 	    SATA_TRAN_ACCEPTED ||
16194 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16195 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16196 		    sdinfo->satadrv_addr.cport)));
16197 		/*
16198 		 * Whoops, no SMART DATA available
16199 		 */
16200 		rval = -1;
16201 		goto fail;
16202 	} else {
16203 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16204 		    sdinfo->satadrv_addr.cport)));
16205 		if (spx->txlt_buf_dma_handle != NULL) {
16206 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16207 			    DDI_DMA_SYNC_FORKERNEL);
16208 			ASSERT(rval == DDI_SUCCESS);
16209 		}
16210 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16211 		    sizeof (struct smart_data));
16212 	}
16213 
16214 fail:
16215 	/* Free allocated resources */
16216 	sata_free_local_buffer(spx);
16217 	sata_pkt_free(spx);
16218 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16219 
16220 	return (rval);
16221 }
16222 
16223 /*
16224  * Used by LOG SENSE page 0x10
16225  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16226  * Note: cannot be called in the interrupt context.
16227  *
16228  * return 0 for success, -1 otherwise
16229  *
16230  */
16231 static int
16232 sata_ext_smart_selftest_read_log(
16233 	sata_hba_inst_t *sata_hba_inst,
16234 	sata_drive_info_t *sdinfo,
16235 	struct smart_ext_selftest_log *ext_selftest_log,
16236 	uint16_t block_num)
16237 {
16238 	sata_pkt_txlate_t *spx;
16239 	sata_pkt_t *spkt;
16240 	sata_cmd_t *scmd;
16241 	int rval;
16242 
16243 #if ! defined(lint)
16244 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16245 #endif
16246 
16247 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16248 	spx->txlt_sata_hba_inst = sata_hba_inst;
16249 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16250 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16251 	if (spkt == NULL) {
16252 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16253 		return (-1);
16254 	}
16255 	/* address is needed now */
16256 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16257 
16258 
16259 	/* Fill sata_pkt */
16260 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16261 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16262 	/* Synchronous mode, no callback */
16263 	spkt->satapkt_comp = NULL;
16264 	/* Timeout 30s */
16265 	spkt->satapkt_time = sata_default_pkt_time;
16266 
16267 	scmd = &spkt->satapkt_cmd;
16268 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16269 
16270 	/*
16271 	 * Allocate buffer for SMART extended self-test log
16272 	 */
16273 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16274 	    sizeof (struct smart_ext_selftest_log));
16275 	if (scmd->satacmd_bp == NULL) {
16276 		sata_pkt_free(spx);
16277 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16278 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16279 		    "sata_ext_smart_selftest_log: "
16280 		    "cannot allocate buffer"));
16281 		return (-1);
16282 	}
16283 
16284 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16285 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16286 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16287 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16288 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16289 	scmd->satacmd_lba_low_msb = 0;
16290 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16291 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16292 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16293 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16294 
16295 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16296 	    sdinfo->satadrv_addr.cport)));
16297 
16298 	/* Send pkt to SATA HBA driver */
16299 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16300 	    SATA_TRAN_ACCEPTED ||
16301 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16302 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16303 		    sdinfo->satadrv_addr.cport)));
16304 
16305 		/*
16306 		 * Whoops, no SMART selftest log info available
16307 		 */
16308 		rval = -1;
16309 		goto fail;
16310 	} else {
16311 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16312 		    sdinfo->satadrv_addr.cport)));
16313 
16314 		if (spx->txlt_buf_dma_handle != NULL) {
16315 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16316 			    DDI_DMA_SYNC_FORKERNEL);
16317 			ASSERT(rval == DDI_SUCCESS);
16318 		}
16319 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16320 		    (uint8_t *)ext_selftest_log,
16321 		    sizeof (struct smart_ext_selftest_log));
16322 		rval = 0;
16323 	}
16324 
16325 fail:
16326 	/* Free allocated resources */
16327 	sata_free_local_buffer(spx);
16328 	sata_pkt_free(spx);
16329 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16330 
16331 	return (rval);
16332 }
16333 
16334 /*
16335  * Returns 0 for success, -1 otherwise
16336  *
16337  * SMART self-test log data is returned in buffer pointed to by selftest_log
16338  */
16339 static int
16340 sata_smart_selftest_log(
16341 	sata_hba_inst_t *sata_hba_inst,
16342 	sata_drive_info_t *sdinfo,
16343 	struct smart_selftest_log *selftest_log)
16344 {
16345 	sata_pkt_t *spkt;
16346 	sata_cmd_t *scmd;
16347 	sata_pkt_txlate_t *spx;
16348 	int rval;
16349 
16350 #if ! defined(lint)
16351 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16352 #endif
16353 
16354 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16355 	spx->txlt_sata_hba_inst = sata_hba_inst;
16356 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16357 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16358 	if (spkt == NULL) {
16359 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16360 		return (-1);
16361 	}
16362 	/* address is needed now */
16363 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16364 
16365 
16366 	/* Fill sata_pkt */
16367 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16368 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16369 	/* Synchronous mode, no callback */
16370 	spkt->satapkt_comp = NULL;
16371 	/* Timeout 30s */
16372 	spkt->satapkt_time = sata_default_pkt_time;
16373 
16374 	scmd = &spkt->satapkt_cmd;
16375 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16376 
16377 	/*
16378 	 * Allocate buffer for SMART SELFTEST LOG
16379 	 */
16380 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16381 	    sizeof (struct smart_selftest_log));
16382 	if (scmd->satacmd_bp == NULL) {
16383 		sata_pkt_free(spx);
16384 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16385 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16386 		    "sata_smart_selftest_log: "
16387 		    "cannot allocate buffer"));
16388 		return (-1);
16389 	}
16390 
16391 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16392 	scmd->satacmd_addr_type = 0;		/* N/A */
16393 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16394 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16395 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16396 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16397 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16398 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16399 	scmd->satacmd_cmd_reg = SATAC_SMART;
16400 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16401 	    sdinfo->satadrv_addr.cport)));
16402 
16403 	/* Send pkt to SATA HBA driver */
16404 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16405 	    SATA_TRAN_ACCEPTED ||
16406 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16407 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16408 		    sdinfo->satadrv_addr.cport)));
16409 		/*
16410 		 * Whoops, no SMART DATA available
16411 		 */
16412 		rval = -1;
16413 		goto fail;
16414 	} else {
16415 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16416 		    sdinfo->satadrv_addr.cport)));
16417 		if (spx->txlt_buf_dma_handle != NULL) {
16418 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16419 			    DDI_DMA_SYNC_FORKERNEL);
16420 			ASSERT(rval == DDI_SUCCESS);
16421 		}
16422 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16423 		    sizeof (struct smart_selftest_log));
16424 		rval = 0;
16425 	}
16426 
16427 fail:
16428 	/* Free allocated resources */
16429 	sata_free_local_buffer(spx);
16430 	sata_pkt_free(spx);
16431 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16432 
16433 	return (rval);
16434 }
16435 
16436 
16437 /*
16438  * Returns 0 for success, -1 otherwise
16439  *
16440  * SMART READ LOG data is returned in buffer pointed to by smart_log
16441  */
16442 static int
16443 sata_smart_read_log(
16444 	sata_hba_inst_t *sata_hba_inst,
16445 	sata_drive_info_t *sdinfo,
16446 	uint8_t *smart_log,		/* where the data should be returned */
16447 	uint8_t which_log,		/* which log should be returned */
16448 	uint8_t log_size)		/* # of 512 bytes in log */
16449 {
16450 	sata_pkt_t *spkt;
16451 	sata_cmd_t *scmd;
16452 	sata_pkt_txlate_t *spx;
16453 	int rval;
16454 
16455 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16456 	spx->txlt_sata_hba_inst = sata_hba_inst;
16457 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16458 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16459 	if (spkt == NULL) {
16460 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16461 		return (-1);
16462 	}
16463 	/* address is needed now */
16464 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16465 
16466 
16467 	/* Fill sata_pkt */
16468 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16469 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16470 	/* Synchronous mode, no callback */
16471 	spkt->satapkt_comp = NULL;
16472 	/* Timeout 30s */
16473 	spkt->satapkt_time = sata_default_pkt_time;
16474 
16475 	scmd = &spkt->satapkt_cmd;
16476 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16477 
16478 	/*
16479 	 * Allocate buffer for SMART READ LOG
16480 	 */
16481 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16482 	if (scmd->satacmd_bp == NULL) {
16483 		sata_pkt_free(spx);
16484 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16485 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16486 		    "sata_smart_read_log: " "cannot allocate buffer"));
16487 		return (-1);
16488 	}
16489 
16490 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16491 	scmd->satacmd_addr_type = 0;		/* N/A */
16492 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16493 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16494 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16495 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16496 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16497 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16498 	scmd->satacmd_cmd_reg = SATAC_SMART;
16499 
16500 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16501 	    sdinfo->satadrv_addr.cport)));
16502 
16503 	/* Send pkt to SATA HBA driver */
16504 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16505 	    SATA_TRAN_ACCEPTED ||
16506 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16507 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16508 		    sdinfo->satadrv_addr.cport)));
16509 
16510 		/*
16511 		 * Whoops, no SMART DATA available
16512 		 */
16513 		rval = -1;
16514 		goto fail;
16515 	} else {
16516 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16517 		    sdinfo->satadrv_addr.cport)));
16518 
16519 		if (spx->txlt_buf_dma_handle != NULL) {
16520 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16521 			    DDI_DMA_SYNC_FORKERNEL);
16522 			ASSERT(rval == DDI_SUCCESS);
16523 		}
16524 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16525 		rval = 0;
16526 	}
16527 
16528 fail:
16529 	/* Free allocated resources */
16530 	sata_free_local_buffer(spx);
16531 	sata_pkt_free(spx);
16532 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16533 
16534 	return (rval);
16535 }
16536 
16537 /*
16538  * Used by LOG SENSE page 0x10
16539  *
16540  * return 0 for success, -1 otherwise
16541  *
16542  */
16543 static int
16544 sata_read_log_ext_directory(
16545 	sata_hba_inst_t *sata_hba_inst,
16546 	sata_drive_info_t *sdinfo,
16547 	struct read_log_ext_directory *logdir)
16548 {
16549 	sata_pkt_txlate_t *spx;
16550 	sata_pkt_t *spkt;
16551 	sata_cmd_t *scmd;
16552 	int rval;
16553 
16554 #if ! defined(lint)
16555 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16556 #endif
16557 
16558 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16559 	spx->txlt_sata_hba_inst = sata_hba_inst;
16560 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16561 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16562 	if (spkt == NULL) {
16563 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16564 		return (-1);
16565 	}
16566 
16567 	/* Fill sata_pkt */
16568 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16569 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16570 	/* Synchronous mode, no callback */
16571 	spkt->satapkt_comp = NULL;
16572 	/* Timeout 30s */
16573 	spkt->satapkt_time = sata_default_pkt_time;
16574 
16575 	scmd = &spkt->satapkt_cmd;
16576 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16577 
16578 	/*
16579 	 * Allocate buffer for SMART READ LOG EXTENDED command
16580 	 */
16581 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16582 	    sizeof (struct read_log_ext_directory));
16583 	if (scmd->satacmd_bp == NULL) {
16584 		sata_pkt_free(spx);
16585 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16586 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16587 		    "sata_read_log_ext_directory: "
16588 		    "cannot allocate buffer"));
16589 		return (-1);
16590 	}
16591 
16592 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16593 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16594 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16595 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16596 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16597 	scmd->satacmd_lba_low_msb = 0;
16598 	scmd->satacmd_lba_mid_lsb = 0;
16599 	scmd->satacmd_lba_mid_msb = 0;
16600 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16601 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16602 
16603 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16604 	    sdinfo->satadrv_addr.cport)));
16605 
16606 	/* Send pkt to SATA HBA driver */
16607 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16608 	    SATA_TRAN_ACCEPTED ||
16609 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16610 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16611 		    sdinfo->satadrv_addr.cport)));
16612 		/*
16613 		 * Whoops, no SMART selftest log info available
16614 		 */
16615 		rval = -1;
16616 		goto fail;
16617 	} else {
16618 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16619 		    sdinfo->satadrv_addr.cport)));
16620 		if (spx->txlt_buf_dma_handle != NULL) {
16621 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16622 			    DDI_DMA_SYNC_FORKERNEL);
16623 			ASSERT(rval == DDI_SUCCESS);
16624 		}
16625 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16626 		    sizeof (struct read_log_ext_directory));
16627 		rval = 0;
16628 	}
16629 
16630 fail:
16631 	/* Free allocated resources */
16632 	sata_free_local_buffer(spx);
16633 	sata_pkt_free(spx);
16634 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16635 
16636 	return (rval);
16637 }
16638 
16639 /*
16640  * Set up error retrieval sata command for NCQ command error data
16641  * recovery.
16642  *
16643  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16644  * returns SATA_FAILURE otherwise.
16645  */
16646 static int
16647 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16648 {
16649 #ifndef __lock_lint
16650 	_NOTE(ARGUNUSED(sdinfo))
16651 #endif
16652 
16653 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16654 	sata_cmd_t *scmd;
16655 	struct buf *bp;
16656 
16657 	/* Operation modes are up to the caller */
16658 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16659 
16660 	/* Synchronous mode, no callback - may be changed by the caller */
16661 	spkt->satapkt_comp = NULL;
16662 	spkt->satapkt_time = sata_default_pkt_time;
16663 
16664 	scmd = &spkt->satapkt_cmd;
16665 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16666 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16667 
16668 	/*
16669 	 * Allocate dma_able buffer error data.
16670 	 * Buffer allocation will take care of buffer alignment and other DMA
16671 	 * attributes.
16672 	 */
16673 	bp = sata_alloc_local_buffer(spx,
16674 	    sizeof (struct sata_ncq_error_recovery_page));
16675 	if (bp == NULL)
16676 		return (SATA_FAILURE);
16677 
16678 	bp_mapin(bp); /* make data buffer accessible */
16679 	scmd->satacmd_bp = bp;
16680 
16681 	/*
16682 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16683 	 * before accessing it. Handle is in usual place in translate struct.
16684 	 */
16685 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16686 
16687 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16688 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16689 
16690 	return (SATA_SUCCESS);
16691 }
16692 
16693 /*
16694  * sata_xlate_errors() is used to translate (S)ATA error
16695  * information to SCSI information returned in the SCSI
16696  * packet.
16697  */
16698 static void
16699 sata_xlate_errors(sata_pkt_txlate_t *spx)
16700 {
16701 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16702 	struct scsi_extended_sense *sense;
16703 
16704 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16705 	*scsipkt->pkt_scbp = STATUS_CHECK;
16706 	sense = sata_arq_sense(spx);
16707 
16708 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16709 	case SATA_PKT_PORT_ERROR:
16710 		/*
16711 		 * We have no device data. Assume no data transfered.
16712 		 */
16713 		sense->es_key = KEY_HARDWARE_ERROR;
16714 		break;
16715 
16716 	case SATA_PKT_DEV_ERROR:
16717 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16718 		    SATA_STATUS_ERR) {
16719 			/*
16720 			 * determine dev error reason from error
16721 			 * reg content
16722 			 */
16723 			sata_decode_device_error(spx, sense);
16724 			break;
16725 		}
16726 		/* No extended sense key - no info available */
16727 		break;
16728 
16729 	case SATA_PKT_TIMEOUT:
16730 		scsipkt->pkt_reason = CMD_TIMEOUT;
16731 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16732 		/* No extended sense key */
16733 		break;
16734 
16735 	case SATA_PKT_ABORTED:
16736 		scsipkt->pkt_reason = CMD_ABORTED;
16737 		scsipkt->pkt_statistics |= STAT_ABORTED;
16738 		/* No extended sense key */
16739 		break;
16740 
16741 	case SATA_PKT_RESET:
16742 		/*
16743 		 * pkt aborted either by an explicit reset request from
16744 		 * a host, or due to error recovery
16745 		 */
16746 		scsipkt->pkt_reason = CMD_RESET;
16747 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16748 		break;
16749 
16750 	default:
16751 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16752 		break;
16753 	}
16754 }
16755 
16756 
16757 
16758 
16759 /*
16760  * Log sata message
16761  * dev pathname msg line preceeds the logged message.
16762  */
16763 
16764 static	void
16765 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16766 {
16767 	char pathname[128];
16768 	dev_info_t *dip = NULL;
16769 	va_list ap;
16770 
16771 	mutex_enter(&sata_log_mutex);
16772 
16773 	va_start(ap, fmt);
16774 	(void) vsprintf(sata_log_buf, fmt, ap);
16775 	va_end(ap);
16776 
16777 	if (sata_hba_inst != NULL) {
16778 		dip = SATA_DIP(sata_hba_inst);
16779 		(void) ddi_pathname(dip, pathname);
16780 	} else {
16781 		pathname[0] = 0;
16782 	}
16783 	if (level == CE_CONT) {
16784 		if (sata_debug_flags == 0)
16785 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16786 		else
16787 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16788 	} else {
16789 		if (level != CE_NOTE) {
16790 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16791 		} else if (sata_msg) {
16792 			cmn_err(level, "%s:\n %s", pathname,
16793 			    sata_log_buf);
16794 		}
16795 	}
16796 
16797 	/* sata trace debug */
16798 	sata_trace_debug(dip, sata_log_buf);
16799 
16800 	mutex_exit(&sata_log_mutex);
16801 }
16802 
16803 
16804 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16805 
16806 /*
16807  * Start or terminate the thread, depending on flag arg and current state
16808  */
16809 static void
16810 sata_event_thread_control(int startstop)
16811 {
16812 	static 	int sata_event_thread_terminating = 0;
16813 	static 	int sata_event_thread_starting = 0;
16814 	int i;
16815 
16816 	mutex_enter(&sata_event_mutex);
16817 
16818 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16819 	    sata_event_thread_terminating == 1)) {
16820 		mutex_exit(&sata_event_mutex);
16821 		return;
16822 	}
16823 	if (startstop == 1 && sata_event_thread_starting == 1) {
16824 		mutex_exit(&sata_event_mutex);
16825 		return;
16826 	}
16827 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16828 		sata_event_thread_starting = 1;
16829 		/* wait til terminate operation completes */
16830 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16831 		while (sata_event_thread_terminating == 1) {
16832 			if (i-- <= 0) {
16833 				sata_event_thread_starting = 0;
16834 				mutex_exit(&sata_event_mutex);
16835 #ifdef SATA_DEBUG
16836 				cmn_err(CE_WARN, "sata_event_thread_control: "
16837 				    "timeout waiting for thread to terminate");
16838 #endif
16839 				return;
16840 			}
16841 			mutex_exit(&sata_event_mutex);
16842 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16843 			mutex_enter(&sata_event_mutex);
16844 		}
16845 	}
16846 	if (startstop == 1) {
16847 		if (sata_event_thread == NULL) {
16848 			sata_event_thread = thread_create(NULL, 0,
16849 			    (void (*)())sata_event_daemon,
16850 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16851 		}
16852 		sata_event_thread_starting = 0;
16853 		mutex_exit(&sata_event_mutex);
16854 		return;
16855 	}
16856 
16857 	/*
16858 	 * If we got here, thread may need to be terminated
16859 	 */
16860 	if (sata_event_thread != NULL) {
16861 		int i;
16862 		/* Signal event thread to go away */
16863 		sata_event_thread_terminating = 1;
16864 		sata_event_thread_terminate = 1;
16865 		cv_signal(&sata_event_cv);
16866 		/*
16867 		 * Wait til daemon terminates.
16868 		 */
16869 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16870 		while (sata_event_thread_terminate == 1) {
16871 			mutex_exit(&sata_event_mutex);
16872 			if (i-- <= 0) {
16873 				/* Daemon did not go away !!! */
16874 #ifdef SATA_DEBUG
16875 				cmn_err(CE_WARN, "sata_event_thread_control: "
16876 				    "cannot terminate event daemon thread");
16877 #endif
16878 				mutex_enter(&sata_event_mutex);
16879 				break;
16880 			}
16881 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16882 			mutex_enter(&sata_event_mutex);
16883 		}
16884 		sata_event_thread_terminating = 0;
16885 	}
16886 	ASSERT(sata_event_thread_terminating == 0);
16887 	ASSERT(sata_event_thread_starting == 0);
16888 	mutex_exit(&sata_event_mutex);
16889 }
16890 
16891 
16892 /*
16893  * SATA HBA event notification function.
16894  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16895  * a port and/or device state or a controller itself.
16896  * Events for different addresses/addr types cannot be combined.
16897  * A warning message is generated for each event type.
16898  * Events are not processed by this function, so only the
16899  * event flag(s)is set for an affected entity and the event thread is
16900  * waken up. Event daemon thread processes all events.
16901  *
16902  * NOTE: Since more than one event may be reported at the same time, one
16903  * cannot determine a sequence of events when opposite event are reported, eg.
16904  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16905  * is taking precedence over reported events, i.e. may cause ignoring some
16906  * events.
16907  */
16908 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16909 
16910 void
16911 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16912 {
16913 	sata_hba_inst_t *sata_hba_inst = NULL;
16914 	sata_address_t *saddr;
16915 	sata_pmult_info_t *pmultinfo;
16916 	sata_drive_info_t *sdinfo;
16917 	sata_port_stats_t *pstats;
16918 	sata_cport_info_t *cportinfo;
16919 	sata_pmport_info_t *pmportinfo;
16920 	int cport, pmport;
16921 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16922 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16923 	char *lcp;
16924 	static char *err_msg_evnt_1 =
16925 	    "sata_hba_event_notify: invalid port event 0x%x ";
16926 	static char *err_msg_evnt_2 =
16927 	    "sata_hba_event_notify: invalid device event 0x%x ";
16928 	int linkevent;
16929 
16930 	/*
16931 	 * There is a possibility that an event will be generated on HBA
16932 	 * that has not completed attachment or is detaching. We still want
16933 	 * to process events until HBA is detached.
16934 	 */
16935 	mutex_enter(&sata_mutex);
16936 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16937 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16938 		if (SATA_DIP(sata_hba_inst) == dip)
16939 			if (sata_hba_inst->satahba_attached == 1)
16940 				break;
16941 	}
16942 	mutex_exit(&sata_mutex);
16943 	if (sata_hba_inst == NULL)
16944 		/* HBA not attached */
16945 		return;
16946 
16947 	ASSERT(sata_device != NULL);
16948 
16949 	/*
16950 	 * Validate address before - do not proceed with invalid address.
16951 	 */
16952 	saddr = &sata_device->satadev_addr;
16953 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16954 		return;
16955 
16956 	cport = saddr->cport;
16957 	pmport = saddr->pmport;
16958 
16959 	buf1[0] = buf2[0] = '\0';
16960 
16961 	/*
16962 	 * If event relates to port or device, check port state.
16963 	 * Port has to be initialized, or we cannot accept an event.
16964 	 */
16965 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16966 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16967 		mutex_enter(&sata_hba_inst->satahba_mutex);
16968 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16969 		mutex_exit(&sata_hba_inst->satahba_mutex);
16970 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16971 			return;
16972 	}
16973 
16974 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16975 	    SATA_ADDR_DPMPORT)) != 0) {
16976 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16977 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16978 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16979 			    "is attached to port %d, ignore pmult/pmport "
16980 			    "event 0x%x", cportinfo->cport_dev_type,
16981 			    cport, event));
16982 			return;
16983 		}
16984 
16985 		mutex_enter(&cportinfo->cport_mutex);
16986 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16987 		mutex_exit(&cportinfo->cport_mutex);
16988 
16989 		/*
16990 		 * The daemon might be processing attachment of port
16991 		 * multiplier, in that case we should ignore events on its
16992 		 * sub-devices.
16993 		 *
16994 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16995 		 * The pmport_state is checked by sata daemon.
16996 		 */
16997 		if (pmultinfo == NULL ||
16998 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16999 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17000 			    "sata_hba_event_notify: pmult is not"
17001 			    "available at port %d:%d, ignore event 0x%x",
17002 			    cport, pmport, event));
17003 			return;
17004 		}
17005 	}
17006 
17007 	if ((saddr->qual &
17008 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17009 
17010 		mutex_enter(&cportinfo->cport_mutex);
17011 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17012 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17013 			    "sata_hba_event_notify: invalid/"
17014 			    "un-implemented port %d:%d (%d ports), "
17015 			    "ignore event 0x%x", cport, pmport,
17016 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17017 			mutex_exit(&cportinfo->cport_mutex);
17018 			return;
17019 		}
17020 		mutex_exit(&cportinfo->cport_mutex);
17021 
17022 		mutex_enter(&sata_hba_inst->satahba_mutex);
17023 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17024 		    cport, pmport);
17025 		mutex_exit(&sata_hba_inst->satahba_mutex);
17026 
17027 		/* pmport is implemented/valid? */
17028 		if (pmportinfo == NULL) {
17029 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17030 			    "sata_hba_event_notify: invalid/"
17031 			    "un-implemented port %d:%d, ignore "
17032 			    "event 0x%x", cport, pmport, event));
17033 			return;
17034 		}
17035 	}
17036 
17037 	/*
17038 	 * Events refer to devices, ports and controllers - each has
17039 	 * unique address. Events for different addresses cannot be combined.
17040 	 */
17041 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17042 
17043 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17044 
17045 		/* qualify this event(s) */
17046 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17047 			/* Invalid event for the device port */
17048 			(void) sprintf(buf2, err_msg_evnt_1,
17049 			    event & SATA_EVNT_PORT_EVENTS);
17050 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17051 			goto event_info;
17052 		}
17053 		if (saddr->qual == SATA_ADDR_CPORT) {
17054 			/* Controller's device port event */
17055 
17056 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17057 			    cport_event_flags |=
17058 			    event & SATA_EVNT_PORT_EVENTS;
17059 			pstats =
17060 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17061 			    cport_stats;
17062 		} else {
17063 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17064 			mutex_enter(&pmportinfo->pmport_mutex);
17065 			/* Port multiplier's device port event */
17066 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17067 			    pmport_event_flags |=
17068 			    event & SATA_EVNT_PORT_EVENTS;
17069 			pstats =
17070 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17071 			    pmport_stats;
17072 			mutex_exit(&pmportinfo->pmport_mutex);
17073 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17074 		}
17075 
17076 		/*
17077 		 * Add to statistics and log the message. We have to do it
17078 		 * here rather than in the event daemon, because there may be
17079 		 * multiple events occuring before they are processed.
17080 		 */
17081 		linkevent = event &
17082 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17083 		if (linkevent) {
17084 			if (linkevent == (SATA_EVNT_LINK_LOST |
17085 			    SATA_EVNT_LINK_ESTABLISHED)) {
17086 				/* This is likely event combination */
17087 				(void) strlcat(buf1, "link lost/established, ",
17088 				    SATA_EVENT_MAX_MSG_LENGTH);
17089 
17090 				if (pstats->link_lost < 0xffffffffffffffffULL)
17091 					pstats->link_lost++;
17092 				if (pstats->link_established <
17093 				    0xffffffffffffffffULL)
17094 					pstats->link_established++;
17095 				linkevent = 0;
17096 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17097 				(void) strlcat(buf1, "link lost, ",
17098 				    SATA_EVENT_MAX_MSG_LENGTH);
17099 
17100 				if (pstats->link_lost < 0xffffffffffffffffULL)
17101 					pstats->link_lost++;
17102 			} else {
17103 				(void) strlcat(buf1, "link established, ",
17104 				    SATA_EVENT_MAX_MSG_LENGTH);
17105 				if (pstats->link_established <
17106 				    0xffffffffffffffffULL)
17107 					pstats->link_established++;
17108 			}
17109 		}
17110 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17111 			(void) strlcat(buf1, "device attached, ",
17112 			    SATA_EVENT_MAX_MSG_LENGTH);
17113 			if (pstats->device_attached < 0xffffffffffffffffULL)
17114 				pstats->device_attached++;
17115 		}
17116 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17117 			(void) strlcat(buf1, "device detached, ",
17118 			    SATA_EVENT_MAX_MSG_LENGTH);
17119 			if (pstats->device_detached < 0xffffffffffffffffULL)
17120 				pstats->device_detached++;
17121 		}
17122 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17123 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17124 			    "port %d power level changed", cport);
17125 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17126 				pstats->port_pwr_changed++;
17127 		}
17128 
17129 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17130 			/* There should be no other events for this address */
17131 			(void) sprintf(buf2, err_msg_evnt_1,
17132 			    event & ~SATA_EVNT_PORT_EVENTS);
17133 		}
17134 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17135 
17136 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17137 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17138 
17139 		/* qualify this event */
17140 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17141 			/* Invalid event for a device */
17142 			(void) sprintf(buf2, err_msg_evnt_2,
17143 			    event & SATA_EVNT_DEVICE_RESET);
17144 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17145 			goto event_info;
17146 		}
17147 		/* drive event */
17148 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17149 		if (sdinfo != NULL) {
17150 			if (event & SATA_EVNT_DEVICE_RESET) {
17151 				(void) strlcat(buf1, "device reset, ",
17152 				    SATA_EVENT_MAX_MSG_LENGTH);
17153 				if (sdinfo->satadrv_stats.drive_reset <
17154 				    0xffffffffffffffffULL)
17155 					sdinfo->satadrv_stats.drive_reset++;
17156 				sdinfo->satadrv_event_flags |=
17157 				    SATA_EVNT_DEVICE_RESET;
17158 			}
17159 		}
17160 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17161 			/* Invalid event for a device */
17162 			(void) sprintf(buf2, err_msg_evnt_2,
17163 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17164 		}
17165 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17166 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17167 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17168 
17169 		/* qualify this event */
17170 		if ((event & (SATA_EVNT_DEVICE_RESET |
17171 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17172 			/* Invalid event for a port multiplier */
17173 			(void) sprintf(buf2, err_msg_evnt_2,
17174 			    event & SATA_EVNT_DEVICE_RESET);
17175 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17176 			goto event_info;
17177 		}
17178 
17179 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17180 
17181 		if (event & SATA_EVNT_DEVICE_RESET) {
17182 
17183 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17184 			    "[Reset] port-mult on cport %d", cport);
17185 			pmultinfo->pmult_event_flags |=
17186 			    SATA_EVNT_DEVICE_RESET;
17187 			(void) strlcat(buf1, "pmult reset, ",
17188 			    SATA_EVENT_MAX_MSG_LENGTH);
17189 		}
17190 
17191 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17192 
17193 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17194 			    "pmult link changed on cport %d", cport);
17195 			pmultinfo->pmult_event_flags |=
17196 			    SATA_EVNT_PMULT_LINK_CHANGED;
17197 			(void) strlcat(buf1, "pmult link changed, ",
17198 			    SATA_EVENT_MAX_MSG_LENGTH);
17199 		}
17200 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17201 
17202 	} else {
17203 		if (saddr->qual != SATA_ADDR_NULL) {
17204 			/* Wrong address qualifier */
17205 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17206 			    "sata_hba_event_notify: invalid address 0x%x",
17207 			    *(uint32_t *)saddr));
17208 			return;
17209 		}
17210 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17211 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17212 			/* Invalid event for the controller */
17213 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17214 			    "sata_hba_event_notify: invalid event 0x%x for "
17215 			    "controller",
17216 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17217 			return;
17218 		}
17219 		buf1[0] = '\0';
17220 		/* This may be a frequent and not interesting event */
17221 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17222 		    "controller power level changed\n", NULL);
17223 
17224 		mutex_enter(&sata_hba_inst->satahba_mutex);
17225 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17226 		    0xffffffffffffffffULL)
17227 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17228 
17229 		sata_hba_inst->satahba_event_flags |=
17230 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17231 		mutex_exit(&sata_hba_inst->satahba_mutex);
17232 	}
17233 	/*
17234 	 * If we got here, there is something to do with this HBA
17235 	 * instance.
17236 	 */
17237 	mutex_enter(&sata_hba_inst->satahba_mutex);
17238 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17239 	mutex_exit(&sata_hba_inst->satahba_mutex);
17240 	mutex_enter(&sata_mutex);
17241 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17242 	mutex_exit(&sata_mutex);
17243 
17244 	/* Tickle event thread */
17245 	mutex_enter(&sata_event_mutex);
17246 	if (sata_event_thread_active == 0)
17247 		cv_signal(&sata_event_cv);
17248 	mutex_exit(&sata_event_mutex);
17249 
17250 event_info:
17251 	if (buf1[0] != '\0') {
17252 		lcp = strrchr(buf1, ',');
17253 		if (lcp != NULL)
17254 			*lcp = '\0';
17255 	}
17256 	if (saddr->qual == SATA_ADDR_CPORT ||
17257 	    saddr->qual == SATA_ADDR_DCPORT) {
17258 		if (buf1[0] != '\0') {
17259 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17260 			    cport, buf1);
17261 		}
17262 		if (buf2[0] != '\0') {
17263 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17264 			    cport, buf2);
17265 		}
17266 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17267 	    saddr->qual == SATA_ADDR_DPMPORT) {
17268 		if (buf1[0] != '\0') {
17269 			sata_log(sata_hba_inst, CE_NOTE,
17270 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17271 		}
17272 		if (buf2[0] != '\0') {
17273 			sata_log(sata_hba_inst, CE_NOTE,
17274 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17275 		}
17276 	}
17277 }
17278 
17279 
17280 /*
17281  * Event processing thread.
17282  * Arg is a pointer to the sata_hba_list pointer.
17283  * It is not really needed, because sata_hba_list is global and static
17284  */
17285 static void
17286 sata_event_daemon(void *arg)
17287 {
17288 #ifndef __lock_lint
17289 	_NOTE(ARGUNUSED(arg))
17290 #endif
17291 	sata_hba_inst_t *sata_hba_inst;
17292 	clock_t delta;
17293 
17294 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17295 	    "SATA event daemon started\n", NULL);
17296 loop:
17297 	/*
17298 	 * Process events here. Walk through all registered HBAs
17299 	 */
17300 	mutex_enter(&sata_mutex);
17301 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17302 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17303 		ASSERT(sata_hba_inst != NULL);
17304 		mutex_enter(&sata_hba_inst->satahba_mutex);
17305 		if (sata_hba_inst->satahba_attached == 0 ||
17306 		    (sata_hba_inst->satahba_event_flags &
17307 		    SATA_EVNT_SKIP) != 0) {
17308 			mutex_exit(&sata_hba_inst->satahba_mutex);
17309 			continue;
17310 		}
17311 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17312 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17313 			mutex_exit(&sata_hba_inst->satahba_mutex);
17314 			mutex_exit(&sata_mutex);
17315 			/* Got the controller with pending event */
17316 			sata_process_controller_events(sata_hba_inst);
17317 			/*
17318 			 * Since global mutex was released, there is a
17319 			 * possibility that HBA list has changed, so start
17320 			 * over from the top. Just processed controller
17321 			 * will be passed-over because of the SKIP flag.
17322 			 */
17323 			goto loop;
17324 		}
17325 		mutex_exit(&sata_hba_inst->satahba_mutex);
17326 	}
17327 	/* Clear SKIP flag in all controllers */
17328 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17329 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17330 		mutex_enter(&sata_hba_inst->satahba_mutex);
17331 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17332 		mutex_exit(&sata_hba_inst->satahba_mutex);
17333 	}
17334 	mutex_exit(&sata_mutex);
17335 
17336 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17337 	    "SATA EVENT DAEMON suspending itself", NULL);
17338 
17339 #ifdef SATA_DEBUG
17340 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17341 		sata_log(sata_hba_inst, CE_WARN,
17342 		    "SATA EVENTS PROCESSING DISABLED\n");
17343 		thread_exit(); /* Daemon will not run again */
17344 	}
17345 #endif
17346 	mutex_enter(&sata_event_mutex);
17347 	sata_event_thread_active = 0;
17348 	mutex_exit(&sata_event_mutex);
17349 	/*
17350 	 * Go to sleep/suspend itself and wake up either because new event or
17351 	 * wait timeout. Exit if there is a termination request (driver
17352 	 * unload).
17353 	 */
17354 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17355 	do {
17356 		mutex_enter(&sata_event_mutex);
17357 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17358 		    delta, TR_CLOCK_TICK);
17359 
17360 		if (sata_event_thread_active != 0) {
17361 			mutex_exit(&sata_event_mutex);
17362 			continue;
17363 		}
17364 
17365 		/* Check if it is time to go away */
17366 		if (sata_event_thread_terminate == 1) {
17367 			/*
17368 			 * It is up to the thread setting above flag to make
17369 			 * sure that this thread is not killed prematurely.
17370 			 */
17371 			sata_event_thread_terminate = 0;
17372 			sata_event_thread = NULL;
17373 			mutex_exit(&sata_event_mutex);
17374 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17375 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17376 			thread_exit();  { _NOTE(NOT_REACHED) }
17377 		}
17378 		mutex_exit(&sata_event_mutex);
17379 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17380 
17381 	mutex_enter(&sata_event_mutex);
17382 	sata_event_thread_active = 1;
17383 	mutex_exit(&sata_event_mutex);
17384 
17385 	mutex_enter(&sata_mutex);
17386 	sata_event_pending &= ~SATA_EVNT_MAIN;
17387 	mutex_exit(&sata_mutex);
17388 
17389 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17390 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17391 
17392 	goto loop;
17393 }
17394 
17395 /*
17396  * Specific HBA instance event processing.
17397  *
17398  * NOTE: At the moment, device event processing is limited to hard disks
17399  * only.
17400  * Port multiplier is supported now.
17401  */
17402 static void
17403 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17404 {
17405 	int ncport;
17406 	uint32_t event_flags;
17407 	sata_address_t *saddr;
17408 	sata_cport_info_t *cportinfo;
17409 	sata_pmult_info_t *pmultinfo;
17410 
17411 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17412 	    "Processing controller %d event(s)",
17413 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17414 
17415 	mutex_enter(&sata_hba_inst->satahba_mutex);
17416 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17417 	event_flags = sata_hba_inst->satahba_event_flags;
17418 	mutex_exit(&sata_hba_inst->satahba_mutex);
17419 	/*
17420 	 * Process controller power change first
17421 	 * HERE
17422 	 */
17423 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17424 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17425 
17426 	/*
17427 	 * Search through ports/devices to identify affected port/device.
17428 	 * We may have to process events for more than one port/device.
17429 	 */
17430 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17431 		/*
17432 		 * Not all ports may be processed in attach by the time we
17433 		 * get an event. Check if port info is initialized.
17434 		 */
17435 		mutex_enter(&sata_hba_inst->satahba_mutex);
17436 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17437 		mutex_exit(&sata_hba_inst->satahba_mutex);
17438 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17439 			continue;
17440 
17441 		/* We have initialized controller port info */
17442 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17443 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17444 		    cport_event_flags;
17445 		/* Check if port was locked by IOCTL processing */
17446 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17447 			/*
17448 			 * We ignore port events because port is busy
17449 			 * with AP control processing. Set again
17450 			 * controller and main event flag, so that
17451 			 * events may be processed by the next daemon
17452 			 * run.
17453 			 */
17454 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17455 			mutex_enter(&sata_hba_inst->satahba_mutex);
17456 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17457 			mutex_exit(&sata_hba_inst->satahba_mutex);
17458 			mutex_enter(&sata_mutex);
17459 			sata_event_pending |= SATA_EVNT_MAIN;
17460 			mutex_exit(&sata_mutex);
17461 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17462 			    "Event processing postponed until "
17463 			    "AP control processing completes",
17464 			    NULL);
17465 			/* Check other ports */
17466 			continue;
17467 		} else {
17468 			/*
17469 			 * Set BSY flag so that AP control would not
17470 			 * interfere with events processing for
17471 			 * this port.
17472 			 */
17473 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17474 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17475 		}
17476 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17477 
17478 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17479 
17480 		if ((event_flags &
17481 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17482 			/*
17483 			 * Got port event.
17484 			 * We need some hierarchy of event processing as they
17485 			 * are affecting each other:
17486 			 * 1. port failed
17487 			 * 2. device detached/attached
17488 			 * 3. link events - link events may trigger device
17489 			 *    detached or device attached events in some
17490 			 *    circumstances.
17491 			 * 4. port power level changed
17492 			 */
17493 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17494 				sata_process_port_failed_event(sata_hba_inst,
17495 				    saddr);
17496 			}
17497 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17498 				sata_process_device_detached(sata_hba_inst,
17499 				    saddr);
17500 			}
17501 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17502 				sata_process_device_attached(sata_hba_inst,
17503 				    saddr);
17504 			}
17505 			if (event_flags &
17506 			    (SATA_EVNT_LINK_ESTABLISHED |
17507 			    SATA_EVNT_LINK_LOST)) {
17508 				sata_process_port_link_events(sata_hba_inst,
17509 				    saddr);
17510 			}
17511 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17512 				sata_process_port_pwr_change(sata_hba_inst,
17513 				    saddr);
17514 			}
17515 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17516 				sata_process_target_node_cleanup(
17517 				    sata_hba_inst, saddr);
17518 			}
17519 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17520 				sata_process_device_autoonline(
17521 				    sata_hba_inst, saddr);
17522 			}
17523 		}
17524 
17525 
17526 		/*
17527 		 * Scan port multiplier and all its sub-ports event flags.
17528 		 * The events are marked by
17529 		 * (1) sata_pmult_info.pmult_event_flags
17530 		 * (2) sata_pmport_info.pmport_event_flags
17531 		 */
17532 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17533 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17534 			/*
17535 			 * There should be another extra check: this
17536 			 * port multiplier still exists?
17537 			 */
17538 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17539 			    ncport);
17540 
17541 			if (pmultinfo != NULL) {
17542 				mutex_exit(&(SATA_CPORT_MUTEX(
17543 				    sata_hba_inst, ncport)));
17544 				sata_process_pmult_events(
17545 				    sata_hba_inst, ncport);
17546 				mutex_enter(&(SATA_CPORT_MUTEX(
17547 				    sata_hba_inst, ncport)));
17548 			} else {
17549 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17550 				    "Port-multiplier is gone. "
17551 				    "Ignore all sub-device events "
17552 				    "at port %d.", ncport);
17553 			}
17554 		}
17555 
17556 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17557 		    SATA_DTYPE_NONE) &&
17558 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17559 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17560 			    satadrv_event_flags &
17561 			    (SATA_EVNT_DEVICE_RESET |
17562 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17563 				/* Have device event */
17564 				sata_process_device_reset(sata_hba_inst,
17565 				    saddr);
17566 			}
17567 		}
17568 		/* Release PORT_BUSY flag */
17569 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17570 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17571 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17572 
17573 	} /* End of loop through the controller SATA ports */
17574 }
17575 
17576 /*
17577  * Specific port multiplier instance event processing. At the moment, device
17578  * event processing is limited to link/attach event only.
17579  *
17580  * NOTE: power management event is not supported yet.
17581  */
17582 static void
17583 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17584 {
17585 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17586 	sata_pmult_info_t *pmultinfo;
17587 	sata_pmport_info_t *pmportinfo;
17588 	sata_address_t *saddr;
17589 	sata_device_t sata_device;
17590 	uint32_t event_flags;
17591 	int npmport;
17592 	int rval;
17593 
17594 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17595 	    "Processing pmult event(s) on cport %d of controller %d",
17596 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17597 
17598 	/* First process events on port multiplier */
17599 	mutex_enter(&cportinfo->cport_mutex);
17600 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17601 	event_flags = pmultinfo->pmult_event_flags;
17602 
17603 	/*
17604 	 * Reset event (of port multiplier) has higher priority because the
17605 	 * port multiplier itself might be failed or removed after reset.
17606 	 */
17607 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17608 		/*
17609 		 * The status of the sub-links are uncertain,
17610 		 * so mark all sub-ports as RESET
17611 		 */
17612 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17613 		    sata_hba_inst, cport); npmport ++) {
17614 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17615 			    cport, npmport);
17616 			if (pmportinfo == NULL) {
17617 				/* That's weird. */
17618 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17619 				    "sata_hba_event_notify: "
17620 				    "invalid/un-implemented "
17621 				    "port %d:%d (%d ports), ",
17622 				    cport, npmport, SATA_NUM_PMPORTS(
17623 				    sata_hba_inst, cport)));
17624 				continue;
17625 			}
17626 
17627 			mutex_enter(&pmportinfo->pmport_mutex);
17628 
17629 			/* Mark all pmport to unknow state. */
17630 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17631 			/* Mark all pmports with link events. */
17632 			pmportinfo->pmport_event_flags =
17633 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17634 			mutex_exit(&pmportinfo->pmport_mutex);
17635 		}
17636 
17637 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17638 		/*
17639 		 * We need probe the port multiplier to know what has
17640 		 * happened.
17641 		 */
17642 		bzero(&sata_device, sizeof (sata_device_t));
17643 		sata_device.satadev_rev = SATA_DEVICE_REV;
17644 		sata_device.satadev_addr.cport = cport;
17645 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17646 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17647 
17648 		mutex_exit(&cportinfo->cport_mutex);
17649 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17650 		    (SATA_DIP(sata_hba_inst), &sata_device);
17651 		mutex_enter(&cportinfo->cport_mutex);
17652 		if (rval != SATA_SUCCESS) {
17653 			/* Something went wrong? Fail the port */
17654 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17655 			mutex_exit(&cportinfo->cport_mutex);
17656 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17657 			    "SATA port %d probing failed", cport));
17658 
17659 			/* PMult structure must be released.  */
17660 			sata_free_pmult(sata_hba_inst, &sata_device);
17661 			return;
17662 		}
17663 
17664 		sata_update_port_info(sata_hba_inst, &sata_device);
17665 
17666 		/*
17667 		 * Sanity check - Port is active? Is the link active?
17668 		 * The device is still a port multiplier?
17669 		 */
17670 		if ((cportinfo->cport_state &
17671 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17672 		    ((cportinfo->cport_scr.sstatus &
17673 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17674 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17675 			mutex_exit(&cportinfo->cport_mutex);
17676 
17677 			/* PMult structure must be released.  */
17678 			sata_free_pmult(sata_hba_inst, &sata_device);
17679 			return;
17680 		}
17681 
17682 		/* Probed succeed, set port ready. */
17683 		cportinfo->cport_state |=
17684 		    SATA_STATE_PROBED | SATA_STATE_READY;
17685 	}
17686 
17687 	/* Release port multiplier event flags. */
17688 	pmultinfo->pmult_event_flags &=
17689 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17690 	mutex_exit(&cportinfo->cport_mutex);
17691 
17692 	/*
17693 	 * Check all sub-links.
17694 	 */
17695 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17696 	    npmport ++) {
17697 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17698 		mutex_enter(&pmportinfo->pmport_mutex);
17699 		event_flags = pmportinfo->pmport_event_flags;
17700 		mutex_exit(&pmportinfo->pmport_mutex);
17701 		saddr = &pmportinfo->pmport_addr;
17702 
17703 		if ((event_flags &
17704 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17705 			/*
17706 			 * Got port multiplier port event.
17707 			 * We need some hierarchy of event processing as they
17708 			 * are affecting each other:
17709 			 * 1. device detached/attached
17710 			 * 2. link events - link events may trigger device
17711 			 *    detached or device attached events in some
17712 			 *    circumstances.
17713 			 */
17714 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17715 				sata_process_pmdevice_detached(sata_hba_inst,
17716 				    saddr);
17717 			}
17718 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17719 				sata_process_pmdevice_attached(sata_hba_inst,
17720 				    saddr);
17721 			}
17722 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17723 			    event_flags & SATA_EVNT_LINK_LOST) {
17724 				sata_process_pmport_link_events(sata_hba_inst,
17725 				    saddr);
17726 			}
17727 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17728 				sata_process_target_node_cleanup(
17729 				    sata_hba_inst, saddr);
17730 			}
17731 		}
17732 
17733 		/* Checking drive event(s). */
17734 		mutex_enter(&pmportinfo->pmport_mutex);
17735 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17736 		    pmportinfo->pmport_sata_drive != NULL) {
17737 			event_flags = pmportinfo->pmport_sata_drive->
17738 			    satadrv_event_flags;
17739 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17740 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17741 
17742 				/* Have device event */
17743 				sata_process_pmdevice_reset(sata_hba_inst,
17744 				    saddr);
17745 			}
17746 		}
17747 		mutex_exit(&pmportinfo->pmport_mutex);
17748 
17749 		/* Release PORT_BUSY flag */
17750 		mutex_enter(&cportinfo->cport_mutex);
17751 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17752 		mutex_exit(&cportinfo->cport_mutex);
17753 	}
17754 
17755 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17756 	    "[DONE] pmult event(s) on cport %d of controller %d",
17757 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17758 }
17759 
17760 /*
17761  * Process HBA power level change reported by HBA driver.
17762  * Not implemented at this time - event is ignored.
17763  */
17764 static void
17765 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17766 {
17767 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17768 	    "Processing controller power level change", NULL);
17769 
17770 	/* Ignoring it for now */
17771 	mutex_enter(&sata_hba_inst->satahba_mutex);
17772 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17773 	mutex_exit(&sata_hba_inst->satahba_mutex);
17774 }
17775 
17776 /*
17777  * Process port power level change reported by HBA driver.
17778  * Not implemented at this time - event is ignored.
17779  */
17780 static void
17781 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17782     sata_address_t *saddr)
17783 {
17784 	sata_cport_info_t *cportinfo;
17785 
17786 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17787 	    "Processing port power level change", NULL);
17788 
17789 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17790 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17791 	/* Reset event flag */
17792 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17793 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17794 }
17795 
17796 /*
17797  * Process port failure reported by HBA driver.
17798  * cports support only - no pmports.
17799  */
17800 static void
17801 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17802     sata_address_t *saddr)
17803 {
17804 	sata_cport_info_t *cportinfo;
17805 
17806 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17807 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17808 	/* Reset event flag first */
17809 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17810 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17811 	if ((cportinfo->cport_state &
17812 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17813 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17814 		    cport_mutex);
17815 		return;
17816 	}
17817 	/* Fail the port */
17818 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17819 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17820 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17821 }
17822 
17823 /*
17824  * Device Reset Event processing.
17825  * The seqeunce is managed by 3 stage flags:
17826  * - reset event reported,
17827  * - reset event being processed,
17828  * - request to clear device reset state.
17829  *
17830  * NOTE: This function has to be entered with cport mutex held. It exits with
17831  * mutex held as well, but can release mutex during the processing.
17832  */
17833 static void
17834 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17835     sata_address_t *saddr)
17836 {
17837 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17838 	sata_drive_info_t *sdinfo;
17839 	sata_cport_info_t *cportinfo;
17840 	sata_device_t sata_device;
17841 	int rval_probe, rval_set;
17842 
17843 	/* We only care about host sata cport for now */
17844 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17845 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17846 	/*
17847 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17848 	 * state, ignore reset event.
17849 	 */
17850 	if (((cportinfo->cport_state &
17851 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17852 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17853 		sdinfo->satadrv_event_flags &=
17854 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17855 		return;
17856 	}
17857 
17858 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17859 	    SATA_DTYPE_PMULT)) {
17860 		/*
17861 		 * Should not happened: this is already handled in
17862 		 * sata_hba_event_notify()
17863 		 */
17864 		mutex_exit(&cportinfo->cport_mutex);
17865 		goto done;
17866 	}
17867 
17868 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17869 	    SATA_VALID_DEV_TYPE) == 0) {
17870 		/*
17871 		 * This should not happen - coding error.
17872 		 * But we can recover, so do not panic, just clean up
17873 		 * and if in debug mode, log the message.
17874 		 */
17875 #ifdef SATA_DEBUG
17876 		sata_log(sata_hba_inst, CE_WARN,
17877 		    "sata_process_device_reset: "
17878 		    "Invalid device type with sdinfo!", NULL);
17879 #endif
17880 		sdinfo->satadrv_event_flags = 0;
17881 		return;
17882 	}
17883 
17884 #ifdef SATA_DEBUG
17885 	if ((sdinfo->satadrv_event_flags &
17886 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17887 		/* Nothing to do */
17888 		/* Something is weird - why we are processing dev reset? */
17889 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17890 		    "No device reset event!!!!", NULL);
17891 
17892 		return;
17893 	}
17894 	if ((sdinfo->satadrv_event_flags &
17895 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17896 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17897 		/* Something is weird - new device reset event */
17898 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17899 		    "Overlapping device reset events!", NULL);
17900 	}
17901 #endif
17902 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17903 	    "Processing port %d device reset", saddr->cport);
17904 
17905 	/* Clear event flag */
17906 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17907 
17908 	/* It seems that we always need to check the port state first */
17909 	sata_device.satadev_rev = SATA_DEVICE_REV;
17910 	sata_device.satadev_addr = *saddr;
17911 	/*
17912 	 * We have to exit mutex, because the HBA probe port function may
17913 	 * block on its own mutex.
17914 	 */
17915 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17916 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17917 	    (SATA_DIP(sata_hba_inst), &sata_device);
17918 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17919 	sata_update_port_info(sata_hba_inst, &sata_device);
17920 	if (rval_probe != SATA_SUCCESS) {
17921 		/* Something went wrong? Fail the port */
17922 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17923 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17924 		if (sdinfo != NULL)
17925 			sdinfo->satadrv_event_flags = 0;
17926 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17927 		    cport_mutex);
17928 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17929 		    "SATA port %d probing failed",
17930 		    saddr->cport));
17931 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17932 		    saddr->cport)->cport_mutex);
17933 		return;
17934 	}
17935 	if ((sata_device.satadev_scr.sstatus  &
17936 	    SATA_PORT_DEVLINK_UP_MASK) !=
17937 	    SATA_PORT_DEVLINK_UP ||
17938 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17939 		/*
17940 		 * No device to process, anymore. Some other event processing
17941 		 * would or have already performed port info cleanup.
17942 		 * To be safe (HBA may need it), request clearing device
17943 		 * reset condition.
17944 		 */
17945 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17946 		if (sdinfo != NULL) {
17947 			sdinfo->satadrv_event_flags &=
17948 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17949 			sdinfo->satadrv_event_flags |=
17950 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17951 		}
17952 		return;
17953 	}
17954 
17955 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17956 	if (sdinfo == NULL) {
17957 		return;
17958 	}
17959 	if ((sdinfo->satadrv_event_flags &
17960 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17961 		/*
17962 		 * Start tracking time for device feature restoration and
17963 		 * identification. Save current time (lbolt value).
17964 		 */
17965 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17966 	}
17967 	/* Mark device reset processing as active */
17968 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17969 
17970 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17971 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17972 
17973 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17974 
17975 	if (rval_set  != SATA_SUCCESS) {
17976 		/*
17977 		 * Restoring drive setting failed.
17978 		 * Probe the port first, to check if the port state has changed
17979 		 */
17980 		sata_device.satadev_rev = SATA_DEVICE_REV;
17981 		sata_device.satadev_addr = *saddr;
17982 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17983 		/* probe port */
17984 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17985 		    (SATA_DIP(sata_hba_inst), &sata_device);
17986 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17987 		    cport_mutex);
17988 		if (rval_probe == SATA_SUCCESS &&
17989 		    (sata_device.satadev_state &
17990 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17991 		    (sata_device.satadev_scr.sstatus  &
17992 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17993 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17994 			/*
17995 			 * We may retry this a bit later - in-process reset
17996 			 * condition should be already set.
17997 			 * Track retry time for device identification.
17998 			 */
17999 			if ((cportinfo->cport_dev_type &
18000 			    SATA_VALID_DEV_TYPE) != 0 &&
18001 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18002 			    sdinfo->satadrv_reset_time != 0) {
18003 				clock_t cur_time = ddi_get_lbolt();
18004 				/*
18005 				 * If the retry time limit was not
18006 				 * exceeded, retry.
18007 				 */
18008 				if ((cur_time - sdinfo->satadrv_reset_time) <
18009 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18010 					mutex_enter(
18011 					    &sata_hba_inst->satahba_mutex);
18012 					sata_hba_inst->satahba_event_flags |=
18013 					    SATA_EVNT_MAIN;
18014 					mutex_exit(
18015 					    &sata_hba_inst->satahba_mutex);
18016 					mutex_enter(&sata_mutex);
18017 					sata_event_pending |= SATA_EVNT_MAIN;
18018 					mutex_exit(&sata_mutex);
18019 					return;
18020 				}
18021 				if (rval_set == SATA_RETRY) {
18022 					/*
18023 					 * Setting drive features failed, but
18024 					 * the drive is still accessible,
18025 					 * so emit a warning message before
18026 					 * return.
18027 					 */
18028 					mutex_exit(&SATA_CPORT_INFO(
18029 					    sata_hba_inst,
18030 					    saddr->cport)->cport_mutex);
18031 					goto done;
18032 				}
18033 			}
18034 			/* Fail the drive */
18035 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18036 
18037 			sata_log(sata_hba_inst, CE_WARN,
18038 			    "SATA device at port %d - device failed",
18039 			    saddr->cport);
18040 		}
18041 		/*
18042 		 * No point of retrying - device failed or some other event
18043 		 * processing or already did or will do port info cleanup.
18044 		 * To be safe (HBA may need it),
18045 		 * request clearing device reset condition.
18046 		 */
18047 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18048 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18049 		sdinfo->satadrv_reset_time = 0;
18050 		return;
18051 	}
18052 done:
18053 	/*
18054 	 * If setting of drive features failed, but the drive is still
18055 	 * accessible, emit a warning message.
18056 	 */
18057 	if (rval_set == SATA_RETRY) {
18058 		sata_log(sata_hba_inst, CE_WARN,
18059 		    "SATA device at port %d - desired setting could not be "
18060 		    "restored after reset. Device may not operate as expected.",
18061 		    saddr->cport);
18062 	}
18063 	/*
18064 	 * Raise the flag indicating that the next sata command could
18065 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18066 	 * reset is reported.
18067 	 */
18068 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18069 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18070 		sdinfo->satadrv_reset_time = 0;
18071 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18072 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18073 			sdinfo->satadrv_event_flags &=
18074 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18075 			sdinfo->satadrv_event_flags |=
18076 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18077 		}
18078 	}
18079 }
18080 
18081 
18082 /*
18083  * Port Multiplier Port Device Reset Event processing.
18084  *
18085  * NOTE: This function has to be entered with pmport mutex held. It exits with
18086  * mutex held as well, but can release mutex during the processing.
18087  */
18088 static void
18089 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18090     sata_address_t *saddr)
18091 {
18092 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18093 	sata_drive_info_t *sdinfo = NULL;
18094 	sata_cport_info_t *cportinfo = NULL;
18095 	sata_pmport_info_t *pmportinfo = NULL;
18096 	sata_pmult_info_t *pminfo = NULL;
18097 	sata_device_t sata_device;
18098 	uint8_t cport = saddr->cport;
18099 	uint8_t pmport = saddr->pmport;
18100 	int rval;
18101 
18102 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18103 	    "Processing drive reset at port %d:%d", cport, pmport);
18104 
18105 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18106 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18107 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18108 
18109 	/*
18110 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18111 	 * state, ignore reset event.
18112 	 */
18113 	if (((cportinfo->cport_state &
18114 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18115 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18116 		sdinfo->satadrv_event_flags &=
18117 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18118 		return;
18119 	}
18120 
18121 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18122 		/*
18123 		 * This should not happen - coding error.
18124 		 * But we can recover, so do not panic, just clean up
18125 		 * and if in debug mode, log the message.
18126 		 */
18127 #ifdef SATA_DEBUG
18128 		sata_log(sata_hba_inst, CE_WARN,
18129 		    "sata_process_pmdevice_reset: "
18130 		    "Invalid device type with sdinfo!", NULL);
18131 #endif
18132 		sdinfo->satadrv_event_flags = 0;
18133 		return;
18134 	}
18135 
18136 #ifdef SATA_DEBUG
18137 	if ((sdinfo->satadrv_event_flags &
18138 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18139 		/* Nothing to do */
18140 		/* Something is weird - why we are processing dev reset? */
18141 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18142 		    "No device reset event!!!!", NULL);
18143 
18144 		return;
18145 	}
18146 	if ((sdinfo->satadrv_event_flags &
18147 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18148 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18149 		/* Something is weird - new device reset event */
18150 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18151 		    "Overlapping device reset events!", NULL);
18152 	}
18153 #endif
18154 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18155 	    "Processing port %d:%d device reset", cport, pmport);
18156 
18157 	/* Clear event flag */
18158 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18159 
18160 	/* It seems that we always need to check the port state first */
18161 	sata_device.satadev_rev = SATA_DEVICE_REV;
18162 	sata_device.satadev_addr = *saddr;
18163 	/*
18164 	 * We have to exit mutex, because the HBA probe port function may
18165 	 * block on its own mutex.
18166 	 */
18167 	mutex_exit(&pmportinfo->pmport_mutex);
18168 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18169 	    (SATA_DIP(sata_hba_inst), &sata_device);
18170 	mutex_enter(&pmportinfo->pmport_mutex);
18171 
18172 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18173 	if (rval != SATA_SUCCESS) {
18174 		/* Something went wrong? Fail the port */
18175 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18176 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18177 		    saddr->pmport);
18178 		if (sdinfo != NULL)
18179 			sdinfo->satadrv_event_flags = 0;
18180 		mutex_exit(&pmportinfo->pmport_mutex);
18181 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18182 		    "SATA port %d:%d probing failed",
18183 		    saddr->cport, saddr->pmport));
18184 		mutex_enter(&pmportinfo->pmport_mutex);
18185 		return;
18186 	}
18187 	if ((sata_device.satadev_scr.sstatus  &
18188 	    SATA_PORT_DEVLINK_UP_MASK) !=
18189 	    SATA_PORT_DEVLINK_UP ||
18190 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18191 		/*
18192 		 * No device to process, anymore. Some other event processing
18193 		 * would or have already performed port info cleanup.
18194 		 * To be safe (HBA may need it), request clearing device
18195 		 * reset condition.
18196 		 */
18197 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18198 		    saddr->pmport);
18199 		if (sdinfo != NULL) {
18200 			sdinfo->satadrv_event_flags &=
18201 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18202 			/* must clear flags on cport */
18203 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18204 			    saddr->cport);
18205 			pminfo->pmult_event_flags |=
18206 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18207 		}
18208 		return;
18209 	}
18210 
18211 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18212 	    saddr->pmport);
18213 	if (sdinfo == NULL) {
18214 		return;
18215 	}
18216 	if ((sdinfo->satadrv_event_flags &
18217 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18218 		/*
18219 		 * Start tracking time for device feature restoration and
18220 		 * identification. Save current time (lbolt value).
18221 		 */
18222 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18223 	}
18224 	/* Mark device reset processing as active */
18225 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18226 
18227 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18228 	mutex_exit(&pmportinfo->pmport_mutex);
18229 
18230 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18231 	    SATA_FAILURE) {
18232 		/*
18233 		 * Restoring drive setting failed.
18234 		 * Probe the port first, to check if the port state has changed
18235 		 */
18236 		sata_device.satadev_rev = SATA_DEVICE_REV;
18237 		sata_device.satadev_addr = *saddr;
18238 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18239 
18240 		/* probe port */
18241 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18242 		    (SATA_DIP(sata_hba_inst), &sata_device);
18243 		mutex_enter(&pmportinfo->pmport_mutex);
18244 		if (rval == SATA_SUCCESS &&
18245 		    (sata_device.satadev_state &
18246 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18247 		    (sata_device.satadev_scr.sstatus  &
18248 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18249 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18250 			/*
18251 			 * We may retry this a bit later - in-process reset
18252 			 * condition should be already set.
18253 			 * Track retry time for device identification.
18254 			 */
18255 			if ((pmportinfo->pmport_dev_type &
18256 			    SATA_VALID_DEV_TYPE) != 0 &&
18257 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18258 			    sdinfo->satadrv_reset_time != 0) {
18259 				clock_t cur_time = ddi_get_lbolt();
18260 				/*
18261 				 * If the retry time limit was not
18262 				 * exceeded, retry.
18263 				 */
18264 				if ((cur_time - sdinfo->satadrv_reset_time) <
18265 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18266 					mutex_enter(
18267 					    &sata_hba_inst->satahba_mutex);
18268 					sata_hba_inst->satahba_event_flags |=
18269 					    SATA_EVNT_MAIN;
18270 					mutex_exit(
18271 					    &sata_hba_inst->satahba_mutex);
18272 					mutex_enter(&sata_mutex);
18273 					sata_event_pending |= SATA_EVNT_MAIN;
18274 					mutex_exit(&sata_mutex);
18275 					return;
18276 				}
18277 			}
18278 			/* Fail the drive */
18279 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18280 
18281 			sata_log(sata_hba_inst, CE_WARN,
18282 			    "SATA device at port %d:%d - device failed",
18283 			    saddr->cport, saddr->pmport);
18284 		} else {
18285 			/*
18286 			 * No point of retrying - some other event processing
18287 			 * would or already did port info cleanup.
18288 			 * To be safe (HBA may need it),
18289 			 * request clearing device reset condition.
18290 			 */
18291 			sdinfo->satadrv_event_flags |=
18292 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18293 		}
18294 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18295 		sdinfo->satadrv_reset_time = 0;
18296 		return;
18297 	}
18298 	/*
18299 	 * Raise the flag indicating that the next sata command could
18300 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18301 	 * reset is reported.
18302 	 */
18303 	mutex_enter(&pmportinfo->pmport_mutex);
18304 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18305 		sdinfo->satadrv_reset_time = 0;
18306 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18307 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18308 			sdinfo->satadrv_event_flags &=
18309 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18310 			/* must clear flags on cport */
18311 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18312 			    saddr->cport);
18313 			pminfo->pmult_event_flags |=
18314 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18315 		}
18316 	}
18317 }
18318 
18319 /*
18320  * Port Link Events processing.
18321  * Every link established event may involve device reset (due to
18322  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18323  * set device reset event for an attached device (if any).
18324  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18325  *
18326  * The link established event processing varies, depending on the state
18327  * of the target node, HBA hotplugging capabilities, state of the port.
18328  * If the link is not active, the link established event is ignored.
18329  * If HBA cannot detect device attachment and there is no target node,
18330  * the link established event triggers device attach event processing.
18331  * Else, link established event triggers device reset event processing.
18332  *
18333  * The link lost event processing varies, depending on a HBA hotplugging
18334  * capability and the state of the port (link active or not active).
18335  * If the link is active, the lost link event is ignored.
18336  * If HBA cannot detect device removal, the lost link event triggers
18337  * device detached event processing after link lost timeout.
18338  * Else, the event is ignored.
18339  *
18340  * NOTE: Port multiplier ports events are handled by
18341  * sata_process_pmport_link_events();
18342  */
18343 static void
18344 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18345     sata_address_t *saddr)
18346 {
18347 	sata_device_t sata_device;
18348 	sata_cport_info_t *cportinfo;
18349 	sata_drive_info_t *sdinfo;
18350 	uint32_t event_flags;
18351 	int rval;
18352 
18353 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18354 	    "Processing port %d link event(s)", saddr->cport);
18355 
18356 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18357 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18358 	event_flags = cportinfo->cport_event_flags;
18359 
18360 	/* Reset event flags first */
18361 	cportinfo->cport_event_flags &=
18362 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18363 
18364 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18365 	if ((cportinfo->cport_state &
18366 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18367 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18368 		    cport_mutex);
18369 		return;
18370 	}
18371 
18372 	/*
18373 	 * For the sanity sake get current port state.
18374 	 * Set device address only. Other sata_device fields should be
18375 	 * set by HBA driver.
18376 	 */
18377 	sata_device.satadev_rev = SATA_DEVICE_REV;
18378 	sata_device.satadev_addr = *saddr;
18379 	/*
18380 	 * We have to exit mutex, because the HBA probe port function may
18381 	 * block on its own mutex.
18382 	 */
18383 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18384 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18385 	    (SATA_DIP(sata_hba_inst), &sata_device);
18386 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18387 	sata_update_port_info(sata_hba_inst, &sata_device);
18388 	if (rval != SATA_SUCCESS) {
18389 		/* Something went wrong? Fail the port */
18390 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18391 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18392 		    cport_mutex);
18393 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18394 		    "SATA port %d probing failed",
18395 		    saddr->cport));
18396 		/*
18397 		 * We may want to release device info structure, but
18398 		 * it is not necessary.
18399 		 */
18400 		return;
18401 	} else {
18402 		/* port probed successfully */
18403 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18404 	}
18405 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18406 
18407 		if ((sata_device.satadev_scr.sstatus &
18408 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18409 			/* Ignore event */
18410 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18411 			    "Ignoring port %d link established event - "
18412 			    "link down",
18413 			    saddr->cport);
18414 			goto linklost;
18415 		}
18416 
18417 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18418 		    "Processing port %d link established event",
18419 		    saddr->cport);
18420 
18421 		/*
18422 		 * For the sanity sake check if a device is attached - check
18423 		 * return state of a port probing.
18424 		 */
18425 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18426 			/*
18427 			 * HBA port probe indicated that there is a device
18428 			 * attached. Check if the framework had device info
18429 			 * structure attached for this device.
18430 			 */
18431 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18432 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18433 				    NULL);
18434 
18435 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18436 				if ((sdinfo->satadrv_type &
18437 				    SATA_VALID_DEV_TYPE) != 0) {
18438 					/*
18439 					 * Dev info structure is present.
18440 					 * If dev_type is set to known type in
18441 					 * the framework's drive info struct
18442 					 * then the device existed before and
18443 					 * the link was probably lost
18444 					 * momentarily - in such case
18445 					 * we may want to check device
18446 					 * identity.
18447 					 * Identity check is not supported now.
18448 					 *
18449 					 * Link established event
18450 					 * triggers device reset event.
18451 					 */
18452 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18453 					    satadrv_event_flags |=
18454 					    SATA_EVNT_DEVICE_RESET;
18455 				}
18456 			} else if (cportinfo->cport_dev_type ==
18457 			    SATA_DTYPE_NONE) {
18458 				/*
18459 				 * We got new device attached! If HBA does not
18460 				 * generate device attached events, trigger it
18461 				 * here.
18462 				 */
18463 				if (!(SATA_FEATURES(sata_hba_inst) &
18464 				    SATA_CTLF_HOTPLUG)) {
18465 					cportinfo->cport_event_flags |=
18466 					    SATA_EVNT_DEVICE_ATTACHED;
18467 				}
18468 			}
18469 			/* Reset link lost timeout */
18470 			cportinfo->cport_link_lost_time = 0;
18471 		}
18472 	}
18473 linklost:
18474 	if (event_flags & SATA_EVNT_LINK_LOST) {
18475 		if ((sata_device.satadev_scr.sstatus &
18476 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18477 			/* Ignore event */
18478 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18479 			    "Ignoring port %d link lost event - link is up",
18480 			    saddr->cport);
18481 			goto done;
18482 		}
18483 #ifdef SATA_DEBUG
18484 		if (cportinfo->cport_link_lost_time == 0) {
18485 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18486 			    "Processing port %d link lost event",
18487 			    saddr->cport);
18488 		}
18489 #endif
18490 		/*
18491 		 * When HBA cannot generate device attached/detached events,
18492 		 * we need to track link lost time and eventually generate
18493 		 * device detach event.
18494 		 */
18495 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18496 			/* We are tracking link lost time */
18497 			if (cportinfo->cport_link_lost_time == 0) {
18498 				/* save current time (lbolt value) */
18499 				cportinfo->cport_link_lost_time =
18500 				    ddi_get_lbolt();
18501 				/* just keep link lost event */
18502 				cportinfo->cport_event_flags |=
18503 				    SATA_EVNT_LINK_LOST;
18504 			} else {
18505 				clock_t cur_time = ddi_get_lbolt();
18506 				if ((cur_time -
18507 				    cportinfo->cport_link_lost_time) >=
18508 				    drv_usectohz(
18509 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18510 					/* trigger device detach event */
18511 					cportinfo->cport_event_flags |=
18512 					    SATA_EVNT_DEVICE_DETACHED;
18513 					cportinfo->cport_link_lost_time = 0;
18514 					SATADBG1(SATA_DBG_EVENTS,
18515 					    sata_hba_inst,
18516 					    "Triggering port %d "
18517 					    "device detached event",
18518 					    saddr->cport);
18519 				} else {
18520 					/* keep link lost event */
18521 					cportinfo->cport_event_flags |=
18522 					    SATA_EVNT_LINK_LOST;
18523 				}
18524 			}
18525 		}
18526 		/*
18527 		 * We could change port state to disable/delay access to
18528 		 * the attached device until the link is recovered.
18529 		 */
18530 	}
18531 done:
18532 	event_flags = cportinfo->cport_event_flags;
18533 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18534 	if (event_flags != 0) {
18535 		mutex_enter(&sata_hba_inst->satahba_mutex);
18536 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18537 		mutex_exit(&sata_hba_inst->satahba_mutex);
18538 		mutex_enter(&sata_mutex);
18539 		sata_event_pending |= SATA_EVNT_MAIN;
18540 		mutex_exit(&sata_mutex);
18541 	}
18542 }
18543 
18544 /*
18545  * Port Multiplier Port Link Events processing.
18546  */
18547 static void
18548 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18549     sata_address_t *saddr)
18550 {
18551 	sata_device_t sata_device;
18552 	sata_pmport_info_t *pmportinfo = NULL;
18553 	sata_drive_info_t *sdinfo = NULL;
18554 	uint32_t event_flags;
18555 	uint8_t cport = saddr->cport;
18556 	uint8_t pmport = saddr->pmport;
18557 	int rval;
18558 
18559 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18560 	    "Processing port %d:%d link event(s)",
18561 	    cport, pmport);
18562 
18563 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18564 	mutex_enter(&pmportinfo->pmport_mutex);
18565 	event_flags = pmportinfo->pmport_event_flags;
18566 
18567 	/* Reset event flags first */
18568 	pmportinfo->pmport_event_flags &=
18569 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18570 
18571 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18572 	if ((pmportinfo->pmport_state &
18573 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18574 		mutex_exit(&pmportinfo->pmport_mutex);
18575 		return;
18576 	}
18577 
18578 	/*
18579 	 * For the sanity sake get current port state.
18580 	 * Set device address only. Other sata_device fields should be
18581 	 * set by HBA driver.
18582 	 */
18583 	sata_device.satadev_rev = SATA_DEVICE_REV;
18584 	sata_device.satadev_addr = *saddr;
18585 	/*
18586 	 * We have to exit mutex, because the HBA probe port function may
18587 	 * block on its own mutex.
18588 	 */
18589 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18590 	    saddr->pmport));
18591 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18592 	    (SATA_DIP(sata_hba_inst), &sata_device);
18593 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18594 	    saddr->pmport));
18595 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18596 	if (rval != SATA_SUCCESS) {
18597 		/* Something went wrong? Fail the port */
18598 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18599 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18600 		    saddr->pmport));
18601 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18602 		    "SATA port %d:%d probing failed",
18603 		    saddr->cport, saddr->pmport));
18604 		/*
18605 		 * We may want to release device info structure, but
18606 		 * it is not necessary.
18607 		 */
18608 		return;
18609 	} else {
18610 		/* port probed successfully */
18611 		pmportinfo->pmport_state |=
18612 		    SATA_STATE_PROBED | SATA_STATE_READY;
18613 	}
18614 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18615 	    saddr->cport, saddr->pmport));
18616 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18617 	    saddr->cport, saddr->pmport));
18618 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18619 
18620 		if ((sata_device.satadev_scr.sstatus &
18621 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18622 			/* Ignore event */
18623 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18624 			    "Ignoring port %d:%d link established event - "
18625 			    "link down",
18626 			    saddr->cport, saddr->pmport);
18627 			goto linklost;
18628 		}
18629 
18630 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18631 		    "Processing port %d:%d link established event",
18632 		    cport, pmport);
18633 
18634 		/*
18635 		 * For the sanity sake check if a device is attached - check
18636 		 * return state of a port probing.
18637 		 */
18638 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18639 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18640 			/*
18641 			 * HBA port probe indicated that there is a device
18642 			 * attached. Check if the framework had device info
18643 			 * structure attached for this device.
18644 			 */
18645 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18646 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18647 				    NULL);
18648 
18649 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18650 				if ((sdinfo->satadrv_type &
18651 				    SATA_VALID_DEV_TYPE) != 0) {
18652 					/*
18653 					 * Dev info structure is present.
18654 					 * If dev_type is set to known type in
18655 					 * the framework's drive info struct
18656 					 * then the device existed before and
18657 					 * the link was probably lost
18658 					 * momentarily - in such case
18659 					 * we may want to check device
18660 					 * identity.
18661 					 * Identity check is not supported now.
18662 					 *
18663 					 * Link established event
18664 					 * triggers device reset event.
18665 					 */
18666 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18667 					    satadrv_event_flags |=
18668 					    SATA_EVNT_DEVICE_RESET;
18669 				}
18670 			} else if (pmportinfo->pmport_dev_type ==
18671 			    SATA_DTYPE_NONE) {
18672 				/*
18673 				 * We got new device attached! If HBA does not
18674 				 * generate device attached events, trigger it
18675 				 * here.
18676 				 */
18677 				if (!(SATA_FEATURES(sata_hba_inst) &
18678 				    SATA_CTLF_HOTPLUG)) {
18679 					pmportinfo->pmport_event_flags |=
18680 					    SATA_EVNT_DEVICE_ATTACHED;
18681 				}
18682 			}
18683 			/* Reset link lost timeout */
18684 			pmportinfo->pmport_link_lost_time = 0;
18685 		}
18686 	}
18687 linklost:
18688 	if (event_flags & SATA_EVNT_LINK_LOST) {
18689 #ifdef SATA_DEBUG
18690 		if (pmportinfo->pmport_link_lost_time == 0) {
18691 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18692 			    "Processing port %d:%d link lost event",
18693 			    saddr->cport, saddr->pmport);
18694 		}
18695 #endif
18696 		if ((sata_device.satadev_scr.sstatus &
18697 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18698 			/* Ignore event */
18699 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18700 			    "Ignoring port %d:%d link lost event - link is up",
18701 			    saddr->cport, saddr->pmport);
18702 			goto done;
18703 		}
18704 		/*
18705 		 * When HBA cannot generate device attached/detached events,
18706 		 * we need to track link lost time and eventually generate
18707 		 * device detach event.
18708 		 */
18709 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18710 			/* We are tracking link lost time */
18711 			if (pmportinfo->pmport_link_lost_time == 0) {
18712 				/* save current time (lbolt value) */
18713 				pmportinfo->pmport_link_lost_time =
18714 				    ddi_get_lbolt();
18715 				/* just keep link lost event */
18716 				pmportinfo->pmport_event_flags |=
18717 				    SATA_EVNT_LINK_LOST;
18718 			} else {
18719 				clock_t cur_time = ddi_get_lbolt();
18720 				if ((cur_time -
18721 				    pmportinfo->pmport_link_lost_time) >=
18722 				    drv_usectohz(
18723 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18724 					/* trigger device detach event */
18725 					pmportinfo->pmport_event_flags |=
18726 					    SATA_EVNT_DEVICE_DETACHED;
18727 					pmportinfo->pmport_link_lost_time = 0;
18728 					SATADBG2(SATA_DBG_EVENTS,
18729 					    sata_hba_inst,
18730 					    "Triggering port %d:%d "
18731 					    "device detached event",
18732 					    saddr->cport, saddr->pmport);
18733 				} else {
18734 					/* keep link lost event */
18735 					pmportinfo->pmport_event_flags |=
18736 					    SATA_EVNT_LINK_LOST;
18737 				}
18738 			}
18739 		}
18740 		/*
18741 		 * We could change port state to disable/delay access to
18742 		 * the attached device until the link is recovered.
18743 		 */
18744 	}
18745 done:
18746 	event_flags = pmportinfo->pmport_event_flags;
18747 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18748 	    saddr->pmport));
18749 	if (event_flags != 0) {
18750 		mutex_enter(&sata_hba_inst->satahba_mutex);
18751 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18752 		mutex_exit(&sata_hba_inst->satahba_mutex);
18753 		mutex_enter(&sata_mutex);
18754 		sata_event_pending |= SATA_EVNT_MAIN;
18755 		mutex_exit(&sata_mutex);
18756 	}
18757 }
18758 
18759 /*
18760  * Device Detached Event processing.
18761  * Port is probed to find if a device is really gone. If so,
18762  * the device info structure is detached from the SATA port info structure
18763  * and released.
18764  * Port status is updated.
18765  *
18766  * NOTE: Port multiplier ports events are handled by
18767  * sata_process_pmdevice_detached()
18768  */
18769 static void
18770 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18771     sata_address_t *saddr)
18772 {
18773 	sata_cport_info_t *cportinfo;
18774 	sata_pmport_info_t *pmportinfo;
18775 	sata_drive_info_t *sdevinfo;
18776 	sata_device_t sata_device;
18777 	sata_address_t pmport_addr;
18778 	char name[16];
18779 	uint8_t cport = saddr->cport;
18780 	int npmport;
18781 	int rval;
18782 
18783 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18784 	    "Processing port %d device detached", saddr->cport);
18785 
18786 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18787 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18788 	/* Clear event flag */
18789 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18790 
18791 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18792 	if ((cportinfo->cport_state &
18793 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18794 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18795 		    cport_mutex);
18796 		return;
18797 	}
18798 	/* For sanity, re-probe the port */
18799 	sata_device.satadev_rev = SATA_DEVICE_REV;
18800 	sata_device.satadev_addr = *saddr;
18801 
18802 	/*
18803 	 * We have to exit mutex, because the HBA probe port function may
18804 	 * block on its own mutex.
18805 	 */
18806 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18807 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18808 	    (SATA_DIP(sata_hba_inst), &sata_device);
18809 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18810 	sata_update_port_info(sata_hba_inst, &sata_device);
18811 	if (rval != SATA_SUCCESS) {
18812 		/* Something went wrong? Fail the port */
18813 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18814 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18815 		    cport_mutex);
18816 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18817 		    "SATA port %d probing failed",
18818 		    saddr->cport));
18819 		/*
18820 		 * We may want to release device info structure, but
18821 		 * it is not necessary.
18822 		 */
18823 		return;
18824 	} else {
18825 		/* port probed successfully */
18826 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18827 	}
18828 	/*
18829 	 * Check if a device is still attached. For sanity, check also
18830 	 * link status - if no link, there is no device.
18831 	 */
18832 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18833 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18834 	    SATA_DTYPE_NONE) {
18835 		/*
18836 		 * Device is still attached - ignore detach event.
18837 		 */
18838 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18839 		    cport_mutex);
18840 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18841 		    "Ignoring detach - device still attached to port %d",
18842 		    sata_device.satadev_addr.cport);
18843 		return;
18844 	}
18845 	/*
18846 	 * We need to detach and release device info structure here
18847 	 */
18848 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18849 		/*
18850 		 * A port-multiplier is removed.
18851 		 *
18852 		 * Calling sata_process_pmdevice_detached() does not work
18853 		 * here. The port multiplier is gone, so we cannot probe
18854 		 * sub-port any more and all pmult-related data structure must
18855 		 * be de-allocated immediately. Following structure of every
18856 		 * implemented sub-port behind the pmult are required to
18857 		 * released.
18858 		 *
18859 		 *   - attachment point
18860 		 *   - target node
18861 		 *   - sata_drive_info
18862 		 *   - sata_pmport_info
18863 		 */
18864 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18865 		    cport); npmport ++) {
18866 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18867 			    sata_hba_inst,
18868 			    "Detaching target node at port %d:%d",
18869 			    cport, npmport);
18870 
18871 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18872 
18873 			/* Remove attachment point. */
18874 			name[0] = '\0';
18875 			(void) sprintf(name, "%d.%d", cport, npmport);
18876 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18877 			sata_log(sata_hba_inst, CE_NOTE,
18878 			    "Remove attachment point of port %d:%d",
18879 			    cport, npmport);
18880 
18881 			/* Remove target node */
18882 			pmport_addr.cport = cport;
18883 			pmport_addr.pmport = (uint8_t)npmport;
18884 			pmport_addr.qual = SATA_ADDR_PMPORT;
18885 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18886 
18887 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18888 
18889 			/* Release sata_pmport_info & sata_drive_info. */
18890 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18891 			    cport, npmport);
18892 			ASSERT(pmportinfo != NULL);
18893 
18894 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18895 			if (sdevinfo != NULL) {
18896 				(void) kmem_free((void *) sdevinfo,
18897 				    sizeof (sata_drive_info_t));
18898 			}
18899 
18900 			/* Release sata_pmport_info at last */
18901 			(void) kmem_free((void *) pmportinfo,
18902 			    sizeof (sata_pmport_info_t));
18903 		}
18904 
18905 		/* Finally, release sata_pmult_info */
18906 		(void) kmem_free((void *)
18907 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18908 		    sizeof (sata_pmult_info_t));
18909 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18910 
18911 		sata_log(sata_hba_inst, CE_WARN,
18912 		    "SATA port-multiplier detached at port %d", cport);
18913 
18914 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18915 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18916 		    saddr->cport)->cport_mutex);
18917 	} else {
18918 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18919 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18920 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18921 			(void) kmem_free((void *)sdevinfo,
18922 			    sizeof (sata_drive_info_t));
18923 		}
18924 		sata_log(sata_hba_inst, CE_WARN,
18925 		    "SATA device detached at port %d", cport);
18926 
18927 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18928 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18929 		    saddr->cport)->cport_mutex);
18930 
18931 		/*
18932 		 * Try to offline a device and remove target node
18933 		 * if it still exists
18934 		 */
18935 		sata_remove_target_node(sata_hba_inst, saddr);
18936 	}
18937 
18938 
18939 	/*
18940 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18941 	 * with the hint: SE_HINT_REMOVE
18942 	 */
18943 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18944 }
18945 
18946 /*
18947  * Port Multiplier Port Device Deattached Event processing.
18948  *
18949  * NOTE: No Mutex should be hold.
18950  */
18951 static void
18952 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18953     sata_address_t *saddr)
18954 {
18955 	sata_pmport_info_t *pmportinfo;
18956 	sata_drive_info_t *sdevinfo;
18957 	sata_device_t sata_device;
18958 	int rval;
18959 	uint8_t cport, pmport;
18960 
18961 	cport = saddr->cport;
18962 	pmport = saddr->pmport;
18963 
18964 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18965 	    "Processing port %d:%d device detached",
18966 	    cport, pmport);
18967 
18968 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18969 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18970 
18971 	/* Clear event flag */
18972 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18973 
18974 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18975 	if ((pmportinfo->pmport_state &
18976 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18977 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18978 		return;
18979 	}
18980 	/* For sanity, re-probe the port */
18981 	sata_device.satadev_rev = SATA_DEVICE_REV;
18982 	sata_device.satadev_addr = *saddr;
18983 
18984 	/*
18985 	 * We have to exit mutex, because the HBA probe port function may
18986 	 * block on its own mutex.
18987 	 */
18988 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18989 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18990 	    (SATA_DIP(sata_hba_inst), &sata_device);
18991 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18992 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18993 	if (rval != SATA_SUCCESS) {
18994 		/* Something went wrong? Fail the port */
18995 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18996 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18997 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18998 		    "SATA port %d:%d probing failed",
18999 		    saddr->pmport));
19000 		/*
19001 		 * We may want to release device info structure, but
19002 		 * it is not necessary.
19003 		 */
19004 		return;
19005 	} else {
19006 		/* port probed successfully */
19007 		pmportinfo->pmport_state |=
19008 		    SATA_STATE_PROBED | SATA_STATE_READY;
19009 	}
19010 	/*
19011 	 * Check if a device is still attached. For sanity, check also
19012 	 * link status - if no link, there is no device.
19013 	 */
19014 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19015 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19016 	    SATA_DTYPE_NONE) {
19017 		/*
19018 		 * Device is still attached - ignore detach event.
19019 		 */
19020 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19021 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19022 		    "Ignoring detach - device still attached to port %d",
19023 		    sata_device.satadev_addr.pmport);
19024 		return;
19025 	}
19026 	/*
19027 	 * We need to detach and release device info structure here
19028 	 */
19029 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19030 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19031 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19032 		(void) kmem_free((void *)sdevinfo,
19033 		    sizeof (sata_drive_info_t));
19034 	}
19035 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19036 	/*
19037 	 * Device cannot be reached anymore, even if the target node may be
19038 	 * still present.
19039 	 */
19040 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19041 
19042 	/*
19043 	 * Try to offline a device and remove target node if it still exists
19044 	 */
19045 	sata_remove_target_node(sata_hba_inst, saddr);
19046 
19047 	/*
19048 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19049 	 * with the hint: SE_HINT_REMOVE
19050 	 */
19051 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19052 }
19053 
19054 
19055 /*
19056  * Device Attached Event processing.
19057  * Port state is checked to verify that a device is really attached. If so,
19058  * the device info structure is created and attached to the SATA port info
19059  * structure.
19060  *
19061  * If attached device cannot be identified or set-up, the retry for the
19062  * attach processing is set-up. Subsequent daemon run would try again to
19063  * identify the device, until the time limit is reached
19064  * (SATA_DEV_IDENTIFY_TIMEOUT).
19065  *
19066  * This function cannot be called in interrupt context (it may sleep).
19067  *
19068  * NOTE: Port multiplier ports events are handled by
19069  * sata_process_pmdevice_attached()
19070  */
19071 static void
19072 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19073     sata_address_t *saddr)
19074 {
19075 	sata_cport_info_t *cportinfo = NULL;
19076 	sata_drive_info_t *sdevinfo = NULL;
19077 	sata_pmult_info_t *pmultinfo = NULL;
19078 	sata_pmport_info_t *pmportinfo = NULL;
19079 	sata_device_t sata_device;
19080 	dev_info_t *tdip;
19081 	uint32_t event_flags = 0, pmult_event_flags = 0;
19082 	int rval;
19083 	int npmport;
19084 
19085 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19086 	    "Processing port %d device attached", saddr->cport);
19087 
19088 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19089 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19090 
19091 	/* Clear attach event flag first */
19092 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19093 
19094 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19095 	if ((cportinfo->cport_state &
19096 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19097 		cportinfo->cport_dev_attach_time = 0;
19098 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19099 		    cport_mutex);
19100 		return;
19101 	}
19102 
19103 	/*
19104 	 * If the sata_drive_info structure is found attached to the port info,
19105 	 * despite the fact the device was removed and now it is re-attached,
19106 	 * the old drive info structure was not removed.
19107 	 * Arbitrarily release device info structure.
19108 	 */
19109 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19110 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19111 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19112 		(void) kmem_free((void *)sdevinfo,
19113 		    sizeof (sata_drive_info_t));
19114 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19115 		    "Arbitrarily detaching old device info.", NULL);
19116 	}
19117 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19118 
19119 	/* For sanity, re-probe the port */
19120 	sata_device.satadev_rev = SATA_DEVICE_REV;
19121 	sata_device.satadev_addr = *saddr;
19122 
19123 	/*
19124 	 * We have to exit mutex, because the HBA probe port function may
19125 	 * block on its own mutex.
19126 	 */
19127 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19128 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19129 	    (SATA_DIP(sata_hba_inst), &sata_device);
19130 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19131 	sata_update_port_info(sata_hba_inst, &sata_device);
19132 	if (rval != SATA_SUCCESS) {
19133 		/* Something went wrong? Fail the port */
19134 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19135 		cportinfo->cport_dev_attach_time = 0;
19136 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19137 		    cport_mutex);
19138 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19139 		    "SATA port %d probing failed",
19140 		    saddr->cport));
19141 		return;
19142 	} else {
19143 		/* port probed successfully */
19144 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19145 	}
19146 	/*
19147 	 * Check if a device is still attached. For sanity, check also
19148 	 * link status - if no link, there is no device.
19149 	 */
19150 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19151 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19152 	    SATA_DTYPE_NONE) {
19153 		/*
19154 		 * No device - ignore attach event.
19155 		 */
19156 		cportinfo->cport_dev_attach_time = 0;
19157 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19158 		    cport_mutex);
19159 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19160 		    "Ignoring attach - no device connected to port %d",
19161 		    sata_device.satadev_addr.cport);
19162 		return;
19163 	}
19164 
19165 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19166 	/*
19167 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19168 	 * with the hint: SE_HINT_INSERT
19169 	 */
19170 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19171 
19172 	/*
19173 	 * Port reprobing will take care of the creation of the device
19174 	 * info structure and determination of the device type.
19175 	 */
19176 	sata_device.satadev_addr = *saddr;
19177 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19178 	    SATA_DEV_IDENTIFY_NORETRY);
19179 
19180 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19181 	    cport_mutex);
19182 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19183 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19184 		/* Some device is attached to the port */
19185 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19186 			/*
19187 			 * A device was not successfully attached.
19188 			 * Track retry time for device identification.
19189 			 */
19190 			if (cportinfo->cport_dev_attach_time != 0) {
19191 				clock_t cur_time = ddi_get_lbolt();
19192 				/*
19193 				 * If the retry time limit was not exceeded,
19194 				 * reinstate attach event.
19195 				 */
19196 				if ((cur_time -
19197 				    cportinfo->cport_dev_attach_time) <
19198 				    drv_usectohz(
19199 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19200 					/* OK, restore attach event */
19201 					cportinfo->cport_event_flags |=
19202 					    SATA_EVNT_DEVICE_ATTACHED;
19203 				} else {
19204 					/* Timeout - cannot identify device */
19205 					cportinfo->cport_dev_attach_time = 0;
19206 					sata_log(sata_hba_inst,
19207 					    CE_WARN,
19208 					    "Could not identify SATA device "
19209 					    "at port %d",
19210 					    saddr->cport);
19211 				}
19212 			} else {
19213 				/*
19214 				 * Start tracking time for device
19215 				 * identification.
19216 				 * Save current time (lbolt value).
19217 				 */
19218 				cportinfo->cport_dev_attach_time =
19219 				    ddi_get_lbolt();
19220 				/* Restore attach event */
19221 				cportinfo->cport_event_flags |=
19222 				    SATA_EVNT_DEVICE_ATTACHED;
19223 			}
19224 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19225 			cportinfo->cport_dev_attach_time = 0;
19226 			sata_log(sata_hba_inst, CE_NOTE,
19227 			    "SATA port-multiplier detected at port %d",
19228 			    saddr->cport);
19229 
19230 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19231 				/* Log the info of new port multiplier */
19232 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19233 				    saddr->cport)->cport_mutex);
19234 				sata_show_pmult_info(sata_hba_inst,
19235 				    &sata_device);
19236 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19237 				    saddr->cport)->cport_mutex);
19238 			}
19239 
19240 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19241 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19242 			for (npmport = 0; npmport <
19243 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19244 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19245 				    saddr->cport, npmport);
19246 				ASSERT(pmportinfo != NULL);
19247 
19248 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19249 				    saddr->cport)->cport_mutex);
19250 				mutex_enter(&pmportinfo->pmport_mutex);
19251 				/* Marked all pmports with link events. */
19252 				pmportinfo->pmport_event_flags =
19253 				    SATA_EVNT_LINK_ESTABLISHED;
19254 				pmult_event_flags |=
19255 				    pmportinfo->pmport_event_flags;
19256 				mutex_exit(&pmportinfo->pmport_mutex);
19257 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19258 				    saddr->cport)->cport_mutex);
19259 			}
19260 			/* Auto-online is not available for PMult now. */
19261 
19262 		} else {
19263 			/*
19264 			 * If device was successfully attached, the subsequent
19265 			 * action depends on a state of the
19266 			 * sata_auto_online variable. If it is set to zero.
19267 			 * an explicit 'configure' command will be needed to
19268 			 * configure it. If its value is non-zero, we will
19269 			 * attempt to online (configure) the device.
19270 			 * First, log the message indicating that a device
19271 			 * was attached.
19272 			 */
19273 			cportinfo->cport_dev_attach_time = 0;
19274 			sata_log(sata_hba_inst, CE_WARN,
19275 			    "SATA device detected at port %d", saddr->cport);
19276 
19277 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19278 				sata_drive_info_t new_sdinfo;
19279 
19280 				/* Log device info data */
19281 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19282 				    cportinfo));
19283 				sata_show_drive_info(sata_hba_inst,
19284 				    &new_sdinfo);
19285 			}
19286 
19287 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19288 			    saddr->cport)->cport_mutex);
19289 
19290 			/*
19291 			 * Make sure that there is no target node for that
19292 			 * device. If so, release it. It should not happen,
19293 			 * unless we had problem removing the node when
19294 			 * device was detached.
19295 			 */
19296 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19297 			    saddr->cport, saddr->pmport);
19298 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19299 			    saddr->cport)->cport_mutex);
19300 			if (tdip != NULL) {
19301 
19302 #ifdef SATA_DEBUG
19303 				if ((cportinfo->cport_event_flags &
19304 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19305 					sata_log(sata_hba_inst, CE_WARN,
19306 					    "sata_process_device_attached: "
19307 					    "old device target node exists!");
19308 #endif
19309 				/*
19310 				 * target node exists - try to unconfigure
19311 				 * device and remove the node.
19312 				 */
19313 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19314 				    saddr->cport)->cport_mutex);
19315 				rval = ndi_devi_offline(tdip,
19316 				    NDI_DEVI_REMOVE);
19317 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19318 				    saddr->cport)->cport_mutex);
19319 
19320 				if (rval == NDI_SUCCESS) {
19321 					cportinfo->cport_event_flags &=
19322 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19323 					cportinfo->cport_tgtnode_clean = B_TRUE;
19324 				} else {
19325 					/*
19326 					 * PROBLEM - the target node remained
19327 					 * and it belongs to a previously
19328 					 * attached device.
19329 					 * This happens when the file was open
19330 					 * or the node was waiting for
19331 					 * resources at the time the
19332 					 * associated device was removed.
19333 					 * Instruct event daemon to retry the
19334 					 * cleanup later.
19335 					 */
19336 					sata_log(sata_hba_inst,
19337 					    CE_WARN,
19338 					    "Application(s) accessing "
19339 					    "previously attached SATA "
19340 					    "device have to release "
19341 					    "it before newly inserted "
19342 					    "device can be made accessible.",
19343 					    saddr->cport);
19344 					cportinfo->cport_event_flags |=
19345 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19346 					cportinfo->cport_tgtnode_clean =
19347 					    B_FALSE;
19348 				}
19349 			}
19350 			if (sata_auto_online != 0) {
19351 				cportinfo->cport_event_flags |=
19352 				    SATA_EVNT_AUTOONLINE_DEVICE;
19353 			}
19354 
19355 		}
19356 	} else {
19357 		cportinfo->cport_dev_attach_time = 0;
19358 	}
19359 
19360 	event_flags = cportinfo->cport_event_flags;
19361 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19362 	if (event_flags != 0 || pmult_event_flags != 0) {
19363 		mutex_enter(&sata_hba_inst->satahba_mutex);
19364 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19365 		mutex_exit(&sata_hba_inst->satahba_mutex);
19366 		mutex_enter(&sata_mutex);
19367 		sata_event_pending |= SATA_EVNT_MAIN;
19368 		mutex_exit(&sata_mutex);
19369 	}
19370 }
19371 
19372 /*
19373  * Port Multiplier Port Device Attached Event processing.
19374  *
19375  * NOTE: No Mutex should be hold.
19376  */
19377 static void
19378 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19379     sata_address_t *saddr)
19380 {
19381 	sata_pmport_info_t *pmportinfo;
19382 	sata_drive_info_t *sdinfo;
19383 	sata_device_t sata_device;
19384 	dev_info_t *tdip;
19385 	uint32_t event_flags;
19386 	uint8_t cport = saddr->cport;
19387 	uint8_t pmport = saddr->pmport;
19388 	int rval;
19389 
19390 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19391 	    "Processing port %d:%d device attached", cport, pmport);
19392 
19393 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19394 
19395 	mutex_enter(&pmportinfo->pmport_mutex);
19396 
19397 	/* Clear attach event flag first */
19398 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19399 
19400 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19401 	if ((pmportinfo->pmport_state &
19402 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19403 		pmportinfo->pmport_dev_attach_time = 0;
19404 		mutex_exit(&pmportinfo->pmport_mutex);
19405 		return;
19406 	}
19407 
19408 	/*
19409 	 * If the sata_drive_info structure is found attached to the port info,
19410 	 * despite the fact the device was removed and now it is re-attached,
19411 	 * the old drive info structure was not removed.
19412 	 * Arbitrarily release device info structure.
19413 	 */
19414 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19415 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19416 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19417 		(void) kmem_free((void *)sdinfo,
19418 		    sizeof (sata_drive_info_t));
19419 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19420 		    "Arbitrarily detaching old device info.", NULL);
19421 	}
19422 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19423 
19424 	/* For sanity, re-probe the port */
19425 	sata_device.satadev_rev = SATA_DEVICE_REV;
19426 	sata_device.satadev_addr = *saddr;
19427 
19428 	/*
19429 	 * We have to exit mutex, because the HBA probe port function may
19430 	 * block on its own mutex.
19431 	 */
19432 	mutex_exit(&pmportinfo->pmport_mutex);
19433 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19434 	    (SATA_DIP(sata_hba_inst), &sata_device);
19435 	mutex_enter(&pmportinfo->pmport_mutex);
19436 
19437 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19438 	if (rval != SATA_SUCCESS) {
19439 		/* Something went wrong? Fail the port */
19440 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19441 		pmportinfo->pmport_dev_attach_time = 0;
19442 		mutex_exit(&pmportinfo->pmport_mutex);
19443 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19444 		    "SATA port %d:%d probing failed", cport, pmport));
19445 		return;
19446 	} else {
19447 		/* pmport probed successfully */
19448 		pmportinfo->pmport_state |=
19449 		    SATA_STATE_PROBED | SATA_STATE_READY;
19450 	}
19451 	/*
19452 	 * Check if a device is still attached. For sanity, check also
19453 	 * link status - if no link, there is no device.
19454 	 */
19455 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19456 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19457 	    SATA_DTYPE_NONE) {
19458 		/*
19459 		 * No device - ignore attach event.
19460 		 */
19461 		pmportinfo->pmport_dev_attach_time = 0;
19462 		mutex_exit(&pmportinfo->pmport_mutex);
19463 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19464 		    "Ignoring attach - no device connected to port %d:%d",
19465 		    cport, pmport);
19466 		return;
19467 	}
19468 
19469 	mutex_exit(&pmportinfo->pmport_mutex);
19470 	/*
19471 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19472 	 * with the hint: SE_HINT_INSERT
19473 	 */
19474 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19475 
19476 	/*
19477 	 * Port reprobing will take care of the creation of the device
19478 	 * info structure and determination of the device type.
19479 	 */
19480 	sata_device.satadev_addr = *saddr;
19481 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19482 	    SATA_DEV_IDENTIFY_NORETRY);
19483 
19484 	mutex_enter(&pmportinfo->pmport_mutex);
19485 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19486 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19487 		/* Some device is attached to the port */
19488 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19489 			/*
19490 			 * A device was not successfully attached.
19491 			 * Track retry time for device identification.
19492 			 */
19493 			if (pmportinfo->pmport_dev_attach_time != 0) {
19494 				clock_t cur_time = ddi_get_lbolt();
19495 				/*
19496 				 * If the retry time limit was not exceeded,
19497 				 * reinstate attach event.
19498 				 */
19499 				if ((cur_time -
19500 				    pmportinfo->pmport_dev_attach_time) <
19501 				    drv_usectohz(
19502 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19503 					/* OK, restore attach event */
19504 					pmportinfo->pmport_event_flags |=
19505 					    SATA_EVNT_DEVICE_ATTACHED;
19506 				} else {
19507 					/* Timeout - cannot identify device */
19508 					pmportinfo->pmport_dev_attach_time = 0;
19509 					sata_log(sata_hba_inst, CE_WARN,
19510 					    "Could not identify SATA device "
19511 					    "at port %d:%d",
19512 					    cport, pmport);
19513 				}
19514 			} else {
19515 				/*
19516 				 * Start tracking time for device
19517 				 * identification.
19518 				 * Save current time (lbolt value).
19519 				 */
19520 				pmportinfo->pmport_dev_attach_time =
19521 				    ddi_get_lbolt();
19522 				/* Restore attach event */
19523 				pmportinfo->pmport_event_flags |=
19524 				    SATA_EVNT_DEVICE_ATTACHED;
19525 			}
19526 		} else {
19527 			/*
19528 			 * If device was successfully attached, the subsequent
19529 			 * action depends on a state of the
19530 			 * sata_auto_online variable. If it is set to zero.
19531 			 * an explicit 'configure' command will be needed to
19532 			 * configure it. If its value is non-zero, we will
19533 			 * attempt to online (configure) the device.
19534 			 * First, log the message indicating that a device
19535 			 * was attached.
19536 			 */
19537 			pmportinfo->pmport_dev_attach_time = 0;
19538 			sata_log(sata_hba_inst, CE_WARN,
19539 			    "SATA device detected at port %d:%d",
19540 			    cport, pmport);
19541 
19542 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19543 				sata_drive_info_t new_sdinfo;
19544 
19545 				/* Log device info data */
19546 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19547 				    pmportinfo));
19548 				sata_show_drive_info(sata_hba_inst,
19549 				    &new_sdinfo);
19550 			}
19551 
19552 			mutex_exit(&pmportinfo->pmport_mutex);
19553 
19554 			/*
19555 			 * Make sure that there is no target node for that
19556 			 * device. If so, release it. It should not happen,
19557 			 * unless we had problem removing the node when
19558 			 * device was detached.
19559 			 */
19560 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19561 			    saddr->cport, saddr->pmport);
19562 			mutex_enter(&pmportinfo->pmport_mutex);
19563 			if (tdip != NULL) {
19564 
19565 #ifdef SATA_DEBUG
19566 				if ((pmportinfo->pmport_event_flags &
19567 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19568 					sata_log(sata_hba_inst, CE_WARN,
19569 					    "sata_process_device_attached: "
19570 					    "old device target node exists!");
19571 #endif
19572 				/*
19573 				 * target node exists - try to unconfigure
19574 				 * device and remove the node.
19575 				 */
19576 				mutex_exit(&pmportinfo->pmport_mutex);
19577 				rval = ndi_devi_offline(tdip,
19578 				    NDI_DEVI_REMOVE);
19579 				mutex_enter(&pmportinfo->pmport_mutex);
19580 
19581 				if (rval == NDI_SUCCESS) {
19582 					pmportinfo->pmport_event_flags &=
19583 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19584 					pmportinfo->pmport_tgtnode_clean =
19585 					    B_TRUE;
19586 				} else {
19587 					/*
19588 					 * PROBLEM - the target node remained
19589 					 * and it belongs to a previously
19590 					 * attached device.
19591 					 * This happens when the file was open
19592 					 * or the node was waiting for
19593 					 * resources at the time the
19594 					 * associated device was removed.
19595 					 * Instruct event daemon to retry the
19596 					 * cleanup later.
19597 					 */
19598 					sata_log(sata_hba_inst,
19599 					    CE_WARN,
19600 					    "Application(s) accessing "
19601 					    "previously attached SATA "
19602 					    "device have to release "
19603 					    "it before newly inserted "
19604 					    "device can be made accessible."
19605 					    "at port %d:%d",
19606 					    cport, pmport);
19607 					pmportinfo->pmport_event_flags |=
19608 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19609 					pmportinfo->pmport_tgtnode_clean =
19610 					    B_FALSE;
19611 				}
19612 			}
19613 			if (sata_auto_online != 0) {
19614 				pmportinfo->pmport_event_flags |=
19615 				    SATA_EVNT_AUTOONLINE_DEVICE;
19616 			}
19617 
19618 		}
19619 	} else {
19620 		pmportinfo->pmport_dev_attach_time = 0;
19621 	}
19622 
19623 	event_flags = pmportinfo->pmport_event_flags;
19624 	mutex_exit(&pmportinfo->pmport_mutex);
19625 	if (event_flags != 0) {
19626 		mutex_enter(&sata_hba_inst->satahba_mutex);
19627 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19628 		mutex_exit(&sata_hba_inst->satahba_mutex);
19629 		mutex_enter(&sata_mutex);
19630 		sata_event_pending |= SATA_EVNT_MAIN;
19631 		mutex_exit(&sata_mutex);
19632 	}
19633 
19634 	/* clear the reset_in_progress events */
19635 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19636 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19637 			/* must clear flags on cport */
19638 			sata_pmult_info_t *pminfo =
19639 			    SATA_PMULT_INFO(sata_hba_inst,
19640 			    saddr->cport);
19641 			pminfo->pmult_event_flags |=
19642 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19643 		}
19644 	}
19645 }
19646 
19647 /*
19648  * Device Target Node Cleanup Event processing.
19649  * If the target node associated with a sata port device is in
19650  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19651  * If the target node cannot be removed, the event flag is left intact,
19652  * so that event daemon may re-run this function later.
19653  *
19654  * This function cannot be called in interrupt context (it may sleep).
19655  *
19656  * NOTE: Processes cport events only, not port multiplier ports.
19657  */
19658 static void
19659 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19660     sata_address_t *saddr)
19661 {
19662 	sata_cport_info_t *cportinfo;
19663 	dev_info_t *tdip;
19664 
19665 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19666 	    "Processing port %d device target node cleanup", saddr->cport);
19667 
19668 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19669 
19670 	/*
19671 	 * Check if there is target node for that device and it is in the
19672 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19673 	 */
19674 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19675 	    saddr->pmport);
19676 	if (tdip != NULL) {
19677 		/*
19678 		 * target node exists - check if it is target node of
19679 		 * a removed device.
19680 		 */
19681 		if (sata_check_device_removed(tdip) == B_TRUE) {
19682 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19683 			    "sata_process_target_node_cleanup: "
19684 			    "old device target node exists!", NULL);
19685 			/*
19686 			 * Unconfigure and remove the target node
19687 			 */
19688 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19689 			    NDI_SUCCESS) {
19690 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19691 				    saddr->cport)->cport_mutex);
19692 				cportinfo->cport_event_flags &=
19693 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19694 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19695 				    saddr->cport)->cport_mutex);
19696 				return;
19697 			}
19698 			/*
19699 			 * Event daemon will retry the cleanup later.
19700 			 */
19701 			mutex_enter(&sata_hba_inst->satahba_mutex);
19702 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19703 			mutex_exit(&sata_hba_inst->satahba_mutex);
19704 			mutex_enter(&sata_mutex);
19705 			sata_event_pending |= SATA_EVNT_MAIN;
19706 			mutex_exit(&sata_mutex);
19707 		}
19708 	} else {
19709 		if (saddr->qual == SATA_ADDR_CPORT ||
19710 		    saddr->qual == SATA_ADDR_DCPORT) {
19711 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19712 			    saddr->cport)->cport_mutex);
19713 			cportinfo->cport_event_flags &=
19714 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19715 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19716 			    saddr->cport)->cport_mutex);
19717 		} else {
19718 			/* sanity check */
19719 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19720 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19721 			    saddr->cport) == NULL)
19722 				return;
19723 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19724 			    saddr->pmport) == NULL)
19725 				return;
19726 
19727 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19728 			    saddr->cport, saddr->pmport)->pmport_mutex);
19729 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19730 			    saddr->pmport)->pmport_event_flags &=
19731 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19732 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19733 			    saddr->cport, saddr->pmport)->pmport_mutex);
19734 		}
19735 	}
19736 }
19737 
19738 /*
19739  * Device AutoOnline Event processing.
19740  * If attached device is to be onlined, an attempt is made to online this
19741  * device, but only if there is no lingering (old) target node present.
19742  * If the device cannot be onlined, the event flag is left intact,
19743  * so that event daemon may re-run this function later.
19744  *
19745  * This function cannot be called in interrupt context (it may sleep).
19746  *
19747  * NOTE: Processes cport events only, not port multiplier ports.
19748  */
19749 static void
19750 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19751     sata_address_t *saddr)
19752 {
19753 	sata_cport_info_t *cportinfo;
19754 	sata_drive_info_t *sdinfo;
19755 	sata_device_t sata_device;
19756 	dev_info_t *tdip;
19757 
19758 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19759 	    "Processing port %d attached device auto-onlining", saddr->cport);
19760 
19761 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19762 
19763 	/*
19764 	 * Check if device is present and recognized. If not, reset event.
19765 	 */
19766 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19767 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19768 		/* Nothing to online */
19769 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19770 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19771 		    saddr->cport)->cport_mutex);
19772 		return;
19773 	}
19774 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19775 
19776 	/*
19777 	 * Check if there is target node for this device and if it is in the
19778 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19779 	 * the event for later processing.
19780 	 */
19781 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19782 	    saddr->pmport);
19783 	if (tdip != NULL) {
19784 		/*
19785 		 * target node exists - check if it is target node of
19786 		 * a removed device.
19787 		 */
19788 		if (sata_check_device_removed(tdip) == B_TRUE) {
19789 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19790 			    "sata_process_device_autoonline: "
19791 			    "old device target node exists!", NULL);
19792 			/*
19793 			 * Event daemon will retry device onlining later.
19794 			 */
19795 			mutex_enter(&sata_hba_inst->satahba_mutex);
19796 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19797 			mutex_exit(&sata_hba_inst->satahba_mutex);
19798 			mutex_enter(&sata_mutex);
19799 			sata_event_pending |= SATA_EVNT_MAIN;
19800 			mutex_exit(&sata_mutex);
19801 			return;
19802 		}
19803 		/*
19804 		 * If the target node is not in the 'removed" state, assume
19805 		 * that it belongs to this device. There is nothing more to do,
19806 		 * but reset the event.
19807 		 */
19808 	} else {
19809 
19810 		/*
19811 		 * Try to online the device
19812 		 * If there is any reset-related event, remove it. We are
19813 		 * configuring the device and no state restoring is needed.
19814 		 */
19815 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19816 		    saddr->cport)->cport_mutex);
19817 		sata_device.satadev_addr = *saddr;
19818 		if (saddr->qual == SATA_ADDR_CPORT)
19819 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19820 		else
19821 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19822 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19823 		if (sdinfo != NULL) {
19824 			if (sdinfo->satadrv_event_flags &
19825 			    (SATA_EVNT_DEVICE_RESET |
19826 			    SATA_EVNT_INPROC_DEVICE_RESET))
19827 				sdinfo->satadrv_event_flags = 0;
19828 			sdinfo->satadrv_event_flags |=
19829 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19830 
19831 			/* Need to create a new target node. */
19832 			cportinfo->cport_tgtnode_clean = B_TRUE;
19833 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19834 			    saddr->cport)->cport_mutex);
19835 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19836 			    sata_hba_inst, &sata_device.satadev_addr);
19837 			if (tdip == NULL) {
19838 				/*
19839 				 * Configure (onlining) failed.
19840 				 * We will NOT retry
19841 				 */
19842 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19843 				    "sata_process_device_autoonline: "
19844 				    "configuring SATA device at port %d failed",
19845 				    saddr->cport));
19846 			}
19847 		} else {
19848 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19849 			    saddr->cport)->cport_mutex);
19850 		}
19851 
19852 	}
19853 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19854 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19855 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19856 	    saddr->cport)->cport_mutex);
19857 }
19858 
19859 
19860 static void
19861 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19862     int hint)
19863 {
19864 	char ap[MAXPATHLEN];
19865 	nvlist_t *ev_attr_list = NULL;
19866 	int err;
19867 
19868 	/* Allocate and build sysevent attribute list */
19869 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19870 	if (err != 0) {
19871 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19872 		    "sata_gen_sysevent: "
19873 		    "cannot allocate memory for sysevent attributes\n"));
19874 		return;
19875 	}
19876 	/* Add hint attribute */
19877 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19878 	if (err != 0) {
19879 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19880 		    "sata_gen_sysevent: "
19881 		    "failed to add DR_HINT attr for sysevent"));
19882 		nvlist_free(ev_attr_list);
19883 		return;
19884 	}
19885 	/*
19886 	 * Add AP attribute.
19887 	 * Get controller pathname and convert it into AP pathname by adding
19888 	 * a target number.
19889 	 */
19890 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19891 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19892 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19893 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19894 
19895 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19896 	if (err != 0) {
19897 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19898 		    "sata_gen_sysevent: "
19899 		    "failed to add DR_AP_ID attr for sysevent"));
19900 		nvlist_free(ev_attr_list);
19901 		return;
19902 	}
19903 
19904 	/* Generate/log sysevent */
19905 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19906 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19907 	if (err != DDI_SUCCESS) {
19908 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19909 		    "sata_gen_sysevent: "
19910 		    "cannot log sysevent, err code %x\n", err));
19911 	}
19912 
19913 	nvlist_free(ev_attr_list);
19914 }
19915 
19916 
19917 
19918 
19919 /*
19920  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19921  */
19922 static void
19923 sata_set_device_removed(dev_info_t *tdip)
19924 {
19925 	int circ;
19926 
19927 	ASSERT(tdip != NULL);
19928 
19929 	ndi_devi_enter(tdip, &circ);
19930 	mutex_enter(&DEVI(tdip)->devi_lock);
19931 	DEVI_SET_DEVICE_REMOVED(tdip);
19932 	mutex_exit(&DEVI(tdip)->devi_lock);
19933 	ndi_devi_exit(tdip, circ);
19934 }
19935 
19936 
19937 /*
19938  * Set internal event instructing event daemon to try
19939  * to perform the target node cleanup.
19940  */
19941 static void
19942 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19943     sata_address_t *saddr)
19944 {
19945 	if (saddr->qual == SATA_ADDR_CPORT ||
19946 	    saddr->qual == SATA_ADDR_DCPORT) {
19947 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19948 		    saddr->cport)->cport_mutex);
19949 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19950 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19951 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19952 		    cport_tgtnode_clean = B_FALSE;
19953 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19954 		    saddr->cport)->cport_mutex);
19955 	} else {
19956 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19957 		    saddr->cport, saddr->pmport)->pmport_mutex);
19958 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19959 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19960 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19961 		    pmport_tgtnode_clean = B_FALSE;
19962 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19963 		    saddr->cport, saddr->pmport)->pmport_mutex);
19964 	}
19965 	mutex_enter(&sata_hba_inst->satahba_mutex);
19966 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19967 	mutex_exit(&sata_hba_inst->satahba_mutex);
19968 	mutex_enter(&sata_mutex);
19969 	sata_event_pending |= SATA_EVNT_MAIN;
19970 	mutex_exit(&sata_mutex);
19971 }
19972 
19973 
19974 /*
19975  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19976  * i.e. check if the target node state indicates that it belongs to a removed
19977  * device.
19978  *
19979  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19980  * B_FALSE otherwise.
19981  */
19982 static boolean_t
19983 sata_check_device_removed(dev_info_t *tdip)
19984 {
19985 	ASSERT(tdip != NULL);
19986 
19987 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19988 		return (B_TRUE);
19989 	else
19990 		return (B_FALSE);
19991 }
19992 
19993 /* ************************ FAULT INJECTTION **************************** */
19994 
19995 #ifdef SATA_INJECT_FAULTS
19996 
19997 static	uint32_t sata_fault_count = 0;
19998 static	uint32_t sata_fault_suspend_count = 0;
19999 
20000 /*
20001  * Inject sata pkt fault
20002  * It modifies returned values of the sata packet.
20003  * It returns immediately if:
20004  * pkt fault injection is not enabled (via sata_inject_fault,
20005  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20006  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20007  * pkt is not directed to specified fault controller/device
20008  * (sata_fault_ctrl_dev and sata_fault_device).
20009  * If fault controller is not specified, fault injection applies to all
20010  * controllers and devices.
20011  *
20012  * First argument is the pointer to the executed sata packet.
20013  * Second argument is a pointer to a value returned by the HBA tran_start
20014  * function.
20015  * Third argument specifies injected error. Injected sata packet faults
20016  * are the satapkt_reason values.
20017  * SATA_PKT_BUSY		-1	Not completed, busy
20018  * SATA_PKT_DEV_ERROR		1	Device reported error
20019  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20020  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20021  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20022  * SATA_PKT_ABORTED		5	Aborted by request
20023  * SATA_PKT_TIMEOUT		6	Operation timeut
20024  * SATA_PKT_RESET		7	Aborted by reset request
20025  *
20026  * Additional global variables affecting the execution:
20027  *
20028  * sata_inject_fault_count variable specifies number of times in row the
20029  * error is injected. Value of -1 specifies permanent fault, ie. every time
20030  * the fault injection point is reached, the fault is injected and a pause
20031  * between fault injection specified by sata_inject_fault_pause_count is
20032  * ignored). Fault injection routine decrements sata_inject_fault_count
20033  * (if greater than zero) until it reaches 0. No fault is injected when
20034  * sata_inject_fault_count is 0 (zero).
20035  *
20036  * sata_inject_fault_pause_count variable specifies number of times a fault
20037  * injection is bypassed (pause between fault injections).
20038  * If set to 0, a fault is injected only a number of times specified by
20039  * sata_inject_fault_count.
20040  *
20041  * The fault counts are static, so for periodic errors they have to be manually
20042  * reset to start repetition sequence from scratch.
20043  * If the original value returned by the HBA tran_start function is not
20044  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20045  * is injected (to avoid masking real problems);
20046  *
20047  * NOTE: In its current incarnation, this function should be invoked only for
20048  * commands executed in SYNCHRONOUS mode.
20049  */
20050 
20051 
20052 static void
20053 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20054 {
20055 
20056 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20057 		return;
20058 
20059 	if (sata_inject_fault_count == 0)
20060 		return;
20061 
20062 	if (fault == 0)
20063 		return;
20064 
20065 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20066 		return;
20067 
20068 	if (sata_fault_ctrl != NULL) {
20069 		sata_pkt_txlate_t *spx =
20070 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20071 
20072 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20073 		    spx->txlt_sata_hba_inst->satahba_dip)
20074 			return;
20075 
20076 		if (sata_fault_device.satadev_addr.cport !=
20077 		    spkt->satapkt_device.satadev_addr.cport ||
20078 		    sata_fault_device.satadev_addr.pmport !=
20079 		    spkt->satapkt_device.satadev_addr.pmport ||
20080 		    sata_fault_device.satadev_addr.qual !=
20081 		    spkt->satapkt_device.satadev_addr.qual)
20082 			return;
20083 	}
20084 
20085 	/* Modify pkt return parameters */
20086 	if (*rval != SATA_TRAN_ACCEPTED ||
20087 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20088 		sata_fault_count = 0;
20089 		sata_fault_suspend_count = 0;
20090 		return;
20091 	}
20092 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20093 		/* Pause in the injection */
20094 		sata_fault_suspend_count -= 1;
20095 		return;
20096 	}
20097 
20098 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20099 		/*
20100 		 * Init inject fault cycle. If fault count is set to -1,
20101 		 * it is a permanent fault.
20102 		 */
20103 		if (sata_inject_fault_count != -1) {
20104 			sata_fault_count = sata_inject_fault_count;
20105 			sata_fault_suspend_count =
20106 			    sata_inject_fault_pause_count;
20107 			if (sata_fault_suspend_count == 0)
20108 				sata_inject_fault_count = 0;
20109 		}
20110 	}
20111 
20112 	if (sata_fault_count != 0)
20113 		sata_fault_count -= 1;
20114 
20115 	switch (fault) {
20116 	case SATA_PKT_BUSY:
20117 		*rval = SATA_TRAN_BUSY;
20118 		spkt->satapkt_reason = SATA_PKT_BUSY;
20119 		break;
20120 
20121 	case SATA_PKT_QUEUE_FULL:
20122 		*rval = SATA_TRAN_QUEUE_FULL;
20123 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20124 		break;
20125 
20126 	case SATA_PKT_CMD_UNSUPPORTED:
20127 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20128 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20129 		break;
20130 
20131 	case SATA_PKT_PORT_ERROR:
20132 		/* This is "rejected" command */
20133 		*rval = SATA_TRAN_PORT_ERROR;
20134 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20135 		/* Additional error setup could be done here - port state */
20136 		break;
20137 
20138 	case SATA_PKT_DEV_ERROR:
20139 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20140 		/*
20141 		 * Additional error setup could be done here
20142 		 */
20143 		break;
20144 
20145 	case SATA_PKT_ABORTED:
20146 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20147 		break;
20148 
20149 	case SATA_PKT_TIMEOUT:
20150 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20151 		/* Additional error setup could be done here */
20152 		break;
20153 
20154 	case SATA_PKT_RESET:
20155 		spkt->satapkt_reason = SATA_PKT_RESET;
20156 		/*
20157 		 * Additional error setup could be done here - device reset
20158 		 */
20159 		break;
20160 
20161 	default:
20162 		break;
20163 	}
20164 }
20165 
20166 #endif
20167 
20168 /*
20169  * SATA Trace Ring Buffer
20170  * ----------------------
20171  *
20172  * Overview
20173  *
20174  * The SATA trace ring buffer is a ring buffer created and managed by
20175  * the SATA framework module that can be used by any module or driver
20176  * within the SATA framework to store debug messages.
20177  *
20178  * Ring Buffer Interfaces:
20179  *
20180  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20181  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20182  *
20183  *	Note that the sata_trace_debug() interface was created to give
20184  *	consumers the flexibilty of sending debug messages to ring buffer
20185  *	as variable arguments.  Consumers can send type va_list debug
20186  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20187  *	and sata_vtrace_debug() relationship is similar to that of
20188  *	cmn_err(9F) and vcmn_err(9F).
20189  *
20190  * Below is a diagram of the SATA trace ring buffer interfaces and
20191  * sample consumers:
20192  *
20193  * +---------------------------------+
20194  * |    o  o  SATA Framework Module  |
20195  * | o  SATA  o     +------------------+      +------------------+
20196  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20197  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20198  * | o        o     +------------------+   |  +------------------+
20199  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20200  * |                        |        |        +------------------+
20201  * |           +------------------+  |
20202  * |           |SATA Debug Message|  |
20203  * |           +------------------+  |
20204  * +---------------------------------+
20205  *
20206  * Supporting Routines:
20207  *
20208  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20209  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20210  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20211  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20212  *
20213  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20214  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20215  * /etc/system to desired size in unit of bytes.
20216  *
20217  * The individual debug message size in the ring buffer is restricted
20218  * to DMSG_BUF_SIZE.
20219  */
20220 void
20221 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20222 {
20223 	sata_trace_dmsg_t *dmsg;
20224 
20225 	if (sata_debug_rbuf == NULL) {
20226 		return;
20227 	}
20228 
20229 	/*
20230 	 * If max size of ring buffer is smaller than size
20231 	 * required for one debug message then just return
20232 	 * since we have no room for the debug message.
20233 	 */
20234 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20235 		return;
20236 	}
20237 
20238 	mutex_enter(&sata_debug_rbuf->lock);
20239 
20240 	/* alloc or reuse on ring buffer */
20241 	dmsg = sata_trace_dmsg_alloc();
20242 
20243 	if (dmsg == NULL) {
20244 		/* resource allocation failed */
20245 		mutex_exit(&sata_debug_rbuf->lock);
20246 		return;
20247 	}
20248 
20249 	dmsg->dip = dip;
20250 	gethrestime(&dmsg->timestamp);
20251 
20252 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20253 
20254 	mutex_exit(&sata_debug_rbuf->lock);
20255 }
20256 
20257 void
20258 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20259 {
20260 	va_list ap;
20261 
20262 	va_start(ap, fmt);
20263 	sata_vtrace_debug(dip, fmt, ap);
20264 	va_end(ap);
20265 }
20266 
20267 /*
20268  * This routine is used to manage debug messages
20269  * on ring buffer.
20270  */
20271 static sata_trace_dmsg_t *
20272 sata_trace_dmsg_alloc(void)
20273 {
20274 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20275 
20276 	if (sata_debug_rbuf->looped == TRUE) {
20277 		sata_debug_rbuf->dmsgp = dmsg->next;
20278 		return (sata_debug_rbuf->dmsgp);
20279 	}
20280 
20281 	/*
20282 	 * If we're looping for the first time,
20283 	 * connect the ring.
20284 	 */
20285 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20286 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20287 		dmsg->next = sata_debug_rbuf->dmsgh;
20288 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20289 		sata_debug_rbuf->looped = TRUE;
20290 		return (sata_debug_rbuf->dmsgp);
20291 	}
20292 
20293 	/* If we've gotten this far then memory allocation is needed */
20294 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20295 	if (dmsg_alloc == NULL) {
20296 		sata_debug_rbuf->allocfailed++;
20297 		return (dmsg_alloc);
20298 	} else {
20299 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20300 	}
20301 
20302 	if (sata_debug_rbuf->dmsgp != NULL) {
20303 		dmsg->next = dmsg_alloc;
20304 		sata_debug_rbuf->dmsgp = dmsg->next;
20305 		return (sata_debug_rbuf->dmsgp);
20306 	} else {
20307 		/*
20308 		 * We should only be here if we're initializing
20309 		 * the ring buffer.
20310 		 */
20311 		if (sata_debug_rbuf->dmsgh == NULL) {
20312 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20313 		} else {
20314 			/* Something is wrong */
20315 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20316 			return (NULL);
20317 		}
20318 
20319 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20320 		return (sata_debug_rbuf->dmsgp);
20321 	}
20322 }
20323 
20324 
20325 /*
20326  * Free all messages on debug ring buffer.
20327  */
20328 static void
20329 sata_trace_dmsg_free(void)
20330 {
20331 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20332 
20333 	while (dmsg != NULL) {
20334 		dmsg_next = dmsg->next;
20335 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20336 
20337 		/*
20338 		 * If we've looped around the ring than we're done.
20339 		 */
20340 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20341 			break;
20342 		} else {
20343 			dmsg = dmsg_next;
20344 		}
20345 	}
20346 }
20347 
20348 
20349 /*
20350  * This function can block
20351  */
20352 static void
20353 sata_trace_rbuf_alloc(void)
20354 {
20355 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20356 
20357 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20358 
20359 	if (dmsg_ring_size > 0) {
20360 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20361 	}
20362 }
20363 
20364 
20365 static void
20366 sata_trace_rbuf_free(void)
20367 {
20368 	sata_trace_dmsg_free();
20369 	mutex_destroy(&sata_debug_rbuf->lock);
20370 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20371 }
20372 
20373 /*
20374  * If SATA_DEBUG is not defined then this routine is called instead
20375  * of sata_log() via the SATA_LOG_D macro.
20376  */
20377 static void
20378 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20379     const char *fmt, ...)
20380 {
20381 #ifndef __lock_lint
20382 	_NOTE(ARGUNUSED(level))
20383 #endif
20384 
20385 	dev_info_t *dip = NULL;
20386 	va_list ap;
20387 
20388 	if (sata_hba_inst != NULL) {
20389 		dip = SATA_DIP(sata_hba_inst);
20390 	}
20391 
20392 	va_start(ap, fmt);
20393 	sata_vtrace_debug(dip, fmt, ap);
20394 	va_end(ap);
20395 }
20396